[{"content":"Most of us use ChatGPT-style tools every day, yet \u0026quot;what is actually different between GPT-2 and a modern LLM?\u0026quot; is surprisingly hard to answer. The paper names look familiar, but RoPE, GQA, SwiGLU and MoE tend to float around as unrelated acronyms.\nI think they are one story: the 2019 Transformer hit a practical wall, and one component at a time was swapped out to get past it. This post walks through that story, and then recommends an interactive page where you can see it for yourself.\nThe core idea: modern LLMs are accumulated answers to specific problems Modern LLM architecture didn't appear all at once. Here is what problem each component was answering:\nComponent Problem The change RoPE Position information breaks down beyond the trained length Instead of adding a position vector, rotate Q/K so relative distance shows up in the dot product Sliding Window Attention Attention cost grows quadratically with length Look only at nearby tokens; stacked layers widen the receptive field GQA The KV cache eats memory bandwidth during decoding Many query heads share a few KV heads RMSNorm LayerNorm's re-centering is extra work Skip mean subtraction and just rescale by RMS SwiGLU A plain GELU FFN has limited expressiveness A gated, 3-matrix FFN (compared at matched parameter counts) MoE Bigger models cost more to run Activate only a few experts per token (total params ≠ active params) KV Cache Every new token recomputes the whole prefix Store past K/V: O(N²) → O(N), with exactly the same output Speculative Decoding Big models generate one token at a time, slowly A small model drafts, the big model verifies in one parallel pass Notice the pattern: most of these changes aren't about being \u0026quot;smarter.\u0026quot; They are about longer context, lower cost, and faster inference. The skeleton (attention + FFN + residual connections) is nearly the same as in 2019. What changed is how we route around bottlenecks.\nSeeing beats memorizing Reading equations leaves questions like:\nWhat does \u0026quot;the dot product depends only on relative offset\u0026quot; actually mean in RoPE? By how much does GQA really shrink the KV cache? Which experts does an MoE router pick for each token? These tend to click the moment you see them. Here is the order I'd suggest:\nFollow GPT-2 end to end. Tokenizer → embeddings → attention → FFN → logits → sampling → the autoregressive loop. Watch one token get produced. Swap components one at a time. Ask \u0026quot;what changes if I replace this?\u0026quot; Put it all together. Walk through a modern sparse MoE pipeline stage by stage (BPE → token embedding → pre-RMSNorm → RoPE + GQA + KV cache → sparse SwiGLU MoE → speculative decoding), with a GPT-2 diff at every step. Recommended: Inside LLM 3D Inside LLM 3D is an interactive 3D learning site that follows exactly this path, right in your browser.\n👉 https://jiminelee.github.io/inside-llm-3d/\nWhy I trust it:\nIt uses real model values. Not made-up illustration numbers: the visualizations use precomputed activations from real GPT-2 Small (124M) and Qwen2.5-0.5B. It verifies the mechanics. The architecture simulations and the landmark model comparison table are verified. For instance, you can confirm that logits are identical with or without a KV cache, or compare FFN variants at matched parameter counts. A quick tour Part Topic What you'll see I GPT-2 3D forward pass An 8-stage journey of a single token II RoPE, Sliding Window A 2D rotary plane; receptive fields that grow with depth III MHA / MQA / GQA KV head grouping and cache-size comparison IV RMSNorm, SwiGLU, MoE Activation shifts, gating curves, Top-K routing V KV Cache, Speculative Decoding Recompute vs. stored cache; draft → verify animation VI Modern LLM in 3D An 8-stage modern sparse MoE pipeline with stage-by-stage GPT-2 diffs, plus a landmark model comparison table (GPT-2 through Qwen3, Llama 4, DeepSeek-V3.2 and Gemma 4) If you're new, start with Part I. If you already know the Transformer, jump straight to whatever you're curious about (say, GQA in Part III). Each chapter has its own URL (e.g. #/part-3/gqa), so it's easy to share.\nClosing thoughts If you treat LLM architecture as a list of acronyms to memorize, it fades fast. If you treat it as \u0026quot;what was the bottleneck, and what did we change?\u0026quot;, you can read a new model's spec sheet and see where it differs. I hope this page helps build that intuition.\n👉 https://jiminelee.github.io/inside-llm-3d/\nSource code and the activation-extraction scripts are on GitHub: https://github.com/jiminelee/inside-llm-3d\n","permalink":"https://blog.jiminl.com/posts/from-gpt-2-to-modern-llm/","summary":"How modern LLMs evolved from GPT-2 by solving specific bottlenecks in context length, compute, and inference, with an interactive 3D tour.","title":"From GPT-2 to Modern LLM: What Actually Changed in LLMs?"},{"content":"You’re building an LLM-powered service.\nThe model performs well. Everything works as expected. You’re almost ready to ship.\nThere’s just one problem.\nIt’s slow. Really slow.\nUsers have enough time to grab a cup of coffee while waiting for a response. If they can cook a meal before the answer arrives, you’ve got a bigger problem.\nThe obvious solution comes to mind.\n“Let’s upgrade the GPU.”\nBut the response is just as straightforward.\n“Nope. Make it work with what we have.”\nAnd that’s where the real engineering begins.\nFortunately, upgrading your GPU isn’t the only way to speed up LLM inference.\nYou can eliminate unnecessary computation, run your model more efficiently, or make better use of the GPU resources you already have.\nLet’s walk through 10 practical optimization techniques that are actually used in production LLM systems.\nFirst, What’s Actually Slow? Before optimizing anything, you need to understand where the slowdown is happening.\nLLM inference generally consists of two main stages.\nPrefill is when the model processes the input prompt. Think of it as reading and understanding the question before answering.\nDecode is when the model generates its response, one token at a time.\nA few key metrics help us distinguish between different performance problems:\nTTFT (Time to First Token): How long it takes to generate the first token. TPOT (Time per Output Token): The average time needed to generate each subsequent token. E2E Latency: The total time from submitting a request to receiving the complete response. Throughput: The number of requests or tokens the system can process per second. If the first token takes forever to appear, prefill or request queuing might be the bottleneck.\nIf the first token appears quickly but the rest of the response trickles out painfully slowly, decode might be the problem.\nAnd if everything works fine until more users show up, you may have a GPU resource management issue.\nHere’s the important distinction:\nMaking one request faster and handling many requests efficiently are two different optimization problems.\nKeep that in mind as we explore the techniques.\nPart 1. Stop Making the Model Do Unnecessary Work Before figuring out how to make your GPU run faster, ask yourself a simpler question:\n“Do we actually need all this computation?”\nSometimes the easiest optimization is eliminating work that never needed to happen in the first place.\n1. Model Selection: Do You Really Need a 100B Model? This might sound obvious, but it happens more often than you’d think.\nA shiny new 100B-parameter model gets released. Its benchmark scores look incredible.\nNaturally, as engineers, we want to try it.\nBut the feature we’re building simply summarizes three sentences from a news article into one.\nWait a second. Do we really need 100 billion parameters for that?\nIf an 8B model meets your quality requirements, there’s little reason to use a 100B model.\nIt’s like driving a semi-truck to the grocery store to pick up a carton of milk. Sure, it’s powerful, but do you really need all that horsepower?\nSmaller models generally require less computation and memory, which can translate into faster inference.\nOf course, actual performance depends on the model architecture and hardware. A smaller model that frequently produces incorrect answers and requires retries might end up being less efficient.\nThat’s why you should evaluate models of different sizes against your actual production quality requirements.\nYou can even consider Model Routing: use a smaller model for simple requests and a larger model for complex ones.\nChoose the model you need, not the model you want to play with.\n2. Output Optimization: Teach Your LLM to Stop Talking So Much LLMs can be incredibly polite.\n“What animal is this?”\n“Certainly! I’d be happy to help. After carefully analyzing the information you’ve provided, I’ve determined that this animal is an elephant.”\nThanks, but all we needed was elephant.\nThe problem is that LLMs generate all those unnecessary words token by token.\nAnd every token takes time.\nThis becomes particularly relevant for function calling and tool calling, where the output is often just structured data consumed by another program.\nFor example, instead of generating:\n{\u0026#34;animal\u0026#34;:\u0026#34;elephant\u0026#34;,\u0026#34;confidence\u0026#34;:\u0026#34;high\u0026#34;} You could use:\n{\u0026#34;a\u0026#34;:\u0026#34;e\u0026#34;,\u0026#34;c\u0026#34;:2} As long as your application knows that e means elephant and 2 represents high confidence, the shorter format works.\nThere’s a catch, though.\nFewer characters don’t always mean fewer tokens.\nActual token counts depend on the tokenizer, and overly compressed formats can increase output errors.\nSo start by removing unnecessary explanations and fields, then measure the actual token savings.\nSometimes the easiest way to generate tokens faster is to generate fewer tokens.\n3. Thinking Mode: Does Identifying an Elephant Really Require Deep Reasoning? Modern reasoning models can perform additional reasoning before producing their final answers.\nThat’s incredibly useful for complex math problems, coding, and planning.\nBut does every task really need that much thinking?\nConsider this request:\n“Classify this sentence as positive or negative.”\nDoes the model need to generate hundreds of reasoning tokens to answer that?\nIt’s like asking someone what they want for lunch and getting a full market research report in return.\nReasoning tokens consume time and computational resources, even if the final answer is just a single word.\nIf your model supports it, consider disabling Thinking Mode or reducing the thinking budget.\nFor straightforward classification or information extraction, you might use minimal reasoning. For complex planning or problem-solving, you can allocate more.\nOf course, reducing reasoning can hurt accuracy, so always evaluate the quality impact.\nJust because a model can think deeply doesn’t mean every question deserves deep thought.\n4. Prompt Optimization: Long Questions Take Longer to Read Imagine you’re building a smartphone support chatbot.\nA user asks:\n“My Wi-Fi isn’t connecting.”\nYour RAG system retrieves a massive user manual covering Wi-Fi settings, camera features, battery management, display brightness, and everything else.\nThe user has a Wi-Fi problem, but your model is busy reading the entire instruction manual.\nNaturally, that takes time.\nLonger prompts generally require more prefill computation and KV cache memory.\nYou can optimize prompts by retrieving only relevant document sections, removing duplicate search results, or trimming unnecessary conversation history.\nBut be careful.\nRemoving essential context can reduce answer quality.\nThe goal isn’t to make prompts as short as possible. It’s to remove information the model doesn’t need.\n5. Prefix Caching: Why Read the Same Thing Twice? Imagine a customer support chatbot that uses the same system prompt for every user.\nIt contains company policies, product information, and response guidelines, totaling thousands of tokens.\nNow imagine recalculating that entire prompt every time someone asks a question.\nSounds wasteful, right?\nThat’s where Prefix Caching comes in.\nIt reuses the KV cache from previously processed prompt prefixes, reducing redundant prefill computation.\nvLLM supports this through Automatic Prefix Caching.\nThere’s one important requirement: the token prefixes must actually match. Having the same meaning isn’t enough.\nThat’s why placing shared instructions at the beginning of your prompt and variable information toward the end can improve cache reuse.\nOf course, the cached data must still be available in memory, and prefix caching doesn’t directly accelerate the decoding of new output tokens.\nDon’t calculate the same thing twice if you can reuse the result.\nSimple principle. Powerful optimization.\nPart 2. Make the Necessary Computation Faster You’ve eliminated unnecessary work.\nBut your model is still too slow.\nNow it’s time to optimize how the model actually runs.\n6. Quantization: Do You Really Need That Many Bits? LLMs contain billions of parameters that must be read from GPU memory during inference.\nWhat if we could represent those parameters using fewer bits?\nFor example, switching from BF16 to FP8 can theoretically cut raw model weight storage in half.\nWhy does that matter?\nDuring decoding, especially with small batch sizes, LLM performance is often limited by memory bandwidth rather than raw GPU compute.\nThink of a chef who can cook incredibly fast but spends most of the time waiting for someone to bring ingredients from the refrigerator.\nMaking the ingredients easier to deliver can speed up the entire process.\nQuantization reduces the precision used to represent model data, potentially reducing memory usage and data transfer costs.\nThe good news is that many popular open-weight models already have quantized checkpoints available on Hugging Face.\nIn some environments, vLLM also supports online quantization, allowing supported models to be converted to lower precision, such as FP8, during loading.\nBut here’s the catch:\n4-bit isn’t always faster than 8-bit.\nHardware support and dequantization overhead can make lower-precision formats slower in some cases. Quantization can also affect model quality.\nThe goal isn’t to use the fewest bits possible.\nIt’s to find the fastest configuration that meets your quality requirements on your actual GPU.\n7. Speculative Decoding: What If We Could Predict the Next Few Tokens? Traditional autoregressive LLMs generate tokens sequentially.\nOne token.\nThen another.\nThen another.\nWhat if we could predict several upcoming tokens ahead of time?\nThat’s the idea behind Speculative Decoding.\nIn a common approach, a smaller draft model predicts several candidate tokens, and the larger target model verifies them in parallel.\nThink of a junior engineer writing a first draft while a senior engineer reviews it.\nReviewing a good draft can be much faster than writing everything from scratch.\nIf the predictions are accurate, multiple tokens can be accepted in a single verification step.\nBeyond draft-model approaches, techniques such as EAGLE, Multi-Token Prediction (MTP), and N-gram-based speculation are also available.\nAnd here’s the good news:\nYou don’t necessarily have to implement these algorithms yourself.\nvLLM supports several speculative decoding techniques, which can be enabled through configuration when the model and runtime are compatible. Some methods require additional weights.\nHowever, if predictions are frequently rejected or the GPU is already heavily utilized, the additional computation may actually slow things down.\nThat’s why speculative decoding is particularly worth exploring when single-request decoding latency is your main bottleneck.\nPart 3. Make Your GPU Handle More Users Efficiently So far, we’ve mostly focused on speeding up individual requests.\nBut production services rarely have just one user.\nAs concurrent requests increase, efficient GPU resource management becomes critical.\n8. Batching: Let Your GPU Do More Work at Once Imagine 10 users sending requests to your LLM simultaneously.\nIf you process them one by one, you may leave much of the GPU’s parallel processing capability unused.\nBatching groups multiple requests together so they can be processed more efficiently.\nA particularly useful technique for LLM serving is Continuous Batching.\nInstead of waiting for every request in a batch to finish, the system can admit new requests as others complete.\nThink of a restaurant that seats new customers as soon as tables become available, rather than waiting for everyone in the restaurant to finish eating.\nvLLM uses continuous batching to improve GPU utilization and throughput.\nBut there’s an important distinction:\nBatching primarily improves throughput, not necessarily individual request latency.\nIf you only have one user, there’s nothing to batch.\nAnd if you make batches too large, individual requests may actually become slower.\nFor high-concurrency services, measure throughput alongside TTFT and TPOT.\n9. Chunked Prefill: Don’t Let One Request Hog the GPU Imagine several users sending short questions.\nThen one user suddenly uploads a document containing tens of thousands of tokens.\n“Please summarize this.”\nProcessing that massive prompt can occupy substantial GPU resources, potentially delaying other users’ ongoing decoding.\nIt’s like standing in a grocery checkout line with two items while someone ahead of you rolls up with five overflowing shopping carts.\nNot ideal.\nChunked Prefill splits long prefill operations into smaller chunks, allowing the scheduler to interleave them with decoding work from other requests.\nWhy does this help?\nPrefill tends to be more compute-intensive, while decoding with small batches is often memory-bandwidth-bound.\nBy scheduling these workloads together more effectively, the GPU may achieve better utilization.\nvLLM V1 enables chunked prefill by default in supported configurations.\nHowever, chunk sizes and scheduling policies can affect the trade-off between TTFT and TPOT.\nChunked Prefill is especially useful when your service handles a mix of short and long requests.\n10. KV Cache Optimization: The Hidden GPU Memory Hog You’ve successfully loaded your model into GPU memory.\nEverything looks fine.\nThen more users arrive, and suddenly you’re running out of memory.\n“But the model fits!”\nThe culprit might be the KV cache.\nLLMs store previously computed attention keys and values so they don’t have to recompute them for every new token.\nThis is essential for efficient decoding.\nThe problem?\nAs input sequences, generated outputs, and concurrent requests grow, so does KV cache memory usage.\nTwo techniques are particularly useful here.\nPaged KV Cache manages cache memory in smaller blocks rather than requiring large contiguous allocations.\nvLLM’s PagedAttention is a well-known example. It reduces memory waste and helps the system support more concurrent requests.\nKV Cache Quantization stores the cache using lower-precision formats such as FP8.\nFor example, switching KV cache storage from BF16 to FP8 can theoretically reduce the raw cache data size by half.\nOf course, actual performance depends on hardware support, attention kernels, and potential quality impacts.\nOne important detail:\nKV cache optimization doesn’t automatically make a single request faster.\nIts biggest benefit may be improved memory efficiency and higher concurrency.\nSo if you’re running out of GPU memory, don’t just blame the model weights.\nCheck the KV cache, too.\nQuick Guide: Which Optimization Should You Try First? You don’t need to apply all 10 techniques.\nStart with the problem you’re actually experiencing.\nThe first token takes forever Try: 4. Prompt Optimization + 5. Prefix Caching\nCheck input token counts and cache reuse. If requests are stuck in a queue, also investigate batching and chunked prefill.\nThe first token appears quickly, but generation is slow Try: 6. Quantization + 7. Speculative Decoding\nLook for memory bandwidth or sequential decoding bottlenecks.\nThe complete response takes too long Try: 2. Output Optimization + 3. Thinking Mode\nReduce unnecessary output and reasoning tokens.\nPerformance collapses when more users arrive Try: 8. Continuous Batching + 9. Chunked Prefill\nImprove request scheduling and GPU utilization.\nYou’re running out of GPU memory Try: 6. Quantization + 10. KV Cache Optimization\nCheck how much memory your model weights and KV cache consume.\nThe GPU is already busy, but throughput is still too low Try: 1. Model Selection + 2. Output Optimization + 3. Thinking Mode\nFocus on reducing the computation required per request.\nGPU utilization is low, but decoding is still slow Try: 7. Speculative Decoding\nSee whether you can use available compute resources more effectively. If you have enough concurrent requests, investigate batching as well.\nThese are starting points, not universal rules. The right solution depends on your actual bottleneck.\nOne Last Thing: Measure Everything Before and after optimization, track at least three things:\nLatency. Throughput. Quality.\nDon’t just look at averages. Check tail latency metrics such as p95, too.\nAnd benchmark under realistic conditions, including actual concurrency levels, input lengths, and output lengths.\nIf you double inference speed but also double the error rate, you haven’t really solved the problem.\nOptimization techniques can also interact with one another, so introduce changes incrementally and measure how the bottleneck shifts.\nFinal Thoughts: Maybe the GPU Isn’t Slow. Maybe We’re Asking It to Do Too Much. When LLM inference is slow, the GPU is usually the first thing we blame.\nAnd sometimes, hardware really is the limiting factor.\nBut in production systems, performance problems often come from somewhere else.\nAre we using a model that’s unnecessarily large?\nAre we generating tokens nobody needs?\nAre we repeatedly computing things we’ve already calculated?\nAre we scheduling requests inefficiently?\nBeing told you can’t upgrade your GPU can be frustrating.\nBut constraints like these often push us to understand our systems more deeply.\nGreat AI engineering isn’t about throwing more compute at every problem. It’s about getting more useful work done with the resources you already have.\nAnd sometimes, the best optimization starts with one simple question:\n“Do we really need to compute this?”\n","permalink":"https://blog.jiminl.com/posts/10-practical-ways-to-speed-up-llm-inference-3a713edf8ed1/","summary":"You’re building an LLM-powered service.","title":"10 Practical Ways to Speed Up LLM Inference"},{"content":"The hardest part of autonomous AI engineering isn’t training models. It’s building the verification systems that make autonomous decisions trustworthy.\nIt’s Friday afternoon. Just before leaving for the weekend, you enter a single command into your terminal.\nA fleet of AI agents springs into action.\nA training agent fine-tunes a model. An evaluation agent measures its performance. An error-analysis agent investigates failures. A data agent generates new training samples to address weaknesses.\nOnce everything finishes, the cycle starts again.\nThis is Closed-loop AI Engineering: an autonomous system that trains, evaluates, diagnoses, and improves AI models.\nYou close your laptop and enjoy the weekend.\nOn Monday morning, a Slack notification appears:\n“Model performance improved by 4.2%. Deployment-ready.”\nExcellent news.\nUntil you examine the details.\nCritical features have regressed. P99 latency has doubled. Projected inference costs have nearly tripled.\nAnd there’s another problem.\nYou can’t tell whether the model genuinely improved or simply learned to exploit the preferences of its LLM-based evaluator.\nThe system that optimized the model was AI. The system that declared it successful was also AI.\nDid we build a better model, or just a very expensive echo chamber?\n1. AI Is Learning to Develop AI Automating machine learning isn’t new.\nAutoML, hyperparameter optimization, and automated training pipelines have existed for years.\nBut modern AI agents are doing something fundamentally different.\nInstead of merely searching predefined parameter spaces, they can formulate hypotheses, modify training code, execute experiments, analyze failures, and propose subsequent improvements.\nConsider Sakana AI’s The AI Scientist.\nIntroduced in 2024, it demonstrated automated research workflows covering idea generation, experimentation, and paper writing. Its successor, The AI Scientist-v2, extended those capabilities, producing an AI-generated workshop paper that passed peer review.\nMeanwhile, OpenAI’s MLE-bench evaluates agents across 75 real-world Kaggle competitions.\nIn its initial 2024 results, the strongest reported setup reached at least bronze-medal performance in 16.9% of competitions. Later systems have reported substantially higher results, although different compute budgets and agent configurations make direct comparisons difficult.\nThese developments don’t mean AI can replace experienced ML researchers.\nBut they suggest that increasingly sophisticated engineering tasks can be automated.\nAn agent can already generate experiments faster than most human engineers can review them.\nAnd that changes the bottleneck.\nFor years, the central challenge was:\nCan we build and train better models?\nIncreasingly, another question matters more:\nCan we prove that the models AI builds are actually better?\nThese are very different problems.\n2. Making a Better Model Is Easier Than Proving It Suppose you tell an autonomous engineering agent:\n“Maximize model accuracy on our evaluation suite.”\nThe agent runs hundreds of experiments, adjusts training parameters, modifies datasets, and eventually produces a checkpoint with higher accuracy.\nSuccess?\nNot necessarily.\nWhen the Metric Improves but the Product Gets Worse Imagine a customer support assistant.\nA new model answers 95% of routine questions accurately. Its overall benchmark score improves.\nUnfortunately, it also becomes more confident when inventing refund policies and billing rules.\nThose failures represent only a small fraction of requests.\nBut they’re precisely the failures that damage customer trust and create legal exposure.\nThe average score improved.\nThe product got worse.\nThis illustrates Goodhart’s Law:\nWhen a measure becomes a target, it ceases to be a good measure.\nAn autonomous agent doesn’t necessarily optimize what your business values.\nIt optimizes what you’ve instructed it to measure.\nWhen these objectives diverge, the agent may become exceptionally good at improving the wrong thing.\nWhen AI Grades Its Own Homework The problem becomes more complicated with LLM-as-a-Judge.\nLLM judges are essential for evaluating generative AI at scale. Human evaluation alone cannot support rapid experimentation across hundreds of tasks, languages, and model configurations.\nBut automated judges have limitations.\nResearch such as Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena (Zheng et al., 2023) has documented biases including:\nVerbosity bias: Preferring longer responses, even when additional words provide little value. Position bias: Favoring a candidate based on its position in a comparison. Self-enhancement bias: Favoring responses resembling the evaluator’s own outputs. Now imagine an optimization agent running 300 experiments against the same judge.\nInitially, it discovers genuine improvements.\nEventually, it may discover that adding elaborate explanations, unnecessary summaries, or certain stylistic patterns consistently earns higher scores.\nThe evaluation dashboard turns green.\nMeanwhile, users receive increasingly bloated answers.\nThe agent hasn’t necessarily become better at answering questions.\nIt has become better at satisfying the judge.\nThis is why the evaluator must be independent of the optimizer.\nThe problem isn’t using AI to evaluate AI.\nThe problem is allowing the optimization process to exploit weaknesses in the evaluation process.\nWhy One Number Is Never Enough Aggregate metrics introduce another dangerous illusion.\nImagine a multilingual assistant supporting English, Spanish, and Japanese.\nA new checkpoint improves overall accuracy by 3%.\nBut Japanese performance deteriorates significantly while English performance improves.\nFor customers relying on Japanese, this is a serious regression.\nFor an agent optimizing a single global metric, it’s a success.\nThe same problem appears across customer segments, specialized tasks, safety categories, and long-tail distributions.\nProduction evaluation must therefore answer more than “Did the average score improve?”\nIt must establish:\nWhich capabilities must never regress? Which failures are unacceptable, regardless of their frequency? Which trade-offs are permissible? How much evidence is required before deployment? These are engineering and product decisions, not simply statistical calculations.\nA good model isn’t the one with the highest score. It’s the one that best satisfies an explicitly defined contract with its users.\n3. The Production Constraints Autonomous Agents Can’t Ignore Even a genuinely better model may be unsuitable for production.\nResearch benchmarks usually optimize model quality.\nProduction systems must balance quality against memory, latency, cost, reliability, and safety.\nAutonomous engineering needs to understand those constraints.\nSynthetic Data: When Models Learn From Their Own Mistakes Suppose an agent discovers that a model struggles with certain reasoning problems.\nIt generates 20,000 synthetic examples and fine-tunes the model.\nPerformance improves.\nNaturally, it repeats the process.\nSynthetic data can be extremely valuable. But repeatedly training on unverified model-generated outputs creates risks.\nResearch on Model Collapse (Shumailov et al., Nature 2024) demonstrated how uncontrolled recursive training on generated data can progressively destroy information about the tails of the original data distribution.\nRare cases disappear. Diversity decreases. Earlier mistakes can become reinforced.\nThis doesn’t mean synthetic data should be avoided.\nIt means autonomous systems need strict data quality controls, provenance tracking, and independent evaluation sets.\nOtherwise, the training agent may contaminate the very benchmark used to judge its progress.\nA student who memorizes the answer key can achieve a perfect score.\nThat doesn’t mean the student understands the subject.\nAccuracy vs. Latency, Memory, and Cost Consider an on-device translation model.\nAn autonomous agent discovers an architectural change that improves translation quality.\nUnfortunately, the modified model consumes another 400 MB of memory and causes thermal throttling during sustained inference.\nIs it better?\nFrom a translation benchmark perspective, yes.\nFrom a smartphone user’s perspective, probably not.\nCloud deployments face similar problems.\nA model might improve response quality by 1% while tripling inference costs or exceeding critical latency requirements.\nProduction AI engineering is fundamentally about trade-offs.\nThe optimal model isn’t necessarily the most capable model.\nIt’s the model delivering the greatest user value within acceptable operational constraints.\nExperiments Have a Cost Autonomous agents can execute experiments continuously.\nThat’s powerful, but it also creates an economic problem.\nSuppose an agent performs 400 training runs, consuming $15,000 in GPU resources, to improve a secondary metric by 0.1%.\nWas that successful automation?\nNot necessarily.\nA production-grade autonomous system needs experiment budgets, early stopping, and prioritization based on expected value.\nThe goal isn’t to maximize the number of experiments.\nIt’s to maximize useful engineering progress per dollar spent.\n4. Designing an Autonomous Engineering System We Can Trust The solution isn’t to abandon autonomous engineering.\nIt’s to design an architecture where automation and verification are separated.\nA useful principle is:\nAn agent’s autonomy should scale with our ability to verify its decisions, not with how impressive its reasoning appears.\nConsider four layers of such a system.\nLayer 1: Autonomous Experimentation Give agents broad freedom to explore.\nThey should be able to inspect failure logs, propose improvements, modify code, generate training data, and launch experiments.\nBut these activities should occur in isolated environments.\nEach experiment needs resource limits, execution timeouts, and compute budgets.\nAn experimental failure should never compromise production infrastructure.\nThis is where we should maximize autonomy.\nLayer 2: Independent Evaluation This is the most important architectural boundary.\nThe agent optimizing a model must not control the system deciding whether that model passes.\nEvaluation should operate independently, using protected datasets and predefined criteria.\nRather than producing a single score, it should assess multiple dimensions:\nFunctional quality across critical tasks and languages. Safety, robustness, and regression performance. Latency, memory, and inference costs. LLM-judge reliability against human-labeled references. Data contamination and distribution-shift risks. Evaluation criteria must not be silently rewritten by an optimization agent seeking a better score.\nOtherwise, the system can improve its apparent performance simply by moving the goalposts.\nLayer 3: Explicit Release Gates Not every improvement deserves deployment.\nA candidate model should advance only when it satisfies clearly defined requirements.\nFor example:\nNo unacceptable regressions in critical capabilities. Safety and policy requirements satisfied. Latency and memory within operational limits. Inference costs within budget. Human approval for changes involving significant risk. These gates can be automated.\nIn fact, they should be automated wherever the rules are sufficiently precise.\nThe important distinction is between automating a decision and allowing an agent to redefine the decision criteria.\nLayer 4: Continuous Production Verification Offline evaluation cannot anticipate everything.\nReal users behave differently from benchmark datasets.\nThat’s why deployment should also be part of the verification process.\nA candidate can first enter a limited canary release, serving a small percentage of production traffic.\nThe system monitors error rates, latency, fallback behavior, user experience, and other relevant signals.\nIf meaningful regressions appear, automated rollback restores the previous checkpoint.\nNewly discovered failures then become candidates for future training experiments, subject to appropriate privacy and data controls.\nThe resulting loop becomes:\nTrain → Independent Validation → Canary Deployment → Production Feedback → Retrain\nThis is a more meaningful definition of closed-loop AI engineering.\nNot merely a system that repeatedly trains models.\nA system that can independently establish whether its changes are safe and valuable.\n5. The Real Goal: Expanding the Boundary of Autonomy Does this mean human engineers must approve every model update forever?\nOf course not.\nIf AI agents automate hundreds of experiments but every release requires exhaustive human review, we’ve simply moved the bottleneck.\nThe goal is to expand autonomy safely.\nThink of autonomy as something a system earns through demonstrated reliability.\nAssisted: Agents analyze problems and propose changes. Humans execute and approve.\nSupervised: Agents run experiments and evaluations independently, but humans approve releases.\nConstrained autonomy: Low-risk updates that satisfy predefined requirements can deploy automatically through monitored canary releases.\nRisk-based escalation: Architectural changes, unfamiliar data domains, or significant policy modifications require human oversight.\nThese aren’t necessarily sequential maturity levels. They’re different permission boundaries based on the consequences of failure.\nAn agent might operate autonomously for routine model updates while requiring human approval for changes affecting sensitive customer decisions.\nThe appropriate level of autonomy depends on two things:\nHow confidently can we verify the outcome, and how costly would an undetected failure be?\nThis also changes the role of AI engineers.\nFor years, much of our work involved writing training code, debugging pipelines, running experiments, and analyzing results.\nAs agents increasingly handle execution, engineers will spend more time defining objectives, constraints, and decision boundaries.\nQuestions like:\nWhat should our model optimize for? Which failures are unacceptable? What quality-versus-cost trade-offs make sense? What evidence justifies deployment without human approval? These questions require product understanding, systems thinking, and engineering judgment.\nAnd they cannot be answered by training loss alone.\nThe Monday Morning Notification We Actually Want Let’s return to Friday afternoon.\nYou launch your autonomous engineering system and leave for the weekend.\nOn Monday, you receive a notification:\n“Model performance improved by 4.2%.”\nThat’s no longer enough.\nA more trustworthy notification would say:\nAutonomous Release Report\nModel quality: +4.2%; no critical regressions detected.\nPerformance: P99 latency within SLA.\nCost: Projected inference cost reduced by 2.1%.\nVerification: Independent evaluation and safety checks passed.\nProduction: 5% canary rollout completed without detected anomalies.\nDecision: Candidate approved for production promotion.\nThe important achievement isn’t the 4.2% improvement.\nIt’s the evidence supporting the deployment decision.\nEventually, sufficiently reliable systems may not require an engineer to review every such report.\nHumans will intervene when uncertainty, risk, or business consequences demand their judgment.\nBut getting there requires more than increasingly capable training agents.\nIt requires equally sophisticated verification architectures.\nThe future of autonomous AI engineering isn’t just about teaching AI to build better models.\nIt’s about building systems that can prove those models deserve our trust.\n","permalink":"https://blog.jiminl.com/posts/when-ai-builds-ai-who-decides-if-it-got-better-c9d13ed2922b/","summary":"The hardest part of autonomous AI engineering isn’t training models. It’s building the verification systems that make autonomous decisions…","title":"When AI Builds AI, Who Decides If It Got Better?"},{"content":"“On-device AI” sounds simple enough. Take a large language model, shrink it, quantize the weights, and squeeze it into a smartphone. No cloud costs, no network latency, and better privacy. Problem solved.\nIf only it were that easy. My fellow engineers and I would have considerably more hair left on our heads.\nWhile building Galaxy AI, I’ve helped bring AI capabilities to hundreds of millions of mobile devices. One thing I’ve learned is that getting a model to run on a phone is very different from making it work reliably for millions of users.\nA model that performs beautifully in a lab can become a disaster when deployed to real phones, competing with other apps for memory, battling thermal limits, and running on dozens of hardware configurations.\nHere are eight lessons I’ve learned from bringing on-device AI into production.\n1. On-Device Doesn’t Automatically Mean Faster One of the biggest selling points of on-device AI is speed. No network calls should mean lower latency, right?\nNot necessarily.\nModern networks are surprisingly fast. On a good 5G or Wi-Fi connection, network round-trip latency can be measured in tens of milliseconds, although actual latency varies significantly with network conditions and server location.\nMeanwhile, smartphones have a fraction of the memory bandwidth and computational capacity of cloud GPU servers.\nConsider a language model that takes two seconds to generate its first token on a phone. Even after eliminating network latency, it may feel slower than a cloud model that responds in a fraction of that time.\nOf course, this depends on the workload. Small, specialized models can be extremely fast on-device, especially when they avoid unnecessary network requests.\nThe lesson: Optimize end-to-end user latency, not just network latency.\nA model running locally isn’t automatically a faster product.\n2. Users Don’t Care About Your Technical Constraints Imagine an engineer proudly announcing:\n“We managed to fit a 3-billion-parameter model into less than 2GB of memory using 4-bit quantization!”\nAmong AI engineers, that’s an impressive achievement.\nTo an ordinary smartphone user? Nobody cares.\nUsers don’t distinguish between a small model running on their phone and a massive model running in the cloud. They see an AI feature. If it works well, they’re happy. If it produces nonsense, it’s broken.\nYou can’t tell users, “Please lower your expectations. I’m only a tiny on-device model.”\nUnfortunately, cloud AI has already established a high standard for what users expect.\nTo close the quality gap, we rely on techniques such as knowledge distillation, task-specific training, quantization-aware optimization, and careful post-training. Instead of making one small model answer every question imaginable, we can optimize compact models for specific tasks like translation, summarization, or writing assistance.\nBut model architecture is only part of the solution. Product design matters just as much. A well-defined task can often deliver a better experience than an overly ambitious general-purpose assistant.\nThe lesson: Users judge the experience, not the model’s size.\nThe real goal isn’t to build the smartest small model. It’s to deliver an AI feature that feels intelligent within the constraints of the device.\n3. Getting the Model to Run Is Just the Starting Line The first time a language model generates text on a smartphone is exciting.\nUnfortunately, that’s usually when the real engineering work begins.\nOn-device AI forces engineers to make trade-offs that rarely appear in cloud model benchmarks.\nPerformance vs. Temperature\nPush the processor harder, and the phone heats up. After sustained workloads, thermal throttling can reduce performance significantly.\nYour AI might respond quickly to the first question but become noticeably slower after several consecutive requests.\nResponsiveness vs. Memory\nKeeping a model loaded in RAM reduces cold-start latency. But that memory isn’t reserved exclusively for AI.\nThe camera, browser, messaging apps, and operating system all need their share.\nIf your AI model occupies several gigabytes of RAM, the operating system may kill background applications to free memory.\nImagine asking AI to summarize an email, only to discover that the email app itself has been killed.\nCongratulations. You’ve optimized the AI feature and ruined the user experience.\nQuality vs. Battery Life\nMore computation can improve model quality, but it also consumes energy. Users won’t appreciate a slightly better summary if their battery drains noticeably faster.\nThese trade-offs make system-level engineering as important as model quality.\nThe lesson: A successful on-device model must coexist with the rest of the phone.\nMaking a model fit into memory is an achievement. Making sure everything else still works while it runs is the real challenge.\n4. Deployment Is Harder Than You Think Cloud AI has an enormous operational advantage: centralized control.\nWhen a model needs updating, engineers can deploy a new version through a managed rollout, monitor its behavior, and roll back if necessary.\nOn-device AI is different.\nOnce a model is deployed, copies of it live on millions of devices outside your direct control.\nSuppose you discover that your translation model consistently mishandles a particular expression. You fix the problem and produce a better model.\nNow comes the difficult part: getting that model onto users’ phones.\nTraditional approaches rely on application or firmware updates. But users may disable automatic updates, lack storage space, or delay downloading large files.\nThe result is version fragmentation.\nDifferent users run different models, sometimes for months or even years.\nThis complicates debugging, quality assurance, and compatibility testing. A bug affecting one model version on one chipset might not reproduce anywhere else.\nAnd unlike a cloud deployment, you can’t assume everyone will receive your fix immediately.\nThe lesson: Model deployment is a long-term lifecycle problem, not a one-time release.\nYou need to plan for version management, compatibility, rollback strategies, and devices that never update.\n5. Ironically, You Still Need the Cloud Here’s one of my favorite paradoxes about on-device AI.\nTo make on-device AI easier to maintain, you often end up building more cloud infrastructure.\nConsider the update problem.\nInstead of waiting for a full application or firmware update, why not download new model files independently?\nGood idea. But now you need infrastructure to manage those updates.\nYou may need:\nA global content delivery network for distributing model files. Device-aware rollout policies for different hardware configurations. Reliable downloads with interruption recovery and integrity checks. Version management, staged rollouts, and rollback mechanisms. Monitoring to detect failures across the installed device population. At hundreds of millions of devices, even distributing model files becomes a significant engineering challenge.\nAnd there’s another complication.\nOn-device models can’t handle every possible request. Some tasks require more capable cloud models, current information, or resources unavailable on the phone.\nThat leads naturally to hybrid AI, where the system decides whether to process a request locally or send it to the cloud.\nNow you’re maintaining both environments, along with the routing logic between them.\nThe lesson: On-device AI doesn’t eliminate cloud engineering. It changes what the cloud is responsible for.\nFor many large-scale products, the cloud evolves from handling every inference request to supporting model distribution, lifecycle management, and selective inference.\n6. Welcome to the Wild West of NPUs If you want efficient on-device AI, the Neural Processing Unit (NPU) sounds like the perfect solution.\nIt’s designed to accelerate AI workloads while consuming less power than general-purpose processors.\nSimple enough.\nUntil you actually try deploying models across different mobile chipsets.\nUnlike the relatively standardized CUDA ecosystem used by much of cloud AI, mobile hardware is fragmented.\nQualcomm, Samsung, MediaTek, and Apple have different accelerator architectures, software stacks, supported operators, and optimization requirements.\nA model that runs efficiently on one chipset might behave very differently on another.\nUnsupported Operators\nSuppose your model uses an attention operation that works perfectly on one NPU.\nOn another chipset, the compiler might reject it or fall back to CPU execution.\nMoving operations between processors can introduce synchronization and memory-transfer overhead, sometimes eliminating the expected performance benefit.\nQuantization Differences\nDifferent NPUs support different numerical formats and have different performance characteristics for INT8, INT4, FP16, and other precisions.\nA quantization strategy that works well on one device might produce different performance or accuracy results on another.\nHardware-Specific Optimization\nYou may need different compiled artifacts, execution backends, quantization strategies, or even model variants for different chipsets and device generations.\nAnd once you’ve created those variants, you need to test and distribute them correctly.\nWhich brings us right back to deployment and version management.\nThe lesson: NPU acceleration isn’t a free performance upgrade. It’s an additional engineering discipline.\nHardware-aware model design, compiler compatibility, and cross-device validation can determine whether an on-device AI feature succeeds.\n7. On-Device Doesn’t Automatically Guarantee Privacy Privacy is one of the strongest arguments for on-device AI.\nIf sensitive user data never leaves the phone, the exposure associated with sending that data to external servers can be reduced substantially.\nBut there’s an important distinction:\nLocal inference isn’t the same as end-to-end privacy.\nA commercial AI feature consists of much more than the model itself.\nConsider what happens before and after inference.\nTemporary Data\nPreprocessing and postprocessing components might create caches or temporary files containing sensitive information. Those files still need appropriate protection.\nLogging and Telemetry\nEngineers need diagnostic information to investigate crashes, monitor performance, and improve reliability.\nBut what if a crash report accidentally includes part of a user’s prompt or model output?\nYour inference happened entirely on-device, yet sensitive information still left the phone.\nHybrid AI\nIf some requests are routed to the cloud, users need clear privacy guarantees about what data is transmitted and when.\nBuilding trustworthy on-device AI requires security throughout the pipeline: data minimization, access controls, secure storage, careful logging policies, and explicit boundaries around cloud communication.\nHardware-backed security and privacy-preserving analytics can help in appropriate scenarios, but neither replaces comprehensive security engineering.\nThe lesson: Privacy is a property of the entire system, not the location of the model.\nRunning inference locally creates an opportunity for better privacy. Good engineering is what makes that promise credible.\n8. Despite Everything, On-Device AI Is Worth It After seven lessons about performance limitations, memory problems, deployment headaches, and hardware fragmentation, you might reasonably ask:\nWhy bother?\nWhy not just use a cloud API?\nBecause when on-device AI works well, it enables experiences that are difficult to achieve with cloud-only systems.\nPrivacy\nPersonal messages, confidential documents, and sensitive conversations can be processed locally without sending their contents to external inference servers.\nOffline Availability\nTranslation, summarization, and other AI features can remain useful on airplanes, underground trains, and in places without reliable connectivity.\nCost Efficiency\nAt the scale of hundreds of millions of devices, cloud inference costs can become enormous.\nMoving suitable workloads onto hardware users already own can significantly reduce marginal server-side inference costs, even after accounting for model development and delivery infrastructure.\nProduct Integration\nPerhaps most importantly, on-device AI allows intelligence to become a more deeply integrated part of the device itself.\nInstead of treating AI as a remote service that users occasionally invoke, we can build features that are responsive, available, and integrated into everyday workflows.\nAnd from an engineering perspective, there’s something deeply satisfying about solving problems under extreme constraints.\nYou optimize a model, tune its execution, squeeze out unnecessary memory usage, and eventually watch something that once seemed impossible run smoothly on a phone.\nThat’s a special kind of engineering achievement.\nFinal Thoughts On-device AI isn’t just a smaller version of cloud AI.\nIt’s a systems engineering challenge that spans model optimization, runtime performance, memory management, hardware acceleration, deployment infrastructure, and security.\nAnd the most difficult problems often appear only after the model is already working.\nBuilding a smaller model that runs on a phone is impressive.\nBuilding an AI experience that works reliably for millions of people, across different devices, without compromising the rest of their smartphone experience — that’s the real challenge of on-device AI.\n","permalink":"https://blog.jiminl.com/posts/on-device-ai-isnt-just-about-smaller-models-c6997122efb4/","summary":"“On-device AI” sounds simple enough. Take a large language model, shrink it, quantize the weights, and squeeze it into a smartphone. No…","title":"On-Device AI Isn’t Just About “Smaller Models”"},{"content":"Back in 2023, while preparing to introduce large language models across mobile products, I kept hearing an unexpected request. Teams weren’t asking us to build chatbots. Instead, they wanted to replace existing rule-based or machine-learning classifiers with LLMs.\nAt first, this surprised me. Generative AI was attracting attention for entirely new experiences such as fluid conversation, document summarization, content generation, and reasoning. Yet many engineering teams running production systems were interested in something much older and more mundane: classification.\nOnce I listened to their reasons, it made perfect sense. Operating production classifiers was exhausting. Supporting a new language often meant collecting and cleaning a new dataset, while changing the label taxonomy meant revising annotation guidelines, relabeling data, retraining the model, evaluating it, and redeploying it. For global products, that cycle had to be repeated across many languages.\nLLMs seemed to offer a radically simpler interface. Add a new category, and you could change the prompt. Expand to more languages, and the foundation model already understood many of them. Most importantly, the task itself could be defined at runtime rather than encoded into a training pipeline. For teams trapped in repeated data collection and retraining cycles, the idea of building a zero-shot multilingual classifier through prompt engineering felt almost revolutionary.\nBut the dream quickly ran into practical limits. In 2023, LLMs were too slow and too expensive for many high-volume, latency-sensitive classification workloads. More importantly, there was an architectural mismatch: we wanted the system to choose one option from a bounded set, while the model interface was designed to generate tokens.\nLooking back, what we wanted was not necessarily an LLM. We wanted LLM-grade semantic understanding, multilingual capability, runtime task definition, and the speed and determinism of a traditional classifier.\nWe wanted a classifier where the task could be defined at runtime.\nThat is what makes the recent rise of dedicated Decision Models interesting. They are not introducing an entirely new machine-learning problem. They are formalizing an architectural gap that AI engineers have spent the last few years filling with generative models.\nTools such as TypeSafe AI’s Jev are examples of this shift, but the individual product is less important than the broader idea: Decision is becoming a first-class AI primitive.\nWe Frame Too Many Problems as Generation Look inside many modern AI applications and you will find a familiar pattern. The application gathers user input and system state, passes them to an LLM, and asks the model to generate either natural language or structured output such as JSON. The surrounding software then interprets that output and decides what to do next.\nConsider tool selection in an agent. Suppose an agent can use three tools: Search, Calculator, and Calendar. A typical implementation supplies the conversation, tool descriptions, and schemas to an LLM and asks it to produce something like {\u0026quot;tool\u0026quot;: \u0026quot;search\u0026quot;}.\nModern function calling, constrained decoding, and structured-output systems have made this interface much more reliable. Syntax errors are no longer the main problem. The more fundamental question is architectural:\nWhy are we expressing a bounded selection problem through a general-purpose text-generation interface at all?\nWhat the application actually needs may be closer to this:\nSearch: 0.82\nCalculator: 0.11\nCalendar: 0.05\nFallback: 0.02\nSelected action: Search.\nThe core task here is not writing. It is evaluating context and choosing an action from a predefined space. That is a Decision Problem.\nWhether autoregressive token generation happens somewhere inside the implementation is secondary. The important distinction is the contract between software and model: are we asking the AI to produce open-ended content, or are we asking it to evaluate a bounded set of options?\nFor the past several years, generative LLMs have been such capable general-purpose tools that we naturally pushed many different problems through the same abstraction: prompt in, text out. Classification, routing, ranking, tool selection, escalation, verification, and risk assessment were all expressed through generation. That worked surprisingly well, but it also blurred an important distinction.\nIntelligence Does Not Require Generation Many production decisions require real intelligence. A system may need to determine whether a support request belongs to Billing or Technical Support, whether a query can be handled by a local model or must be escalated to a frontier cloud model, which tool an agent should call next, whether a failed action should be retried, or whether generated output is safe to execute automatically.\nKeyword rules are often insufficient for these tasks. They may require understanding long context, subtle intent, policy constraints, ambiguity, and previous actions. In other words, they require semantic intelligence.\nBut needing intelligence does not imply needing free-form text generation. A system can understand a complex situation without expressing that understanding as a stream of natural-language tokens.\nThis is where a different interface becomes useful. Instead of:\nState → Model → Generated Text → Validation → Program\na decision-oriented system can look like:\nState → Model → Typed Decision → Program\nThe output may be a boolean, one item from an enum, a bounded score, a ranking, or a probability distribution over candidate actions. TypeSafe AI summarizes this idea neatly with Jev: “Unstructured state in, typed probabilistic decisions out.”\nThis may look like a small change in output format, but architecturally it changes the boundary between probabilistic AI and deterministic software. The model interprets ambiguous state, and software acts on a typed result.\n“Isn’t This Just a BERT Classifier?” This is the obvious question. Haven’t we been doing classification for years with BERT, RoBERTa, and other encoder models?\nYes. And for many problems, a traditional classifier remains the better engineering choice. If you have a stable task with fixed categories, good labeled data, and predictable traffic, a specialized lightweight classifier will often be faster, cheaper, and easier to validate.\nSuppose your application always classifies incoming requests into Billing, Sales, and Support, and you expect those categories to remain stable for years. A dedicated classifier is probably exactly what you should use.\nThe interesting distinction is not simply classifier versus Decision Model. It is when the action space is defined.\nIn a traditional supervised classifier, the label space is generally defined during training and remains fixed for that deployed model. If the taxonomy changes substantially, the normal workflow is to update the data, retrain, evaluate, and deploy another model.\nA Decision Model moves more of that definition into inference-time context. One request might provide [Billing, Sales, Support]. The next might provide [Refund, Fraud, Account Issue, Other]. Another might ask, “Is this transaction safe to auto-execute under Policy Version 3.2?” with [Yes, No] as the allowed outputs.\nThe action space is no longer only a property of the trained model. It becomes part of the application request.\nA Decision Model moves the action space from training-time model configuration toward inference-time application context.\nThis gives product teams much of the flexibility that made LLM-based classification attractive in the first place, without necessarily paying the full latency and generation overhead of a general-purpose generative model.\nThis Space Did Not Suddenly Appear It would be misleading to claim that Decision Models invented dynamic semantic classification. Engineers have explored this space for years.\nNLI-based zero-shot classification allowed models to evaluate labels described in natural language. Embedding models made it possible to compare queries and candidate actions semantically. Cross-encoders and rerankers provided more precise scoring over candidate sets, while constrained decoding made generative models adhere to predefined structures.\nSo the important development is not a previously impossible algorithm. It is the emergence of Decision as an explicit model interface.\nInstead of treating classification, routing, scoring, and action selection as secondary patterns built on top of other abstractions, systems are increasingly exposing them directly. Jev, OpenAI’s Decisions API, and Liquid AI’s d1 all point in this direction. Their implementations differ, but their timing is revealing: multiple teams are independently treating bounded semantic decisions as something worth exposing directly rather than disguising as generation.\nThe interesting question is not whether “Decision Model” becomes a permanent product category. It is whether Decision becomes a permanent interface in the AI stack.\nReasoning and Decision Are Different Axes A Decision Model does not imply shallow reasoning. Some bounded decisions are extremely difficult.\nImagine asking: “Under our enterprise master services agreement, is this customer eligible for an immediate out-of-warranty hardware replacement?” The final answer may be binary: Yes or No. But reaching it could require interpreting contract language, reviewing support history, checking account entitlements, reconciling exceptions, and applying current policy.\nThe output is bounded, but the reasoning is not necessarily simple.\nReasoning describes the depth of computation. Decision describes the output contract.\nA system may perform substantial reasoning internally while still returning a single typed choice. The complexity of thought does not determine whether the external interface should be an essay or an enum.\nProbabilities as Control Signals Decision-oriented systems become particularly useful when they expose meaningful probability distributions. Probabilities themselves are not new; traditional classifiers have always produced scores or softmax distributions. What matters is calibration and how those probabilities are used by the surrounding system.\nA calibrated decision model enables patterns such as high confidence leading to automatic execution, medium confidence triggering a stronger model or user confirmation, and low confidence escalating to a human. The architecture becomes:\nState → Decision Distribution → Policy Layer → Action\nThis separation is powerful because the model estimates what appears most likely, while the application decides how much confidence is required before taking action. A financial system might require extremely high confidence before automatically moving money, while an internal media-tagging system could tolerate a much lower threshold.\nThe model does not need to encode every business risk preference. The policy layer can.\nOf course, calibration must be validated empirically. A model returning 0.90 does not automatically mean that it will be correct 90 percent of the time in production. Thresholds remain a systems-engineering decision.\nAgents Make the Decision Layer More Important Agentic systems make this abstraction particularly relevant because an autonomous agent can make dozens of intermediate decisions during a single task. It may need to determine what information to retrieve, which tool to use, which sub-agent should handle a step, whether the previous action succeeded, whether to retry, whether user approval is needed, and whether the objective is complete.\nAs agents become more capable, the number of intermediate control decisions grows much faster than the amount of final text they produce. Invoking a frontier reasoning model for every branch can therefore become unnecessarily expensive and slow.\nA better architecture can distribute intelligence across different layers. A powerful model can construct a plan, smaller decision-oriented models can handle bounded routing, verification, and control decisions, and deterministic software can execute validated actions.\nSuppose an orchestrator receives the instruction: “Investigate the user’s disputed charge, issue a refund if it is a verifiable duplicate, and notify them of the result.” The high-level reasoning may require a powerful model, but many downstream steps are bounded decisions: Is this actually a duplicate transaction? Does the amount fall within automatic refund limits? Has the account passed identity verification? Which notification workflow should run?\nA dedicated decision layer can handle these tasks far more efficiently than repeatedly invoking the largest available model. This is not about removing intelligence. It is about allocating the right kind of intelligence to the right part of the system.\nThe AI Stack Is Starting to Unbundle The rise of Decision Models is not an argument against LLMs. Frontier models remain essential for open-ended reasoning, synthesis, code generation, ambiguity resolution, and creative work.\nThe mistake is assuming that one model interface should handle every computational role.\nA more mature AI stack asks a different question:\nWhat output contract does this sub-problem require?\nIf you need to create new content, use Generation. If you need to work through complex multi-step ambiguity, use Reasoning. If you need to find relevant information, use Retrieval. If you need to choose among bounded actions, use Decision. If you need to carry out the selected action reliably, use Deterministic Software.\nReal systems will combine all of them. The important shift is that we no longer need to assume every intelligent task should begin with a prompt and end with a generated string.\nThe model should match the contract.\nBeyond the Token Stream Whether Jev, OpenAI’s Decisions API, d1, or some future system ultimately defines this category is impossible to know. The names will change, and the implementations will evolve.\nBut the architectural question will remain:\nDoes every AI problem really belong inside a text-generation interface?\nGenerative LLMs gave us an extraordinary general-purpose tool. It was natural to spend several years testing how many problems could be solved with it. That experimentation revealed both the power of the abstraction and its limits.\nThe next phase of AI systems engineering may be less about finding one model that does everything and more about separating different computational responsibilities.\nPerhaps what the production AI stack has been missing was not another hundred billion parameters, but a much simpler verb:\nNot Generate. Decide.\n","permalink":"https://blog.jiminl.com/posts/what-jev-reveals-about-the-missing-decision-layer-in-the-ai-stack-57a26000a8ae/","summary":"Back in 2023, while preparing to introduce large language models across mobile products, I kept hearing an unexpected request. Teams…","title":"What Jev Reveals About the Missing Decision Layer in the AI Stack"},{"content":"After humming like a small jet engine all night, your GPU fans finally quiet down. A glorious line appears in your terminal: Training Finished.\nNow comes the moment of truth: saving the model you just spent days babysitting.\nFor many developers, this once felt like a routine step. If you were working in PyTorch, you saved a .pt or .pth file. If you were using TensorFlow, you exported a SavedModel directory and called it a day.\nThen the destinations multiplied. Models needed to move from training clusters to production servers, developer MacBooks, smartphones, and embedded devices. Saving a model became part of deciding how to distribute and run it.\nToday, the landscape includes .pt, .safetensors, .onnx, .tflite, and .gguf. They may look like different answers to the same question, but they serve different purposes:\nPreserving training state so an interrupted run can resume. Distributing tensors without pickle-style code execution. Representing a computational graph for compatible inference runtimes. Packaging models for mobile and embedded deployment. Bundling LLM weights and metadata for convenient local inference. You do not need to memorize every file extension. Start with one question:\nWhere does this model need to go next?\n1. Resuming Training: PyTorch Checkpoints (.pt, .pth) If you work in PyTorch, this probably looks familiar:\ntorch.save(model.state_dict(), \u0026#34;model.pt\u0026#34;) This saves the model’s parameters and persistent buffers. But saving weights is not the same as saving enough state to resume training.\nFor a long training run, you will usually want a broader checkpoint:\ntorch.save({ \u0026#34;model\u0026#34;: model.state_dict(), \u0026#34;optimizer\u0026#34;: optimizer.state_dict(), \u0026#34;scheduler\u0026#34;: scheduler.state_dict(), \u0026#34;epoch\u0026#34;: epoch, \u0026#34;scaler\u0026#34;: scaler.state_dict(), }, \u0026#34;checkpoint.pt\u0026#34;) Alongside the model, this captures optimizer state, the learning rate schedule, training progress, and the gradient scaler if your training setup uses one. Depending on the pipeline, reproducible resumption may also require random number generator and data sampling state.\nThe checkpoint’s job is to preserve the information your training loop needs to continue.\nFlexibility and Pickle The extensions .pt and .pth are naming conventions commonly used for files saved with torch.save().\nPyTorch serialization uses Python’s pickle machinery for objects and metadata, with tensor storage handled separately. This makes checkpoints flexible, but unrestricted pickle loading carries a security risk: a malicious file can execute code with the permissions of the loading process.\nSince PyTorch 2.6, torch.load() defaults to weights_only=True when no custom pickle module is supplied, restricting deserialization and reducing that risk. For large checkpoints, mmap=True allows tensor data to load on demand rather than reading all tensor storage into RAM upfront.\nFor comparison, in the JAX ecosystem, Orbax addresses a similar need, including saving and restoring distributed training state across accelerators.\nUse PyTorch checkpoints when you need to preserve and resume a PyTorch training run.\n2. Distributing Weights: Safetensors (.safetensors) Once training is complete, optimizer buffers and learning rate schedules are usually unnecessary for inference. You can distribute the trained tensors separately from the training checkpoint.\nSafetensors, originally developed by Hugging Face, is designed for this purpose. It stores tensors without relying on executable Python object reconstruction.\nSimple Storage, Efficient Access A Safetensors file contains a JSON header describing each tensor’s name, data type, shape, and location, followed by the raw tensor data.\nThis layout avoids pickle-style code execution and supports memory-mapped access. A loader can access the tensors or slices it needs without first reading the entire file into RAM, which can reduce loading overhead for large models.\nFrom Model Hubs to GPU Serving Safetensors is not limited to model distribution on Hugging Face. It has also become a common weight format in GPU-based LLM serving stacks.\nServing engines such as vLLM can load Safetensors weights directly and prefer them when available, while Hugging Face TGI uses Safetensors for efficient weight loading and multi-GPU tensor parallelism. TensorRT-LLM also supports Hugging Face Safetensors checkpoints as an input format for optimized GPU inference.\nIn other words, the same Safetensors files used to distribute a model can often become the starting point for large-scale GPU serving.\nWhat Comes Alongside the Weights Safetensors stores tensors and optional metadata, but it does not define how a model computes its outputs. Architecture, tokenizer, and generation settings are typically provided separately.\nA model repository might include:\nmodel.safetensors: trained weight tensors. config.json: model architecture and configuration. tokenizer.json: tokenizer vocabulary and rules. tokenizer_config.json: tokenizer settings and special-token configuration. generation_config.json: default generation settings. The exact files vary by model and tooling. The loader still needs a compatible implementation of the model architecture to use the weights.\nThink of Safetensors as a container for the building materials. The model implementation provides the instructions for assembling them.\nUse Safetensors when you want to distribute trained weights efficiently or load them into modern GPU inference stacks without pickle-style deserialization.\n3. Moving Computational Graphs: ONNX (.onnx) Safetensors stores tensors. ONNX, short for Open Neural Network Exchange, also describes the operations that use them.\nConsider a vision block that applies a convolution, batch normalization, and then a ReLU activation. A weight file stores the relevant tensors. An ONNX model represents the operations, their connections, and their parameters.\nIt can include weights in the model file or reference external data files for large tensors.\nThe result is a framework-independent representation of a model’s computational graph and weights.\nWhy the Graph Matters An exported graph allows a compatible runtime to execute the model without the original Python model implementation.\nRuntimes such as ONNX Runtime can analyze that graph, simplify operations, fuse supported patterns, and use hardware-specific execution backends. The available optimizations depend on the model and the runtime.\nExporting is not always effortless. Custom operations, dynamic behavior, and operator-version differences can require additional work. The destination runtime must support the operations in the exported model.\nUse ONNX when you need a portable graph representation for deployment through compatible inference runtimes.\n4. Deploying to the Edge: LiteRT (.tflite) Now move from the server to a smartphone, an automotive system, or an embedded device.\nThe constraints change. Memory competes with other applications. Power consumption affects battery life and heat. Available accelerators differ from device to device.\nLiteRT, formerly TensorFlow Lite, is Google’s framework for on-device inference, while .tflite is the compact model representation commonly consumed by its runtime. It packages a computational graph and weights for deployment on mobile and embedded devices.\nBuilt for On-Device Inference The .tflite format is designed for efficient loading. The LiteRT runtime handles execution, reuses memory where possible, and can run supported operations on a device's GPU or NPU.\nQuantization can further reduce model size and, on compatible hardware, improve inference efficiency. Actual performance depends on the model, its operations, and the available hardware.\nSupported models trained in PyTorch, JAX, or TensorFlow can be converted to .tflite for deployment with LiteRT.\nThis illustrates a broader principle: the framework you train in does not have to be the runtime you deploy to.\nUse .tflite when targeting mobile or embedded devices through the LiteRT ecosystem.\n5. Running LLMs Locally: GGUF (.gguf) For local LLM inference on PCs and Macs, GGUF is a common format. You will often encounter it in tools such as llama.cpp, Ollama, and LM Studio.\nIts appeal combines convenient packaging with extensive support for quantized weights in the surrounding ecosystem.\nConvenient Packaging A typical text-model GGUF file can bundle:\nModel weights. Architecture metadata, such as layer counts and hidden dimensions. Tokenizer vocabulary and related information. A chat template, when provided. Information needed to interpret quantized tensors. For supported models, this often lets you download one file and load it in a compatible application. Some models require additional files, and large models may be split across several files, but the packaging still makes local distribution convenient.\nThe runtime must understand the model’s architecture. Metadata describes the model; the runtime implements its computation.\nSmaller Models Through Quantization Quantization reduces model size by storing weights at lower precision.\nFor example, an 8-billion-parameter model needs roughly 16 GB for its FP16 weights. A 4-bit quantized version can shrink those weights to around 5 GB. Inference still requires additional memory for the KV cache and runtime buffers.\nLabels such as Q8_0, Q5_K_M, and Q4_K_M describe different quantization options. Lower bit widths generally mean smaller files and lower memory requirements, with a possible loss in quality. GGUF can also store floating-point weights; quantization is common, not mandatory.\nThe goal is to choose a version that fits your hardware while preserving enough quality for your use case.\nFor a deeper look at quantization formats and labels, see my guide: Untangling the LLM Quantization Alphabet Soup: Q4_K_M, W4A16, GPTQ, AWQ, and Beyond.\nUse GGUF when distributing supported models for local inference through tools such as llama.cpp.\n6. The Lifecycle of a Model Before looking at how these formats fit into a model’s lifecycle, here is the simplest way to remember them:\n.pt preserves training state. Safetensors moves tensors. ONNX moves computational graphs. .tflite takes models to the edge. GGUF packages LLMs for local inference. These are not competing answers to the same problem. They solve different problems at different stages of a model’s journey.\nDuring training, checkpoints preserve the state needed to continue your work. Once the model is ready, its destination determines the next step:\nFor sharing weights, publish Safetensors files with the accompanying configuration and tokenizer files. For deployment through ONNX-compatible runtimes, export the restored model to ONNX. For mobile or edge deployment, convert a supported model to .tflite, optionally applying quantization to reduce size and improve efficiency on compatible hardware. For local LLM inference, package a supported model as GGUF, often quantizing the weights to fit the memory available on personal hardware. These are possible paths, not a mandatory sequence. A model can move from a restored training checkpoint to a deployment format without first being saved as Safetensors. Some serving systems can also load distributed weights directly into their own model implementations.\nConversion involves more than changing a file extension. Graph formats require the model’s computation as well as its weights. GGUF conversion requires a supported architecture and the appropriate inference metadata, typically including model configuration and tokenizer information.\nThe path depends on the model, the conversion tools, and where you want to run it.\n7. Formats vs. Runtimes One more thing to keep in mind: don’t confuse a file format with an execution runtime.\nONNX represents a computational graph and weights; ONNX Runtime optimizes and executes supported graphs through its execution backends. .tflite stores a model representation; LiteRT manages its execution and supported hardware acceleration. GGUF stores tensors and metadata; llama.cpp implements supported architectures and manages execution, including CPU/GPU placement and KV cache allocation. A file extension alone does not guarantee faster inference. Performance depends on how well the runtime and hardware support the model’s operations and numerical formats.\nThe format determines how the model is represented. The runtime manages how it executes. The hardware performs the computation.\nKeeping these roles clear makes tool selection and performance debugging much easier.\n8. Looking Beyond File Extensions Saving a model can look like the final line of a training script. In practice, it is often the beginning of the model’s next journey.\nA checkpoint helps training continue. A tensor container helps distribute weights and feed modern GPU serving stacks. A graph format enables deployment through compatible runtimes. An edge format brings models to mobile and embedded hardware. A local inference package makes LLMs easier to run on personal hardware.\nEach serves a purpose, and one model may use several during its lifetime.\nThe useful question is:\nWhere does this model need to go next?\nOnce you know the destination, the choice becomes much clearer.\n","permalink":"https://blog.jiminl.com/posts/a-practical-guide-to-ai-model-formats-pt-safetensors-onnx-tflite-and-gguf-4f14e6e6d455/","summary":"After humming like a small jet engine all night, your GPU fans finally quiet down. A glorious line appears in your terminal: Training…","title":"A Practical Guide to AI Model Formats: .pt, Safetensors, ONNX, TFLite, and GGUF"},{"content":"Lately, more developers and tinkerers than ever are setting up their own local LLM environments on desktop rigs and home servers.\nPoking around Hugging Face, Reddit’s r/LocalLLaMA, or open-source AI discords, the first weight class that usually catches your eye is around 8B — an 8-billion-parameter model. Models in this range deliver impressive coding capabilities and sharp English reasoning without requiring the small datacenter setup demanded by a 70B behemoth.\nNaturally, anyone with a passing familiarity with computer architecture and quantization breaks out the napkin math:\n“If an 8B model is quantized down to 4 bits, each parameter takes up exactly 0.5 bytes. 8 billion parameters times 0.5 bytes equals exactly 4GB. That means that dusty 4GB card in my closet or an entry-level budget GPU should handle it just fine, right?”\nPulling out your phone’s calculator and multiplying the two numbers yields a mathematically airtight result. It feels like an open-and-shut case. But the moment you spin up your terminal with high hopes and hit Enter on your run command, your screen delivers a cold, red splash of text instead of fluent prose:\ntorch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate ... You put a 4GB model onto a 4GB card — why did the memory blow up? Where did all those missing gigabytes vanish to?\nLet’s unpack the hidden overhead of real-world LLM inference runtimes. We will skip the dry academic formulas and take an under-the-hood look at what is actually happening across your GPU’s memory stages.\nBy the end of this breakdown, you will be able to calculate the VRAM footprint required to run any model you have your eye on.\n1. The 4-Bit Illusion: Model Weights Are Heavier Than They Look The first misconception to clear up is the actual size of the model weight file on disk. Many assume that a “4-bit model” means every single number inside the architecture is cleanly packed into a 4-bit (0.5-byte) integer, resulting in a neat 4.0GB file.\nIn practice, download a real quantized file — whether in .gguf, .safetensors, or an EXL2 format—and you will notice the file size sits somewhere between 4.6GB and 5.5GB. Two engineering realities explain this discrepancy.\nWhy It’s 4.2 to 4.5 bpw Instead of Flat 4.0 LLMs are natively trained using high-precision representations like FP16 (16-bit floating point, 2 bytes), BF16, or FP32 (4 bytes). Forcing those smooth, high-precision values into a rigid 4-bit integer grid — which offers only 16 possible values — inevitably triggers severe quantization noise and degrades output quality. Pushed too far, the model begins to hallucinate incoherently or loses track of basic sentence syntax.\nModern quantization frameworks like AWQ (Activation-aware Weight Quantization, Lin et al., 2023), GPTQ (Frantar et al., 2022), and llama.cpp’s custom GGUF quantization schemes bypass this problem using grouped (or block-level) quantization.\nRather than compressing billions of parameters into a single global scale, the engine slices weight matrices into smaller groups of 32, 64, or 128 elements. Each group receives its own reconstruction metadata: a floating-point scale value (capturing the group’s dynamic range) and a zero-point offset, typically stored in FP16.\nBecause this metadata accompanies every single group, it inflates the effective footprint per parameter beyond pure 4-bit storage. In practice, an average “4-bit” model consumes roughly 4.2 to 4.5 bpw (bits per weight). You are not just packing the raw numbers; you are packing the decoding key needed to restore them with minimal precision loss.\nThe Untouchable Layers That Guard Model Intelligence An even bigger contributor is that real-world quantization pipelines deliberately leave certain sensitive layers alone. Certain modules inside a Transformer architecture degrade catastrophic amounts of reasoning capability if forced down to 4 bits.\nPrime offenders include:\nThe Token Embedding Layer, which converts token IDs into high-dimensional vectors. The final LM Head (Output Layer), which generates logits across the full vocabulary to predict the next token. Normalization layers (like LayerNorm or RMSNorm), which sit between attention blocks to keep activations bounded and stable. To preserve the model’s actual IQ, modern quantization tools keep these sensitive layers intact at full 16-bit precision (FP16 or BF16, 2 bytes per value). With modern architectures expanding vocabulary sizes from 32,000 up to 128,000 tokens or more, the embedding table and LM head alone can consume several hundred megabytes up to roughly 1GB.\nAdd it all up, and an 8B 4-bit model file generally clocks in around 4.8GB to 5.2GB. Before you even run your first prompt, the model weights alone have already blown past a 4GB VRAM ceiling.\n2. The Context Trap: The Growing Weight of the KV Cache Suppose you discover your weights exceed 4GB and decide to upgrade to a 6GB card instead. The weights load onto the board without crashing. You fire off a prompt, ready to watch tokens generate on screen.\nAs soon as generation starts, a second major memory consumer kicks in: the KV Cache (Key-Value Cache).\nThe Model’s Working Memory for Ongoing Dialogue Autoregressive models generate text token-by-token, predicting each subsequent word based on all preceding ones. If the engine had to recalculate attention from the initial prompt all the way through the newest token at every single step, generation times would scale quadratically. A long conversation would quickly slow down to minutes per token.\nThe KV Cache eliminates that bottleneck. The engine caches the intermediate Key and Value projection tensors computed during prior tokens directly inside VRAM. It functions like working memory: as long as prior tokens remain cached, the model only needs to compute attention for the newest arriving token against the historical keys and values.\nThe catch is that this short-term working memory grows linearly with the length of your conversation — your context window.\nEven Modern Architectures Carry Real Weight Recent architectures are far more memory-efficient than older Transformer models thanks to technologies like Grouped-Query Attention (GQA).\nUnder standard Multi-Head Attention (MHA), every attention query head gets its own dedicated Key and Value heads. GQA allows multiple query heads to share a single Key-Value head pair. This slashes KV cache memory consumption significantly compared to vanilla Transformers. Even with GQA in place, however, the raw physical memory requirement remains substantial.\nFor a typical 8B architecture with 32 layers, 8 KV heads, a head dimension of 128, running standard 16-bit precision (FP16/BF16 at 2 bytes per element):\nMemory per single token: roughly 131 KB 4,000 tokens (4K context, typical short exchange): approximately 0.52 GB 8,000 tokens (8K context, summarizing an article or code snippet): approximately 1.05 GB 32,000 tokens (32K context, long document analysis): approximately 4.2 GB 128,000 tokens (full native window for multi-document reasoning): roughly 16.8 GB At 8,000 tokens — hardly an extreme prompt when pasting in documentation or multiple files — you have already dedicated over 1GB of VRAM strictly to tracking the conversation history.\nIf you are exploring Agentic workflows where models use browser tools, inspect system error logs, and manage persistent task loops, context lengths can easily swell into tens of thousands of tokens. Once context scales, the KV cache quickly overtakes the size of the model weights themselves.\n3. The Worktable: Activation Tensors and Runtime Buffers You have loaded the weights and budgeted memory for the conversation history. The GPU’s Tensor Cores are ready to churn through matrix multiplications. Yet there is still another transient category of memory consumption at work: Activation Memory and execution buffers.\nThink of running an LLM like working in a carpenter’s workshop. Even if you have the finest tools and materials, if every square inch of your room is stacked to the ceiling with finished furniture and lumber, you cannot swing a hammer or guide a saw. You need open space on a workbench to manipulate materials.\nIn deep learning inference, that open workbench space is your activation buffer.\nStored in 4-Bit, Calculated in 16-Bit (W4A16) Compressing weights to 4 bits is primarily a packing strategy to fit the model within VRAM storage constraints and maximize memory bandwidth. Most mainstream 4-bit quantization formats are W4A16 — weights are stored at 4 bits (Weight 4-bit), but computational activations are processed in 16-bit floating point (Activation 16-bit).\nWhen the GPU executes a matrix-vector or matrix-matrix multiplication (GEMV/GEMM), it pulls those 4-bit weights out of memory and dequantizes them on the fly into 16-bit representations just prior to the math operation. As the signal propagates through tens of transformer blocks, the intermediate activations — layer normalization outputs, softmax distributions, and intermediate projection values — require temporary memory buffers.\nIntermediate Compute Buffers: Layer-by-layer forward passes, softmax evaluations, and attention computations generally require a dynamic workspace spanning a few hundred megabytes up to around 1GB of VRAM. Batch Size Scaling: If you run multiple concurrent user prompts on a self-hosted server, activation memory scales with batch size. Even in a single-user setup (batch size = 1), temporary allocation spikes occur during prompt ingestion (the prefill phase) when thousands of prompt tokens are evaluated in parallel. 4. Platform Taxes: The OS and Runtime Baseline Finally, there are the non-negotiable overheads claimed by your operating system, display server, and machine learning framework.\nThe CUDA Context Baseline Whether you run PyTorch, vLLM, TensorRT-LLM, or C++ backends like llama.cpp, targeting an NVIDIA GPU requires initializing the CUDA driver runtime.\nCreating a CUDA context — mapping virtual GPU memory addresses, establishing driver communication channels, and spinning up framework memory pools — immediately claims roughly 300MB to 800MB of VRAM before a single parameter is touched. Running a blank Python script that does nothing more than call torch.cuda.init() will show an immediate drop in available memory.\nDisplay Server and GUI Overhead If your card is plugged into a monitor running a desktop operating system rather than sitting as a headless Linux server node, your everyday OS environment takes a cut.\nOn Windows, the Desktop Window Manager (DWM), GPU-accelerated web browsers, and background apps typically tie up anywhere from 500MB to 1.5GB of video memory. On macOS, unified memory pools dynamically split allocations, but desktop buffers still claim their share. As a result, the usable memory available for your LLM is almost always lower than the capacity stamped on your GPU’s box.\nThe Itemized Receipt: Real-World VRAM Requirements for 8B (4-Bit) Let’s assemble these line items into a realistic VRAM bill for hosting a typical 8B 4-bit model with a standard 4K to 8K context window:\nModel Weights (Quantized 4-bit): ~4.8 GB — 5.2 GB\n(Includes core 4-bit quantized weights, group-level scale/zero-point metadata, and unquantized FP16 embedding and output heads.) KV Cache (4K to 8K Context): ~0.5 GB — 1.1 GB\n(Assuming standard 16-bit precision under GQA architecture.) Activation \u0026amp; Intermediate Runtime Buffers: ~0.3 GB — 0.8 GB\n(Workspace for on-the-fly dequantization, attention buffers, and prompt prefill spikes.) CUDA Driver Context \u0026amp; Framework Overhead: ~0.5 GB — 0.8 GB\n(Baseline runtime allocations, communication pipelines, and driver context initialization.) Total Usable VRAM Required: ~6.1 GB — 7.9 GB\n(The realistic safe zone to prevent out-of-memory crashes on dedicated hardware.) Reviewing these line items makes it obvious why running an 8B model on a 4GB graphics card triggers an immediate out-of-memory crash. You realistically need roughly 7GB to 8GB of headroom to give the model room to breathe.\nPush that context window out to 16K or 32K tokens, and the KV cache expansion will quickly drive your memory footprint past 10GB.\nFinal Thoughts Spec sheets and introductory tutorials often lean on simplified theoretical equations. Multiplying parameter counts by bit depths provides a useful back-of-the-envelope baseline, but real production inference depends on dynamic variables: quantization metadata, scratchpad buffers, evolving context states, and OS overhead.\nThe next time a colleague or forum user asks why their 4GB card cannot run an 8B 4-bit model, show them this memory breakdown. It serves as a handy guide to the unseen engineering layers that keep our local AI systems running smoothly.\n","permalink":"https://blog.jiminl.com/posts/can-you-really-run-an-8b-4-bit-llm-on-a-4gb-gpu-spoiler-no-cc60a03aae09/","summary":"Lately, more developers and tinkerers than ever are setting up their own local LLM environments on desktop rigs and home servers.","title":"Can You Really Run an 8B 4-Bit LLM on a 4GB GPU? (Spoiler: No)"},{"content":"“Use full fine-tuning for maximum performance. Use LoRA when you want cheaper training.”\nThat advice is not wrong.\nBut it is far too simple for production AI.\nIn practice, choosing between full fine-tuning and LoRA is not just a training decision. It is an engineering decision across model quality, deployment, serving, and iteration speed.\nA few lessons from production:\n- If maximizing task quality matters more than training and operational cost, full fine-tuning usually gives you the largest optimization space.\n- But full fine-tuning can degrade capabilities outside the target task. If you still need the foundation model’s broader abilities, catastrophic forgetting and behavioral regressions become real concerns.\nLoRA does not eliminate regressions, but it keeps the base model intact, making specialization easier to isolate, swap, and reverse.\n- One of LoRA’s biggest advantages is serving multiple specialized tasks from a single base model.\nInstead of deploying a separate full model for every task, you can load or switch task-specific adapters depending on the request.\nThis matters especially when:\n1. You cannot afford to run multiple large models, such as on-device.\n2. You want to consolidate many specialized workloads onto a smaller serving fleet in the cloud.\nLoRA is not just a cheaper way to train a model.\nIt can change how specialized models are deployed and operated.\n- The runtime overhead of switching or loading LoRA adapters can be modest compared with maintaining separate copies of the full model.\nAnd if you eventually want a single standalone model, you can merge the adapter into the base model after training.\nOf course, once you merge it, you give up the flexibility of multi-adapter serving.\n- LoRA is also useful as a surgical fix.\nIf the foundation model works well overall but repeatedly fails on a specific pattern, you may not need to retrain the entire model.\nYou can specialize that behavior without creating another full copy of the model or permanently modifying the shared base.\n- Finally, consider iteration speed.\nHow often will you train, deploy, evaluate, discover problems, and repeat?\nIf your development cycle cannot tolerate full fine-tuning every time, that should influence the architecture from the beginning.\nFull fine-tuning vs. LoRA is not simply:\n“better performance vs. cheaper training.”\nIt is a trade-off across model quality, capability preservation, training cost, iteration speed, deployment flexibility, memory footprint, and serving cost.\nThat is why, in production AI, fine-tuning strategy is ultimately a systems engineering decision.\n","permalink":"https://blog.jiminl.com/posts/full-fine-tuning-vs-lora-a-production-ai-perspective-8237fbfc35fb/","summary":"“Use full fine-tuning for maximum performance. Use LoRA when you want cheaper training.”","title":"Full Fine-Tuning vs. LoRA: A Production AI Perspective"},{"content":"Browse Hugging Face or GitHub for five minutes, and you will run headfirst into a barrage of cryptic acronyms. You just wanted to spin up the latest open-source language model on your laptop or home lab server, but the download button is gatekept by a wall of hieroglyphs:\nQ4_K_M, W4A16, GPTQ, AWQ, PTQ, QAT...\nYour brain naturally starts spinning: “If W4A16 means 4-bit quantization, how is that different from Q4_K_M or AWQ? Which one of these three is the best algorithm?”\nLet’s clear up the confusion right out of the gate: W4A16, AWQ, and Q4_K_M are not competing technologies fighting for the same crown. The reason this vocabulary feels so intimidating is not that the math is impossible to grasp, but because concepts from completely different levels of abstraction are routinely crammed into the same sentence.\nYou can untangle this knot by breaking the problem down into four distinct questions:\nWhen are we quantizing? (Timing: PTQ vs. QAT) What are we compressing, and to how many bits? (Precision Target: W4A16, W8A8) How do we minimize error and accuracy loss? (Optimization Algorithm: GPTQ, AWQ, SmoothQuant) How is it packaged, and what runtime executes it? (Container / Format / Runtime: GGUF, Q4_K_M, EXL2, llama.cpp) Let’s unpack each layer step by step.\nNote: This post is not an intro guide to the raw arithmetic of quantization itself. It is a roadmap to show how all these industry terms fit together.\n1. Why Squeeze a Perfectly Good Model in the First Place? Large language models are enormous memory hogs. Even a “compact” 7B or 8B model uses 16-bit floating point (FP16 or BF16) as its native format. Because FP16 uses 2 bytes per parameter, just fitting the static weights into memory requires:\n7 billion parameters × 2 bytes = ~14 GB\nAnd that is just to get the model through the door. Once inference kicks off, the KV cache expands dynamically to remember conversation context, while activation buffers fill up with intermediate layer computations. If you are running an everyday desktop GPU with 8 GB to 12 GB of VRAM, loading that native 7B model will crash your driver with an instant Out-Of-Memory (OOM) error before generating a single token.\nWhat happens if we crush those weights down to 4 bits (0.5 bytes)? The theoretical footprint for the raw weights plunges to 7 billion × 0.5 bytes = roughly 3.5 GB.\nIn practice, the final file is never mathematically 3.5 GB on the dot. Squeezing continuous floating-point numbers into 4-bit containers (which only provide 16 distinct integer buckets from 0 to 15) requires extra metadata like scaling factors and zero-points to adjust the bucket boundaries. Even with that overhead, you are still slashing the model’s footprint by 70% to 75%.\nThe payoff goes way beyond saving VRAM. LLM inference during the token generation phase is fundamentally memory-bandwidth bound, not compute-bound. The hardware spends far more time waiting to pull weights out of VRAM or system DRAM than it does running matrix math on its compute cores. Slashing the total data volume unblocks memory bandwidth, dramatically boosting tokens-per-second throughput. On CPU-only servers, Apple Silicon Macs with unified memory, and mobile hardware, the performance leap feels like night and day.\nEvery quantization strategy boils down to a single engineering challenge:\n“How far can we strip down the bit precision without destroying the model’s intelligence, reasoning, and coherence?”\n2. When Do We Quantize? PTQ vs. QAT When architecting a quantization pipeline, the first fork in the road is deciding at what stage of the model lifecycle the compression happens.\nPTQ (Post-Training Quantization): “Shaping the Baked Loaf” PTQ takes an already fully trained FP16 or BF16 checkpoint and converts it down to low-bit integers (INT8, INT4, etc.) after the fact.\n[Pre-trained FP16/BF16 Checkpoint] ➡️ [Pass Calibration Data] ➡️ [Quantization Optimization] ➡️ [Export INT4/INT8 Model]\nAlmost every GGUF, GPTQ, and AWQ checkpoint you download from Hugging Face is built using PTQ. Instead of burning hundreds of thousands of dollars in compute to retrain a massive model from scratch, an engineer can run PTQ on a single workstation or cloud GPU instance in anywhere from a few minutes to a couple of hours.\nQAT (Quantization-Aware Training): “Training on a Strict Diet” QAT integrates quantization simulations directly into the training or fine-tuning process.\nThe true weights are maintained in higher precision (FP32 or FP16), but “fake quantization” operations are injected into the forward pass. This forces the model to experience the rounding noise and precision loss of 4-bit representation during training. During backpropagation, the gradients update the high-precision weights specifically to adapt to and cancel out those quantization errors.\n[High-Precision Weights] ➡️ [Fake Quantization] ➡️ [Forward Pass with Loss] ➡️ [Backward Pass] ➡️ [Update Quant-Resilient Weights]\nWhen pushing down to aggressively low bit-widths (like 2-bit or 3-bit regimes), standard PTQ often hits a wall where output quality degrades sharply, making QAT a valuable way to recover accuracy. However, running QAT on massive modern LLMs demands enormous GPU clusters and delicate training stability tuning. In production, standard practice is to push modern PTQ techniques as far as possible first, reserving QAT for scenarios where PTQ quality drops below acceptable thresholds.\nModern PTQ algorithms preserve remarkable reasoning quality at 4 bits, so QAT is not automatically the default or superior choice for every deployment.\n3. The Precision Spec Sheet: What Does W4A16 Actually Mean? Terms like W4A16 and W8A8 are shorthand notations for numeric precision targets:\nW (Weight): The bit-width used for static model parameters stored on disk. A (Activation): The bit-width used for dynamic intermediate tensors passed between layers as tokens are processed. Breaking down the typical spectrum:\nW16A16: Full uncompressed baseline (16-bit weights, 16-bit activations). W8A16: Weights compressed to 8-bit integers while keeping activations in 16-bit float. Cuts memory roughly in half with practically zero perceptible accuracy loss. W4A16: Weights compressed to 4-bit, activations kept at 16-bit. This is the dominant standard for local inference engines and single-GPU hosting. W8A8: Both weights and activations quantized to 8-bit, enabling fast INT8-INT8 matrix multiplication kernels for massive throughput gains on enterprise data center GPUs. W4A8: An aggressive profile aiming for both maximum memory compression and accelerated low-precision compute kernels. Here is the key takeaway: Activations are not static bytes baked into your model weights file. They are dynamic tensors generated on the fly inside attention mechanisms and feed-forward layers based on the user’s input prompt.\nTherefore, W4A16 is not a file container format. It is a computational and precision specification indicating that the model holds 4-bit weights and processes 16-bit activations at inference time.\nLooking at the label “W4A16” alone tells you nothing about which mathematical algorithm produced those 4-bit weights. A model optimized via GPTQ with 4-bit weights and 16-bit activations is W4A16; a model optimized via AWQ with the exact same bit allocations is also W4A16.\n4. Mitigating Quantization Error: GPTQ vs. AWQ If you take a floating-point tensor and naively round every number to the nearest 4-bit integer — an approach known as Round-to-Nearest (RTN) — smaller models like 7B or 13B degrade immediately into repetitive nonsense. To prevent that collapse, researchers developed intelligent PTQ algorithms that actively compensate for rounding errors. The two standout approaches are GPTQ and AWQ.\nFair warning: The mechanics here get technical. If you are just looking for the high-level picture, you can simply remember that GPTQ and AWQ are two different mathematical strategies for packing high-precision weights into tiny footprints without breaking the model’s brain.\nGPTQ: Error Compensation via Second-Order Calculus Introduced by Frantar et al. in 2022 (GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers), GPTQ adapts the classic 1990s Optimal Brain Surgeon (OBS) framework to modern multi-billion-parameter architectures.\nThe core intuition: when you round a specific weight down to a coarse 4-bit value, you introduce an error. Rather than ignoring that error, GPTQ adjusts the remaining unquantized weights in that row to mathematically cancel out the deviation, keeping the layer’s overall output as close to original as possible.\nUnder the hood, the pipeline works as follows:\nA small calibration dataset (typically 128 to 256 sample sequences) passes through the model. The algorithm tracks activation outputs per layer to approximate second-order derivative information — specifically, the inverse Hessian matrix. Using Cholesky decomposition of this matrix, it quantizes weights column by column, continuously diffusing and compensating the residual rounding error across the remaining unquantized weights. Think of it like laying patio pavers: if one stone settles slightly crooked, you subtly adjust the bedding sand beneath the surrounding stones so the finished patio remains flat and level.\nAWQ: Protecting the Elite 1% Published by Lin et al. in 2023 (AWQ: Activation-aware Weight Quantization), AWQ tackles the problem from a fresh perspective.\nIts central thesis: not all weights in a neural network are equally important. In fact, a tiny fraction — less than 1% of the total channels — protects almost all of the model’s reasoning capacity and output quality.\nHow do we pinpoint that critical 1%? The AWQ researchers discovered that the raw magnitude of a weight is not what matters most. What matters is the magnitude of the activations multiplying against that weight.\nIf a weight is small (say, 0.1) but gets multiplied by a massive activation spike of 100, its contribution to the final layer output is 10. Conversely, if a weight is relatively large (1.0) but multiplies against an activation of 0.01, its output impact is negligible (0.01).\nAWQ feeds calibration text through the network to observe activation distributions across channels. Once it identifies the salient top 1% weight channels, it applies intelligent per-channel scaling. Instead of keeping those critical channels in FP16 (which would complicate memory layouts and slow down matrix kernels), it mathematically rescales the weights and activations in tandem. This contracts the dynamic range of those vital channels, shielding them from severe truncation when projected onto the 4-bit quantization grid.\nBecause AWQ focuses on activation distribution shapes rather than aggressively over-optimizing specific weight values to a narrow calibration set, it exhibits less risk of calibration overfitting. It retains strong generalization across diverse domains like code generation and math, making it a premier 4-bit standard across modern high-throughput serving engines like vLLM and SGLang.\n5. What Q4_K_M and GGUF Actually Mean: Packaging and Block Quantization Now let’s turn to the local LLM community standard: llama.cpp and the GGUF ecosystem. When you see a file tagged Q4_K_M, what is actually going on under the hood?\nLet’s dissect the naming convention:\nQ4: The base precision targets 4 bits per weight. K: Indicates the use of modern k-quants (block-wise and super-block quantization), moving past older legacy schemes like Q4_0 and Q4_1. M: Stands for Medium, a mixed-precision profile preset that assigns different bit-widths across different layers based on their measured sensitivity. Q4_K: The Mechanics of Blocks and Super-Blocks If you try to apply a single scale factor across an entire tensor containing millions of parameters, outliers will stretch the range and destroy your precision grid. To prevent this, k-quants groups weights into compact blocks of 32 values, each with its own local scale. It then bundles 8 of those blocks together into a 256-element super-block.\nCrucially, the scale factors and offset metadata are not left as uncompressed 16-bit floats. They are quantized down to lower bit-widths (such as 6-bit integers) and packed alongside the quantized data.\nBecause of this metadata overhead, a “Q4” file does not average exactly 4.0 bits per parameter. Its effective bits per weight (bpw) typically lands around 4.5 bpw.\nQ4_K_M: Not All Layers Carry the Same Weight A widespread misconception is that a Q4_K_M file compresses every single tensor in the model strictly to 4 bits. That is not how it works.\nInside a transformer, certain layers — such as the attention projection outputs and feed-forward down-projections — are far more sensitive to precision degradation than others.\nThe llama.cpp engineering community developed mixed-precision recipes that selectively allocate higher bit-widths to sensitive layers while keeping less critical layers at lower precisions:\nQ4_K_S (Small): Prioritizes minimal file size by holding virtually all tensors to a tight 4-bit format, accepting a minor bump in perplexity. Q4_K_M (Medium): Preserves fidelity by selectively bumping critical attention and feed-forward layers up to 5-bit or 6-bit quantization (such as Q5_K or Q6_K), striking the sweet spot between RAM consumption and perplexity. Q4_K_M is therefore not a standalone mathematical quantization algorithm like GPTQ. It is a carefully engineered mixed-precision packaging preset designed for balanced local execution.\n6. Storage Precision vs. Compute Precision: Is Q4_K_M Strictly W4A16? “If I run a GGUF file tagged Q4_K_M, is the engine executing a W4A16 pipeline?”\nThe short answer: Not necessarily. It depends entirely on your runtime engine, your hardware backend, and the execution kernels selected.\nTo understand real-world inference, you have to separate Storage Precision (how bytes sit in memory) from Compute Precision (how arithmetic executes in the silicon):\nStorage and Memory Allocation: In DRAM or VRAM, weights reside in compressed 4-bit block formats to conserve memory footprint and reduce memory bus traffic. Matrix Multiplication (GEMM / GEMV): NVIDIA GPU Backends: A compute kernel may stream 4-bit weights out of VRAM, dequantize them on the fly into FP16 or BF16 registers right before computation, and execute standard 16-bit tensor operations alongside 16-bit activations. CPU and Apple Silicon Metal Backends: llama.cpp often takes a different route. It can dynamically quantize incoming activation vectors into temporary 8-bit integers on the fly, executing low-precision integer dot products via SIMD or Apple AMX instructions without ever expanding the weights back to 16-bit floats. Just because a file is labeled Q4_K_M does not mean the entire execution stack runs in a fixed W4A16 pipeline. The runtime engine dynamically selects whichever compute kernel yields the lowest latency on your specific processor architecture.\n7. The Big Picture: A Mental Model for LLM Quantization The next time you see these terms thrown around in release notes or technical threads, you can place them into this clean framework:\nIf someone says: “I’m serving an AWQ-optimized W4A16 model,” you now know that means:\n“They took an existing pre-trained model (PTQ), analyzed activation magnitudes to preserve the top 1% critical channels (AWQ), and configured the serving engine to process 4-bit weights alongside 16-bit activations (W4A16).”\nAnd if someone says: “I grabbed the GGUF Q4_K_M build,” you can translate that to:\n“They downloaded a model packaged for the llama.cpp ecosystem using 256-element super-blocks (Q4_K) with a balanced mixed-precision preset that keeps critical layers at 5- to 6-bit precision (Medium preset).”\nQuantization is not just simple lossy data compression. It is a sophisticated discipline sitting at the intersection of neural network mathematics, numerical representations, compiler runtimes, and silicon memory architecture.\nOnce you understand which layer of the stack each term belongs to, you can stop guessing and start picking the exact right model build for your hardware constraints with confidence.\n","permalink":"https://blog.jiminl.com/posts/untangling-the-llm-quantization-alphabet-soup-q4-k-m-w4a16-gptq-awq-and-beyond-3edebc188418/","summary":"Browse Hugging Face or GitHub for five minutes, and you will run headfirst into a barrage of cryptic acronyms. You just wanted to spin up…","title":"Untangling the LLM Quantization Alphabet Soup: Q4_K_M, W4A16, GPTQ, AWQ, and Beyond"},{"content":"When an AI model falls short of quality expectations, the proposed fix is often a larger model, a newer architecture, or a more complex reasoning approach.\nThat proposal may be right. The current model may lack capacity, or it may be unable to process the inputs or relationships the task requires.\nBut poor quality is an outcome, not a diagnosis. Unclear ground truth, unrepresentative data, training that does not reflect the errors that matter to the product, and architectural limitations can all produce the same result. If you change the architecture before separating these causes, you are using the most expensive option to test a diagnosis that is still vague.\nAn architecture change should not be the first response to a quality problem. It should be the last major investment approved, after the remaining errors have been shown to reflect an architectural limitation.\nStart Where System-Wide Diagnosis Ends Quality problems in a production AI product can originate in real-world inputs, retrieval and preprocessing, post-processing, or how the product presents the result. The previous article explained why failures must be traced across the entire system.\nThis article begins after the problem has been reproduced under real-world conditions and the system and product execution paths have been checked, confirming that the remaining quality work lies within model development.\nThe question is now where to invest: data, training, or model architecture. The three influence one another, but changing them all at once makes it impossible to know what produced the result. Before approving the next level of investment, define the evidence that would support it instead of choosing the solution that sounds most plausible.\nThe Request-Routing Problem That Seemed to Need a Larger Model Consider a hypothetical organization that uses a classification model to route user requests to the appropriate specialist team.\nOverall offline quality remains roughly unchanged. But during a limited operational trial, some requests repeatedly go to the wrong team. Responses are delayed while staff reread and reroute them, adding to the operational workload.\nThe errors are not evenly distributed. They cluster in a few request types that are rare but consequential when misrouted. Because common requests dominate the overall average, the problem barely registers there.\nThe model engineers suspect that the current model cannot adequately understand complex phrasing or subtle differences in intent. They consider replacing it with a larger language model or adopting a multistage architecture that selects a broad category before identifying a more specific one.\nThe explanation is intuitive, and the work is easy to plan. Select a new model, run a comparative evaluation, and set a migration schedule. It is also easier to start within the model group than to reopen the ground-truth criteria and ask multiple stakeholders to assess the errors together.\nBut only one fact has been established so far: some predictions differ from the recorded ground truth. The team has not yet shown that the current model is unable to make the necessary distinctions.\nInspect the Errors Instead of Recalculating the Average Rather than calculate the overall score again, the model engineers create two review samples.\nThe first is a random sample that reflects the distribution of production inputs. The second deliberately includes errors that have a high impact on users and operations, even if they are rare.\nA random sample alone allows common request types to dominate the analysis. A sample containing only high-impact cases can make a rare problem look system-wide. Reviewing both separates error frequency from error impact.\nThe model engineers examine the original request, the existing ground truth, the model prediction, and the actual routing outcome side by side. Operations staff who understand the business rules independently assess the same cases.\nWhat had been grouped together as “model errors” now splits into distinct hypotheses: ground-truth criteria, data representativeness, training, and architectural limitations. Error analysis is not retrospective reporting. It is technical work that defines the problem the next investment must solve.\nYou Cannot Compare Models Until the Ground Truth Is Sound When reviewers reassess the error sample, they find that some cases have no consistent ground truth.\nA single request may contain two different needs. Some historical records label the team that first received the request as correct, while others use the team that ultimately resolved it. Operations staff also disagree about which need should take priority.\nIn these cases, a prediction is not necessarily wrong simply because it differs from the existing label. A larger model will not make an ambiguous objective clear. Even if it scores higher on the existing evaluation, that result cannot show whether it follows the actual routing policy more faithfully.\nThe reviewers decide which need takes priority when a request contains several, whether ground truth should reflect the initial assignment or the final resolution, and how to handle cases that people cannot agree on in an automated classification evaluation. They then relabel a separate evaluation sample using the agreed criteria and hold it fixed for subsequent experiments.\nCorrecting the evaluation criteria is not administrative work that comes before model improvement. It determines what counts as improvement.\nSeparate the Data and Training Hypotheses Once the analysis is limited to errors with clear ground truth, a new pattern appears. The errors cluster in request types and phrasings that are poorly represented in the training data. Common categories contain varied examples, while rare but important categories lack both representative and borderline cases.\nThe model engineers hold the architecture and training conditions constant, recheck the labels in those slices, and add examples that better represent them. They measure the result on the evaluation sample fixed earlier.\nIn this hypothetical scenario, some of the target errors decline. That does not prove data was the only cause. It does provide evidence that the current architecture can learn at least some of the necessary distinctions when given appropriate examples.\nTesting a data hypothesis does not mean adding data indiscriminately. The engineers need to know which errors the data is meant to reduce, whether its labels are trustworthy, and which part of the real input distribution it represents. Adding data without a target is no different from scaling a model without one.\nErrors remain after the data is cleaned and expanded. Analysis of those residual errors shows that the model tends to choose common categories. Misclassifying a rare category creates more operational burden, but the existing training objective treats cases similarly and optimizes for a higher overall average. Common requests also dominate the training sample.\nRelevant information may exist in the data without the training process making sufficient use of it.\nThe model engineers keep the architecture and cleaned data fixed while changing the training conditions. They adjust the objective to account for high-impact errors and change the sample mix so that common categories do not dominate training. They also verify that these changes do not degrade overall quality.\nEven if the target slice improves again after these changes in this hypothetical scenario, the result does not establish that training is always more important than architecture. It shows only that if a different training approach can reduce the target errors with the same data and architecture, those residual errors cannot yet be attributed to an architectural limitation.\nOnly then is there a sound basis for testing whether the remaining errors reflect a limitation of the current architecture.\nCompare Architectures on the Same Problem Before investing in a product migration, the model engineers compare the current and candidate architectures using the same cleaned data and evaluation criteria. Where practical, they align the comparison budget and tuning opportunities. They also document in advance the training conditions each architecture requires and any factors that cannot be held constant.\nThe comparison examines the error slices the project is actually trying to improve, not just the overall average. It also covers response time, compute, reliability, and operational complexity. Without these controls, improvements from additional data, compute, or tuning opportunities given to the candidate model can be mistaken for improvements from the architecture itself.\nIn this hypothetical case, the candidate architecture improves some aggregate metrics but delivers no consistent additional benefit in the critical error slices across repeated experiments. Once the added resources and migration work are considered, the evidence is not strong enough to justify replacing the entire architecture.\nThe organization keeps the current architecture. The people responsible for the relevant work instead clarify the routing rules and ground-truth definition, strengthen the data in weak slices, and adjust the training objective and sample mix. They continue to track the high-impact error slices alongside the overall average.\nThe important outcome is not a particular score improvement. Breaking one quality problem into distinct hypotheses changed the investment decision.\nThe Investment Approval Sequence: Error Analysis → Data → Training → Architecture The reasoning in this case can be compressed into four stages. Each stage requires different evidence before the next level of investment is approved.\nError Analysis\nThe problem must be reproducible under real-world conditions. The ground-truth criteria and target error slices must be defined, and error frequency must be separated from error impact. Data\nSignificant labeling and representativeness problems must be corrected. The errors resolved by data changes must be distinguishable from those that remain. Training\nAfter reasonable training alternatives have been tested, the residual errors must continue to recur consistently, with evidence that further training adjustments offer limited additional value. Architecture\nA controlled comparison on the same problem and under the same evaluation conditions must show that the candidate architecture consistently reduces the target errors. This Sequence Is Not a Waterfall This framework defines the order for approving major investments, not the calendar order of the work. Low-cost experiments can run in parallel. While examining data learning curves, the model engineers might test a different objective function or explore a candidate architecture on a small scale.\nThe framework also does not require an endless search through every possible data and training method. Important low-cost hypotheses should be tested within a reasonable scope, with the experimental boundaries and stopping conditions set in advance. If a new labeling problem or a change in the data emerges, the investigation may need to return to an earlier hypothesis.\nConversely, data and training experiments should not continue when there is a clear architectural limitation. Architecture can be evaluated earlier when:\nThe current model cannot process an input format or modality required by the task. The required context window or output format clearly falls outside the boundaries of the current design. The model repeatedly underfits reliable data across several reasonable training conditions. The current architecture is fundamentally unlikely to meet established latency, memory, power, or privacy requirements. The product is now trying to solve a different task. A limited comparison using the same data and evaluation conditions has already shown a consistent advantage for the candidate architecture. Even in these cases, the errors and requirements still need to be verified. Architecture may be the first improvement candidate, but the larger the change and the more product migration it entails, the greater the burden of proof.\nSeparate Exploration From Migration Approval Exploring a new architecture and migrating a product to it are different decisions.\nSmall comparative experiments can begin early. But a product migration may require changes to data and training pipelines, renewed validation, system integration, and additional operational work. Promising results from exploration are not enough to approve a full migration.\nA product migration proposal should present the evidence from the four preceding stages on a single page: the errors to be solved and their impact, trustworthy evaluation criteria, what data and training changes resolved and what remains, and the results of a controlled architecture comparison.\nThe proposal should also include product-level costs and stopping conditions. The decision must account for whether the expected quality gain justifies the latency, compute, reliability, migration, and operational complexity. It should also specify in advance which results would warrant further investment and which would bring the work to a stop.\nNarrow the Cause Before Reaching for the Expensive Fix Selecting a new model and developing a migration plan can feel like progress. Rereading errors, agreeing on ground truth, and finding gaps in the data can seem slower by comparison.\nThat is precisely when one question should come before the name of the model:\nWhich errors remain, and what evidence now says that the architecture must change?\n","permalink":"https://blog.jiminl.com/posts/break-down-the-errors-before-changing-the-architecture-f55fdfaf1f6c/","summary":"When an AI model falls short of quality expectations, the proposed fix is often a larger model, a newer architecture, or a more complex…","title":"Break Down the Errors Before Changing the Architecture"},{"content":"Ask an AI chatbot to write a few paragraphs, then copy the result into a plain-text editor.\nThere is no logo tucked into the corner like an image watermark. There is no obvious metadata attached to the text. And just by reading it, you usually cannot point to some hidden mark that proves an AI wrote it.\nBut that may increasingly change.\nThe text itself may look completely ordinary while the pattern of word — or more precisely, token — choices contains a hidden statistical signal indicating that an AI generated it.\nThat is the basic idea behind an invisible text watermark for large language models.\nWhy Do We Suddenly Need Watermarks for Text? When generative AI first became widely available, people mostly asked:\nHow well can AI write like a human?\nNow the question is moving in the opposite direction:\nIf AI can write this well, how do we know whether a human wrote it at all?\nGenerative AI can now produce news articles, product reviews, spam, phishing messages, homework assignments, essays, and other documents at enormous scale.\nAs a result, content provenance — where a piece of content came from and how it was created — is becoming increasingly important.\nAnd this is no longer merely an interesting technical problem. It has entered the realm of regulation.\nArticle 50 of the EU AI Act requires providers of AI systems — including general-purpose AI systems — that generate synthetic audio, images, video, or text to ensure that their outputs are marked in a machine-readable format and can be detected as artificially generated or manipulated. The technical solutions must, as far as technically feasible, be effective, interoperable, robust, and reliable. These Article 50 transparency obligations became applicable on August 2, 2026.\nThere is an important distinction here.\nThe law does not simply say that every piece of AI-generated text must visibly display a giant “AI GENERATED” label.\nThere are separate obligations for different actors. AI providers have technical marking obligations for synthetic outputs, while certain deployers that publish AI-generated or manipulated text for the purpose of informing the public on matters of public interest may have human-facing disclosure obligations, subject to exceptions.\nThat distinction is one reason invisible watermarking has emerged as an important technical candidate.\nWhy Text Watermarking Is Harder Than Image Watermarking The basic idea behind invisible image watermarking is relatively intuitive.\nAn image may contain millions of pixel values. A system can introduce tiny modifications across those pixels that are difficult for humans to notice but detectable by software.\nAudio has similar possibilities. Signals can be embedded in ways designed to remain inaudible — or at least imperceptible — to human listeners.\nText is different.\nConsider a sentence like:\nIt’s very cold in Chicago today.\nYou could technically change the color of a few letters by an imperceptible amount, embedding information in formatting that a human reader would never notice.\nBut this approach is fragile.\nCopy the text into a plain-text editor, strip the formatting, or simply retype the sentence, and the hidden information disappears immediately.\nSo if we want a watermark that survives ordinary text handling, we need to put the signal into the language itself.\nAnd this is where an interesting property of LLMs becomes useful.\nLLMs Usually Have More Than One Way to Say the Same Thing An LLM does not normally generate an entire paragraph in one shot.\nIt looks at the sequence generated so far, calculates a probability distribution over possible next tokens, chooses one, and then repeats the process.\nImagine the model has generated:\nThe weather is cold and ___\nThe next token might correspond to something like:\ncloudy dry brisk delicious The last option is extremely unlikely in this context. But the first three might all be reasonably plausible depending on the larger sentence.\nA conventional LLM chooses among candidates based on the probability distribution produced by the model and the decoding strategy being used.\nWatermarking takes advantage of this room for choice.\nSuppose we use a secret key to create a rule that subtly favors some otherwise reasonable token choices over others.\nIn one context, the system might slightly prefer cloudy.\nIn another, it might slightly prefer brisk.\nLooking at one word tells you almost nothing.\nBut if the same kind of biased choice is repeated across hundreds of generated tokens, a statistical pattern begins to emerge.\nTo a human reader, the paragraph still looks perfectly natural.\nBut a detector that knows the watermarking scheme can ask:\nAre the model’s token choices matching this secret pattern far more often than we would expect by chance?\nIf the answer is yes, the detector has evidence that the text was generated using the watermarking process.\nThe crucial idea is this:\nThe system does not necessarily insert new information into the text. Instead, it slightly influences which of several already-plausible token choices the model makes.\nThat is the core idea behind generative text watermarking.\nOne of the Early Approaches: The Green List One of the best-known early papers for understanding LLM watermarking is the 2023 ICML paper “A Watermark for Large Language Models” by John Kirchenbauer and colleagues.\nIn a simplified version of the approach, before generating the next token, the system divides the vocabulary pseudorandomly into two groups according to a secret rule.\nOne group is often described as a green list.\nThe remaining tokens form the other group.\nThe generation algorithm then slightly increases the likelihood of selecting tokens from the green list, without pushing the model so aggressively that the output becomes unnatural.\nSuppose, for simplicity, that a human-written document has no reason to prefer green-list tokens over other equally plausible tokens.\nA watermarked LLM, however, will generate green tokens somewhat more often than chance would predict.\nThe detector can then perform a statistical test:\nIf this text were not watermarked, how likely would it be to contain this many green tokens?\nIf the probability is extremely small, the detector can conclude that the text is likely to contain the watermark.\nWhat matters here is that no individual word is “the watermark.”\nThe watermark is the statistical bias distributed across many token-generation decisions.\nThat distinction is important.\nYou cannot normally point at one word and say:\nAha! That word proves an AI wrote this.\nThe evidence emerges only when enough token choices are examined together.\nHow Is Google’s SynthID-Text Different? One of the most prominent real-world implementations of this idea is Google DeepMind’s SynthID.\nSynthID first became widely known as a watermarking technology for AI-generated images, but Google later expanded it to audio, video, and text.\nGoogle has deployed SynthID-Text for text generated in the Gemini app and web experience.\nThe high-level philosophy is similar to the earlier watermarking approaches.\nWhen an LLM has multiple plausible choices for the next token, the generation process introduces a hidden rule that influences which candidate eventually gets selected.\nBut the production algorithm described by Google DeepMind is more sophisticated than simply adding a small fixed probability bonus to a predetermined list of tokens.\nIn a 2024 Nature paper, Google DeepMind introduced SynthID-Text, which uses a technique called Tournament Sampling.\nA simplified way to imagine it is as a miniature tournament among candidate tokens.\nFirst, several candidate tokens are sampled from the LLM’s original probability distribution.\nThose candidates then compete against one another.\nCandidate A might compete with Candidate B. A pseudorandom watermarking function — derived from the watermark key and recent context — assigns scores that determine which candidate advances.\nThe winners compete again.\nEventually, one token survives the tournament and becomes the output token.\nThe important part is that the original candidates were sampled from the model’s normal distribution in the first place.\nThe system is not simply forcing some bizarre, contextually inappropriate word into the sentence just because that word happens to carry a watermark.\nIf the model thinks airplane makes virtually no sense as the next word, watermarking does not suddenly make airplane a good choice.\nThat matters because a watermark that noticeably degrades output quality would have very limited practical value.\nGoogle DeepMind tested this at unusually large scale.\nIn a live experiment, roughly 20 million watermarked and unwatermarked Gemini responses were compared using real user feedback. The researchers found no statistically significant degradation in user-perceived response quality from the non-distortionary watermarking configuration.\nThis illustrates one of the central engineering problems in text watermarking:\ndetectability and text quality have to be balanced against each other.\nMake the watermark too weak, and the detector cannot reliably find it.\nMake it too strong, and you risk changing the distribution enough to hurt quality, diversity, or accuracy.\nSynthID-Text is specifically designed to navigate that tradeoff.\nAnd Anthropic Is Adopting Text Watermarking Too In August 2026, Anthropic announced that future Claude models would generate text containing a watermark.\nInterestingly, Anthropic did not develop an entirely unrelated system from scratch. It chose an approach based on Google DeepMind’s SynthID-Text, which Google had made available for broader use.\nAnthropic’s explanation reinforces the same basic idea.\nDuring generation, there are moments when an LLM has several choices that would all produce reasonable text.\nThose are opportunities to encode a watermark signal through the model’s token selection.\nBut when the answer is essentially determined, watermarking should not override correctness.\nConsider:\nIsaac Newton’s famous work is the Principia ___.\nIn the intended title, Mathematica is effectively the only reasonable continuation.\nChoosing a different word simply to strengthen the watermark would be absurd.\nYou should not sacrifice factual correctness just to leave a stronger statistical fingerprint.\nCode creates a similar problem.\nNatural language often provides many ways to express essentially the same thing:\n“Return the result.”\n“Give back the result.”\n“Produce the result.”\nProgramming languages are far less forgiving.\nChanging a single token can change program behavior, introduce a syntax error, alter a variable name, or break an API call.\nThat means code often gives watermarking systems less freedom than open-ended prose.\nAnthropic explicitly notes that watermark strength depends on how much freedom the model has in choosing words. It also says that the watermark does not rely on hidden characters, does not require extra tokens, and does not encode identifying information about a user, organization, or conversation.\nThis highlights an important shift:\nThe watermark is not necessarily something added on top of the finished text. It is becoming part of the generation algorithm itself.\nSo How Is This Different From an AI Text Detector? This is where two technologies are often confused.\nAn AI text detector and a watermark detector are solving fundamentally different problems.\nA generic AI detector examines an existing piece of text and looks for statistical characteristics associated with machine-generated writing.\nIt might analyze things such as:\nword distributions syntactic patterns repetition burstiness predictability perplexity other learned stylistic signals It then makes an inference along the lines of:\nThis looks like something an AI probably wrote.\nA watermark detector asks a much narrower question:\nDoes this text contain the specific secret statistical signal produced by a watermarking algorithm that I know how to detect?\nAn analogy may help.\nA generic AI detector is somewhat like a handwriting expert examining a ransom note and saying:\nBased on the writing style, I think this person may have written it.\nA watermark detector is closer to checking a banknote for a security feature deliberately embedded when the note was manufactured.\nThat difference matters.\nA successfully detected watermark can provide much more specific evidence than simply saying:\n“This text looks AI-generated.”\nBut even watermarking has serious limitations.\nInvisible Text Watermarks Are Not Magic At first, text watermarking sounds almost too good to be true.\nIf every AI model added a hidden watermark, perhaps we could scan the internet and instantly separate human-written content from machine-generated content.\nReality is much messier.\nShort Text Is Harder to Classify A watermark is fundamentally a statistical signal.\nImagine flipping a coin ten times and getting six heads.\nThat tells you almost nothing.\nBut imagine flipping the same coin several thousand times and getting heads 80% of the time.\nNow something looks suspicious.\nText watermarking works in much the same way.\nAs the generated text gets longer, the detector gets more token choices to examine, which generally gives it more statistical evidence.\nWith a one-sentence answer, there simply may not be enough information.\nGoogle explicitly says SynthID-Text works best on longer, more varied outputs. Anthropic similarly explains that watermark confidence increases with the amount of suitable generated text available for analysis.\nThis is an inherent limitation of statistical watermarking.\nYou cannot extract hundreds of observations from a sentence containing only a few dozen tokens.\nFactual or Highly Constrained Text Carries Less Signal Creative writing gives a language model enormous freedom.\nThere might be dozens of perfectly reasonable ways to express the same thought.\nThat creates lots of opportunities to encode a watermark.\nBut other kinds of text are much more constrained.\nExamples include:\nmathematical expressions names quotations technical terminology source code exact factual answers In those cases, the model may have very little freedom to choose alternative tokens.\nTrying to force a watermark into those choices can reduce correctness.\nSo there is an unavoidable class of outputs where:\nthe more strongly you insist on exactness, the less room you may have to embed a watermark.\nThis is not merely an implementation flaw.\nIt comes directly from the nature of the medium.\nRewriting Can Weaken — or Remove — the Watermark This is probably the most fundamental problem.\nSuppose an AI generates a watermarked essay.\nIf a human fixes a typo, changes a few sentences, or removes a paragraph, much of the underlying token pattern may remain.\nResearch on earlier watermarking schemes has found that statistical watermarks can sometimes remain detectable even after substantial human or machine paraphrasing, especially when enough text remains.\nBut now imagine taking the result and giving it to another LLM:\nKeep the meaning, but rewrite every sentence from scratch.\nIf nearly every token changes, the statistical pattern encoded in the original token choices can disappear as well.\nAnthropic explicitly acknowledges this limitation.\nLight editing may leave enough of the watermark intact to detect it, but a complete rewrite in which the words are replaced can remove it.\nThis is one reason text watermarking is particularly difficult compared with watermarking other media.\nAn image watermark can be designed to survive transformations such as compression, cropping, filtering, or changes in resolution.\nBut with text, replacing words is not merely changing the format of the data.\nThe words are the data.\nChange enough of them, and you have effectively reconstructed the content.\nIt Does Not Detect Every AI Model Suppose Anthropic has a detector for Claude’s watermark.\nThat does not automatically mean the detector can identify text generated by Gemini, Llama, ChatGPT, or every other model.\nDifferent providers can use different algorithms, different keys, or no watermark at all.\nEven implementations based on a common framework may use provider-specific secrets.\nAnthropic therefore describes the conclusion of its detector much more narrowly.\nThe watermark can provide evidence that:\nClaude was likely involved in producing the content.\nIt cannot serve as a universal answer to the question:\nWas any AI involved in writing this?\nAnthropic also notes another subtle point: a watermark cannot necessarily distinguish between “Claude wrote this from scratch” and “Claude substantially rewrote or edited this.”\nIn other words, watermarking is not a Universal AI Detector.\nIt is closer to a provenance signal associated with a particular generation process.\nA Less Obvious Side Effect: Watermarks Can Blur Authorship Text watermarking introduces another problem that is easy to overlook.\nA watermark can tell us that an AI system likely participated in producing a piece of text. But that does not necessarily mean the AI was the original author.\nImagine that a researcher writes an entire article from scratch.\nThe ideas, argument, structure, examples, and conclusions are all human-created.\nAt the end, however, the author asks an AI assistant:\nFix the grammar and make the writing more natural.\nOr perhaps the original article was written in another language and the author uses an AI model only for translation.\nIf the AI rewrites enough of the text during that process, the final version may contain the model’s watermark.\nA detector could then correctly conclude:\nThis text contains a watermark associated with an AI model.\nBut a reader might interpret that result very differently:\nAn AI wrote this article.\nThose are not the same claim.\nThe final text may carry an AI watermark even though the underlying intellectual work was primarily human.\nThat distinction becomes especially important in education, publishing, journalism, and academic work, where a simple label such as “AI-generated” can carry implications far beyond what the watermark actually proves.\nIn other words, stronger provenance signals can still lead to weaker conclusions if people interpret them too broadly.\nA watermark may provide evidence of AI participation.\nIt does not necessarily provide evidence of AI authorship.\nThe Even Harder Problem: Open Models There is another problem once we move beyond hosted models.\nFor a service such as Gemini or Claude, the provider controls the inference stack.\nIf the company wants its generation service to use a particular watermarking algorithm, it can integrate that algorithm directly into the sampling process.\nUsers interacting with the hosted API or application do not normally get to replace the provider’s internal decoder.\nOpen-weight models are different.\nSuppose someone downloads an open-weight LLM and runs it on their own infrastructure.\nEven if the official implementation includes a watermark-aware sampling algorithm, the operator can modify the inference code.\nThey can simply replace the watermarked sampler with ordinary sampling.\nThe model weights do not magically force the watermark to exist.\nThis exposes a broader limitation:\nWatermarking technology can become highly effective at marking participating generation systems, but technology alone cannot guarantee that every AI-generated piece of content in the world will contain a watermark.\nThat problem involves much more than an algorithm.\nStandards, regulation, platform policies, ecosystem incentives, and deployment practices all matter.\nWhy Watermarking Still Matters At this point, a reasonable question is:\nIf watermarks can be removed, do not work equally well on short text, and cannot identify every AI model, why bother?\nBecause imperfect does not mean useless.\nAirport security screening cannot identify every possible threat.\nWe do not therefore conclude that airport security has no value.\nThe purpose of an invisible text watermark is not to become a magical detector that determines with 100% certainty whether any AI anywhere created a document.\nIts value is more modest — and more realistic.\nIt gives us a way to create a provenance signal at the moment content is generated.\nGoogle DeepMind itself describes SynthID not as a “silver bullet” for identifying AI-generated content, but as an important building block in a broader ecosystem of AI-content identification technologies.\nThat is probably the right way to think about the future of content provenance.\nIt is unlikely to depend on a single technology.\nInstead, different layers may work together.\nAt generation time, an AI system might embed an invisible watermark.\nFor file-based media, a system might attach cryptographic provenance information through standards such as C2PA.\nPlatforms might display visible AI-generated labels.\nAnd when provenance metadata or watermarks are unavailable, specialized forensic detectors might provide additional evidence.\nNone of these mechanisms is perfect individually.\nTogether, however, they can make the provenance chain much stronger.\nSo the right question is probably not:\n“Can this one technology perfectly catch everything made by AI?”\nA better question is:\n“How many trustworthy signals can we leave behind showing that AI participated in creating this content?”\nFor most of the history of the internet, when we read something online, we primarily asked:\nWhat does this say?\nIn the age of generative AI, we may need to add another question:\nWhere did this come from?\nAnd someday, part of the answer may already be hiding invisibly inside the very sentences we are reading.\n","permalink":"https://blog.jiminl.com/posts/ai-written-text-can-carry-an-invisible-trace-how-llm-text-watermarks-work-30de9a31f55a/","summary":"Ask an AI chatbot to write a few paragraphs, then copy the result into a plain-text editor.","title":"AI-Written Text Can Carry an Invisible Trace: How LLM Text Watermarks Work"},{"content":"When an AI product produces a bad result in production, teams look at the model first. They ask whether quality scores have dropped, whether a new version introduced a problem, whether they need more data, or whether they should move to a larger model.\nThis is a natural response. The failure presents itself to the user as a model output, and model metrics are usually the easiest numbers for the team to inspect.\nBut diagnosing a production failure takes more than diagnosing the model.\nThe model may indeed be the source of the problem. It may lack a capability the product requires or repeatedly produce incorrect outputs under certain conditions.\nBut once an error harms a user, the questions cannot stop at the model. Why did evaluation fail to catch it? Why did the execution system fail to detect or block it? Why did the product present an uncertain result as a definitive answer? Why did human intervention or a safe fallback fail?\nFixing the model may remove the immediate defect. But if the path that allowed the same kind of error to go undetected, reach the user, and grow in impact remains intact, the production failure has not been resolved. This is why most production failures take more than a model fix.\nA production failure is not one bad output. It is the entire path that produced it, missed it, and delivered it to the user.\nWhy Diagnosis Converges on the Model There are three reasons the model becomes the default explanation.\nFirst, the symptom visible to the user looks like a model output. A wrong answer, an irrelevant recommendation, or a missed detection makes it easy to conclude that the model was wrong.\nSecond, models are relatively easy to measure. Teams can rerun evaluations, train a new version, and compare it with the previous one. Changes in real-world inputs, interactions among services, and human behavior are much harder to reduce to a single metric.\nThird, one team can begin changing a model, while diagnosing the system requires several teams. The owners of data pipelines, evaluation, platforms, applications, and product operations must examine execution records and assumptions together.\nOrganizations therefore tend to converge first on the cause that is easiest to investigate and has the clearest ownership, not necessarily the actual cause.\nResearch on technical debt in machine learning systems identifies data dependencies, feedback loops, changes in the external environment, and configuration issues as sources of long-term risk. The AI Risk Management Framework from the U.S. National Institute of Standards and Technology likewise addresses not only models, but also context of use, data, human oversight, and monitoring and response in production.\nThe 4+1 Failure Map Four causal domains shape the outcomes of production AI:\nData and real-world inputs / Model / System and execution / Product and operations\nOne cross-cutting function, evaluation and observability, spans all four.\nLet’s call this the 4+1 Failure Map.\nThe four causal domains are not mutually exclusive buckets. Problems in several domains may be connected within the same incident.\nA retrieval timeout, for example, is a system and execution problem. If it causes incomplete context to reach the model, an assumption about data and real-world inputs has also broken. If the product presents the answer with certainty without indicating that context is missing, product and operations have amplified the impact.\nEvaluation and observability test assumptions before launch and expose failures in production. Based on those signals, teams must also ask whether the impact could have been limited within each of the four domains.\nThe purpose of the 4+1 Failure Map is not to give an incident a single label. It is to locate three points:\nWhere an assumption first broke Where the failure could have been detected Where its impact could have been limited before it reached the user Google Flu Trends: A Bad Estimate Does Not Reveal the Cause Google Flu Trends used changes in search queries to estimate current levels of influenza-like illness more quickly. It was an attempt to understand current conditions through search signals before traditional surveillance data became available.\nAccording to Google’s official account, the initial model used search terms that had tracked previous flu seasons well and was retrained once a year. During a season, it did not incorporate the latest surveillance data from the U.S. Centers for Disease Control and Prevention into its estimates.\nDuring the 2012–2013 season, the model estimated levels of influenza-like illness far above those reported by the CDC. Google retrained the model and later introduced an approach that continuously incorporated official surveillance data during the season. Google’s official account\nWe cannot classify this case as either a data failure or a model failure. Google changed the model, and the public record does not allow us to separate the respective contributions of the search signals, modeling methods, and process for updating reference data.\nA report on a CDC-led forecasting challenge also explained that influenza forecasts based on digital data can be affected by bias and error in the source data, and that the algorithms and methods involved require continued maintenance. It identified both the data and the forecasting methods as possible sources of error.\nOn the 4+1 Failure Map, this incident does not fit into one box. What the search signals represented is a question about data and real-world inputs. How those signals were converted into estimates of current illness levels is a model question. Whether the error could have been detected and the estimates updated using the latest reference data is a question of evaluation and observability.\nThe public evidence does not establish where the initial fault occurred. That is precisely the lesson. Observing a bad estimate does not, by itself, tell us which domain to fix.\nTay: Pre-Launch Testing Cannot Represent the Entire Public Environment Microsoft stated that before launching its public chatbot Tay, it implemented filters, studied diverse user groups, and conducted stress tests under a range of conditions.\nYet within the first 24 hours after launch, a coordinated attack by some users exploited a vulnerability that had not been anticipated. The chatbot posted inappropriate content, and Microsoft took the service offline. The company said it had prepared for several forms of abuse but had missed this particular type of attack. Microsoft’s official retrospective\nThe public record does not reveal exactly which internal mechanism was exploited. Nor does it establish how much the model, filters, learning approach, or interaction design contributed. Tay should therefore not be classified as either a pure model failure or a pure non-model failure.\nThe lesson supported by this case is narrower. The user behavior covered in pre-launch evaluation may differ from behavior in a public environment. Evaluation and observability must ask not only whether normal use has been covered, but also how broadly the possibility of abuse has been tested. Product and operations must determine how to contain a problem when it occurs and when to suspend the service.\nOperational mitigation cannot wait simply because the initial fault has not yet been located. Microsoft’s decision to take the service offline shows that identifying the cause and limiting the impact are separate decisions.\nGoogle Flu Trends and Tay are not representative samples proving how often non-model failures occur. They illustrate two different diagnostic patterns in which a bad output alone is insufficient to determine either the cause or the remedy.\nHow One Wrong Answer Becomes a Production Failure Suppose a customer support AI gives a user the wrong refund deadline. The visible symptom is simple: “The AI gave the wrong answer.”\nBut the incident may look very different when we trace the propagation path.\nThe refund policy changed, but the knowledge base was not updated in time. The first assumption broke in data and real-world inputs.\nThe evaluation set contained no examples involving the new policy, so the existing quality score remained unchanged. Evaluation and observability failed to reveal that reality had changed.\nThe retrieval system correctly passed the outdated document to the model, and the model answered according to the document it received. The model participated in producing the wrong outcome, but it was not the initial fault on this path.\nThe product displayed the answer as definitive policy without showing the age of the source or indicating uncertainty. There was no fallback for escalating to a person or checking the official policy. Product and operations amplified the impact.\nRetraining the model would leave the outdated material, the evaluation gap, and the missing fallback untouched. A complete fix would need to update the knowledge base, strengthen evaluation, check document freshness, change how the answer is presented, and provide a path to human intervention.\nNow consider the opposite case. Even when given the latest policy and all necessary context under controlled execution conditions, the model might repeatedly confuse a general rule with its exceptions. In that case, the initial fault is likely in the model.\nEven then, resolving the production incident does not end with the model. Teams must also address why evaluation failed to catch the recurring error and why the product failed to limit an answer with weak support. Otherwise, the same kind of failure can reach users again.\nThe same symptom can require entirely different investment decisions depending on the initial fault and the propagation path.\nMitigate Severe Impact Before Completing the Diagnosis Users should not continue to suffer harm while the team builds the 4+1 Failure Map.\nWhen an incident involves safety, security, privacy, discrimination, or regulatory risk, the team may need to disable the feature, roll back to a previous version, reduce its scope, or switch to a safe fallback before the cause has been confirmed.\nProduction response must separate two activities:\nImmediate mitigation: Limit the impact and return the system to a safe state. Full remediation: Fix the initial fault and the failures in detection, propagation control, and mitigation to prevent recurrence. Fast mitigation must not replace root cause analysis. Conversely, mitigation must not be delayed while the team waits for a complete analysis.\nThe 4+1 Failure Map does not replace a formal incident-response process or established safety and regulatory procedures. It gives multiple teams a shared diagnostic language so they do not converge on a single model change without sufficient evidence.\nFive Questions Before Approving Model Work A reported quality problem should not automatically trigger approval for retraining or model replacement. Before making a major investment in model work, leaders should be able to answer at least five questions.\n1. Can the problem be reproduced with actual production inputs? Use the actual inputs and conditions from the time of the incident, not sanitized evaluation inputs. If the problem cannot be reproduced, investigate input corruption, changes over time, and execution conditions first.\n2. Is the model’s raw output the same as the result the user received? Compare the results before and after preprocessing, retrieval, post-processing, and product presentation. Do not assume that the result the user saw was the model’s raw output.\n3. Does the current evaluation measure the failure the user experienced? If the evaluation set and metrics cannot distinguish failures under the same conditions, the team will not be able to tell whether a model change solved the problem. Do not use model improvement to cover a gap in evaluation.\n4. Does the error remain when execution settings and external dependencies are controlled? Check whether the error recurs when the model version, configuration, inputs, retrieval results, and external services are held constant. Otherwise, the team may mistake system variation for a model problem.\n5. Have we defined the propagation and mitigation fixes that must accompany the model change? Even if the model is the initial fault, fixing it may not be enough. The remediation scope must also define actions and ownership for detecting the same kind of error in evaluation, identifying it during execution, and limiting it before it reaches the user.\nIf the error remains in the model with valid inputs and controlled execution conditions, model work should begin. Measures to repair the propagation and mitigation paths should proceed separately at the same time.\nIf the team has not examined the actual inputs, evaluation, and execution path, however, retraining is not a diagnosis. It is a guess.\nLeaders should not assign responsibility for an incident to a single team. They must divide the work across the domains where an assumption first broke, where the failure could have been detected, and where its impact could have been limited. Neither asking the model team to absorb every failure nor building a system that works only when the model is perfect is sustainable.\nThe ability to fix models is essential in production AI. Equally important is the ability to recognize when fixing the model alone cannot close the incident.\nThe next time a model quality problem is reported, do not immediately ask, “Which model should we switch to?”\nAsk this first:\nWhere did the assumption first break, and where could we have detected and limited the failure?\n","permalink":"https://blog.jiminl.com/posts/why-a-model-fix-is-often-not-enough-in-production-ai-ace99b474b3f/","summary":"When an AI product produces a bad result in production, teams look at the model first. They ask whether quality scores have dropped…","title":"Why a Model Fix Is Often Not Enough in Production AI"},{"content":"Even a Good AI Model Can Be Wrong for the Product The model is a core component of an AI product. That is why teams often select or develop the model first, then build the rest of the product around it. The order feels intuitive: if the model is the core technology, a better model should lead to a better product.\nBut what if search results take ten seconds to appear? What if a music recommendation feature requires users to enter 100 songs and 30 artists they like? What if a world-class on-device image analysis model makes a smartphone too hot to hold after five minutes? None of these models is right for the product.\nThe problem is not model quality. It is that model development began before the team defined the conditions the product required. Model development for an AI product should begin with a product–model contract that defines the conditions the model must meet.\nA Production Model Is a System Component Model development itself has a strong research component. It is difficult to know in advance which data and training methods will work. But once a model enters a product, it becomes a system component whose inputs, outputs, execution environment, and failure handling must be defined. It must also meet requirements for latency, cost, memory, power, throughput, privacy, safety, and reliability.\nModel metrics are relatively easy for one team to measure and improve, but the conditions for product success are distributed across several organizations. The product team thinks about user experience, the application team about integration, and the platform team about compute resources and reliability. Organizations therefore tend to solve an already well-defined model problem before addressing product-wide trade-offs. But the best-defined problem is not necessarily the problem that should be solved first.\nWhen development begins without shared criteria, the model team reasonably optimizes the metrics it has been given. During integration, however, the team may discover that the product cannot provide the inputs the model expects, that a small percentage of output-format errors destabilizes downstream features, or that the model size and inference method exceed latency and cost limits. By then, substantial resources have already been invested. It is difficult either to discard the model or to change the product architecture. The surrounding system becomes more complex, or the model must be rebuilt.\nThis is not the fault of any one team. Each team may have achieved its own objectives. The failure comes from the absence of shared criteria connecting each team’s goals and results to those of the product as a whole.\nEven a good model can be wrong for the product.\nThe Product–Model Contract The product–model contract is a technical agreement that lets the product, model, platform, and application teams explicitly test how a choice in one area affects the others before making a major development investment. To do that, they translate the conditions for product success into requirements they can test during model selection, development, and evaluation.\n“Contract” does not mean a legal document or a specification that can never change once finalized. It makes explicit what the relevant teams must satisfy together and gives them a shared basis for judgment.\nThe contract combines three categories with four fields. The categories are user outcomes, operating envelope, and system interfaces. Every requirement within those categories has four fields: criterion, validation method, assumptions, and ownership.\nWhat must be satisfied How and in what environment it will be validated Which constraints are confirmed and which assumptions remain unvalidated Who will verify the item and participate in decisions about changes Each item should be expressible as a testable statement:\nUnder [condition], [criterion] must be met. We will validate it using [environment and method]. [Owner] will validate the still-unconfirmed assumption that [assumption].\n1. User Outcomes The first concern is not the model’s score, but the outcome users need to achieve. What problem does the model solve? What must change for users to find it useful? What is the product-level quality bar, and how much does the model contribute to that outcome? If the team cannot explain this connection, it may mistake an easy-to-measure metric for the product objective.\nModel evaluation is necessary, but the team must be able to explain how a higher score changes users’ task success or trust in the product. Otherwise, it may optimize a difference that does not matter to the product.\nShortly after I joined a company, I presented a model I had spent a week thinking through and building to a much more senior colleague. They listened quietly, then asked:\n“How long would it take to turn that model into a product?”\n“About three months,” I replied.\n“What would change?”\n“The model’s accuracy would improve from 90% to 95%.”\n“No. What would the customer experience differently?”\n“It would also find items that are written differently but sound almost the same.”\n“How many customers actually have that problem?”\nI had no answer. I had pursued the work because I enjoyed analyzing the existing model’s technical weakness and figuring out how to solve it.\nWhen I said nothing, my colleague told me:\n“You’re saying you want to use company resources for three months to pursue something you find interesting.”\nI could explain the technical weakness and the improvement in score, but not how many customers would notice a difference or what that difference would be. To evaluate a proposed model improvement, the team must answer not only “How much will the score increase?” but also “What will users be able to do better as a result?”\n2. Operating Envelope The second part defines the operating conditions the model must meet in practice. What ranges of latency, cost, memory, power, throughput, privacy, safety, and reliability are acceptable? What boundary conditions must it withstand?\nThe operating envelope is neither a deployment check performed after development nor premature optimization of the implementation. It is a set of criteria for deciding which model architectures and execution approaches are viable. We cannot know every condition at the outset, but we must distinguish confirmed constraints from assumptions that still need validation. Otherwise, product constraints surface only during integration.\nUsing a larger, more capable model to improve quality can increase cost and latency. Providing more input and context may not be viable in the actual product because of privacy or user experience constraints. The operating envelope filters out choices that cannot work before experimentation begins.\nA few years ago, my team was developing a new on-device model. We needed to surpass the quality of an on-device model we had already released. Because the existing model already performed exceptionally well, we selected a larger model with the latest architecture and gave it more data. The resulting model performed noticeably better.\nBut it never made it to market. Its current draw and heat generation were too high in the on-device environment. Our team had extensive experience developing on-device AI models, so we understood that current draw and heat mattered. But the existing model was small and fast enough that we had never needed to worry about them. We implicitly ignored these constraints for the new model. We also thought we could focus on performance first and address them later.\nThe lesson was not that we were unaware of the operating constraints. It was that we failed to make known constraints explicit criteria for selecting and evaluating the new model. No matter how well a model performs, it cannot be considered a good model if it cannot ship.\n3. System Interfaces The third part covers information exchanged between the model and other components. What inputs and context can the product provide? What errors or omissions may occur? What outputs and failure signals do surrounding systems require, and what fallback should they use? The interface must cover not only data types but the actual input conditions that determine model quality. The team must verify whether the clean inputs and rich context assumed in evaluation will be available in the product.\nConsider a model that determines whether a phone call is a voice-phishing scam. The model team is told that it can receive the call audio and a speech-recognition transcript, so it trains the model with those inputs. But when the model is integrated into the product, its performance plummets. Both inputs are passed correctly, but the actual speech-recognition output does not match the clean transcript the model assumed it would receive.\nEach team made reasonable decisions, but they did not define actual speech-recognition quality in a phone-call environment as a shared interface condition. Had they verified the input’s quality and conditions, not just its presence, they could have discussed component-boundary problems before development.\nThe speech-recognition team could simulate audio that reflects the characteristics of the phone network, and the voice-phishing model team could augment its data to account for speech-recognition errors.\nIf the model cannot guarantee its output format 100% of the time, the surrounding system could detect errors and switch to a safe fallback. Rather than making the model responsible for every problem or having each team prepare independently, the teams must jointly decide who will detect and compensate for poor input quality and output failures. That shared decision is necessary to protect system quality.\nA Contract Statement for the Voice-Phishing Example The voice-phishing example above can be expressed as the following contract statement. The ownership assignments are illustrative, not a description of how the work was actually divided.\nSystem Interfaces: With actual call audio and speech-recognition output, the voice-phishing model meets agreed detection quality; model and speech-recognition teams validate under representative phone-network and recognition-error conditions, while the speech-recognition team verifies the unconfirmed assumption that output quality matches training/evaluation assumptions.\nTest the Contract Before Model Selection Consider two hypothetical models.\nThe first achieves higher quality in standalone evaluation but requires extensive input data and compute resources. The second scores slightly lower but works with the inputs the product can provide and meets its latency and reliability requirements.\nThe contract is not a document written after a model has been selected to explain why it fits. It should provide criteria for testing candidate models with representative inputs in an execution environment close to the real one and surface any conditions that remain unvalidated.\nThe performance table alone makes the first model look better, but the product–model contract is not a tool for predetermining the answer. The team must test whether the quality difference has a meaningful effect on user outcomes and whether the required inputs and operating conditions can be met consistently. It may choose the second model or, if the first model’s quality is essential, change the product architecture or resource plan. The contract’s purpose is not to dictate the answer, but to surface trade-offs.\nThe contract is not static. It should change as the team’s understanding of the product and technology changes. But no one team should change it implicitly. The relevant teams must decide together which assumption proved false, which condition should be adjusted, and how the change will affect users and the system.\nTechnology Exploration and Product Development Need Different Approaches When exploring a new technology, it is reasonable to start with a model or prototype to learn what it does well and where it fails. The product team may not yet know what it should require.\nBut an exploration should have a question, a time frame, and exit criteria. The question for exploration is, “What can this model do?” The question for product development is, “What must be true for users to trust this feature?” The answer to the first helps define the second question; it does not replace it.\nThe transition point comes when the team decides, based on its exploration, to invest in actual product development. That is when it should write and test the product–model contract.\nWhat Leaders Should Do Before Model Development Begins Before approving a direction for a model, the leaders responsible for product, AI, platform, and application engineering should jointly write at least one testable statement for each of the three areas. They should assign a validation method and an owner to every unconfirmed assumption and derive the model evaluation criteria from the contract.\nThe answers do not need to be complete from the beginning. What matters is leaving missing information as assumptions to validate rather than filling the gaps with convenient guesses.\nThis upfront work may appear to slow model development. But it brings forward the discovery of fundamental mismatches that would otherwise surface during integration. Avoiding the development of a model that does not fit the product makes the overall project faster.\nBefore selecting a model, ask:\nNot “What is the best model we can build?” but “What model does this product need?”\n","permalink":"https://blog.jiminl.com/posts/even-a-good-ai-model-can-be-wrong-for-the-product-088c12a95e39/","summary":"Even a Good AI Model Can Be Wrong for the Product","title":"Even a Good AI Model Can Be Wrong for the Product"},{"content":"A hands-on Python course for understanding what agent frameworks actually do AI agents can seem mysterious when introduced through large frameworks. Behind the abstractions, however, an agent is built from a small set of understandable components: an LLM call, a loop, conversation history, tools, and rules for deciding what happens next.\nAgent Harness from Scratch is a hands-on course that builds these components incrementally using Python and the OpenAI-compatible API.\nhttps://github.com/jiminelee/agent-harness-course\nThe course starts with a single LLM request and gradually adds:\nAn agent loop and conversation history Function calling and tool registries Memory compression Planning and task decomposition Error recovery and reflection Concurrent tool execution with asyncio Guardrails and human approval Structured tracing and observability Multi-agent orchestration Packaging, caching, cost tracking, and prompt versioning Each module is a standalone Python program. The code intentionally avoids frameworks such as LangChain or AutoGen so you can see the mechanics directly. Implementations favor clarity over production-level error handling and abstraction.\nThe default setup uses Ollama and gemma4:e4b, so the course can run locally. Because it uses the OpenAI Python SDK and an OpenAI-compatible request format, it can also be adapted to OpenAI and other compatible providers.\nThis course is intended for developers who are already comfortable with Python and basic LLM API calls. Following the full project should take roughly 10–15 hours, depending on how many experiments you try.\nThe final module also provides a roadmap explaining what would need to change before using these ideas in a production system.\nFun fact: the course itself was developed with help from an AI agent. AI accelerated coding, review, and documentation — but the goals, curriculum, architecture, constraints, and evaluation still required human judgment.\nThat is also the central lesson of the project: a capable model is only one component. Reliable agent behavior comes from the system designed around it.\n","permalink":"https://blog.jiminl.com/posts/build-an-ai-agent-harness-from-scratch-83fc5ec2a388/","summary":"A hands-on Python course for understanding what agent frameworks actually do","title":"Build an AI Agent Harness from Scratch"},{"content":"We all remember when ChatGPT first burst onto the scene. The world was captivated by its ability to spit out highly plausible, articulate answers to almost any question we threw at it. But as the honeymoon phase faded, the limits of generative AI became increasingly obvious. Assign it a multi-step, complex task, and it would often lose its train of thought halfway through — or worse, confidently hallucinate a completely fabricated response.\nRecently, the AI landscape has undergone a massive paradigm shift.\nThe industry is no longer just asking, “Who can write the most eloquent text?” The new battleground is, “Who can flawlessly execute real-world tasks?”\nAt the very center of this shift is the concept of Agentic AI. In this post, we’ll dive deep into what “Agentic” actually means, how its underlying loops work, what an “Agent Harness” is, the very real bottlenecks engineers face today, and how we actually evaluate these systems.\n1. What Exactly is “Agentic” AI? Let’s start with the root word: Agency.\nAgentic AI moves past the paradigm of a machine that simply generates text. It refers to an AI system that acts with agency and autonomy.\nInstead of passively waiting for a prompt and returning a static answer, an Agentic AI takes a final Goal from the user and works backward. To achieve that goal, the AI independently creates a plan, interacts with its environment, strategically uses external tools, and self-corrects errors along the way — all while minimizing human intervention.\nBefore we get carried away, let’s clarify one thing: despite the phrase “minimal human intervention,” real-world agentic systems rarely operate with 100% autonomy. In high-stakes environments like finance, healthcare, or enterprise infrastructure, the cost of a mistake is simply too high. In these cases, a “Human-in-the-Loop” (HITL) architecture — where the agent prepares everything but requires human sign-off for critical actions — is the absolute standard.\nThe core magic of Agentic AI isn’t total autonomy; it’s goal-oriented, iterative self-correction.\nIf a traditional LLM is a brilliant but passive encyclopedia that only answers exactly what you ask, an Agentic AI is a smart, proactive project manager.\nLet’s look at an example. If you tell a traditional AI, “Write a 5-page report on global warming,” it will immediately generates a draft based on its pre-trained weights. If it lacks recent data or its logic breaks down in paragraph three, it doesn’t care. Its only goal is to finish the text string.\nIf you give that exact same goal to an Agentic AI, the workflow looks completely different:\n“To make this reliable, I need the latest 2025–2026 carbon emission data. Let’s trigger the web search tool.” After fetching the data: “Let me outline an introduction, body, and conclusion, and draft the first version.” Self-Review: “The logic in the second body paragraph is weak. I need to search for some academic papers to back this up.” It patches the holes, runs a final review, and then presents the finished report to the user. Breaking down problems, using tools to find solutions, and critically reviewing its own output — this iterative process is the defining power of Agentic AI.\n2. Why the Sudden Explosion of Agents? If you’ve been in the AI space for a while, you might be thinking, “Wait, autonomous agents have been researched in academia for years. Why is this exploding right now?”\nIt’s true that AI agents aren’t a brand-new concept. However, they largely stayed trapped in research labs. Even when ChatGPT debuted, LLMs were overwhelmingly confined to simple Q\u0026amp;A chat interfaces.\nThe tipping point happened in 2024. The ability of LLMs to understand when and how to call external tools (Function Calling) drastically improved. Knowledge tools, which started as simple RAG (Retrieval-Augmented Generation), expanded into web search, SQL querying, and file system navigation. Furthermore, the base reasoning capabilities of the models leaped forward, allowing them to formulate reliable, multi-step plans.\nThis explosion is the result of several technological pillars maturing at the exact same time:\nMature Reasoning Models: Models can now reliably execute a “Plan -\u0026gt; Execute -\u0026gt; Reflect” loop without going completely off the rails. Explosion of the Tool Ecosystem: The infrastructure connecting AI to thousands of external services (GitHub, Slack, Notion, Jira) is now highly mature. MCP (Model Context Protocol): Universal interface that allows agents to call diverse external tools using a common language. Massive Context Windows: Models can now remember context for much longer, allowing them to handle complex, 50-step workflows without forgetting the original goal. Plummeting Inference Costs: Because agents require calling the LLM dozens of times per task, cheaper API costs have made looping economically viable for production. 3. The Core Engine: Deconstructing the Agentic Loop So, we know what Agentic AI feels like, but how does it actually work under the hood? At the heart of these systems is the Agentic Loop — a continuous cycle of iteration.\nThe simplest possible pseudo-code for an agent loop looks like this:\ndef agent(goal: str) -\u0026gt; str: plan = llm.plan(goal) max_iterations = 20 for _ in range(max_iterations): action = llm.decide_next_action(plan, memory) result = tools.execute(action) memory.update(result) if llm.evaluate(result, goal) == \u0026#34;DONE\u0026#34;: return memory.final_answer() plan = llm.replan(plan, result) return \u0026#34;Goal could not be completed within iteration limit.\u0026#34; That’s it. The LLM isn’t generating one long response — it’s being called multiple times, each time with updated context, to drive a feedback loop.\nThe most famous framework for this is ReAct (Reasoning and Acting). Because ReAct is so well-known, many people mistakenly think ReAct and the Agentic Loop are the exact same thing. They aren’t. ReAct is just one specific pattern. In actual production environments, you’ll see a mix of patterns like Plan-and-Execute, Reflexion, and Graph-based Agents architectures.\nLet’s look at the two most important structures: the intuitive ReAct pattern, and the Graph/State Machine structure that actually powers modern enterprise AI.\n3.1 The Intuitive ReAct Pattern ReAct loops through three distinct phases: Thought -\u0026gt; Action -\u0026gt; Observation. It is beautifully simple and is usually the gateway drug for developers learning about agents.\n[Thought] The user wants to plan a business trip to Austin, Texas. I need flights, hotels, and weather info. Let’s start with the weather API.\n[Action] Call Weather API (Location: Austin)\n[Observation] “Austin weather for Thursday: 68°F, partly cloudy, 10% chance of rain.”\n[Thought] Weather is clear. Now I need to check outgoing flights.\n[Action] Call Airline API\n[Observation] “Multiple seats available on the 10:00 AM departure.”\n(…Repeats until the final goal is met…)\n3.2 The Production Standard: Graph / State Machine Agents While ReAct is great for tutorials, production environments require something much more robust. Major frameworks like LangGraph and OpenAI’s Agents SDK operate on State Machine or Graph-based architectures.\nThe flow looks more like this:\nGoal Input\n↓\nPlanner (Breaks down tasks)\n↓\nExecutor (Takes action)\n↓\nTool Use (Calls APIs)\n↓\nUpdate Memory/State (Saves progress)\n↓\nEvaluator (Checks the work)\n↓\nReplanner (Adjusts plan or concludes)\nThe critical difference here is State. ReAct moves linearly, whereas Graph-based agents explicitly manage and store the current state of the workflow. This allows for complex branching logic, parallel task execution, and the ability to safely revert to a previous node if an error occurs.\nHere is what those phases actually entail:\nPerception \u0026amp; Goal Understanding: Translating a vague request (“Set up my Austin trip”) into a concrete checklist (flights, hotel, weather, itinerary). Reasoning \u0026amp; Planning: Deconstructing a massive problem into bite-sized, manageable sub-tasks. Action \u0026amp; Tool Use: Executing the plan. Because LLMs don’t have real-time internal data, external APIs and databases act as the agent’s hands and eyes. State Update \u0026amp; Observation: Logging the outcome. If the Airline API returns a 500 Server Error, the agent observes this, updates its state, and searches for an alternative route without having to restart the entire workflow. Evaluation \u0026amp; Replanning: Looking at the outcome and asking, “Is this good enough?” If not, it modifies the plan and loops again. 4. The Tech Stack Behind the Magic To turn that conceptual loop into working software, you need four core components:\n1. The Brain: LLM as a Reasoning Engine\nIn an agentic system, the LLM isn’t just a copywriter; it’s the core logic engine. It needs to possess deep reasoning capabilities to determine which tool to use, when to use it, and whether a sub-task is complete. If the model’s reasoning is flawed, the initial plan will be wrong, and every subsequent action will just compound the error.\n2. Limbs for the Digital World: Tool Use \u0026amp; Function Calling\nTools are what allow the AI to break out of its isolated sandbox. By defining a set of tools (e.g., a calculator, a web browser, an internal SQL database), the AI can dynamically generate the exact commands needed to interact with the outside world. The introduction of MCP (Model Context Protocol) has hyper-charged this, standardizing how agents talk to tools.\n3. Evolved Storage: Memory Systems\nTo handle long-running tasks, agents need distinct memory systems.\nShort-term memory acts as the agent’s scratchpad, keeping track of its current step within the context window (“I am on step 3 of 5”). Long-term memory relies on external storage (Vector DBs, SQL, Graph DBs) to remember user preferences across different sessions (“This user always prefers reports in paragraph format, no bullet points”). 4. The Plumber: Orchestration Frameworks\nWriting the code for an agent from scratch — handling the LLM calls, parsing outputs, executing tools, managing state, catching errors, and handling multi-agent communication — will quickly turn into a 1,000-line spaghetti nightmare. Orchestration frameworks abstract this boilerplate so developers can focus purely on logic.\nThese orchestration frameworks are collectively known in the industry as Agent Harnesses.\n5. The Engine That Runs the Loop: Agent Harness If the Agentic Loop is the theory, the Agent Harness is the reality. It is one of the most hotly debated topics in AI engineering today.\nWhat is a Harness? In software engineering (much like horseback riding), a harness is a framework used to secure, control, and direct the power of a complex system. An Agent Harness puts a bridle on the wildly powerful (but unpredictable) LLM, forcing it to run safely toward a specific goal.\nIt handles three massive responsibilities:\nLoop Execution: Automatically driving the Plan -\u0026gt; Execute -\u0026gt; Observe -\u0026gt; Replan cycle. Tool Bridging: Executing the tool calls the LLM requests and feeding the raw data back into the model. State Persistence: Ensuring that the AI’s memory and progress aren’t wiped out between loop iterations. Without a harness, your agent is just an idea on a whiteboard.\nWhy is Everyone Obsessed with Harnesses Right Now? Before modern harnesses, building an agent meant manually hardcoding the entire loop. Every time you added a single new tool, you had to refactor massive chunks of routing logic.\nA good harness abstracts this “plumbing,” reducing hundreds of lines of fragile code down to a few dozen lines of robust infrastructure.\nAs the industry realized that the quality of the harness affects the agent’s success rate just as much as the size of the LLM, the race to build the best framework began.\nMajor Frameworks to Watch LangGraph: The current heavyweight champion for production. It maps the agentic loop as a directed graph of Nodes (tasks) and Edges (conditional routing). Because it explicitly manages State, developers have incredible control over complex branching and loops. OpenAI Agents SDK: A highly accessible framework emphasizing “Handoffs.” It makes it trivially easy to build multi-agent workflows — for example, a “Research Agent” doing the heavy lifting before seamlessly tossing the baton to a “Writer Agent.” AutoGen (Microsoft Research): A conversational framework where multiple specialized AI agents literally talk to each other to solve problems (e.g., an Assistant Agent writes code, and a Proxy Agent tests it and reports the errors back). Highly flexible and great for experimental/research setups. 6. The Harsh Reality: Limitations in the Field It’s easy to get starry-eyed about agents, but engineers actually deploying these systems are fighting some brutal uphill battles every single day.\nCost and Latency: Agents do not fire one prompt and get one answer. A single user request might trigger 15 background LLM calls as the agent plans, searches, fails, and retries. This burns through token budgets instantly and can take several minutes to complete. If your app requires sub-second response times, agentic workflows are currently too heavy. Compounding Errors \u0026amp; Infinite Loops: If an agent hallucinates even a tiny detail during the initial planning phase, it will base its subsequent tool searches on that lie, creating a snowball effect of bad data. Furthermore, agents often get stuck in “infinite loops,” obsessively searching for data they can’t find and refusing to move on. Security Risks: Giving an AI unrestricted read/write access to your database or terminal is terrifying. A clever user can use “Prompt Injection” to trick an agent into dropping a database table or exfiltrating private API keys. Strict Human-in-the-loop (HITL) checkpoints are non-negotiable. The Nightmare of Evaluation: If a standard chatbot gives a wrong answer, it’s easy to grade. But how do you grade an agent’s process? If Agent A finds the answer via 5 web searches, but Agent B writes a Python script to calculate the answer in 1 step, which one is better? 7. How Do We Actually Evaluate Agents? Because standard Q\u0026amp;A benchmarks are useless for agents, the industry has developed new metrics to measure autonomous performance:\nSuccess Rate: Did it actually achieve the final goal? e.g., “Did the item successfully get added to the cart?” Cost: Token usage and total API calls. e.g., “Did it take 3 API calls or 15 calls to get the exact same result?” Tool Efficiency: Did it take the optimal path?. e.g., “Did it hallucinate a non-existent API endpoint before finding the right one?” Latency: Total time to resolution. e.g., “Is the user going to abandon the page before the agent finishes?” Safety: Did it violate permissions? e.g., “Did it try to delete files it wasn’t supposed to touch?” To test these metrics, the industry relies on virtual sandbox environments. The big three benchmarks right now are SWE-bench (measuring software engineering/bug fixing), WebArena (navigating and operating mock websites), and GAIA (complex tasks blending web search, file handling, and code execution).\n8. Conclusion: From “What to Ask” to “What to Delegate” Agentic AI represents a fundamental leap forward. It’s an AI that understands your ultimate objective, formulates a plan, leverages external tools, and critiques its own work. While we are still wrestling with real-world friction around latency, token costs, and security, frameworks like LangGraph and OpenAI’s Agents SDK are rapidly bridging the gap between theory and production.\nIf there is one way to summarize this entire shift, it is this:\nIn the Chatbot era, the primary question was, “What should I ask the AI?”\nIn the Agent era, the primary question is, “What should I delegate to the AI?”\nMoving forward, the competitive edge for both individuals and enterprises will lie in how well they can provide AI with clear goals, powerful tools, and secure harnesses. We are no longer just talking to algorithms — we are onboarding our newest digital coworkers.\nThe developers who will do the most interesting work in the next three years aren’t the ones who can write the cleverest prompt. They’re the ones who can design reliable systems around fundamentally unreliable components — and know exactly which guardrails to put where.\nThat’s not a new problem. It’s just software engineering, applied to a new kind of component.\n","permalink":"https://blog.jiminl.com/posts/introduction-to-agentic-ai-beyond-the-chatbot-943260c4fd8f/","summary":"We all remember when ChatGPT first burst onto the scene. The world was captivated by its ability to spit out highly plausible, articulate…","title":"Introduction to Agentic AI: Beyond the Chatbot"},{"content":" Do LLMs Just Pick the Most Likely Next Word?\nIf you ask people this question, nine out of ten will probably say yes.\n“Transformers train on massive amounts of data, run it through complex mechanisms like Attention, and ultimately use statistics to pick the most plausible next word.”\nThat answer is only half right. If Large Language Models (LLMs) really just picked the single “highest probability word” every single time to finish a sentence, the fluent, highly creative AI we see today simply wouldn’t exist.\nOpen up Gemini or ChatGPT right now and type this in:\nFinish this sentence: “Yesterday morning, I woke up and…”\nIf the LLM mathematically selected the most likely word every time, you’d get the exact same response on every attempt. But in reality, it gives you a slightly different answer every time you ask.\nThe Transformer architecture does incredible things, but the real magic happens at the very end of inference — right after all the complex internal calculations are done, and just before the next token hits your screen.\nThis split second is when the LLM decides what to say, choosing which path to walk down among countless branching futures. It’s almost like standing at the crossroads of a multiverse.\nToday, we’re going to dig into how this final stage of inference works and see exactly how sampling parameters like Temperature, Top-k, and Top-p operate in that crucial last millisecond.\n1. The Big Picture: The LLM Inference Pipeline \u0026amp; the Final Split Second Before we talk about sampling parameters, let’s map out the overall pipeline of how an LLM generates a word. We’ll keep it conceptual rather than diving too deep into the nitty-gritty of Transformer math.\nWhen you type in a prompt, roughly the following sequence happens under the hood:\nTokenize: Your text is chopped into smaller pieces (tokens) that the model can digest. Embedding: These pieces are converted into numeric vectors the model can understand. Attention \u0026amp; MLP: Through the Attention mechanism, the model figures out the context and relationships between words. The Multi-Layer Perceptron (MLP) then pulls up the knowledge the model has learned. Final Hidden State: All of this context and understanding is compressed into a final, dense vector. LM Head: This compressed vector is projected across the entire vocabulary dictionary the model knows. Logits: The model calculates a “logit” — a raw score indicating how suitable every single word in its massive dictionary is to be the next word. By this point, the model has assigned a score to every token in its vocabulary, effectively ranking how likely each token is to come next. In other words, it knows exactly who the #1 most likely word is.\nBut as we established earlier, the LLM doesn’t just pick that obvious winner. Doing so often reduces diversity and can make long-form text repetitive.\n2. The Limits of a “First-Place Only” World Technically, in that final step, those raw Logit scores are passed through a function called Softmax, which converts them into statistical probabilities. Simply put, it transforms the scores so that the probabilities of every word — from 1st place to dead last — add up perfectly to 1.0 (or 100%).\nThis process doesn’t change the rankings. First place is still first place; second place is still second place. Only the scale of the values changes.\nThe most intuitive way for the model to pick an answer is just to grab the #1 token (a method known as Greedy Search).\nBut doing this completely kills the model’s creativity. You’d get the exact same words and the exact same results for a given prompt, every single time. Even humans don’t always speak using the most predictable, mathematically probable words.\nAnother massive problem: if you ask a model to write a long article using only this method, the text will become agonizingly repetitive, often getting stuck in endless loops repeating the exact same sentence forever.\n3. Probability-Based Sampling To fix this, we use Random Sampling. The idea is to respect the 1st place winner, but also give 2nd place, 3rd place, and even the token in last place a fighting chance. Of course, 1st place gets the biggest advantage. Second place gets the next biggest, and so on.\nImagine taking every word the LLM knows and building a massive roulette wheel. If the model has a vocabulary of 10,000 words, it’s a roulette wheel with 10,000 slots.\nThe key here is that the width of each slot is sized to match the probability the model calculated. If the #1 word has a 50% probability, it takes up half the entire roulette wheel. If the #2 word is at 10%, it gets 1/10th of the wheel, while the word in dead last gets a sliver so microscopic it’s practically invisible.\nNow, you spin the wheel, and whatever word the “gods of probability” land on is your final result. With this setup, the 1st and 2nd place words are still highly likely to be picked, but the chance of drawing something else isn’t zero. This breathes life and creativity into the model.\nHowever, there is a terrifying trap hidden in this roulette system.\nIt’s a characteristic of language model probability distributions known as the “High probability head + Unreliable tail.”\nLet’s say your prompt is: “I want to visit a famous city like”\nA typical model’s vocabulary contains anywhere from tens of thousands to over a hundred thousand words. If you look at the probability distribution after Softmax, the top few words (the “head”) hold perfectly logical probabilities for the context: “Paris” (45%), “London” (25%), “Rome” (15%).\nThe problem is the endless “tail” that follows. Glued to the roulette wheel are tens of thousands of junk tokens that have absolutely nothing to do with the context — words like “apple” (0.0001%), “spaceship” (0.00001%), or even meaningless strings of random letters — each holding a microscopic fraction of a percent.\nBecause their probability isn’t exactly zero, if you keep spinning that roulette wheel enough times, eventually the ball is going to land on one of these bizarre tokens from the unstable tail.\nImagine you’re spinning the wheel and a totally random, nonsensical token gets picked. Because of the autoregressive nature of Transformers, this bad output immediately becomes part of the next input. The context gets hopelessly tangled, and the quality of the entire output collapses.\nIn short: we need Random Sampling to give the model creativity, but we also desperately need a safety mechanism to control it.\nEnter our sampling parameters: Temperature, Top-p, and Top-k.\n4. Temperature: Shaking Up the Logit Space The first control mechanism we’ll look at is Temperature, which sculpts the overall shape of the probability distribution. Temperature rescales the logits before Softmax.\nThink of it as a dial that decides whether to amplify or reduce the gap between the “rich” (high probability tokens) and the “poor” (low probability tokens).\nLow Temperature (Below 1.0): “The Cold, Conservative Choice” When you set the Temperature below 1.0 (e.g., 0.5), it widens the wealth gap in the probabilities. The probabilities that were already high get even higher, and the small ones sink even lower. Even if the original gap between 1st and 2nd place was small, passing it through a low temperature gives the #1 word absolute dominance. The probabilities of lower-ranked words flatline. As a result, the top words take up massive chunks of the roulette wheel, making them overwhelmingly likely to be chosen. The model outputs safe, consistent, and highly predictable text. This is fantastic when factual accuracy is paramount, like when coding, solving math problems, or translating text. High Temperature (Above 1.0): “The Free-Spirited Artist” Conversely, turning up the heat shrinks the inequality gap. The crushing dominance of the #1 word is reduced, while the suppressed probabilities of the 2nd, 3rd, 4th, and even lower-tier words are pulled up. Because a much wider variety of words now have a fighting chance on the roulette wheel, the model starts spitting out unpredictable, fresh, and creative ideas. 5. Top-K: The Cutthroat Survival Audition Even if you tweak the overall highs and lows with Temperature, you still have tens of thousands of low-probability words lingering in the tail. No matter how low you drop the temperature, those probabilities never truly hit zero.\nTo completely amputate this tail and stabilize the sampling process, we use Top-k.\nThe mechanism works exactly like a survival reality show.\nThe model ranks every single word candidate in descending order of probability. Then, it keeps only the top ‘K’ words that you set, and ruthlessly deletes the tens of thousands of words that didn’t make the cut.\nFor example, if you set K=50, the top 50 words survive — no matter how high or low their actual probabilities are. The model then takes the probabilities of those surviving 50 words, mathematically readjusts them so they equal 100%, and builds a brand new roulette wheel using only them. Since everyone from rank 51 onwards was evicted, the surviving 50 split the remaining space proportionally.\nThis entirely eliminates the risk of picking those weird, context-destroying tokens deep in the tail.\nThe Limitation:\nHowever, Top-k has a fatal flaw: it is painfully inflexible.\nSometimes you have a “narrow context” where there are realistically only 2 or 3 valid next words (like “Yes” or “No”). Other times, you have an “open-ended context,” like writing a novel, where hundreds of different words would work perfectly fine.\nIf you lock K=50, the model is forced to keep 50 candidates alive even when there are clearly only 2 right answers, unnecessarily introducing noise. On the flip side, in an open context where it should be flexing its imagination, it’s artificially suffocated to just 50 options.\n6. Top-P: The Pursuit of Flexibility To elegantly solve Top-k’s fixed-cutoff problem, Top-p stepped onto the scene.\nInstead of just chopping the list at a hard rank (like the top 50), Top-p cuts off the candidates based on “Cumulative Probability” — meaning it adds the probabilities together as it goes down the list.\nIf that sounds a bit dense, let’s break it down. Imagine you set your P value to 0.9 (or 90%).\nFirst, the model sorts the words from highest to lowest probability. It starts dropping them into a “probability bucket,” starting with 1st place, adding their probabilities together as it goes. The exact second the total probability inside the bucket hits 90%, the model slams the door. Any remaining words (the tail) are tossed out. “Bucket is full, try again next time.” Let’s look at why this simple shift makes the model incredibly flexible:\nObvious Answers (High Confidence): What if the #1 word alone has an 85% probability, and #2 has 6%? The model drops both into the bucket, hitting 91%. That instantly crosses the 0.9 threshold! So, it naturally leaves only 2 candidates and trashes the rest. It perfectly prevents context collapse in narrow situations. Diverse Expressions (Low Confidence): What if the probabilities are super fragmented? Say 1st place is 5%, 2nd is 4%, 3rd is 3.5%, and so on. To reach that 90% cumulative threshold, the model has to keep scooping dozens or even hundreds of words into the bucket. The candidate pool dynamically widens, allowing the model to maximize its creativity to fit the situation. By dynamically adjusting the size of the candidate pool based on its own confidence, Top-p has cemented itself as a top-tier sampling technique.\n7. The Rise of Min-P Of course, the research hasn’t stopped there. Min-p has recently gained popularity in open-weight LLM communities because it adapts the cutoff relative to the model’s confidence.\nSo, what is Min-p?\nIf Top-p uses the “sum of cumulative probability” as its threshold, Min-p sets the cutoff based on a relative ratio to the top word’s probability.\nLet’s say you set Min-p to 0.05 (5%).\nIf the model is highly confident and the #1 word has an 80% probability, the cutoff becomes 5% of that 80% (which is 4%). Any token with a raw probability below 4% is considered part of the tail and thrown away.\nConversely, if the context is wide open and the #1 word only has a 20% probability, the cutoff drastically drops to 1% (5% of 20%).\nIn short, the cutoff dynamically scales in direct proportion to “how confident the #1 token is.”\nMany users of recent open-weight models report that Min-p often produces more coherent outputs in certain settings, although the optimal sampling strategy remains model-dependent.\n8. Practical Combinations in the Wild So, how do you actually use these parameters in the real world? First, you need to understand how the specific framework you’re using applies them.\nSome frameworks apply them in the order of Temperature -\u0026gt; Top-k -\u0026gt; Top-p -\u0026gt; Final Sampling, while others might use a totally different sequence. Some APIs don’t even let you touch Top-k at all.\nJust because an API gives you all these dials doesn’t mean you should crank them all at once. Temperature, Top-p, and Min-p are all pulling towards the exact same goals: controlling “randomness” and “creativity.”\nIf you tweak all of them simultaneously, it becomes literally impossible to figure out which variable actually changed your output.\nIn practice, many systems use Temperature and Top-p together. However, when experimenting, it’s often easier to tune one parameter at a time to understand its individual effect.\nWhen writing code or extracting hard facts, drop the Temperature close to 0 to lock in consistency. When you’re writing a novel or brainstorming marketing copy, leave Temperature at 1.0 and open up the Top-p or Min-p values to unleash the model’s full potential. This keeps your variables isolated and your results much easier to control.\nWrapping Up If you’ve ever played around with LLM APIs, you’ve likely seen the classic advice: “To reduce randomness, lower temperature and top-p; to increase creativity, raise them.” More often than not, people just slide these values around blindly without knowing why.\nHopefully, this post gave you a clear look under the hood at how these numbers actually shape what an LLM says, and helps you master your own inference parameters going forward!\n","permalink":"https://blog.jiminl.com/posts/temperature-top-k-top-p-min-p-the-hidden-dials-behind-every-llm-response-34698ef440c3/","summary":"Do LLMs Just Pick the Most Likely Next Word?","title":"Temperature, Top-k, Top-p, Min-p: The Hidden Dials Behind Every LLM Response"},{"content":"If you’ve spent any time poking around large language model (LLM) infrastructure, you’ve probably heard the mantra: “LLMs are memory bandwidth bound.”\nThis means that the reason your AI feels sluggish isn’t because the GPU lacks computing power, but because the memory speed simply can’t keep up. While true, this doesn’t paint the full picture of how LLM computations actually work.\nToday, we’re going to dig into why LLMs are trapped in this “Memory Bandwidth Bound” box rather than a “Compute Bound” one, and explore the ingenious ways engineers around the world are trying to break through this bottleneck.\n1. Where It All Began: The Von Neumann Dilemma Before we talk modern systems, we need to revisit the granddaddy of computer architecture: the Von Neumann Architecture. Its core philosophy — physically separating the compute unit from the memory — is the root of our current bottleneck.\nImagine a massive Amazon fulfillment center:\nCompute Unit (GPU): An ultra-fast robotic arm that scans thousands of boxes per second. Memory: A colossal warehouse packed with goods. Memory Bandwidth: The conveyor belt connecting the warehouse to the robot. When an order comes in, the warehouse manager finds the box and puts it on the belt. The robot scans it in a microsecond. Then… it stops and waits. “Next box, please? I’m already done.”\nNo matter how fast the robot is, the total output of our fulfillment center is entirely bottlenecked by the speed of the conveyor belt.\n2. Enter the GPU, and a Difficult Guest Named “LLM” To fix this, GPUs hired thousands of cheap, specialized robots instead of one versatile one, processing massive piles of boxes simultaneously. During AI Training, this works perfectly. Bulk orders come in (Batch Processing), forklifts dump mountains of boxes at once, and the robots work at 100% capacity in a true Compute Bound state.\nThe Auto-regressive Nightmare But LLM Inference — the real-time chatting you do with ChatGPT or Claude — is a different beast. From a hardware perspective, LLMs have a terrible habit: they are Auto-regressive. They don’t write sentences all at once; they generate answers one token (word) at a time, feeding each new word back into the system to predict the next.\nThis loop creates a hardware nightmare. Take a 175-billion parameter model. Stored in 16-bit precision (FP16), it takes up about 350GB. To calculate just one single word, the GPU must stream that entire 350GB of data down the conveyor belt layer by layer.\nBack to our warehouse: An order comes in for one box. The robot waits for all 350GB worth of boxes to roll down the belt, inspects all of them just to scan one barcode, and then does it all over again for the next word. The actual math takes milliseconds; fetching the warehouse takes an eternity.\nThis is why LLM inference is currently drowning in the Memory Bandwidth Bound swamp, despite having access to the fastest compute engines on earth.\n3. The Two Faces of LLM Inference: Prefill vs. Decoding The process of generating an LLM response is actually split into two distinct phases, and they utilize hardware in completely different ways.\nPhase 1: Prefill — “Reading the giant order form” (Compute Bound) Imagine you hand an LLM a 50-page PDF or a massive block of code and say, “Summarize this.”\nDuring this phase, the GPU can process all the input text (tokens) simultaneously in parallel. Because the text is already there, the model doesn’t need to predict the future; it can calculate how all these words relate to each other (Attention) all at once.\nIn our warehouse, this is like a mail truck dumping tens of thousands of order forms onto the floor at once. The conveyor belt is never empty, and the robots are working so fast their motors are catching fire. This phase is perfectly Compute Bound. Your multi-thousand-dollar GPU is doing exactly what you paid for — multiplying giant matrices at warp speed.\nPhase 2: Decoding — “Writing the response word-by-word” (Memory Bound) Once the input is read, the LLM starts generating the summary. Here is where the auto-regressive trap springs. It must spit out one word at a time.\nFor every single word, it has to pull the entire 350GB warehouse of weights off the shelves. This phase is the definition of extreme Memory Bandwidth Bound.\nHow Does This Feel to the User (UX)? How does this hardware reality translate to your screen?\nWhen you hit ‘Enter’ and the chatbot pauses for a moment — that’s the Prefill phase. When it finally starts typing like a slow typewriter and you get frustrated — that’s the Decoding phase choking on memory bandwidth.\nEngineers track this user experience using two core metrics:\nTTFT (Time To First Token) — “Why isn’t it answering?”\nMeaning: The time between hitting enter and the first word appearing on screen. UX: This relies entirely on the Prefill speed. It’s the time it takes the GPU to chew through your massive PDF. If TTFT is too long, users think the app is broken. TPOT (Time Per Output Token) — “Why is it typing so slowly?”\nMeaning: The speed at which words are generated after the first one appears (often called Generation Rate). UX: This is dictated entirely by Decoding (your memory conveyor belt speed). The average human reads about 4 to 5 words per second. If the TPOT is slower than human reading speed, the user is left twiddling their thumbs. If it pushes 20–30 tokens a second, the AI feels incredibly snappy and “smart.” 4. The Roofline Model A highly regarded research paper titled “LLM Inference Unveiled: Survey and Roofline Model Insights” tackles this systematically. The researchers built a simulation tool called ‘LLM-Viewer’ to map out the exact bottlenecks layer by layer.\n4.1. The Axes and the Roofs The Roofline model is a 2D graph that maps system limitations, literally looking like a roof.\nDemonstration of the Roofline model of Nvidia A6000 GPU. The computation is in FP16. from https://arxiv.org/html/2402.16363v6 X-axis: Arithmetic Intensity (OPs/Byte): How many calculations (operations) the GPU performs for every 1 byte of data it pulls from memory. If you reuse the data a lot, intensity is high. Y-axis: Attainable Performance (FLOPs/s): The actual compute speed the system can achieve. The graph has two physical “roofs” (limits):\nThe Slanted Roof (Left): Performance here is completely capped by Arithmetic Intensity × Peak Memory Bandwidth. If your calculation intensity is low, you are trapped under this slope. This is the Memory-Bound zone. The Flat Roof (Right): The hard ceiling of the hardware’s maximum compute capability. If you hit this line, your GPU is working at 100% capacity. This is the Compute-Bound zone. (Note: For an NVIDIA RTX A6000 running in FP16, the graph shows you need an arithmetic intensity of about 200 OPs/Byte before you can start utilizing 100% of the GPU’s compute power.)\n4.2. The Ridge Point (The Cut-off) The exact spot where the slanted roof meets the flat roof is the Ridge Point. This is the minimum arithmetic intensity required to fully saturate the GPU.\nRidge Point = Peak Compute Performance / Peak Memory Bandwidth\nLet’s plug in the specs for an NVIDIA H100 GPU:\nPeak Compute: ~1,979 TFLOPS (using BF16 Tensor Cores with sparsity) Peak Memory Bandwidth: ~3.35 TB/s (HBM3) H100 Ridge Point: 1,979 / 3.35 ≈ 591 FLOPs/Byte This means for the H100 to actually work at 100% capacity, it must perform at least 591 math operations for every single byte of data it fetches. If it doesn’t, it slides down the slanted roof into Memory-Bound territory.\n4.3. What the Data Actually Shows Using LLM-Viewer, researchers proved how drastically different the two phases of LLM inference are:\nAnalysis for layers in Llama-2–7b using the Roofline model of Nvidia A6000 GPU. In this example, the sequence length is 2048 and the batch size is 1. from https://arxiv.org/html/2402.16363v6 Prefill Phase: Because it processes thousands of tokens in parallel, it pulls data once and multiplies it against many different tokens. The arithmetic intensity easily blasts past 591, comfortably parking on the right-side flat roof (Compute-Bound). Decoding Phase: Generating a single word requires reading the entire model, plus fetching the ever-expanding context of the conversation (KV-Cache). It moves massive amounts of data onto the conveyor belt just to do a tiny bit of math. The arithmetic intensity plummets to roughly 1 to 10 FLOPs/Byte. It crashes to the bottom-left of the slanted roof (Memory-Bound), meaning over 90% of the H100’s legendary computing power simply evaporates into thin air. 5. The Software Counterattack: “Let’s use the conveyor belt less!” Software engineers aren’t just sitting around accepting defeat. If the conveyor belt is narrow, the goal is to figure out how to put lighter boxes on it, or how to cram more boxes into a single trip.\n1) Compress the Boxes: Quantization\nThe most widely used tactic. Instead of storing data as standard 16-bit numbers (FP16), engineers crush them down to 8-bit (FP8), 4-bit (INT4), or even extreme 1-bit/1.58-bit levels (like the recent breakthroughs with BitNet). This allows you to shove 4x to 10x more data down the same conveyor belt at once. While early quantization made models noticeably dumber, modern techniques preserve the AI’s intelligence while effectively nuking the bandwidth bottleneck.\n2) Put the Idle Robots to Work: Speculative Decoding\nEngineers realized: “The main robot is just sitting there waiting for memory. Let’s make it guess the future!” You put a tiny, fast “Draft Model” next to the massive “Target Model.” The tiny model uses barely any memory and rapidly guesses the next few words (e.g., “The”, “apple”, “tree”). When the massive 350GB memory finally arrives, the main robot checks all three guessed words in parallel. If the guess is correct, you just generated three words for the memory-cost of one. It’s basically magic.\n3) Stop Taking Things Out of the Warehouse: FlashAttention\nHistorically, when calculating the relationships between words (Attention), GPUs would write intermediate math steps back to the main memory (HBM) and read them back again. FlashAttention rewrote the algorithm to say: “Stop going outside! Do all the intermediate math inside the ultra-fast, tiny on-chip cache (SRAM), and only send the final answer out.” This slashed unnecessary trips on the conveyor belt.\n4) Optimize the Past: KV Cache Optimizations (GQA \u0026amp; Prompt Caching)\nTo avoid re-reading the entire conversation history for every new word, LLMs save the context in memory (the KV Cache). As models now support millions of tokens of context, this cache can actually grow larger than the model itself!\nTo fix this, modern architectures use Grouped Query Attention (GQA) to share and compress this memory. Furthermore, API providers now use Prompt Caching to “freeze” the math for frequently used prompts, massively lightening the load for both Prefill and Decoding.\n6. The Hardware Revolution Hardware engineers have another plan: if memory bandwidth is the problem, build a massive memory bandwidth.\n1) HBM (High Bandwidth Memory): Building Superhighways\nIf old-school DRAM was a warehouse miles away, HBM is a skyscraper warehouse built directly on top of the GPU factory. By drilling microscopic holes through the silicon, they hardwire thousands of data lanes straight into the chip. The reason NVIDIA’s new Blackwell (B200) chip boasts double the bandwidth of the H100 (over 8 TB/s) is entirely thanks to next-gen HBM3e and HBM4 technologies.\n2) NVLink \u0026amp; CXL: The Giant Mega-GPU\nBecause putting memory on a single chip has physical limits, the industry is moving to Rack-scale optimization. Systems like NVIDIA’s GB200 NVL72 stitch dozens of GPUs together with ultra-high-speed copper cables (NVLink). To the software, it looks like one singular, monstrous GPU with terabytes of memory and infinite bandwidth. Additionally, standards like CXL (Compute Express Link) are emerging to allow chips to dynamically borrow memory from data center pools.\n3) LPU (Groq): “What if we just demolish the warehouse?”\nCompanies like Groq are taking radical approaches with LPUs (Language Processing Units). Their philosophy? “Even with an HBM superhighway, going off-chip is still a bottleneck. Let’s delete the external warehouse entirely.”\nThey rely entirely on SRAM — the blazing-fast memory located directly inside the processor. They achieve internal bandwidths dozens of times faster than an H100, resulting in response speeds that flow like a waterfall.\nThe catch? Because chips have very little internal memory, running a massive model requires networking hundreds of chips together, which is incredibly complex and expensive. Still, they are dominating the “Ultra-Low Latency” niche.\n4) PIM (Processing-in-Memory): “Just put a calculator in the warehouse!”\nEven with an 8-lane superhighway, moving giant datasets out of memory is inefficient. So, engineers are flipping the paradigm with PIM: embedding compute units (ALUs) directly inside the memory chips themselves.\nInstead of moving heavy data to the GPU to do simple matrix multiplication, the memory does the math internally. The heavy data never gets on the conveyor belt, magically erasing the bandwidth bottleneck and drastically reducing power consumption.\n7. Conclusion: The Future is a Great Logistics Network As we’ve seen, LLM inference isn’t just about how fast a chip can crunch numbers. The true battleground is deciding “who can build the widest conveyor belt” and “who can pack the boxes most efficiently.”\nThis is why global memory manufacturers are betting their lives on HBM yields, why NVIDIA is just as obsessed with networking cables (NVLink) as they are with teraflops, and why AI researchers pull all-nighters trying to shrink models down to 1-bit sizes. They are all trying to shatter the “Memory Bandwidth Bound” ceiling.\nBecause at the end of the day, even if your genius robotic arm can scan trillions of barcodes a second, if the boxes don’t arrive on time, it’s just the most expensive unemployed worker in the world.\n","permalink":"https://blog.jiminl.com/posts/what-does-llms-are-memory-bandwidth-bound-really-mean-4a1a57161b53/","summary":"If you’ve spent any time poking around large language model (LLM) infrastructure, you’ve probably heard the mantra: “LLMs are memory…","title":"What Does “LLMs Are Memory Bandwidth Bound” Really Mean?"},{"content":"The evolution of deep learning and the advancement of GPUs go hand in hand. While this has always been true, in the current era of AI — driven by Large Language Models (LLMs) — this relationship is more critical than ever.\nI previously touched on why GPUs are so perfectly suited for AI in my post, Why GPUs Ate the AI World. Today, we’re going a level deeper. Let’s look under the hood of Nvidia GPUs and break down exactly what makes them so incredibly fast at running deep learning models.\n1. General-Purpose Cores vs. Special-Purpose Cores Every calculation in a GPU happens inside a core. The basic workflow is simple: move data from memory to the core, crunch the numbers, and write the results back to memory.\nHowever, modern GPUs have evolved their cores specifically to handle the unique quirks of deep learning computations.\nThe Swiss Army Knife: CUDA Cores First, let’s look at the CUDA Core, which handles traditional scalar operations. With all the recent hype around AI accelerators built for matrix math, it’s easy to forget about the CUDA Core. But its role is absolutely indispensable.\nIf you tear down the execution pipeline of an LLM, you’ll find essential tasks sandwiched between those massive matrix multiplications. We’re talking about calculating activation functions (like ReLU or GELU), normalizing data distributions (LayerNorm), converting logits into probabilities (Softmax), and managing the complex control flow required by Attention mechanisms.\nAll of these tasks run on CUDA Cores. Without them, your deep learning pipeline would grind to a halt.\nThe Heavy Artillery: Tensor Cores On the flip side, over 90% of modern deep learning operations consist of gigantic matrix multiplications. To accelerate this, modern GPUs deploy a specialized task force: the Tensor Core. Tensor Cores can’t do as many different types of math as CUDA Cores, but they multiply matrices at face-melting speeds. They essentially exist to say, “I don’t care about anything else; I was born to multiply matrices!”\nThe secret sauce of the Tensor Core is FMA (Fused Multiply-Add). In deep learning, the most common operation is multiplying values and adding them to another value.\nD = A * B + C\nIn traditional computing, you would multiply the numbers, save the result to a temporary register, and then perform the addition.\nTensor Cores, however, fuse these matrix multiplications and additions into a single, physical hardware instruction. Doing two things at once creates a kind of hardware magic:\nFirst, pipeline throughput goes through the roof. It saves clock cycles and significantly reduces power consumption.\nSecond, it preserves numerical precision. In a non-fused approach, you have to round the decimal point immediately after the multiplication step before you can add. Fused operations perform the math with full precision internally and only round the numbers once at the very end. This prevents rounding errors from snowballing out of control.\nUltimately, a Tensor Core is just a massive engine made up of hundreds of these fused units, designed to chew through massive matrix math in one gulp.\n2. Saving Memory Bandwidth with Low Precision As mentioned earlier, to do math, you have to physically move data from memory to the processor. But your memory bandwidth is a fixed “highway,” meaning there’s a hard limit on how many “delivery trucks” can pass through at once.\nWhat’s the most intuitive way to fix this?\nShrink the cargo. By using low-precision data formats, we shrink the footprint of the data, allowing us to pack way more numbers onto those delivery trucks.\nUse Only What You Need The 32-bit floating-point (FP32) format, once the gold standard for scientific computing, is simply too bloated for deep learning. The industry shifted to 16-bit (FP16), and now we are down to 8-bit (FP8). By swapping FP16 for FP8, you cut bandwidth usage in half, allowing you to feed twice as much data into the Tensor Cores in the exact same amount of time, using the exact same hardware.\nBut naturally, dropping bits increases calculation errors. So, how do we get around that?\nNvidia engineers came up with a brilliant compromise: Mixed Precision. The input data sent into the math units is compressed down to FP8. However, the “Accumulator” circuit — the part that constantly adds up the running totals — is designed to operate at a much higher precision, like FP32 or at least FP16. This gives us the best of both worlds: we save massive amounts of memory bandwidth without destroying the mathematical integrity of the final output.\nThis works because, statistically, the precision of a single input value doesn’t matter too much, but the precision of the accumulator — where millions of tiny values pile up — matters immensely.\nDynamic Precision and the Transformer Engine It goes even deeper. Even within the FP8 format, there are two distinct variations based on what you’re trying to do: E4M3 and E5M2.\nFor forward passes and inference — where precision is more important than representing gigantic numbers — the GPU uses E4M3 (4 exponent bits, 3 mantissa bits). For backward pass training — where you might lose a little detail but absolutely need the dynamic range to capture tiny gradients or massive spikes — it switches to E5M2 (5 exponent bits, 2 mantissa bits).\nThis is where Nvidia’s Transformer Engine steps in. It’s a software layer that analyzes the statistical distribution of data at every layer of the model. It performs intelligent scaling: automatically dropping to 4-bit or 8-bit to save bandwidth where it’s safe to do so, and automatically scaling back up to higher bit depths in layers where precision is a matter of life and death.\nBlackwell Ultra SM architecture (https://developer.nvidia.com/blog/inside-nvidia-blackwell-ultra-the-chip-powering-the-ai-factory-era/) 3. The Factory Floor: The SM (Streaming Multiprocessor) Pulling data directly from the GPU’s main memory is an agonizingly slow and expensive process. To fix this, GPUs use independent production lines called SMs (Streaming Multiprocessors), which are engineered for extreme efficiency.\nIf a GPU is a massive industrial city, an SM is an independent mega-factory operating within it.\nHere is how the inside of an SM is laid out:\nThe Brains: Warp Scheduler and Dispatch Unit The basic unit of execution on a GPU is called a Thread. It’s conceptually similar to a CPU thread, but it’s an ultra-lightweight version purpose-built for the GPU.\nWhile a CPU might run a few dozen or a few hundred threads at once, a GPU runs hundreds of thousands, or even millions, of threads simultaneously. Because managing millions of individual threads is chaotic, the GPU groups them into manageable bundles called “Warps.” A Warp typically consists of 32 threads, and every thread in a Warp is forced to execute the exact same instruction at the exact same time.\nFor example, 32 threads tasked with adding two numbers are bundled into one Warp. The GPU issues a single command to the Warp, and all 32 threads simultaneously add their specific pairs of numbers. This architecture is called SIMT (Single Instruction, Multiple Threads).\nTo manage this, the SM has a Warp Scheduler and a Dispatch Unit. The Scheduler monitors the status of dozens of Warps every single clock cycle. The moment it sees that a Warp has received all its necessary data from memory and is ready to work, the Dispatch Unit instantly fires that Warp’s instructions directly into the execution units.\nThe Register File The SM contains a massive Register File, which is hundreds of times faster than the GPU’s main memory. When threads are launched, they store their local variables directly in these registers, allowing them to do math at blisteringly fast speeds without waiting on slow main RAM.\nHowever, there is a catch: if a developer writes bloated code that requires too many registers per thread, the SM can’t physically fit as many Warps inside it. This drops “occupancy,” meaning there’s less work available to feed the execution units, leaving expensive hardware sitting idle.\nExecution Units These are the actual blue-collar workers that execute the math when the Dispatch Unit tells them to:\nTensor Core: The massive engine handling matrix multiply-accumulate pipelines at the Warp level. CUDA Core: The general-purpose unit handling control flow, logic, and standard scalar math. LD/ST (Load/Store Unit): The logistics team dedicated strictly to fetching and saving data from memory. Supercharging Efficiency The SM utilizes data caches and shared memory to aggressively cut down on the time wasted moving data around.\nTiling: Instead of fetching data from main memory over and over, the LD/ST unit grabs a chunk (Tile) of a matrix just once and places it into the SM’s hyper-fast Shared Memory. From then on, the Tensor Cores just rapidly cycle data in and out of that local Shared Memory. This maximizes math operations while minimizing memory fetches — a concept known as increasing “arithmetic intensity.” TMA (Tensor Memory Accelerator): Introduced in architectures like Hopper, TMA is dedicated hardware that handles memory copying asynchronously in the background. It frees up the cores so they can dedicate 100% of their time to crunching numbers rather than hauling data. TMEM (Tensor Memory): Starting with the Blackwell architecture, Nvidia slapped a dedicated 256KB block of SRAM directly next to the Tensor Core. Previously, moving intermediate results between registers and shared memory created a bottleneck. Now, the Tensor Core has its own exclusive stash to dump and retrieve data instantly. 4. Software: CUDA Hardware this complex requires an orchestrator, and that is where CUDA (Compute Unified Device Architecture) comes in. It’s the programming interface that lets developers direct the hardware.\nCPUs and GPUs have entirely different work ethics. If CPU threads are a handful of Michelin-star chefs who meticulously cook a complex 5-course meal from start to finish, GPU threads are an army of 100,000 prep cooks whose only job is to chop carrots simultaneously.\nDevelopers write CUDA code (usually in C++) to define what this army does.\nLet’s look at a basic addVectors script—a program that adds two arrays (A and B) of 1,000,000 numbers to create array C—to see how the whole pipeline connects.\nStep 1. Writing the Kernel: The Work Order First, we write a single function that millions of threads will execute identically. The __global__ keyword tells the compiler: \u0026quot;The CPU will call this function, but the GPU will actually execute it.\u0026quot;\nThis GPU-executed function is called a Kernel.\n#include \u0026lt;iostream\u0026gt; #include \u0026lt;cuda_runtime.h\u0026gt; // [Kernel Definition] The work order for the GPU threads __global__ void addVectors(float* A, float* B, float* C, int N) { // 1. Global Indexing: Figure out exactly which piece of data *this specific thread* should process int i = blockIdx.x * blockDim.x + threadIdx.x; // 2. Boundary Check: Make sure we don\u0026#39;t try to calculate past the total number of items (N) if (i \u0026lt; N) { // 3. The actual math (This is where the CUDA core fires) C[i] = A[i] + B[i]; } } Step 2. Running the Pipeline: The CPU (Host) Code Before looking at the next block of code, you need to understand Grids and Blocks.\nDumping a million threads onto a chip with no structure is a recipe for chaos. Therefore, CUDA organizes threads into a 3-tier hierarchy:\nThread: The individual worker (e.g., a single prep cook). Block: A group of threads working together (e.g., a team of 256 cooks). All threads in the same block are assigned to the same SM, meaning they can talk to each other via Shared Memory. Grid: A collection of Blocks. It represents the entire workspace created by a single kernel launch. All blocks in a grid share the GPU’s global memory (VRAM). Now, let’s look at the host code. We allocate memory, calculate the thread layout, and fire the kernel over to the GPU.\nint main() { int N = 1000000; // 1 million data points size_t size = N * sizeof(float); // 1. Allocate and initialize memory on the CPU (Host) float *h_A = new float[N]; float *h_B = new float[N]; float *h_C = new float[N]; for (int i = 0; i \u0026lt; N; i++) { h_A[i] = 1.0f; h_B[i] = 2.0f; } // 2. Allocate memory on the GPU (Device Global Memory / VRAM) float *d_A, *d_B, *d_C; cudaMalloc((void**)\u0026amp;d_A, size); cudaMalloc((void**)\u0026amp;d_B, size); cudaMalloc((void**)\u0026amp;d_C, size); // 3. Data Transfer (Host to Device): Copy data from CPU RAM to GPU VRAM // *Note: This is where massive PCIe bandwidth bottlenecks usually happen!* cudaMemcpy(d_A, h_A, size, cudaMemcpyHostToDevice); cudaMemcpy(d_B, h_B, size, cudaMemcpyHostToDevice); // ========================================================= // 4. [The Core Concept] Setting up the Thread Hierarchy // ========================================================= // The developer decides to group 256 threads into a single block. int threadsPerBlock = 256; // How many blocks do we need to process 1,000,000 items? // We use integer division with a ceiling formula: (N + threads - 1) / threads int blocksPerGrid = (N + threadsPerBlock - 1) / threadsPerBlock; // Math check: 1,000,000 / 256 = 3906.25 -\u0026gt; We need 3,907 blocks. // 5. Kernel Launch: \u0026lt;\u0026lt;\u0026lt;Blocks, Threads per Block\u0026gt;\u0026gt;\u0026gt; // Right now, 3,907 blocks * 256 threads = 1,000,192 threads are instantiated on the GPU. addVectors\u0026lt;\u0026lt;\u0026lt;blocksPerGrid, threadsPerBlock\u0026gt;\u0026gt;\u0026gt;(d_A, d_B, d_C, N); // 6. Return Data (Device to Host): Bring the computed results back to the CPU cudaMemcpy(h_C, d_C, size, cudaMemcpyDeviceToHost); // 7. Clean up memory cudaFree(d_A); cudaFree(d_B); cudaFree(d_C); delete[] h_A; delete[] h_B; delete[] h_C; return 0; } Step 3. What happens in the GPU when this runs? The exact millisecond you execute that main function, all the hardware architecture we discussed wakes up:\nCUDA Launch (\u0026lt;\u0026lt;\u0026lt;3907, 256\u0026gt;\u0026gt;\u0026gt;): The GPU's global scheduler spawns 3,907 blocks. SM Distribution: These blocks are distributed evenly across the dozens of SMs on the chip. Warp Splitting: Once a block of 256 threads lands inside an SM, it is immediately chopped into groups of 32, creating 8 Warps. Residency: These Warps claim their space in the SM’s Register File and become “resident.” Execution: The Warp Scheduler watches them, and the Dispatch Unit fires them into the execution units (CUDA cores, in this simple addition example) the moment their data arrives. With just a few lines of code, you’ve orchestrated a million parallel operations across tens of thousands of physical cores.\nBut it doesn’t stop there. There is one final software optimization happening in the background to keep everything moving.\n5. Hiding the Memory Bottleneck You can increase bandwidth, compress data, and use tiling, but you can never overcome the speed of light. The physical latency required to fetch data from memory will never be zero. This is especially painful during the Decode phase of LLM generation, which is notoriously memory-bound.\nTo fight this, GPUs use another trick: if you have to wait for memory, do something else while you wait.\nZero-Overhead Context Switching If a CPU thread stalls because it’s waiting on RAM, the operating system intervenes and performs a “context switch.” It saves the thread’s current state to memory and loads a new thread’s state. This is a very heavy, expensive operation.\nGPUs do the same thing, but they do it almost instantly.\nResidency: Inside an SM, dozens of Warps have already checked into the “hotel.” Their data is fully loaded into the local registers. They are resident. Instant Swapping: Let’s say Warp #1 is doing math, realizes it needs a chunk of data from VRAM, and stalls. Instead of doing a heavy backup process like a CPU, the GPU’s Warp Scheduler just points to Warp #2 and says, “You’re up.” Because Warp #2 is already resident and has its local variables loaded in the registers, the switch happens with virtually zero overhead. By having an army of Warps sitting in the registers ready to go, the GPU can perfectly hide memory latency. Whenever one Warp stalls waiting for a delivery, another Warp seamlessly tags in to keep the math cores fed at 100% utilization.\n6. Summary: The Deep Learning Pipeline Let’s pull all of this together and see how these hardware and software components orchestrate a modern LLM inference or training run.\nData Loading: Hundreds of gigabytes of model parameters are loaded into the VRAM (Global Memory). Kernel Execution: The PyTorch/CUDA code launches, generating hundreds of thousands of Threads that calculate their specific target data locations. Warp Residency: Threads are bundled into groups of 32 called Warps, which immediately take up residence in the ultra-fast registers inside the SMs. Tiling Efficiency: The TMA hardware works in the background, hauling chunks of matrix data from VRAM into local Shared Memory and TMEM. The data is recycled locally to maximize math operations per byte fetched. Warp Scheduling: When Warps inevitably stall waiting on memory (like in the Decode phase), the Warp Scheduler instantly swaps in a fresh Warp. This zero-overhead switching keeps the execution units constantly fed. High-Speed Math: Data packed efficiently into FP8 (or smaller) formats floods into the FMA (Fused Multiply-Add) units inside the Tensor Cores, yielding massive throughput. Returning Results: The mixed-precision accumulators (running in FP32) ensure the math stays accurate. The final results are routed back through Shared Memory to their final destination. Wrapping Up Modern GPUs didn’t come to dominate deep learning just by cramming more cores onto a piece of silicon.\nThey won by using an elegant, highly orchestrated fusion of hardware and software to solve the physics problems of memory bandwidth and latency — specifically the massive memory-bound bottlenecks that plague LLMs.\nAs an engineer, looking past the Python code and understanding exactly where the silicon breathes and where the bottlenecks choke is more than just trivia. In the AI era, that deep system-level insight is the ultimate weapon for breaking through performance ceilings.\n","permalink":"https://blog.jiminl.com/posts/how-modern-gpus-accelerate-deep-learning-and-llms-3710e8c77d64/","summary":"The evolution of deep learning and the advancement of GPUs go hand in hand. While this has always been true, in the current era of AI —…","title":"How Modern GPUs Accelerate Deep Learning and LLMs"},{"content":"You’ve carefully built your deep learning model, and it only has a few hundred megabytes of parameters. But the moment you hit “train” and run nvidia-smi, you’re in for a shock—your GPU memory usage instantly spikes into the gigabytes.\nSpoiler alert: This is completely normal. In fact, if your memory usage during training is roughly the same as your model’s weight size, it usually means your model isn’t actually training!\nWhy does this happen? Because unlike inference, training isn’t just about holding weights and running a forward pass. The core of training is calculating derivatives to update the model, and doing so requires leaving a massive trail of historical data in your GPU memory.\nToday, we’re going to break down the main culprits behind GPU memory consumption during training and explain exactly why this happens.\n1. It’s Not Just the Model Taking Up Space What we casually call “model size” (the weights and biases) is actually just the tip of the iceberg when it comes to total training memory.\nWhen you train a deep learning model, the things hogging your GPU VRAM generally fall into four main buckets:\nModel Weights: The model itself. Gradients: The calculated derivatives used to update the weights. Optimizer States: The historical tracking data kept by algorithms like Adam. Intermediate Activations: The values computed during the forward pass, saved specifically for the backward pass. Let’s look at how each of these takes a bite out of your memory.\n2. Weights and Gradients Weights are straightforward. They’re the chunks of parameters for the layers we defined. In deep learning, we typically use 32-bit floating-point numbers (float32), which take up 4 bytes each.\nSo, how much memory do you need just to hold a 1-Billion parameter (1B) model?\n1 parameter = 4 bytes. 1 Billion parameters * 4 bytes = 4 GB.\nBut it doesn’t stop there. Enter the gradients.\nTraining a model means incrementally tweaking its weights via backpropagation. To know how to tweak a weight, we have to calculate: “How much should I change this parameter to decrease the loss?” That value is your gradient.\nThe kicker here is that for every single weight parameter, you need a corresponding gradient value. So, gradients double your baseline memory footprint.\nFor a 1B model: Weights (4 GB) + Gradients (4 GB) = 8 GB of memory.\nWhile techniques like Mixed Precision or certain optimizations can alter these ratios, the fundamental rule remains: you always need dedicated space to store derivatives.\n3. Optimizer States: Adam is a Memory Monster The next big memory hog is your optimizer.\nSGD is lightweight, but Adam is heavy.\nAdam (and its variant AdamW) are the go-to optimizers for training modern models. You don’t need to know the deep math behind Adam for this discussion, but here is the crucial takeaway:\nAdam maintains two extra states for each parameter:\nMomentum: Which direction were we heading last time? Variance: How big were our steps? Adam is smart because it doesn’t just look at the current gradient; it uses momentum and variance to remember past movements. However, this intelligence comes at a steep cost: two additional numbers stored per parameter.\nIf you are training with standard Adam, here is your per-parameter math:\nWeight: 4 bytes Gradient: 4 bytes Momentum: 4 bytes Variance: 4 bytes That’s a total of 16 bytes per parameter! Your memory footprint is now 4 times the size of the original model weights. That 1B parameter model now demands 16 GB of VRAM just to exist in the training loop.\nRecently, the community has tackled this with 8-bit Optimizers. These compress the optimizer statistics from 32-bit to 8-bit integers. Using libraries like bitsandbytes, you can drastically cut down this overhead.\nimport bitsandbytes as bnb # Standard: torch.optim.AdamW(model.parameters(), lr=1e-4) optimizer = bnb.optim.AdamW8bit( model.parameters(), lr=1e-4 ) # -\u0026gt; Reduces optimizer state memory by roughly 75% 4. Intermediate Activations: The Real Final Boss Your memory usage has already skyrocketed, but we aren’t done. Up until now, the memory growth has been directly proportional to your model size (2x, 4x, etc.).\nBut the most terrifying culprit is Intermediate Activations.\nWhy do we save them? Deep learning frameworks like PyTorch provide Autograd (Automatic Differentiation). It’s a lifesaver that calculates derivatives for us so we don’t have to do it by hand. But magic always has a price.\nTo summarize the core concept of Autograd:\nDuring Inference: You pass inputs forward and get an output. You can immediately forget all the intermediate math steps because you’re only moving forward. During Training: You move forward (Forward Pass), but then you have to trace your steps backward (Backward Pass). To compute gradients via the Chain Rule on the way back, the network constantly asks, “Wait, what was the exact value when I passed through this layer earlier?” To answer that, PyTorch carefully hoards all those intermediate tensors created during the forward pass. The Activation Explosion Unlike the optimizer states, activation memory is highly sensitive to your data and architecture — often much more than the raw parameter count.\nBatch Size: Double your batch size, and you double the intermediate values you need to store. Sequence Length: In Transformer models, increasing the input sequence length causes attention mechanism memory to explode quadratically. Network Depth: The deeper the network, the more intermediate steps there are to stash away. 5. The nvidia-smi Illusion There’s one more mystery. Sometimes, even after your training finishes or you explicitly delete tensors with the del keyword, nvidia-smi still shows your VRAM as completely full.\nYour first thought might be: “Is there a memory leak?”\nUsually, no. This is just PyTorch’s Caching Allocator doing its job.\nRequesting and releasing GPU memory from the OS is a slow, expensive operation. So, when PyTorch is done with a tensor, it deletes the data but doesn’t return the empty VRAM space to the operating system right away.\nInstead, PyTorch holds onto it, assuming, “I’m probably going to need this space again in a millisecond, so I’ll just keep it.” Therefore, nvidia-smi reports the memory as \u0026quot;in use,\u0026quot; even though internally, PyTorch sees it as free real estate.\nTo see what’s actually going on, you need to ask PyTorch directly:\ntorch.cuda.memory_allocated(): VRAM currently occupied by actual tensors. torch.cuda.memory_reserved(): Total VRAM PyTorch has claimed from the OS (including the cache). import torch # VRAM actively holding tensors allocated = torch.cuda.memory_allocated() / 1e9 # Total VRAM PyTorch is hoarding from the OS (including cache) reserved = torch.cuda.memory_reserved() / 1e9 print(f\u0026#34;Allocated: {allocated:.2f} GB\u0026#34;) print(f\u0026#34;Reserved : {reserved:.2f} GB\u0026#34;) # Value in nvidia-smi ≈ reserved # Actual tensor usage ≈ allocated 6. So, How Do I Actually Reduce Memory Usage? Telling you to “just drop your batch size to 1” isn’t helpful. Let’s look at more practical, modern solutions.\n1) Mixed Precision (AMP) This gives you the best bang for your buck. Instead of doing everything in float32, you mix in float16 or bfloat16 for certain operations.\nThe massive activation tensors generated during the forward pass are stored in FP16, instantly slashing their memory footprint in half. It speeds up computation and saves memory — a total win-win.\nWith PyTorch, it only takes a few lines of code to apply:\nfrom torch.amp import autocast, GradScaler scaler = GradScaler(\u0026#39;cuda\u0026#39;) for batch in dataloader: optimizer.zero_grad() # Run forward pass in FP16/BF16 with autocast(device_type=\u0026#34;cuda\u0026#34;, dtype=torch.float16): output = model(batch) loss = criterion(output, target) # Scaled backward pass in FP32 scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() 2) Activation Checkpointing (Gradient Checkpointing) This is a strategic trade-off: trading compute for memory.\nInstead of saving all intermediate activations during the forward pass, you only save a few “checkpoints.” During the backward pass, when you need an intermediate value you threw away, you simply recompute it on the fly from the nearest checkpoint.\nPros: Drastically reduces activation memory footprint. Cons: Slower training speed (since you are calculating some forward steps twice). While the slowdown sounds annoying, training a bit slower is infinitely better than crashing with an Out Of Memory (OOM) error!\nfrom torch.utils.checkpoint import checkpoint class TransformerLayer(nn.Module): def forward(self, x): # Wrapped in a checkpoint, intermediate values inside these blocks aren\u0026#39;t saved x = checkpoint(self.attention, x, use_reentrant=False) x = checkpoint(self.ffn, x, use_reentrant=False) return x # In Hugging Face Transformers, it\u0026#39;s just one line: model.gradient_checkpointing_enable() 3) FlashAttention If you are working with Transformer models, this is basically mandatory now. The standard Attention mechanism is bottlenecked by memory I/O. FlashAttention uses a technique called “tiling” to heavily optimize GPU memory I/O.\nThe result? It uses a fraction of the memory and runs significantly faster. In PyTorch 2.0 and above, this is often applied automatically when you use F.scaled_dot_product_attention.\nimport torch.nn.functional as F # PyTorch 2.0+ - Automatically utilizes optimized kernels like FlashAttention out = F.scaled_dot_product_attention( query, key, value, attn_mask=None, dropout_p=0.0, is_causal=True, ) # To explicitly force and verify FlashAttention is being used: with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False): out = F.scaled_dot_product_attention(query, key, value) 4) Distributed Training (FSDP, ZeRO) If you have multiple GPUs, you can chop the model up. Distributed training is a massive topic on its own, but here is the quick rundown:\nDDP (Distributed Data Parallel): Every GPU holds a full replica of the model. (Very memory inefficient). FSDP (Fully Sharded Data Parallel) / ZeRO: The model weights, gradients, and optimizer states are sharded (split) across all your GPUs. If a GPU needs a piece of the model it doesn’t have, it briefly borrows it from a neighboring GPU. This is the magic that makes training massive LLMs possible. 7. TL;DR: Training Memory is the Cost of Calculus To wrap things up:\nFor inference, weights are all you need. Training requires calculating derivatives (gradients) to update those weights. To calculate those derivatives, PyTorch has to hoard the intermediate results from the forward pass. Optimizers like Adam carry around extra historical baggage for every single parameter. So, seeing your memory usage dwarf your model size isn’t a bug — it’s just how the math works.\nNext time you hit an OOM error, before you awkwardly drop your batch size to 1, try leaning into Mixed Precision, Gradient Checkpointing, and FlashAttention!\n","permalink":"https://blog.jiminl.com/posts/why-your-tiny-deep-learning-model-is-hogging-all-your-gpu-vram-85bc58ee5050/","summary":"You’ve carefully built your deep learning model, and it only has a few hundred megabytes of parameters. But the moment you hit “train” and…","title":"Why Your Tiny Deep Learning Model is Hogging All Your GPU VRAM"},{"content":"As large language models (LLMs) continue to evolve rapidly, building generative AI products is easier than ever. But if you’re actually putting an LLM-powered service into production, there’s one universal headache everyone runs into.\nEvaluation.\nYou stay up all night tweaking prompts and maybe fine-tuning a shiny new model. You run a test prompt, and the LLM spits out an answer with absolute confidence. You stare blankly at the screen and think:\n“Hmm… this is pretty good? Wait, is this actually better than yesterday’s version? It kind of looks the same. Or maybe it’s worse?”\nWhen this happens enough times, you start pulling your hair out.\nUnlike machine learning models for classification or stock prediction, where you have clear-cut labels to measure accuracy, generative tasks don’t have a single “correct” answer. There’s no objective math for evaluating a comforting response to “How are you feeling today?” or a summary of a 100-page financial report.\nHaving a human read and score every single output is a fast track to burning through your time and budget. Plus, Human Reviewer A might be a generous grader, while Reviewer B is ruthless. Sometimes, the same person will give two different scores depending on whether they’ve had their morning coffee.\nBut falling back on legacy methods like simple word-matching doesn’t do justice to the fluency of modern LLMs either.\nThen, someone had a lightbulb moment:\n“If LLMs are so smart, why don’t we just make them grade the tests?”\nEnter LLM-as-a-Judge.\nIn this post, we’ll dive into why this technique emerged, how to actually use it, and — just as importantly — when you should absolutely not use it.\n1. What Exactly is LLM-as-a-Judge? It is exactly what it sounds like: using an LLM to play the role of a referee or grader.\nThink of it like a classroom. The student (the smaller, faster model you built) takes a test, and the teacher (a massive, high-performance model like GPT or Claude) grades it. Instead of just slapping a “B+” on the paper, the teacher gives specific, actionable feedback: “I’m giving this an 8 out of 10. The facts are correct, but the tone is a bit too abrasive for the user.”\nDidn’t we already have ways to evaluate language? We did. But applying those old-school methods to modern language models is like bringing a flip phone to a smartphone fight.\nROUGE / BLEU (Relics of the Past): These were the go-to metrics for summarization and translation. They basically check how many words the AI’s answer shares with the answer key. They don’t understand context or meaning; they only care about overlapping vocabulary. Human Evaluation: The gold standard, obviously. But it’s slow, wildly expensive, and inconsistent due to subjective human bias. LLM-as-a-Judge is the sweet spot in the middle. It understands context and nuance like a human, but it can grade tests 24/7, at scale, without getting tired or asking for a raise.\n2. How Does the LLM Judge Actually Grade? It sounds simple to just tell the model to “evaluate this,” but it requires more finesse than that. Typically, we use three main frameworks:\nPairwise Comparison You put two answers (Model A and Model B) side-by-side and ask, “Who did it better?” Just like humans are often much better at relative comparison than absolute scoring, models excel at picking a winner. This is a fantastic way to figure out which model has the upper hand.\nSingle Answer Scoring You show the judge one answer and say, “Rate this on a scale of 1 to 10.” This is great for tracking absolute performance metrics over time. A quick warning, though: if you change the judge model, its grading criteria will subtly shift, skewing your scores. Even different checkpoints of the same LLM can grade differently. Always lock in your model version!\nReference-based Grading When there is a clear gold standard — like typo correction or strict fact-checking — you hand the judge the answer key and tell it to grade against that reference. This drastically minimizes hallucinations and ensures tight accuracy.\n3. Case Study: Translation Evaluation — Seeing the ‘Context’ One of the biggest wins for LLM-based evaluation is in machine translation. Let’s look at how LLM-as-a-Judge shook things up.\nThe Limits of the Old Way (BLEU) For years, translation performance was judged by the BLEU score. Put simply, it asks, “How many words overlap with the reference?” Here’s where it completely breaks down.\nLet’s say we’re translating the conversational French phrase “Tu as mangé ?” into English.\nReference: “Did you have a meal?” Model A: “Have you eaten?” Model B: “Meal did you?” To a human, Model A is a perfectly natural translation, while Model B is absolute gibberish. But to a simple word-matching BLEU score, Model A gets heavily penalized because its words (“Have,” “eaten”) don’t perfectly overlap with the reference. Meanwhile, the nonsense Model B might score artificially higher just for hitting the word “Meal”. It punishes models for expressing the exact same meaning with different vocabulary.\nEnter the LLM Judge Drop an LLM-as-a-Judge into this scenario, and the game changes entirely. We aren’t asking the LLM to count words; we’re asking, “Does this mean the same thing?”\nResearch shows that LLM judges perfectly understand the nuanced similarities between “Did you have a meal?” and “Have you eaten?”, completely ignoring the structural differences. As a result, the alignment with human judgment skyrocketed. Today, top tech companies use LLMs as their first line of defense to check “does this make sense?” instead of “do the exact words match?”\n4. Even Judges Show Bias: Pitfalls and Solutions If you thought, “Hey, it’s AI, it must be completely objective!” — think again. LLMs inherit human biases from their training data. Left unchecked, you aren’t proving your model got better; you’re just proving it “caters to the judge’s taste.”\nHere’s why these biases happen and how to fix them.\nPosition Bias: “I just like the first one.” When comparing two answers (Pairwise), the judge often leans toward the first answer presented, regardless of its actual quality. It’s exactly like how humans instinctively pick the top item on a restaurant menu.\n💡 The Fix: Flip the Order The bulletproof method is to ask twice:\nAsk in A-then-B order (“Is A or B better?”) Ask in B-then-A order (“Is B or A better?”) Only count the data if the judge agrees with itself both times. If the results conflict, toss the data or call in a third-party judge model to break the tie.\nVerbosity Bias: “They talked a lot, so they must be smart.” LLMs have a bias toward verbosity. They tend to award higher scores to longer, structurally complex answers — even if the actual content is thin. This leads to the frustrating scenario where a concise, perfect answer loses points just for being brief.\n💡 The Fix: Explicit Constraints \u0026amp; Tighter Rubrics Just putting “Don’t evaluate based on length” in your prompt isn’t enough.\nAdd a ‘Conciseness’ metric directly to your grading rubric and explicitly instruct the judge to penalize unnecessarily long answers. If possible, use Reference-based grading. You can assign a harsh penalty if the model’s output is drastically longer than the gold standard reference. Affinity Bias: “Hey, you sound just like me!” GPT loves text written by GPT. Claude prefers the Claude style. Because they naturally favor the distribution of data they were trained on, they show a clear stylistic bias. Birds of a feather flock together.\n💡 The Fix: Cross-Evaluation Use a different model for the player and the referee.\nIf you’re evaluating a Llama model, use GPT as the judge. If you’re testing GPT, bring in a Claude model to ref the game. Reasoning Limits: “Uh, I don’t know the answer either…” If you ask a judge to grade a problem that’s beyond its own intelligence or reasoning capabilities, it might confidently declare a wrong answer as correct. The judge must always be smarter than the student.\n💡 The Fix: Provide the Gold Standard Instead of telling the judge, “Solve this and grade it,” say, “Here is the correct answer (Reference). Compare the student’s answer to this and check if they align.” Don’t make the judge do the math from scratch; narrow its job to simply checking for logical consistency against the answer key.\n5. Latest Trends: Smarter, Lighter Judges The LLM-as-a-Judge space has moved past the “Wait, can we actually do this?” phase and into the “How do we make this cheaper and more reliable?” phase.\nThe Rise of Dedicated Evaluation Models: Prometheus \u0026amp; M-Prometheus Because this technique has become so critical, we’re seeing open-source models built exclusively for grading.\nPrometheus 2: This model cranked up its evaluation performance to the point where it closely mirrors GPT-4’s judgments, specifically for grading tasks. M-Prometheus: A massive upgrade for multilingual evaluation. We finally have a judge that truly grasps the idioms and nuances of various languages, providing native-level feedback rather than awkward, machine-translated critiques. New Benchmarks: JuStRank JuStRank: Instead of just checking if a judge can assign a good standalone score, this benchmark measures how well a judge’s overall ranking of different systems aligns with human consensus. Now, you can actually quantify how fair and decisive your judge model is. 6. Evaluation Prompt Example (Summarization Task) Let’s say you want to use an LLM-as-a-Judge for a summarization feature.\nThe secret sauce here is balancing ‘Relevance’ (did it capture the core message?) with ‘Consistency/Hallucination’ (did it make stuff up?).\nHere is how you can structure your prompt:\n# System Prompt You are an expert text editor and evaluator with 20 years of experience. Your task is to evaluate the quality of an AI-generated [Summary] based on the provided [Source Text]. # Evaluation Rubric Score the summary from 1 to 5 based on the following four criteria. 1. Comprehensiveness: - Does it include all core information and key messages from the source? - Are any crucial numbers or conclusions missing? 2. Consistency (Hallucination Check): - Were any external facts added, or was the original meaning distorted? - (CRITICAL) If there is ANY contradictory information to the source text, immediately assign a score of 1. 3. Conciseness: - Does it deliver the core message without unnecessary repetition or fluff? - Is the summary somehow longer or more complex than the source? 4. Readability: - Is the sentence structure natural and grammatically correct? - Are spelling and punctuation accurate? # Input Data [Source Text]: {source_text} [Summary]: {summary} # Output Format You MUST return your response in the JSON format below. Under \u0026#39;reasoning\u0026#39;, provide a specific, detailed justification for each score. { \u0026#34;reasoning\u0026#34;: { \u0026#34;comprehensiveness\u0026#34;: \u0026#34;...\u0026#34;, \u0026#34;consistency\u0026#34;: \u0026#34;...\u0026#34;, \u0026#34;conciseness\u0026#34;: \u0026#34;...\u0026#34;, \u0026#34;readability\u0026#34;: \u0026#34;...\u0026#34; }, \u0026#34;scores\u0026#34;: { \u0026#34;comprehensiveness\u0026#34;: 0, \u0026#34;consistency\u0026#34;: 0, \u0026#34;conciseness\u0026#34;: 0, \u0026#34;readability\u0026#34;: 0 }, \u0026#34;overall_score\u0026#34;: 0.0 } 3 Key Takeaways Hallucination Defense: By adding a hard constraint in the ‘Consistency’ section (“score a 1 if contradictory”), you aggressively filter out models that are highly fluent but completely lying. Conciseness Check: Explicitly penalizing fluff stops the “Verbosity Bias” we talked about earlier right in its tracks. JSON Output: Forcing structured data means you can pipe these results straight into your database or automated evaluation pipelines without manual data wrangling. 7. When You Should NEVER Use LLM-as-a-Judge Knowing when to bench the LLM judge is just as important as knowing when to play it.\nDo not hand everything over to the LLM. Because this method is so convenient, engineers tend to shoehorn it into places it doesn’t belong.\nUsing an LLM for problems that can be solved with traditional machine learning metrics (like Precision and Recall) is like hiring Shakespeare to do your taxes.\nWhy Shouldn’t I Use It Everywhere? Inconsistent Results In code, 1+1=2 forever. But an LLM might give you an 8 today and a 7 tomorrow. You're left guessing: \u0026quot;Did my model get worse, or did the judge just wake up on the wrong side of the bed?\u0026quot; It makes debugging a nightmare. Speed and Cost Calculating Precision/Recall takes a fraction of a millisecond and costs literally nothing. An LLM evaluation costs API credits and takes several seconds per run. Doing this at scale adds up fast. Data Contamination and the Lazy Trap Let’s be honest: a lot of developers use LLM evaluators because they are “too lazy to build a ground-truth label dataset.” But doing this just builds massive technical debt. You end up in an infinite loop where humans have to constantly double-check the AI judge to make sure it’s grading the AI student correctly. 💡 The Golden Rule: Don’t replace an objective ruler (multiple-choice) with a subjective movie review (short essay).\nWrapping Up LLM-as-a-Judge is a brilliant, irreplaceable tool in the generative AI era — especially when you need qualitative evaluations. It has evolved to a point where it is essentially mandatory for modern GenAI stacks.\nBut like any shiny new tool, blind faith is dangerous.\nTake a step back and ask yourself: Are you outsourcing your evaluations to an LLM just because it’s easier? Are you blindly trusting the scores it spits out? Are you ignoring the prompt engineering and cross-model selection required to actually make those scores accurate?\nLLM-as-a-Judge needs to be treated as an engineering discipline and a precision tool — not just an escape hatch for when building a proper evaluation pipeline feels like too much work.\n","permalink":"https://blog.jiminl.com/posts/understanding-llm-as-a-judge-benefits-biases-and-best-practices-4b4d5cc3cbcd/","summary":"As large language models (LLMs) continue to evolve rapidly, building generative AI products is easier than ever. But if you’re actually…","title":"Understanding LLM-as-a-Judge: Benefits, Biases, and Best Practices"},{"content":"If you’ve been using PyTorch since the 2.0 release, you’ve likely encountered — and hopefully benefited from — torch.compile(). It’s the headline feature designed to speed up your models with a single line of code.\nBut how exactly does it pull off this optimization magic?\nTo understand how torch.compile() works, we first need to understand the problem it solves. We have to look at the past to appreciate the present.\nPrerequisite: It might help to check out my previous post on From PyTorch Code to the GPU: What Really Happens Under the Hood? to get the most out of this deep dive.\n1. The Bottleneck: Why Do We Need a Compiler? Before we get into the optimization details, let’s talk about PyTorch’s default mode: Eager Mode. This is what we all know and love, but it’s also where our performance bottlenecks live.\nEager Execution: The Price of Being “Pythonic” PyTorch became the dominant framework largely because it executes Python code immediately line-by-line. This is called Eager Execution.\nx = torch.randn(100) y = x * 2 # \u0026lt;--- GPU executes this immediately! print(y) # \u0026lt;--- Value is ready to inspect instantly It behaves exactly like standard Python. You might think, “Isn’t that obvious?” But if you remember the early days of TensorFlow (1.x), you know it wasn’t always this way. Old-school TensorFlow required you to define a static graph before running anything, which made interactive development a nightmare.\nPyTorch’s Eager Mode is heaven for debugging, but it can be hell for hardware efficiency. The issue lies in the communication overhead between the CPU (Python) and the GPU.\nThe Micromanaging Chef Imagine a kitchen where the Chef is the CPU (Python) and the Sous-Chef is a super-fast Robot (GPU).\nIn Eager Mode, the workflow looks like this:\nThe Chef hands the Robot an onion: “Chop this.” The Robot chops it in 0.001 seconds, then stands idle, waiting. The Chef looks at the recipe again, grabs a carrot, hands it over: “Sauté this.” The Robot sautés it in 0.001 seconds, then waits again. The restaurant owner walks in and asks, “I spent a fortune on this Robot, why is dinner taking so long?” The Robot is innocent. The bottleneck isn’t the Robot’s chopping speed (GPU Compute); it’s the Chef’s micromanagement. The Robot spends most of its time waiting for the Chef to issue the next command.\nMemory Bandwidth Bound Let’s look at a simple operation: x * 2 + 1.\nFetch: Go to the warehouse (HBM/VRAM), get x, bring it to the workbench (Registers). Compute: Multiply by 2. Store: Put the result back in the warehouse. (Round trip #1). Fetch: Go back to the warehouse, get that result. Compute: Add 1. Store: Put the final result back in the warehouse. (Round trip #2). We are wasting massive amounts of time just moving data back and forth. If we were smart, we would keep the result of x * 2 on the workbench and immediately add 1, cutting our warehouse trips in half.\nKernel Launch Overhead “Kernel Launch” is the technical term for the CPU telling the GPU to do something.\nFor very small operations, the time it takes the CPU to write the “work order” and send it to the GPU takes longer than the actual calculation itself. This is the “sauté the carrot” scenario — the paperwork costs more than the labor.\nEnter torch.compile The goal of torch.compile() is Operator Fusion. Ideally, we want to reduce warehouse (HBM) visits to a single round trip and combine multiple instructions into one \u0026quot;work order\u0026quot; to minimize Kernel Launch Overhead.\nSeeing is Believing: A Benchmark Enough theory. Let’s see the actual speed difference. The code below simulates a typical Memory Bound operation (element-wise math).\nRead the comments carefully to follow the logic.\nimport torch import time # GPU operations are asynchronous, so we must synchronize to measure time accurately. def timed(fn, x): torch.cuda.synchronize() start = time.time() result = fn(x) torch.cuda.synchronize() return time.time() - start # A classic memory-bound operation: lots of reading/writing for simple math. def heavy_calc(x): return torch.sin(x) + torch.cos(x) * torch.tan(x) # Prepare some heavy data x = torch.randn(10000, 10000).cuda() print(\u0026#34;=== Benchmark Start ===\u0026#34;) # 1. Eager Mode (Default) # Huge overhead from memory round-trips. eager_time = timed(heavy_calc, x) print(f\u0026#34;Eager Mode : {eager_time:.5f}s\u0026#34;) # 2. Prepare Compile Mode # Nothing happens yet (Lazy initialization). opt_calc = torch.compile(heavy_calc) # 3. First Run (Warm-up) # This is slow! The compiler is analyzing code and generating kernels. first_run = timed(opt_calc, x) print(f\u0026#34;Compiled (1st Run): {first_run:.5f}s \u0026lt;-- Slow! (Compilation Overhead)\u0026#34;) # 4. Second Run (Cached) # Now we use the optimized Triton kernel. It should be blazing fast. second_run = timed(opt_calc, x) print(f\u0026#34;Compiled (2nd Run): {second_run:.5f}s \u0026lt;-- Fast! ({eager_time / second_run:.1f}x Speedup 🚀)\u0026#34;) Example Output (Colab T4):\n=== Benchmark Start === Eager Mode : 0.01981s Compiled (1st Run): 0.05608s \u0026lt;-- Slow! (Compilation Overhead) Compiled (2nd Run): 0.00413s \u0026lt;-- Fast! (4.8x Speedup 🚀) 4.8x faster.\nKey Takeaway: The first run is slow because the “Smart Chef” is rewriting the entire recipe (compiling). Every run after that uses the optimized recipe, resulting in massive speedups.\nNow that we see that it works, let’s look at how it works under the hood.\n2. The Frontend: TorchDynamo \u0026amp; Guards The first step is distinguishing between “PyTorch stuff” and “Standard Python stuff.” This is where things can get blurry, so pay attention.\nPython Frame Evaluation Hook (The Spy) The first hero in our stack is TorchDynamo. Its job is to analyze your Python code and generate an FX Graph — a representation of your code consisting purely of PyTorch operations.\nPython code is compiled into bytecode before it runs (those .pyc files you see are bytecode). TorchDynamo hooks into the Python frame evaluation API (PEP 523) to \u0026quot;spy\u0026quot; on this bytecode right before it executes.\nIt scans the bytecode and identifies PyTorch operations. If it sees something it understands (like torch.add), it adds it to the FX Graph.\nBut what if it sees something it doesn’t understand, like numpy or a side-effect like print()?\nTorchDynamo pauses the graph capture. It says, “I don’t know what this is. Python, take the wheel.” This is called a Graph Break. It splits the graph, lets Python handle the unsupported part, and then tries to resume capturing afterwards.\nGuards: The Bouncer Compilers hate change. If you have code like if x.sum() \u0026gt; 0:, the execution path changes based on the data.\nTo manage this, TorchDynamo sets up Guards. Think of a Guard as a bouncer at a club.\nWhen you run your compiled model a second time, the Guard checks: “Does the input tensor have the exact same Shape and Dtype as last time?”\nIf the answer is yes, we use the cached, optimized kernel. If the answer is no, the Guard says “Entry denied,” and triggers a recompilation.\n3. The Middle-end: AOTAutograd \u0026amp; FX Graph vs. ATen IR AOTAutograd (The Fortune Teller) Dynamo only captures the Forward pass. But for deep learning training, we need backpropagation.\nAOTAutograd (Ahead-Of-Time Autograd) takes the forward graph and simulates the PyTorch Autograd engine. It predicts, “To backpropagate through this, I will need these specific formulas later.” It then generates the Backward graph and stitches them together into a Joint Graph.\nFX Graph vs. ATen IR AOTAutograd does something else crucial: Decomposition (or Lowering).\nThe graph coming out of Dynamo is high-level. It contains complex instructions like torch.nn.CrossEntropyLoss.\nAOTAutograd breaks these down into ATen IR (Intermediate Representation) — the lowest-level mathematical primitives.\nCrossEntropy becomes a combination of aten.log_softmax, aten.neg, and aten.nll_loss. Eventually, everything becomes simple adds, multiplies, and matrix matmuls. Why lower the code? It is much easier to write optimization rules for 50 simple “LEGO blocks” (primitive ops) than for 2,000 complex, unique structures. This allows the compiler to spot patterns like “Hey, I can fuse this add and that multiply.”\n4. The Backend: TorchInductor \u0026amp; Triton Now we have a graph of primitive math operations. We need to turn this into fast GPU code. This is the job of TorchInductor.\nLoop Fusion \u0026amp; Scheduling Inductor analyzes the graph and looks for Memory Bound operations to fuse.\nBefore: Read A -\u0026gt; Multiply -\u0026gt; Save to Temp -\u0026gt; Read Temp -\u0026gt; Add -\u0026gt; Save to B. After (Fused): Read A -\u0026gt; Multiply \u0026amp; Add immediately (in registers) -\u0026gt; Save to B. It eliminates the “Save to Temp” and “Read Temp” steps entirely. In our kitchen analogy, this is chopping the onion and tossing it directly into the pan, rather than putting it in a prep bowl first.\nCode Generation: Triton Once the schedule is optimized, Inductor generates Triton code.\nTriton is a game-changer from OpenAI. It allows you to write high-performance GPU kernels using Python syntax.\nBefore Triton, you had to write CUDA. CUDA is powerful but difficult. It requires you to micromanage individual threads — like telling 1,000 soldiers exactly where to stand.\nCUDA: Moving individual grains of sand with tweezers. Triton: Stacking bricks. Triton operates on Blocks. You tell it, “Take this block of data and multiply it there,” and it handles the complex memory management and thread synchronization for you.\nTorchInductor effectively acts as a Triton code generator. It writes the Triton kernel that maximizes cache (SRAM) usage on the GPU, so you don’t have to.\n⚠️ A Reality Check Inductor is smart, but it knows its limits. For standard Matrix Multiplications (GEMM) or Convolutions, the libraries written by NVIDIA engineers (cuBLAS, cuDNN) have been hand-optimized for decades.\nIf Inductor sees a big Matrix Multiplication, it usually won’t try to compile it itself. It will simply call the cuBLAS library, effectively saying, “I’ll let the expert handle this part.”\n5. Real-World Performance In a modern PyTorch 2.x environment (as of 2026), here is what you can generally expect:\nTraining: 1.3x ~ 2.4x Speedup Inference: 1.5x ~ 3.0x Speedup Note: These gains are most visible in Transformers or CNNs where memory movement is the bottleneck. For simple MLP models dominated by large Matrix Multiplications (GEMM), cuBLAS was already doing the heavy lifting, so the compiler has less room to optimize.\nUpdates for 2026 Dynamic Shapes: In the early days, changing batch size by 1 would trigger a full recompile. Now, PyTorch supports Symbolic Shapes, allowing it to adapt to changing input sizes without recompiling. FlexAttention: You can now write custom Attention logic in Python, and the compiler will optimize it to near-FlashAttention speeds. Complex masking no longer kills performance. 🚫 When to Avoid torch.compile It’s not a silver bullet. You might want to skip it if:\nDynamic Control Flow: Code that changes paths wildly based on random values or data (e.g., if random() \u0026gt; 0.5:). Debugging: Compiled code is a black box. If you need to print intermediate tensor values to debug, use Eager Mode. Tiny Models: If your model is tiny, the overhead of the “Smart Kitchen” setup takes longer than just cooking the meal. 6. Conclusion The 5-Line Summary TorchDynamo: Spies on your code, captures the execution graph, and handles breaks. AOTAutograd: Predicts the backward pass and breaks complex math down into simple Primitives. TorchInductor: Reorganizes the work to minimize memory movement (Fusion). Triton: Converts that plan into block-based GPU instructions. Result: Massive reduction in memory bottlenecks, leading to 1.3x — 2.4x faster training on modern GPUs (H100/A100). torch.compile() in PyTorch 2.0+ marks the democratization of Deep Learning Compilers. You get to keep the flexibility of Python, while Dynamo, Inductor, and Triton work in the background to give you C++ level performance.\nI hope this look under the hood helps you debug performance issues and write better, faster code.\n","permalink":"https://blog.jiminl.com/posts/how-torch-compile-actually-works-from-python-bytecode-to-fused-triton-kernels-1c78721c3331/","summary":"If you’ve been using PyTorch since the 2.0 release, you’ve likely encountered — and hopefully benefited from — torch.compile(). It’s the…","title":"How torch.compile() Actually Works: From Python Bytecode to Fused Triton Kernels"},{"content":"When running PyTorch code, there is one line we all type out of sheer muscle memory:\n.to('cuda')\nImmediately, the fans in your desktop case spin up like a jet engine preparing for takeoff. (Though if you’re training on a cloud instance, you probably won’t hear a thing.)\nBut have you ever paused to ask yourself:\n“How does Python — a language famous for being slow — control a GPU that operates at such breakneck speeds?”\nToday, we’re going to look at how a few lines of Python manage to command a GPU to perform complex calculations, and exactly what happens between your keyboard and the hardware.\n1. Python: The Driver, Not the Engine Let’s get the most important concept out of the way first.\nThe Python code you write in PyTorch does not run on the GPU.\nTo be precise, Python only issues the commands; C++ and CUDA are the ones doing the heavy lifting. Think of Python as the Foreman.\nThe Foreman (Python) shouts, “Hey, multiply these two matrices!” The actual workers (C++/CUDA) then hop into their heavy machinery (the GPU) to get the job done.\nThanks to this clever architecture, we get to write code in easy, readable Python while achieving C++-level performance.\nWhat you see is Python, but what’s running underneath is pure C++ and CUDA.\n2. The Dispatcher: PyTorch’s Central Control Let’s say you call torch.add(a, b) in Python.\nOnce the call leaves the Python layer, it enters a central control room written in C++ called the Dispatcher.\nThe Dispatcher is an internal component of PyTorch. Its job is to decide exactly which piece of code should run when a function like torch.add is called.\nIt’s not as simple as asking “CPU or GPU?” The Dispatcher acts as a magical traffic controller that ensures all of PyTorch’s features — Auto Differentiation (Autograd), Quantization, XLA, etc. — work together without getting tangled up.\n2–1. The Tensor ID: Dispatch Key Set Every Tensor carries a “Dispatch Key Set” — essentially a detailed ID card.\nThis ID card tells the system everything about the Tensor’s identity:\nBackend Info: Is this a CUDA tensor, a CPU tensor, or an MPS tensor? Layout Info: Is this a standard dense (strided) tensor or a sparse tensor? DType Info: Is it a float or an integer? Autograd Info: Does it have requires_grad=True? Do we need to track gradients? 2–2. The Workflow: Routing the Call When torch.add(a, b) is called, the Dispatcher looks at the ID cards (Key Sets) of the tensors and opens a massive manual known as the Dispatch Table.\nScenario 1: A Simple Addition\n“Okay, both tensors only have the CPU key. No gradients needed. Great, send this straight to the cpu_add_kernel function in the ATen library!\u0026quot;\n(ATen library is a part of PyTorch implementation)\nThe C++ operation runs immediately.\nScenario 2: A Complex GPU Training Step\n“Hold on. Checking the ID card… I see a CUDA key, but I also see an Autograd key.\u0026quot;\nDispatch Keys are sorted by priority. The system handles the highest priority key first. In this case, Autograd outranks CUDA.\nThe Dispatcher passes the ball to the Autograd handler first. The handler says, “Got it. I’ve recorded this addition operation so we can use it for backpropagation later,” and builds a node in the Computational Graph.\nFor a deeper dive into how this works, check out my previous post on PyTorch Autograd.\nThe Autograd handler then passes the ball back to the Dispatcher.\nNow the Dispatcher says, “Okay, next up is the CUDA key. Send this to the CUDA implementation!\u0026quot; and the GPU finally performs the calculation.\nThis entire sequence happens in microseconds at the C++ level. Thanks to the Dispatcher, a single function like torch.add automatically handles gradient tracking, GPU acceleration, and error checking without you having to write a single line of boilerplate.\nYou don’t need to write: if gpu: ... else if autograd: .... PyTorch handles it for you.\n3. Entering the World of CUDA Once the Dispatcher decides, “You, go to CUDA,” we leave the CPU world and enter the realm of the GPU.\nThe language here is neither Python nor C++, but CUDA (Compute Unified Device Architecture).\n3–1. Division of Labor: Host vs. Device We need to define our terms:\nHost: The CPU and system memory (RAM). This is where your Python script and PyTorch’s C++ backend run. Device: The GPU and its dedicated memory (VRAM). This is the construction site where the hard labor happens. When you write Python code, you are effectively piloting a C++ program on the Host. This program picks up a “phone” called the CUDA Runtime API to call the Device and give it orders.\n3–2. The Kernel: Work Orders for the GPU Here comes another term: Kernel.\nA Kernel is a small function designed to run specifically on the GPU. When Python issues a command, PyTorch effectively shouts:\n“Hey GPU! I’m going to Launch an add_kernel. Use the data at address #1 and #2, and write the result to address #3.\u0026quot;\nThis is called a Kernel Launch.\nIf you’ve used PyTorch for years but never wrote a Kernel, don’t worry. That’s normal. PyTorch comes pre-packaged with thousands of highly optimized Kernels deep inside its library.\n3–3. The PCIe Bus: The Narrow Bridge This is where we hit a major hardware bottleneck: the PCIe Bus.\nModern GPUs have insane internal memory bandwidth.\nFor example, NVIDIA’s H100 GPU uses HBM3 memory to achieve a memory bandwidth of over 3 TB/s. The newer H200s are even faster.\nHowever, the bridge connecting the CPU to the GPU — the PCIe interface — is comparatively tiny.\nA typical PCIe Gen 4 x16 link offers about 28~32 GB/s in one direction (approx. 64 GB/s bidirectional).\nCompare 3,000 GB/s (internal GPU speed) to 30 GB/s (connection speed). The bridge is 100x slower than the city it connects to.\nThis is why you shouldn’t abuse .to('cuda'). Every time you run that command, you are forcing data across this slow PCIe bridge.\nExperienced engineers know: move your data to the GPU once, keep it there, do all your math, and only bring the final result back. Moving data back and forth is the quickest way to kill performance.\n4. Inside the Hardware: The Rule of 32 The Kernel has arrived at the GPU. What happens inside the silicon?\nWarps and SIMT While the smallest unit of execution on a GPU is a Thread, the hardware actually groups them into bundles called Warps. A Warp consists of 32 threads.\nAll 32 threads in a Warp must execute the exact same instruction at the same time. This architecture is called SIMT (Single Instruction, Multiple Threads). If the command is “Step forward,” all 32 step forward. If it’s “Add,” all 32 add.\nWhat happens if you have an if-else statement where 16 threads want to do Option A and 16 want to do Option B?\nThe GPU suffers from Warp Divergence. The hardware literally has to pause half the group, let the first half finish, then pause the first half while the second half runs. Performance gets cut in half. Fortunately, PyTorch Kernels are highly optimized to avoid this.\nTo Recap:\nHost (CPU) pushes data to the Device (GPU). (This is the slowest part). PyTorch Launches a C++ CUDA Kernel. Thousands of GPU cores, grouped into Warps (32 threads), execute the math in lockstep. The result stays in GPU memory; Python only holds a pointer (address) to that result. 5. Asynchronous Execution: The CPU Doesn’t Wait When you run output = model(input) in Python and the code moves to the next line, has the GPU finished the calculation?\nNo.\nThe Coffee Shop Analogy Imagine ordering a coffee at a busy cafe (the CPU). You hand over your order, and it gets sent to the barista station (the GPU).\nDo you stand frozen at the register until the coffee is ready? No. You step aside, check your phone, talk to a friend, or look at the pastry case.\nPyTorch works the same way.\nWhen you call a GPU function, the operation is placed in a Queue. The CPU says, “Here’s the order,” and immediately moves on to the next line of Python code without waiting for the result. This is Asynchronous Execution.\nThis allows the CPU to prepare the next batch of data or do other work while the GPU is crunching numbers.\nBut you might ask:\n“Wait, if I use output in the very next line, won't it crash because the data isn't ready?\u0026quot;\nDon’t worry. If you try to use the data, PyTorch handles the timing.\nIf you write print(output) (which requires moving data to CPU to display it), PyTorch recognizes that you need the actual value now. It forces a Synchronization, effectively saying, \u0026quot;Hey GPU, are you done? I'll wait right here until you are.\u0026quot;\nThe Benchmarking Trap Because of this asynchronous nature, measuring speed naively can be misleading.\nIf you use time.time() around a GPU operation without synchronization, you might think your model is running at light speed. In reality, you only measured how long it took to launch the kernel, not how long it took to execute it.\nFor accurate benchmarking, you must force the CPU to wait:\n# Correct way to benchmark torch.cuda.synchronize() # Wait for previous tasks start = time.time() model(input) torch.cuda.synchronize() # Wait for model to actually finish end = time.time() 6. Wrapping Up: Python Skin, C++ Muscle It’s been a deep dive. Let’s summarize the journey:\nPython Code: The Foreman issues orders. Dispatcher: Checks the ID (Dispatch Key), handles Autograd, and routes traffic. PCIe Bus: Data crosses the “slow bridge” to the GPU (optimize this by minimizing transfers!). CUDA Kernel: The work order is launched. GPU Hardware: Warps of 32 threads execute instructions in parallel lockstep. Async Execution: The CPU fires and forgets, only waiting when absolutely necessary. Behind every simple line of PyTorch code lies a sophisticated collaboration between software and hardware.\nWhile you don’t need to know this to build a model, understanding these mechanics helps you debug strange issues and write code that truly utilizes the full power of your hardware.\n","permalink":"https://blog.jiminl.com/posts/from-pytorch-code-to-the-gpu-what-really-happens-under-the-hood-ebc3f9d6612b/","summary":"When running PyTorch code, there is one line we all type out of sheer muscle memory:","title":"From PyTorch Code to the GPU: What Really Happens Under the Hood?"},{"content":" This post is written for engineers who already know the Transformer basics but want to understand why it was designed this way.\nThere is a common misconception when people first encounter the Transformer architecture. It usually goes something like this:\n“Self-Attention is just calculating the similarity between tokens.”\nIntuitively, this makes sense. If you look at the Self-Attention mechanism, you see dot products between vectors. If the dot product is high (meaning the vectors are similar), that token gets more weight.\nIt sounds a lot like a recommendation system: “People who watched this movie also liked…” So, many engineers nod their heads, think, “Ah, it just groups similar words together,” and move on.\nBut you shouldn’t stop there. Today, we are going to go one step deeper.\nOur inquiry starts with a simple question: If Attention is just about calculating similarity between tokens, why do we need to complicate things by creating three separate vectors — Query, Key, and Value?\nIf you dig into this, you realize that Attention isn’t just a similarity metric; it is a routing system that guides how information flows inside the Transformer. Furthermore, you will begin to understand how Attention and the MLP (Multi-Layer Perceptron) collaborate to produce the final output.\nI might be getting ahead of myself. Let’s break this down step by step.\n1. What Self-Attention Actually Does: Ask, Search, Retrieve Let’s describe the job of Self-Attention using plain English instead of math.\n“Attention is an operation where a Query asks a question, selects relevant items from a Key space (indexing), and then mixes the corresponding Values (content) to move that information to a new location.”\nThat’s a bit dense. Let’s break it down into 4 distinct phases:\nQuestion Generation (Query): The current token asks, “I need to know who the subject of this sentence is.” Index Search (Key): Other tokens hold up their tags (Keys) saying, “I’m a noun,” or “I’m a pronoun.” Matching \u0026amp; Selection (Score): We compare the question against the tags. If they are a good match, we give them a high score. Information Retrieval (Value \u0026amp; Aggregation): We grab the actual content (Value) from the high-scoring tokens and merge that information into the current token. When viewed this way, Attention looks a lot like a database lookup.\nThe crucial part here isn’t just finding similar things; it’s that information moves. In step 4, we take information (Value) from other tokens and transport it to the current token.\nIt’s not just verifying, “How much do you look like me?” It is a information gathering process: “I need that piece of data over there, so I’m going to copy it and paste it here.”\n2. The Roles of Q, K, and V: Everyone Has a Job The Transformer converts a single token into three distinct vectors: Q, K, and V.\nOne of the most brilliant aspects of the “Attention is All You Need” paper was the decision to split the input vector into these three separate spaces.\nWhy make it so complex? If the goal is just relevance, couldn’t we just compare the embeddings directly?\nLet’s use a library analogy to explain why this separation is necessary.\nQ (Query): Your Search Term\nYou walk up to the librarian and ask, “Find me books on the American Civil War.”\nThis is the Query. It represents the nature of the information the current token needs to find. K (Key): The Label on the Book Spine\nBooks in the library have labels or metadata that describe them: “History,” “USA,” “1860s,” “Lincoln.”\nThis is the Key. It acts as an identifier designed to be caught by a search tool (Query). V (Value): The Actual Content of the Book\nOnce you match the label (Key), the knowledge you actually read and absorb comes from the pages inside.\nThis is the Value. It is the substantial content that will be passed on to other tokens. From this perspective, the design philosophy of Self-Attention becomes clear:\nIt is not merely measuring similarity. It is closer to a search engine. To make that search accurate and efficient, the data used for searching (Key) is separated from the data being retrieved (Value). 3. “If K is a summary of V, can’t we just search using V?” You might ask: “We generate K from the input token, and V from the same input token. If K is just a representative summary of V, can’t we skip making K and just use V for the search?”\nThat is a sharp question.\nThe answer is no. Doing so would destroy the model’s performance because of Conflicting Optimization Goals.\nK (for searching) and V (for content) require fundamentally opposite vector characteristics:\nGoal of K: Keys need to be distinct. To prevent confusion, their features must be sharp. For example, the Key for “Banana” needs to scream “Fruit” and “Yellow” so it can be easily found. It needs to emphasize distinguishing features and discard noise. Goal of V: Values need to be rich. Since this information will be used as calculation material in the next layer, it needs to preserve context, part of speech, semantic nuance, and more. It’s better to be dense and rich than simple and sharp. If we forced (K=V), a single vector would have to be both a “sharp search index” and a “rich information container” simultaneously. It’s like trying to find food that is incredibly delicious but also perfectly healthy — possible, but very difficult.\nPut another way, it is like writing the entire text of the book on the cover.\nThe cover should act like a cover, and the content should act like content. They have different roles. By separating them, the Transformer gains a much more sophisticated ability to understand language.\n4. “Then can we combine Q and K since they are both for search?” “Okay, I get why V is separate. But Q and K are both used for matching. Can’t we just use one vector for both?”\nAnother great question. In fact, some early recommendation systems used exactly this approach (symmetric dot products).\nHowever, language has a critical feature called Asymmetry. Just like human relationships, relationships between words are not always mutual.\nTake this sentence for example:\n“Tom went to the store because he was hungry.”\nLet’s look at Tom and he.\nWhen Query is he and Key is Tom: To understand the sentence, he needs to know that it refers to Tom. When Query is Tom and Key is he: To understand the sentence, Tom generally has less need to know that he follows it later. In other words, he is very interested in Tom, but Tom might not be as interested in he.\nWhat happens if Q and K are not separated?\nScore(he, Tom) would be mathematically identical to Score(Tom, he). The model would be forced to assume that the interest between two words is always equal.\nBy separating Q and K, we get four different vectors: Q(he), K(he), Q(Tom), K(Tom). Consequently, Score(Q(he), K(Tom)) can be completely different from Score(Q(Tom), K(he)).\nThis allows the Transformer to model Directed Graphs, where A references B strongly, but B ignores A. This is crucial for parsing grammatical structures and logical flow.\n5. Why Attention is Not Just Similarity Let’s circle back to the original misunderstanding. Why isn’t Attention just similarity?\n5.1. Softmax: A Winner-Takes-All Competition The Self-Attention formula includes a Softmax operation.\nSoftmax is fundamentally about relative evaluation. No matter what the absolute input values are, it forces the sum to be 1.\nThis means Attention isn’t asking “How similar are you?” (absolute value). It is asking “Among all these candidates, which one is the most relevant to my current Query?”\nIt is a process of routing through competition, not just measuring distance.\n5.2. Aggregating and Moving The result of a standard similarity check is usually a single number (scalar): “We are 0.7 similar.”\nHowever, the result of Attention is a Vector. Multiple selected Values are mixed (Weighted Sum) to create a brand new vector.\nEssentially, information from various tokens is blended and physically moved to a new location in the sequence.\n6. Attention (Routing) vs. MLP (Computation) If you rip open a Transformer block, it has two main components:\nMulti-Head Attention Feed-Forward Network (MLP) Because the paper is titled “Attention is All You Need,” people tend to obsess over the Attention mechanism and treat the MLP as just a “pass-through” layer.\nHowever, recent research shows they play very different, distinct roles.\n6.1. Attention: The Logistics Hub The Attention layer is, at its core, a Linear Combination. It adds and subtracts Values. It usually does not apply non-linear transformations to the content of itself during the aggregation (though the scoring is non-linear).\nThe job of Attention is “Information Movement.”\n“Move the ‘past tense’ information from the start of the sentence to the verb.” “Copy the gender info from ‘Tom’ and paste it to ‘He’.” Attention acts as the logistics manager or router of the model. It decides where information should go.\n6.2. MLP: The Brain On the other hand, the MLP performs non-linear transformations (using activation functions like GELU or Swish). Unlike Attention, the MLP works on each token individually, without looking at others.\nThe job of the MLP is “Processing and Inference.”\nBased on the info brought in by Attention (“Subject is 3rd person singular” + “Tense is past”), the MLP calculates: “Okay, I need to conjugate the verb this way.” If Attention brings “Bank” and “Finance” together, the MLP processes this to realize: “This is a financial institution, not the side of a river.” Some researchers argue that the factual knowledge the model learns (e.g., “The capital of France is Paris”) is largely stored in the weights of the MLP layers.\nFurther Reading:\nKnowledge Neurons in Pretrained Transformers Locating and Editing Factual Associations in GPT Transformer Feed-Forward Layers Are Key-Value Memories 6.3. Transformer as a System From a systems engineering perspective, here is how the Transformer operates:\nAttention: Looks around the room and gathers necessary context. (Routing) MLP: Takes that gathered info, thinks about it alone, and extracts knowledge or logic. (Computation) Residual Connection: Adds this result to the existing information and passes it to the next layer. This cycle repeats dozens of times. What starts as simple word vectors gradually evolves into a high-dimensional representation capable of understanding context, logic, and complex reasoning.\n7. Conclusion: Don’t Get Lost in the Math We’ve explored why Q, K, and V are separated and how Attention and MLP divide the labor. To summarize:\nAttention is Routing, not just Similarity.\nIt is a sophisticated logistics system divided into Query (Question), Key (Address), and Value (Cargo). Splitting Q, K, and V is Essential.\nThe vector optimized for searching is different from the vector optimized for carrying content. Attention and MLP Collaborate.\nAttention delivers the right information to the right place; MLP analyzes that information to derive meaning. Some say Transformer is just a giant pile of matrix multiplications. While true mathematically, structurally it is a brilliant system design that decouples “Information Retrieval” from “Information Processing.”\nUnderstanding this perspective makes it much easier to interpret attention maps or debug models.\n","permalink":"https://blog.jiminl.com/posts/beyond-similarity-the-true-mechanism-behind-transformer-attention-a29a96782d8e/","summary":"This post is written for engineers who already know the Transformer basics but want to understand why it was designed this way.","title":"Beyond Similarity: The True Mechanism Behind Transformer Attention"},{"content":" 📌 Note: This article was originally written in April 2023. Even though I’ve updated parts of it, some parts may feel a bit dated by today’s standards. However, most of the key ideas about LLMs remain just as relevant today.\nSo… Are LLMs “Foundation Models”? Short answer: kind of, yes — but with caveats.\nLong answer: let’s walk through why a model trained to predict the next token can still feel like a general-purpose engine for NLP tasks.\nQuick recap: what a Language Model actually does Collect a massive amount of text. Show it to a language model. Train it to predict the next token (word/subword). Feed the model’s own output back into the input (auto-regressive) to generate long sequences. In other words, a Language Model predicts the next token; stretched out over many steps, it writes. Now, does making that model large turn it into an NLP foundation model — a base you can adapt to many downstream tasks? A strict yes/no is tough, but in practice: LLMs do a surprisingly good job today and are the closest thing we have so far. Better approaches may come; for now, LLMs are the front-runners.\nWhy can “just next-token prediction” look like general intelligence? Two big reasons.\n1) The breadth of data A student who has read widely writes better than one who hasn’t. Same for LLMs: while “knowledge” in a philosophical sense is debatable, training across diverse, large-scale text exposes the model to patterns, facts, styles, and structures from many domains. That breadth makes next-token prediction look powerful across tasks.\nThink of it this way: someone who’s read a mountain of detective novels can mimic the genre well — even if they’ve never solved a case.\n2) The power of Transformers It’s not just the data. Transformers learn statistical relationships across tokens efficiently. They don’t build an explicit knowledge graph with named entities and edges, but self-attention lets the model connect distant parts of text and maintain coherence over long spans. Multi-head self-attention is why an LLM can hold a thread instead of getting lost mid-paragraph.\nIf LLMs are a kind of foundation, how do we use them? Fine-tuning Assume the LLM already “knows” general language. You then fine-tune it on your task (sentiment, NER, classification, etc.) with labeled data.\nAnother way to view it: use the LLM as an initialization rather than starting from random weights. Starting near a good solution can converge faster and more reliably.\nReality check: As models grew, full fine-tuning became slow and expensive. That’s why we often reach for the next thing…\nIn-Context Learning (ICL): zero-shot \u0026amp; few-shot Instead of changing the model, change the input at inference time.\nZero-shot: “What’s the capital of South Korea?” Few-shot: Provide patterns first: USA -\u0026gt; Washington, D.C.\nJapan -\u0026gt; Tokyo\nChina -\u0026gt; Beijing\nSouth Korea -\u0026gt; ?\nThe model isn’t “answering a question” so much as continuing the pattern in the text you gave it. With strong base models, few-shot — and often zero-shot — are already useful without retraining.\nFine-tuning can still win on accuracy for some tasks. But for many practical cases, ICL gives you ‘good enough’ without training cost.\nPrompt Engineering LLMs are pattern completers. So how you phrase the input matters.\nWorse: What’s the capital of South Korea? Better: You’re a system that answers world-capital questions concisely.\nQuestion: What is the capital of South Korea? The second prompt supplies role, format, and intent, which biases the completion toward what you want.\nConversational LLMs Base LMs aren’t chatbots. But they act like one if:\n1) They see lots of dialog data during pre-training or fine-tuning, and\n2) We wrap user input with a dialog-style prompt before sending it to the model.\nHow is context maintained? We keep a running transcript:\nUser: What’s the capital of South Korea?\nAssistant: Seoul.\nUser: And Japan?\nThe model gets the whole history (up to the context window, measured in tokens), then continues it. That’s it — no magic, just careful prompt construction and truncation when the history gets too long.\nSteering with RLHF Left alone, a base LM will happily produce anything it thinks “fits” the next-token distribution — including unsafe or unhelpful text. Enter Reinforcement Learning with Human Feedback (RLHF): humans rank model responses; a reward model learns those preferences; the LM is optimized to produce safer, more helpful, more “on-policy” outputs.\nImportant: RLHF doesn’t grant new raw capabilities; it steers behavior. Sometimes raw benchmark scores even dip slightly while helpfulness/safety improve.\n\u0026gt; Updated: my article about the alignment: How Reinforcement Learning Taught LLMs to Talk Like Humans\nChallenges we shouldn’t hand-wave away Concentration of power Data access is improving (especially for English), but compute is the new bottleneck. Training frontier models requires huge GPU clusters and budgets, which risks consolidation among a few players. Open weights, shared preference datasets, and efficient training methods can help — but it’s an ongoing tension.\nCarbon footprint Training and serving LLMs consume significant energy. Estimates for a single large run can be hundreds of tons of CO₂-equivalent. The field is working on efficiency (better hardware, algorithms, and scheduling) and reporting emissions more transparently, but this is a real externality.\nHallucinations LLMs will invent details when the next-token distribution “leans that way.” The prose looks confident, which makes fact-checking hard. Mitigations include:\nRetrieval-augmented generation (RAG) to ground answers in external sources, Better prompts and system rules, Task-specific fine-tuning or adapters, Structured output and verification steps. Open questions Do LLMs “reason”? One camp: LLMs just do massive pattern matching.\nAnother: human reasoning might itself be pattern completion over experience.\nTruth likely sits between: techniques like chain-of-thought, tool use, and self-consistency push LLMs to perform surprisingly well on reasoning-like tasks — yet they still fail in distinctly non-human ways.\nArthur C. Clarke had a line for this: “Any sufficiently advanced technology is indistinguishable from magic.” We’re somewhere along that curve — impressive, but not magic.\n\u0026gt; Updated: my article about LLM intelligence: Do LLMs Actually Have “Intelligence”?\nWill LLMs replace doctors or lawyers? Passing an exam ≠ practicing the profession. Real-world work involves clients, tools, procedures, accountability, and context. Today’s LLMs won’t replace entire professions, but they already automate slices of knowledge work (drafting, summarizing, retrieval, brainstorming). The trajectory points toward AI-augmented professionals, not wholesale replacement — at least for now.\nBottom line Are LLMs the foundation model for NLP? Today, they’re the best we’ve got. Are they perfect? No. Can we adapt them to many tasks? Absolutely — and that’s why they feel foundational. ","permalink":"https://blog.jiminl.com/posts/3-3-llm-in-context-learning-hype-and-the-road-ahead-4d987a1b7d1e/","summary":"📌 Note: This article was originally written in April 2023. Even though I’ve updated parts of it, some parts may feel a bit dated by…","title":"(3/3) LLM: In-Context Learning, Hype, and the Road Ahead"},{"content":" 📌 Note: This article was originally written in April 2023. Even though I’ve updated parts of it, some parts may feel a bit dated by today’s standards. However, most of the key ideas about LLMs remain just as relevant today.\nLarge Language Models So, what happens when a regular Language Model gets bigger? You get a Large Language Model (LLM).\nBut we can’t just blow these things up infinitely. Three big roadblocks stand in the way:\nTraining Data: You need a ridiculous amount of it. Algorithms: Scaling requires smarter and more powerful algorithms. Compute Power: Think massive clusters of top-tier GPUs/TPUs. The fact that we can train LLMs today means these problems are being solved, at least partially. Interestingly, the same three factors — data, algorithms, and compute — are exactly what allowed the leap from traditional machine learning to deep learning. And history suggests they’ll be the levers again when the next paradigm shift comes.\nTraining Data Every machine learning model needs data. And the stronger the model you want, the more data you need.\nThis has always been one of the hardest parts of ML: collecting data, and then labeling it with the right answers (positive/negative, named entity positions, etc.).\nBut here’s the twist: language models have a cheat code.\nSelf-Supervised Learning Labeling by hand is expensive — time, money, human effort. Which means scaling is painful.\nTake a simple sentence: “I went to school yesterday.” From that one sentence, you can generate your own training examples automatically:\n“I” → predict “went” “I went” → predict “to” “I went to school” → predict “yesterday” No humans required. As long as you have text, you can create training data automatically.\nThis approach is called self-supervised learning. Unlike classic unsupervised learning (where no labels exist at all), self-supervised methods generate labels directly from the raw data itself. That’s why modern LM training almost always falls under the self-supervised umbrella.\nWeb-Scale Data Back in the early days, available text datasets were tiny: a few MBs of news articles, some licensed books, or manually curated corpora. Even Wikipedia dumps in the single-digit GB range felt massive.\nThen the internet changed everything. The web is fundamentally text-driven, and its scale is mind-boggling. Wikipedia? That’s just a drop in the bucket.\nProjects like Common Crawl began collecting enormous swaths of web data — tens of terabytes and growing. And the best part? It’s freely available.\nOn top of that, many platforms have released their own cleaned-up datasets (within legal limits), which, while smaller, often have much higher quality than raw crawled text.\nWhen the Two Collide Now put these pieces together:\nSelf-supervised learning means we don’t need humans to label text. Web-scale data means we suddenly have oceans of training material. The result? A perfect storm for building today’s LLMs. That’s how we got from tiny datasets in the MB range to massive, automatically labeled corpora in the TB range — the fuel that makes GPTs, PaLMs, and LLaMAs possible.\n⚠️ Spoiler Alert\nThis section dives into the geeky, technical weeds. If that’s not your thing, feel free to just take away this: Transformers are insanely powerful algorithms. Then, skip ahead and scroll straight down to the Compute Power section.\nAlgorithms Even if you have oceans of data, you still need a good algorithm to digest it.\nAnd here enters the celebrity of modern AI: the Transformer.\nReleased by Google in 2017, the Transformer is both an architecture and a set of structural ideas. You’ll hear people call it the Transformer model, the Transformer architecture, or just Transformer. Doesn’t matter — it’s the engine under the hood of nearly every LLM today.\nBut why is this thing so powerful? To explain that, we need to take a quick detour into a core concept: Sequence-to-Sequence models.\nSequence to Sequence First things first: what’s a sequence? It’s just a list of items in order.\n1, 5, 3, 2, 1 → a sequence of numbers ant, frog, dog, horse → a sequence of animals I, went, to, school, yesterday → a sequence of words In NLP, our main interest is the last one: word sequences, or simply, sentences.\nNow, Sequence-to-Sequence (seq2seq) literally means sentence → sentence. In other words, one sentence gets transformed into another.\nThe most obvious example? Translation.\n“나는 어제 학교에 갔다.” → “I went to school yesterday.” But translation isn’t the only seq2seq task:\nSummarization: long text → shorter text Sentiment classification: review text → “positive” or “negative” (classification framed as text output) Named Entity Recognition: input sentence → same sentence but with tags/highlighted entities (also cast as seq2seq) Once you think this way, you realize seq2seq is almost a universal recipe for NLP tasks.\nHow Do We Translate? Here’s the million-dollar question: how does your brain actually translate “나는 어제 학교에 갔다” into “I went to school yesterday”?\nAnswer: we don’t really know.\nA classic hypothesis is the Inter-lingua theory: instead of going word-by-word, the brain converts the sentence into some abstract, universal “meaning language” (the inter-lingua) and then expresses it in the target language.\nConceptually:\nKorean sentence → Inter-lingua Inter-lingua → English sentence In ML terms:\nEncoding: convert source text into a hidden representation Decoding: generate the target text from that hidden representation That hidden representation isn’t human language. It’s an abstract space — what we in ML usually call latent vectors. The “inter-lingua” metaphor is useful, but in practice it’s math.\nEncoding and Decoding — With an Analogy Think data formats:\nEncoding: turning light into video files, or compressing files into ZIP format. Same content, different form. Decoding: playing that video file, unzipping that compressed folder, or decrypting a spy’s coded message. Sometimes we call decoding generation, especially in NLP, since the model isn’t just restoring the original — it’s producing new text in a different form.\nThat’s exactly what translation does:\nEncode: Korean → latent meaning representation Decode: latent meaning → English Why does this matter?\nThis encode/decode structure is perfect for deep learning because ML excels at learning A → B mappings from lots of examples. With enough bilingual pairs (or any source–target pairs), a model can learn how to encode and decode by itself.\nAnd that’s where Transformers come in: they’re the best seq2seq engine we’ve discovered so far.\nBack to Transformers At its core, a Transformer is a very clever encoder–decoder model.\nIf you’ve Googled “Transformer” before, you’ve almost certainly seen a diagram like this: (left = encoder stack, right = decoder stack).\nFlow:\nThe input sentence (“I went to school yesterday”) goes into the encoder stack on the left. It passes through several encoder blocks, gradually turning into a Context representation. That Context is fed into the decoder stack on the right, where it guides generation. The decoder outputs probabilities for each possible next word. Let’s make this concrete. Imagine our vocabulary has 10,000 words:\nID 1 = “a” ID 2 = “apple” … ID 8789 = “went” If the decoder is trying to predict the next word after “I,” it might output something like:\nWord 1 (“a”): 0.00001 Word 2 (“apple”): 0.0004 … Word 8789 (“went”): 0.901 Clearly, “went” is the winner.\nStacking Blocks Those “Encoder” and “Decoder” boxes are actually stacks of blocks:\nEach Encoder Block feeds the next Encoder Block. After stacking N of them, the final block’s output becomes the encoder’s Context. The Decoder works the same way, with multiple Decoder Blocks stacked. Why stack blocks? Same reason we make deep neural networks “deep.” More layers = more expressive power = better performance.\nCaveats:\nIf you scale the model without enough data, performance can get worse. Bigger models demand far more compute and memory for both training and serving. In other words: stacking is powerful, but it comes with a bill — sometimes a very expensive one.\nSo, What’s the Relationship Between Transformers and Language Models? We’re not studying Transformers in isolation — we’re asking why they made LLMs possible.\nAt its core, a Language Model (LM) has a very simple job:\nPredict the next word, given the text so far.\nFor example:\nInput: “The flowers by the roadside are blooming …” Bad guess: “punched.” Good guess: “beautifully.” And guess what? Transformers are ridiculously good at this game.\nBack to Our Example Take the sentence: “나는 어제 학교에 갔다.” (Korean: I went to school yesterday.)\nThe encoder processes this input and produces a hidden Context representation (a compressed “meaning” in vector form). The decoder turns that Context into English — but it uses two inputs: The Context (from the encoder) Outputs (the decoder’s previously generated tokens) Why “Outputs” as input? Because the decoder is auto-regressive — it feeds its own past predictions back in.\nThe Auto-Regressive Loop Walkthrough:\nEncoding: The encoder converts “나는 어제 학교에 갔다” into Context vectors. First step: Context + \u0026lt;start\u0026gt; → predict “I.” Second step: Context + “I” → predict “went.” Third step: Context + “I went” → predict “to.” Repeat until “the school yesterday.” Stop at \u0026lt;end\u0026gt;. Result: “I went to the school yesterday.”\nTwo Key Ideas One word at a time: The decoder generates token by token (why ChatGPT looks like it’s “typing”). Predictions feed back in: Each new token becomes input for the next step (auto-regression). Perfect alignment:\nThe job of an LM is “predict the next word.” The mechanism of the Transformer decoder is auto-regressive next-word prediction. If we want a plain LM that predicts the next word in the same language, we make a small but important tweak…\nEncoder-Only, Decoder-Only The full Encoder–Decoder Transformer is powerful, but not everyone needs both halves. Researchers asked: What if we only used the encoder? What if we only used the decoder?\nEncoder-Only The most famous encoder-only model? BERT.\nBERT keeps just the encoder stack. Sometimes all you need is a good representation of text (context vectors), not generation.\nGreat for classification tasks:\nIs this review positive or negative? Does this sentence contain a person’s name? Classification works on embeddings. Better embeddings → better classifiers. BERT looks at text bidirectionally, encodes whole sentences, and produces rich representations. Plug them into a classifier and accuracy jumps.\nIs BERT a language model? Strictly, no — it doesn’t do auto-regressive next-word prediction. It’s trained as a masked language model (predict the missing word), which is different from traditional LMs.\nDecoder-Only On the other side: GPT.\nGPT (GPT-2/3, ChatGPT, GPT-4…) keeps only the decoder stack.\nWhy drop the encoder? If your goal is just next-word prediction — the pure LM task — you can feed the decoder with the text so far and let it continue auto-regressively.\nInput: “The flowers by the roadside are blooming” Decoder predicts: “beautifully.” That prediction feeds back in, and generation continues. This is why GPT and its cousins (LaMDA, PaLM, LLaMA, Claude, etc.) follow the decoder-only recipe. It’s the simplest and most direct way to scale LMs into generative engines.\nEncoder + Decoder Models like T5 and BART keep the full structure and shine at clear input → output transformations (translation, summarization, etc.).\nEncoder vs. Decoder Historically, encoder-only exploded first (BERT) because many NLP tasks were classification-heavy. Decoder-only models initially looked like “nonsense generators.”\nKey difference:\nEncoder-only models can’t generate text. Decoder-only models can — and with scale, their potential is enormous. Even classification can be reframed as generation (“The review is … [positive/negative]”). That’s why decoder-only LMs became the dominant LLMs.\nA Long Tradition Transformers didn’t invent encoder–decoder. Before 2017, RNNs/LSTMs/GRUs were the standard way to build it. Transformers replaced RNNs.\nBiggest reason people cite: Self-Attention.\nWhy Do Transformers Work So Well? Self-Attention Two concepts are central:\nThe Encoder–Decoder structure Self-Attention Let’s start with Attention itself.\nAttention Attention first showed up in RNN-based seq2seq models. Recall the pipeline:\nInput → Encoder → Context → Decoder → Output\nThe decoder generates tokens one by one. Early models used a fixed Context for every step, but different output words need to “look back” at different parts of the input.\nExample:\n“나는 어제 학교에 갔습니다.” → “I went to school yesterday.”\nIf the model could focus on 갔습니다 (went) and 어제 (yesterday) at the right time, it would more reliably pick “went” (past tense) over “go.”\nThat’s Attention: at each step, re-weight which parts of the input matter most.\nSelf-Attention Seq2seq Attention asks: Which parts of the source should I attend to while generating the target?\nSelf-Attention asks: Within a single sentence, which words should each word attend to?\nExample:\n“The animal didn’t cross the street because it was too tired.”\nHere, “it” should link strongly to “animal”, but also relates to “tired.”\nWhy is this powerful for LMs?\nTo predict “bloomed” in “The flowers by the roadside … bloomed,” “flowers” should get the highest weight. To pick tense, “yesterday” matters more than “school.” Self-Attention lets the model discover this automatically.\nMulti-Head Self-Attention Language has multiple relationship types:\nGrammatical (subject ↔ verb) Semantic (animal ↔ it) Attributes (it ↔ tired) One attention map can’t capture every view. The fix: run multiple attention heads in parallel, each with a different “view.”\nUnder the hood, word embeddings are split into subspaces (chunks of numbers). Each head attends within a different subspace, encouraging different aspects (grammar, meaning, style) to emerge.\nInstead of one spotlight, give the model a dozen flashlights, each shining on a different relationship.\nThat’s the magic of Multi-Head Self-Attention — one of key reasons Transformers dethroned RNNs.\n175B? 540B? What Do Parameter Counts Actually Mean? You’ll often hear sizes like 175B (GPT-3) or 540B (PaLM). These are the number of parameters — the weights in the Transformer.\nMore parameters → more capacity. Hence the popular (but flawed) shortcut:\nBigger model → better performance.\nIn reality, performance depends on more than size:\nHow much data was used? How high-quality was that data? Were the hyperparameters tuned well? How long (and how thoroughly) was the model trained? So why do parameter counts dominate? They’re easy to understand.\nIf someone asks, “Which model is better, A or B?” you could unpack data quality, training steps, and optimizers… or say:\n“Model A is 70B. Model B is 200B. Model B is better.”\nIt’s not necessarily true — but it’s simple.\n⚠️ Pro tip: If someone talks about model quality only in terms of parameter count, be cautious. They either don’t fully understand, or they’re trying to sell you something.\nTransformer in a Nutshell Transformers were designed for Sequence-to-Sequence tasks. The most common form is the Encoder–Decoder structure. Variants exist: Encoder-only (BERT), Decoder-only (GPT), Encoder+Decoder (T5, BART). To generate language, you need a Decoder. A core innovation is Self-Attention. To capture different perspectives (grammar, semantics, style), Transformers use Multi-Head Self-Attention. Compute Power The last ingredient: compute.\nLLMs wouldn’t exist without massive progress in hardware and infrastructure:\nGPUs (and TPUs) unlocked massively parallel training. GPUs were the rocket fuel of the deep learning boom, and today Nvidia still dominates with CUDA, optimized libraries, and cutting-edge hardware. Parallel training techniques allow hundreds (or thousands) of GPUs to train a single model in sync. Cloud infrastructure made it practical. Buying racks of GPUs is brutally expensive — and they start depreciating the moment you unbox them. Renting from AWS, Azure, or GCP lets teams scale without opening a hardware graveyard in the office. In short: faster chips + smarter software + elastic cloud = the horsepower that makes LLMs possible.\nWhy LLMs Happened Now We’ve walked through the three big ingredients:\nData: Web-scale text + self-supervised learning → oceans of training material. Algorithms: Transformers (self-attention, scalable stacks) replaced RNNs. Compute: GPUs/TPUs + cloud infrastructure → enough horsepower to train monster models. Each piece alone would’ve been impressive. Put together, they sparked a step-change.\nA decade ago, we had:\nLimited datasets (a few gigabytes at most). Algorithms (RNNs, LSTMs) that struggled with long sequences. GPUs that couldn’t realistically handle 100B+ parameter models. Today, we have:\nTens of terabytes of training data at our fingertips. Transformer architectures that scale beautifully. GPU/TPU clusters that can train trillion-parameter models. No single breakthrough “invented” LLMs. It was the intersection of trends — data, algorithms, compute — that finally clicked into place.\nThat’s why LLMs feel like they appeared “all of a sudden.” The truth is, researchers were laying the groundwork for years. The moment the three factors aligned, the field exploded.\nAnd that’s where we are now: riding the wave of models that are bigger, smarter, and more capable than anyone thought possible five years ago.\nIn the next post, I’ll dive into zero-shot, few-shot, prompting, and the rest of the story.\n","permalink":"https://blog.jiminl.com/posts/2-3-llm-data-transformers-and-relentless-compute-f429485ec002/","summary":"📌 Note: This article was originally written in April 2023. Even though I’ve updated parts of it, some parts may feel a bit dated by…","title":"(2/3) LLM: Data, Transformers, and Relentless Compute"},{"content":" 📌 Note: This article was originally written in April 2023. Even though I’ve updated parts of it, some parts may feel a bit dated by today’s standards. However, most of the key ideas about LLMs remain just as relevant today.\nGetting Started With the rise of ChatGPT, the buzz around Generative AI and Large Language Models (LLMs) has been explosive. Just a few months ago, terms like “generative” or “language model” felt like insider jargon — something only AI folks tossed around. But now, you’ll hear them casually dropped in coffee shop conversations.\nWhat’s even more surprising is that these aren’t just buzzwords anymore — they’re being used in everyday life. Running an image-to-text model on your laptop? Spinning up something like LLaMA locally? That used to be rare.\nNaturally, this flood of attention has also produced a flood of explainer content. So you might wonder, “Do we really need yet another article on this?” Maybe not. But I wanted to share something practical that might help you better understand what Large Language Models really are.\nThis article won’t dive into math equations or heavy code. Instead, we’ll cover the past, present, and future of LLMs, with some light technical explanations sprinkled in.\nFoundation Models To talk about LLMs, we first need to talk about Foundation Models. The term is pretty literal — foundation means base, so a foundation model is a “base model.”\nBut what does that actually mean? The best way to understand it is to look at what things were like before foundation models existed.\nLife Before Foundation Models Imagine you want to build a system that can tell whether a product review is positive or negative. Traditionally, you’d go through these steps:\nCollect a huge amount of review data from the internet. If you don’t have enough, sometimes you even generate synthetic reviews. Label the data as positive or negative. This step is called annotation or tagging. Pick a machine learning method (these days, usually deep learning) and train on the labeled data. Evaluate the trained model, then repeat until performance is good enough: If there’s not enough data, collect and tag more. If the labels aren’t accurate, fix them. If the algorithm isn’t working well, try another one. Or tune the model hyperparameters. Now take another example: say you want to build a system that extracts names of people and places from text. Same process — except this time, instead of tagging reviews as positive/negative, you highlight names and places.\nIn short, every task required its own dataset and its own model. Obvious? Yes. Efficient? Not really.\nEnter John and Mike Let’s illustrate this with a conversation:\nJohn: “Man, it’s exhausting to collect and label new data for every single task. And the stronger the algorithm, the more data it demands.” Mike: “That’s life as an AI engineer. It’s how it’s always been.” John: “But think about it. At the end of the day, all these tasks deal with language. Isn’t there a shared foundation?” Mike: “Not really. Sentiment classification and name-entity recognition are totally different.” John: “Maybe. But look — my brother’s a humanities major, and I’m an engineer. Our fields are worlds apart, but we can still chat just fine in English.” Mike: “Right, because you both learned English.” John: “Exactly. What if we gave an AI that same foundation — train it once on the basics of language, and then just add task-specific knowledge on top? Like how I can switch between engineer mode at work and boyfriend mode with my girlfriend, but I’m still the same person.” Mike: “Hmm… interesting point.” That idea? That’s a Foundation Model.\nWhy It Matters Traditionally, “Engineer John” and “Boyfriend John” would be two totally separate people — born different, trained different, lived different. But in the foundation model view, it’s one John who can switch modes depending on the context.\nNow imagine a NLP Foundation Model.\nWant to build a sentiment classifier? Just fine-tune it with a small set of positive/negative labels. Want to build a name extractor? Use the same foundation model, but fine-tune it with tagged sentences. With this approach:\nYou need less data per task. Or, with the same amount of data, you get better performance. If neither is true, then there’s no point in building foundation models. But when it works, the payoff is huge: one base model, lightly tuned, powering many tasks.\nAnd in NLP, the strongest foundation models we have today are Large Language Models.\nLarge Language Models So, LLMs are foundation models — specifically, foundation models for NLP. But what exactly is a language model?\nWhat’s a Language Model? The phrase “language model” sounds fuzzy, doesn’t it? It feels like it should mean “a model of language,” but that’s not very precise.\nIn NLP, a language model has a specific definition: It predicts the next word given some text.\nFor example:\nInput: “The flowers along the road bloomed …” Likely next word: “beautifully.” Unlikely next word: “punched.” A good language model learns from tons of real sentences and picks the most natural continuation. Importantly, it doesn’t just memorize — it generalizes patterns from the data.\nTwo Main Uses With a language model, you can:\nPredict the next word in a sequence (auto-completion). Judge how natural a sentence is (assign probabilities). Examples:\n“The flowers bloomed beautifully.” → High probability “The flowers punched beautifully.” → Low probability Why This Matters for Foundation Models Predicting the next word may sound simple, but it requires surprisingly deep abilities:\nVocabulary knowledge: knowing many words. Grammar knowledge: picking the right form. Context awareness: using prior sentences to choose the right meaning. If a model can do all that, then it has learned something pretty close to “understanding language.”\nSo, the next logical step? Make the model bigger. Much bigger.\nBecause one of the core beliefs in machine learning is: scale makes models smarter.\nIn the next post, I’ll take a brief look at the background that made the rise of LLMs possible.\n","permalink":"https://blog.jiminl.com/posts/1-3-llm-how-llms-became-the-bedrock-of-modern-ai-011ff3aa6fb0/","summary":"📌 Note: This article was originally written in April 2023. Even though I’ve updated parts of it, some parts may feel a bit dated by…","title":"(1/3) LLM: How LLMs Became the Bedrock of Modern AI"},{"content":"LLMs are Massive. I Mean, Really Massive.\nBecause of their sheer size, most LLM optimization techniques focus on one thing: how the model handles memory.\nToday, I want to talk about PagedAttention, a technology that has become the gold standard in the field. It’s also the beating heart of vLLM, one of the trendiest serving frameworks out there right now.\nBut before we dive into how it works, let’s talk about the problem it’s trying to solve.\n1. The Real Culprit Isn’t the Model Size When people hear that LLMs eat up memory, they usually blame the model’s parameters (weights).\nThey aren’t wrong. A 70B parameter model occupies roughly 140GB of VRAM just by sitting there. However, this is a constant. Once you decide to use a 70B model, that number doesn’t change. It’s a massive chunk of memory, but at least it’s predictable.\nThe real problem is the variable. The culprit that actually causes memory to explode during production is the KV Cache.\nWhat exactly is a KV Cache? I’ve covered the nitty-gritty of this in my previous post, “Understanding the KV Cache (feat. Self-Attention),” but for today, let’s keep it simple.\nLLMs are essentially “next-word prediction” machines.\n“Once upon a time, there was a…”\nTo generate the next word, “dragon,” the model needs to understand the context of the preceding words. This context is stored in the form of vectors (clusters of numbers) called the KV Cache.\nOnce “dragon” is generated, the model needs to generate the next word. To do that, it now needs the context for “Once upon a time, there was a dragon.” The KV Cache just grew by one word.\nEvery time a token is generated, it gets tucked into the KV Cache. It keeps growing and growing. If a conversation gets long, the stored context becomes a mountain of data.\nTo make matters worse, every user has a different conversation length. One person might just say “Hi,” while another asks the model to write a full-length novel.\nThis unpredictability — not knowing how much will be input or how much will be generated — is where the inefficiency begins.\n2. The Legacy Problem: Too Many “Reserved Seats” Before PagedAttention, how did deep learning frameworks manage this KV Cache?\nSince they didn’t know how much space would be needed, they just reserved the maximum possible amount.\nImagine a restaurant owner who sees one customer walk in. Fearing that the customer might eventually bring 100 friends, the owner reserves a 100-seat long table and refuses to let anyone else sit there.\nIn LLM terms, the framework would allocate a contiguous block of memory equal to the model’s maximum sequence length (e.g., 2048 tokens) right from the start.\nThis leads to two types of serious waste:\nInternal Fragmentation: You reserved space for 2048 tokens, but the user only generated 100. The remaining 1948 slots are just dead space. External Fragmentation: Small gaps of memory are left over between different requests, but because they aren’t contiguous, they can’t be used to store a long sequence. Think of a bar with stools. People come and go, leaving single empty seats scattered around. You see 1 empty seat here, 2 there, and another 1 further down. Total empty seats: 4.\nNow, a group of 3 friends walks in. They want to sit together. Even though you have 4 seats available, you can’t seat them because you don’t have 3 consecutive seats.\nThe KV Cache worked the same way. It demanded contiguous memory. So, even if there was enough total memory available, it would go to waste if it wasn’t in one solid block.\nResearch shows that in traditional systems, roughly 60% to 80% of GPU memory was being wasted. Imagine buying a $40,000 A100 GPU and using $30,000 of it just to heat the room.\n3. Finding Answers in a 30-Year-Old Textbook To solve this, researchers didn’t look at the latest AI papers. Instead, they cracked open a classic Computer Science textbook: Operating Systems.\nOperating systems like Windows, macOS, and Linux faced this exact same problem decades ago. Giving every program a giant “chunk” of memory was wasteful. The solution they found was Virtual Memory and Paging.\nThe core idea of PagedAttention is beautifully simple:\n“Does data really need to be stored in a contiguous block? Why not break it up and shove the pieces wherever there’s a gap?”\nThe Art of Packing a Suitcase Imagine you’re playing Tetris.\nThe long straight blocks are great. You can clear four lines at once. But as anyone who has played knows, you can’t always count on them. Eventually, you end up with weird gaps, and the long blocks just sit on top, taking up space until it’s Game Over.\nHave you ever wished you could just snap that long block into three pieces and fit them into those annoying gaps?\nCongratulations. You just invented PagedAttention.\nWhile legacy methods treated the KV Cache like that long, rigid Tetris block, PagedAttention breaks the data down:\nIt splits the KV Cache into small units called Blocks. (Usually, one block holds data for 16 tokens.) It takes these blocks and puts them anywhere there is a free spot in the GPU memory, regardless of physical location. By doing this, you don’t need to find a giant contiguous space. You can use every last nook and cranny of the VRAM. Memory waste drops to nearly zero.\n4. Keeping it Organized: The Block Table You might be thinking: “Splitting them up is fine, but if the data is scattered everywhere, how do you keep the sentence in order?”\nFor an LLM, sequence is everything. If the data gets mixed up, you’ll get gibberish.\nThis is where the Block Table comes in. Think of it as an address book. It maps two things:\nLogical Blocks: The order of the sentence as the user sees it (Block 0, Block 1…). Physical Blocks: The actual address in the GPU memory (Block 0 is at Address 100, Block 1 is at Address 5…). With this address book, the system can always find the correct token data, no matter where it’s physically hiding in the VRAM.\nThe Attention Calculation Flow Let’s look at the “under the hood” process:\nA user sends a prompt. As the model starts computing, the PagedAttention kernel kicks in. The kernel checks the Block Table: “Okay, the first part of the context is in that corner, and the second part is over there.” It fetches those scattered pieces and performs the Attention calculation instantly. This process is incredibly efficient. There’s almost no overhead in finding and retrieving the data.\nOne reason it’s so fast is that the vLLM team implemented a custom CUDA kernel at the GPU low-level. Instead of using complex conditional logic in high-level code, PagedAttention handles the Block Table lookup and Attention calculation simultaneously across thousands of GPU cores.\nBecause of this, we can trick the model into thinking the data is contiguous while wasting zero memory.\n5. Memory Sharing: The Real Game Changer The benefits of PagedAttention don’t stop at filling gaps. By managing memory in blocks, a revolutionary feature becomes possible: Memory Sharing.\nImagine this scenario:\nUser: “Explain the philosophy of G.W.F. Hegel.”\nSystem: (To ensure a high-quality answer, the system uses Parallel Sampling to generate three different responses at once.)\nIn a traditional system, the KV Cache for the prompt (“Explain the philosophy of G.W.F. Hegel”) would be copied three times — once for each response process. That’s 3x the memory for the exact same data.\nWith PagedAttention:\nReference: It creates only one set of KV Cache blocks for the prompt. Mapping: All three processes point to that same block in their block tables (Read-Only). Copy-on-Write: Only when the three responses start to diverge (generating different words) does the system allocate new, separate blocks for each. This is the exact same Copy-on-Write (CoW) technique used when Linux forks a process. It’s a classic programming pattern.\nThanks to this, advanced decoding techniques like Beam Search or Parallel Sampling can run with a fraction of the memory they used to require.\n6. So, How Much Faster Is It? All these techniques are packed into the vLLM library. So, what does the performance look like?\nCompared to the HuggingFace Transformers library (the previous standard), vLLM is anywhere from 2x to 24x faster in terms of throughput.\nA quick clarification: this doesn’t mean a single user gets their answer 24x faster (Latency). It means the number of users the system can handle at the same time (Throughput) increases by up to 24x.\nWhy does throughput increase? It’s simple math:\nPagedAttention eliminates memory waste. The “saved” memory can be used to squeeze in more simultaneous requests (Increased Batch Size). More users are processed in a single GPU compute cycle. Consequently, the traffic a single server can handle skyrockets. For a business, this translates directly to cost savings. Instead of running 10 GPU servers, you might be able to handle the same load with just one or two using vLLM.\n7. Swap-out / Swap-in: The Safety Net What happens if the server is so popular that even with PagedAttention, the GPU memory hits its limit? Normally, the system would crash with an “Out Of Memory” (OOM) error.\nBut PagedAttention borrows one more piece of wisdom from the OS: Swapping.\nBlocks that aren’t immediately needed are “swapped out” of the GPU memory and moved to the CPU memory (RAM). When those blocks are needed again, they are “swapped in” back to the GPU.\nWhile moving data between the GPU and CPU is slower, it prevents the worst-case scenario: a server crash. It ensures the service remains stable even under extreme load.\n8. Conclusion: Innovation through Reinterpretation If you’ve ever taken an Operating Systems course, this might all feel strangely familiar. That’s because PagedAttention is a brilliant application of 30-year-old OS paging concepts to the modern problem of LLM serving.\nTo recap:\nThe Problem: Memory fragmentation and waste due to unpredictable KV Cache sizes. The Solution: PagedAttention, which breaks memory into blocks for non-contiguous storage. The Tool: A Block Table that bridges logical and physical addresses. The Bonus: Massive throughput gains and memory sharing for complex decoding. Looking at the lightning-fast evolution of AI, it’s easy to get overwhelmed by new theories. But often, the best innovations come from applying the “old” wisdom of Computer Science to new problems. It almost makes me wish I’d paid a little more attention in my undergraduate CS classes!\n","permalink":"https://blog.jiminl.com/posts/pagedattention-the-os-trick-that-made-llm-serving-scalable-4f764e2c4b49/","summary":"LLMs are Massive. I Mean, Really Massive.","title":"PagedAttention: The OS Trick That Made LLM Serving Scalable"},{"content":" Note: This article was originally written in May 2024. Even though I’ve updated parts of it, some parts may feel a bit dated by today’s standards. However, most of the key ideas about LLMs remain just as relevant today.\nWhy Context Window Size Matters in LLMs When you look at a new LLM release these days, there’s one number that always makes the headlines: context window size. Accuracy, cost, latency — those all matter, but context length has become a bragging right of its own. Google even announced that Gemini can handle up to 1 million tokens in a single context window.\nBut what exactly is a context window? Why does it matter so much, and why is it such a hard technical problem? Let’s dive in.\nWhat’s a Context Window, Anyway? In simple terms, the context window is the maximum amount of input text an LLM can process at once. If you’re using ChatGPT, it’s the length of your prompt — the question you ask or the instructions you give.\nSince LLMs don’t process raw characters but tokens, we measure context size in tokens. Roughly speaking, in English, 1 token ≈ 2 to 4 characters (though this varies depending on the tokenizer).\nHere’s how popular models stack up:\nThe bigger the context window, the more information you can stuff into a single prompt.\nWhy Bigger Is Better Imagine you’re building a document summarizer with an LLM. You’d probably use a prompt like this:\nYou are a summarizer. Summarize the following document faithfully, without adding outside information, and preserve the original language.\n(original text)\nThe catch: how much of that document can you actually fit inside the prompt?\nA short story is ~100K tokens (Harry Potter and the Sorcerer’s Stone is in this ballpark). The Lord of the Rings trilogy? About 750K tokens. Add HTML tags or PDF metadata, and the input size balloons further. Now factor in multimodal input: modern LLMs also accept images, audio, even video. Google claims Gemini 1.5’s 1M token window can fit an hour of video or 11 hours of audio in one shot.\nIn other words: the bigger the window, the richer and more complex the tasks you can handle.\nWhy It’s Hard to Scale Up So if everyone wants bigger windows, why don’t all models just support it? Turns out, it’s not as easy as flipping a switch.\nFrom here on, we’ll dive into the inner workings of the Transformer itself — so a bit of background knowledge is helpful.\nIf you’re new to Transformers, I recommend checking out this blog post or one of the many excellent Transformer explainers available online before continuing.\n1. It’s Not About Parameters Model size (embedding dimensions, number of layers, heads, etc.) doesn’t directly set the context window. Architecturally, Transformers can, in theory, handle arbitrarily long inputs.\nBut in practice, models are only trained up to a certain input length. GPT-3.5, for instance, is “guaranteed” to work well up to 4K tokens. Sure, you could feed it 8K — but performance would degrade. That’s why APIs enforce strict limits: not because the model literally can’t run longer, but because providers don’t want you seeing garbage outputs.\n2. Training Data If you only ever read 10-page short stories, you might become an excellent short-story writer. But ask you to write a 10-volume epic? You’d probably stumble.\nLLMs are the same. To handle long inputs, they need to train on long sequences. But high-quality long-form data is hard to find. Simply concatenating short snippets doesn’t cut it — you end up with noise, not real long-form structure.\n3. Compute Cost Transformers use attention mechanisms with quadratic complexity: doubling the input length makes computation ~4× slower.\nTraining time doubles (6 months → 12 months). Inference latency doubles (3s → 6s). Serving cost rises, so API prices go up. This is why you see so many innovations like FlashAttention, Multi-Query Attention (MQA), and Grouped Query Attention (GQA) — they make long contexts computationally feasible.\n4. Positional Encoding Transformers need to know not just what tokens are, but where they are. Early models used absolute positional encodings (token #1 always has vector A, token #2 always vector B, etc.).\nThe problem? If you trained only up to 4,096 tokens, the model has never seen what token #8,192 looks like. It generates a positional vector — but it’s unfamiliar, so quality drops.\nTwo clever fixes emerged:\nALiBi (Attention with Linear Biases) Instead of encoding absolute positions, ALiBi encodes relative distances between tokens. Whether “friend” and “played” are tokens #2 and #3 or #402 and #403 doesn’t matter — the model just learns they’re next to each other.\nThis makes models much more robust to longer inputs. The catch: you need to train with ALiBi from scratch.\nPositional Interpolation For existing models, there’s a hack: squeeze more positions into the same encoding space. A 4-position model with indices [0,1,2,3] can be interpolated into [0,0.5,1,1.5,2,2.5,3,3.5].\nIt’s not as strong as ALiBi, but it lets you extend context windows without retraining from scratch.\nThe Context Arms Race So why do labs keep pushing context limits?\nUser demand: more serious use cases (long docs, multimodal input) need longer windows. Performance gains: giving models more input often makes them smarter. Marketing: “1M tokens!” sounds impressive on a launch slide. Of course, offering giant windows is expensive. That’s why providers tier their APIs: a 4K context is cheap, a 128K or 1M context costs much more.\nFinal Thoughts Context window size isn’t just a random number in a model spec — it hides a lot of deep engineering trade-offs in data, compute, and architecture.\nNext time you see a flashy LLM release boasting “Now with 1M tokens!”, you’ll know what’s behind the claim: months of data curation, expensive training, and clever math tricks to keep the whole thing running fast enough to be usable.\n","permalink":"https://blog.jiminl.com/posts/understanding-context-window-size-in-llms-db2151275268/","summary":"Note: This article was originally written in May 2024. Even though I’ve updated parts of it, some parts may feel a bit dated by today’s…","title":"Understanding Context Window Size in LLMs"},{"content":"Let’s talk about one of the most talked-about LLM patterns: RAG. The acronym stands for Retrieval-Augmented Generation.\nBefore diving in, a quick detour: what’s the difference between search and retrieval? It matters for understanding RAG.\nSearch is the act of finding something among many candidates. You search the web for a specific page; you press Ctrl/Cmd+F to search inside a long document. Retrieval literally means bringing back or pulling out items from a collection. In a library, you retrieve a specific book from the stacks; in a database, you retrieve a particular row. In practice, retrieval usually includes search: you first find what you need, then you pull it out to use it. So when people say RAG, they really mean search + fetch relevant items → use them to improve generation. “Search-and-retrieve-augmented generation” would be more precise but also a mouthful. Since we search precisely to retrieve and use the results, “Retrieval-Augmented Generation” is a fine name.\nAlright, why did RAG show up in the first place?\nThe Chronic Problem with LLMs Decoder-style LLMs do one thing extremely well: predict the next token given the previous tokens. If a model sees “Once upon a,” it learns to continue with “time.” How? During training it ingests a massive amount of text and learns statistical regularities.\nBut what happens when the model faces inputs outside its training experience? Humans can say “I don’t know.” Models generally can’t — machine learning systems don’t naturally have a concept of knowing that they don’t know. So they still predict the next token as best they can. That’s when hallucinations happen: the model produces fluent, confident, but factually wrong text.\nThink of someone who’s incredibly persuasive, hates admitting ignorance, and knows nothing about, say, medieval European history. Ask them about it, and they’ll spin a very convincing yet completely fabricated story. LLMs can behave the same way: plausible text, shaky truth.\nAsk a general-purpose model, “Who’s the tallest person on our team?” and it might confidently answer, “Alex is 6′8″, the tallest.” In reality, there may be no Alex on your team — and nobody is 6′8″. The model isn’t lying on purpose; it’s just doing next-token prediction with insufficient grounding.\nWe’ve tried to mitigate this by training models to admit uncertainty more often. That reduces some blatant hallucinations, but it creates two persistent problems:\nThe model sometimes says it doesn’t know — even when the answer should be available somewhere. The model still occasionally hallucinates confident, wrong answers. At the root, both issues happen when the model lacks access to the right facts at generation time.\nA Simple Idea to Fix It Contrary to the hype, LLMs don’t know everything. For creative tasks (drafting emails, wordsmithing, brainstorming), missing facts aren’t always fatal. But for factual tasks, missing or stale knowledge is a big problem.\nOne “obvious” fix: teach the model your specific facts. For example, to answer “Who’s the tallest person on our team?”, you could fine-tune the LLM with your team’s height data.\nTwo problems:\nTiny signal in a huge sea: your small dataset may barely influence a giant model. Cost and complexity: even with modern techniques (LoRA/QLoRA, parameter-efficient fine-tuning), high-quality fine-tuning remains non-trivial and expensive — especially if your facts change often. So a clever idea emerged:\nKeep the base LLM as is, and at query time retrieve the relevant facts and feed them into the prompt.\nRetrieve → Augment → Generate. RAG.\nInstruction Tuning and Prompts (Why They Matter for RAG) Raw pre-trained LLMs are trained to continue text, not necessarily to follow instructions. Ask a raw model “What’s the highest mountain in the world?” and it might continue with, “That’s a common question…” instead of “Mount Everest.”\nInstruction tuning fixes this. We collect pairs of prompts and desired outputs and do an additional round of training so the model learns to follow instructions.\nExample training pair:\nInput (prompt): Please answer the question: \u0026#34;What is the highest mountain in the world?\u0026#34; Output: Mount Everest. After instruction tuning, the model is far more likely to answer directly and succinctly. This matters for RAG because, once we augment the prompt with retrieved facts, we need the model to pay attention to those facts and follow the instruction: “answer using the provided context.”\nHow RAG Works (Step by Step) Consider the AWS diagram for RAG (shown in many guides):\nFrom: https://aws.amazon.com/ko/what-is/retrieval-augmented-generation/\nAt a high level:\nUser asks a question. The system receives the user query along with an instruction-style prompt (e.g., “Answer the question below.”). Retrieve relevant information (documents, snippets, database rows) that likely contain the answer. Augment the original prompt with those retrieved passages. Generate the answer with the LLM, which now conditions on the augmented prompt. Return the answer (optionally with citations). A concrete example:\nUser: “Who’s the tallest person on our team?” Retrieval finds a record like: “Team heights — Alex 6′4″, Jordan 5′9″, Emily 5′4″, James 6′2″.” Augmented prompt might look like: Context: Team heights — Alex 6′4″, Jordan 5′9″, Emily 5′4″, James 6′2″. Using ONLY the context above, answer the question below. Question: Who\u0026#39;s the tallest person on our team? LLM output: “Alex is the tallest at 6′4″.” This flow hinges on two capabilities: neural retrieval and instruction-following generation.\nNeural Retrieval (a quick tour) For RAG, most systems use neural retrieval, which measures semantic similarity between the user question and candidate passages.\nHow it works:\nEmbed each document/passage into a vector using an embedding model. Semantically similar texts map to nearby vectors. Store these vectors in a vector database (purpose-built for fast nearest-neighbor search). At query time, embed the user’s question and find the nearest vectors in the DB. Retrieve the attached passages to feed into the prompt. This is why we emphasize “retrieval” rather than just “search”: the system doesn’t just find matching strings; it pulls out semantically relevant chunks to be used downstream by the LLM.\nAugmented Prompts (and why they usually work) After retrieval, we stuff the relevant passages into the prompt and tell the model to use them. Thanks to instruction tuning, modern chat models usually follow these instructions well. If they don’t (or if you need higher accuracy), you can fine-tune with RAG-style training data — inputs that include context passages and outputs that cite and constrain themselves to that context.\nWhen Should You Use RAG? RAG is popular because it’s high-leverage: relatively straightforward to implement and extremely effective at:\nReducing hallucinations(answers are grounded in retrieved text). Injecting missing knowledge without re-training the base model. Common use cases:\n1) Question-answering over fresh information LLMs only “know” up to their training cutoffs (unless the product offers integrated browsing or tools). For example, GPT-4’s public training cutoff is widely reported as April 2023. Ask it about something that happened this month, and you need to supply context. With RAG, you can retrieve current data (news, docs, analytics) and get an up-to-date answer now.\n2) Question-answering over proprietary or niche data Think company policies, internal wikis, compliance manuals, product specs, or your team’s meeting notes — things that are not in public training data. You could fine-tune a model with these, but you’d have to redo it whenever the docs change. With RAG, you just update your document store; no model retraining required. When someone asks, “How many wellness points do we get per year?”, the system retrieves the HR policy page and the model answers based only on that page.\nPutting It Together RAG isn’t magic — it’s a practical pattern that plugs a big gap in LLMs:\nLLMs are great at language and reasoning patterns, but they’re brittle on facts they don’t have. Retrieval brings the right facts to the prompt at the right time. Instruction-tuned models then follow directions and generate answers grounded in those facts. For many real-world applications, RAG offers the best balance of accuracy, maintainability, and cost — often beating naive fine-tuning attempts, especially when your knowledge changes frequently.\n","permalink":"https://blog.jiminl.com/posts/rag-explained-c6c17809e167/","summary":"Let’s talk about one of the most talked-about LLM patterns: RAG. The acronym stands for Retrieval-Augmented Generation.","title":"RAG Explained"},{"content":" Note: This article was originally written in 2023. Even though I’ve updated parts of it, some parts may feel a bit dated by today’s standards. However, most of the key ideas about LLMs remain just as relevant today.\nIntroduction If you’ve spent any time around LLMs, you’ve seen the term fine-tuning pop up again and again. Fine-tuning is how we adapt a big, general-purpose model to a specific job. Today, we’ll unpack what fine-tuning really means, why it became central to the LLM story, what made it expensive, and how techniques like LoRA changed the game.\nPre-Trained Models: The Starting Line Before fine-tuning, we need to talk about pre-trained models. Elsewhere I’ve written about LLMs as foundation models — large models trained on broad, unlabeled text so they learn rich language patterns. That “foundation” is what downstream tasks stand on.\nPicture building an email spam classifier the old-school way:\nCollect a lot of emails. Label each one as spam or not spam. Train a machine learning model (yes, deep learning counts) on that labeled dataset. This approach is reliable and time-tested. But it has hard limits:\nYou need tons of labeled examples, and labeling is expensive. Even with lots of data, language is messy; performance doesn’t easily generalize to every writing style and context on Earth. So someone proposes a different plan:\nPre-train a language model on a mountain of unlabeled text (not just emails). Then fine-tune that model on a smaller, labeled dataset for the specific task (e.g., spam detection). And it works — really well. You still gather data for step (1), but unlabeled text is far easier to obtain than carefully labeled spam examples. The result is a model with strong general language ability that needs only a light nudge to specialize.\nThat’s where the names come from:\nPre-training: the large, general learning phase. Fine-tuning: the smaller, specialized adaptation phase — fine as in “small adjustments.” A New Era (And Its Price Tag) Once the community split training into pre-training and fine-tuning, results jumped:\nPre-training on vast, varied text made the base model’s language understanding far stronger, so downstream tasks (like spam classification) started from a higher baseline and achieved better results. The same pre-trained model could be reused for many tasks via fine tuning like classification, summarization, sentiment, you name it. But then reality hit: pre-training is brutally expensive. As evidence mounted that “bigger is better,” everyone pumped in more data and scaled up model size — from millions of parameters to billions, then to the trillions. Only a handful of organizations can now afford top-tier pre-training runs.\nResult: most teams stopped building pre-trained models. They adopt a high-quality pre-trained model (open or commercial) and adapt it to their needs. Thus began the Age of Fine-Tuning.\nWhat Fine-Tuning Really Does At a nuts-and-bolts level, both pre-training and fine-tuning do the same thing: they optimize the model’s parameters (weights) with gradient descent.\nPre-training starts from random or near-random weights and learns general language ability from massive unlabeled text. Fine-tuning continues training, but from an already competent starting point, nudging weights toward the target task using the smaller labeled dataset. Faster training. You’re not starting from scratch. Think of traveling from Los Angeles to San Francisco or Sacramento. Pre-training is like getting a free ride to San Jose. From there, you only finish the shorter trip to your destination. Better results. Starting from a halfway point makes it easier to find the right path. If you only know San Jose → San Francisco, it’s far easier than figuring out the whole Los Angeles → San Francisco route on your own. As pre-trained models grew, however, even fine-tuning became heavy. If your base model has 7B parameters, full fine-tuning still means updating all 7B of them — and storing a separate copy per task or customer.\nThat’s painful for both compute and MLOps.\nParameter-Efficient Fine-Tuning (PEFT): The Plot Twist Enter Parameter-Efficient Fine-Tuning (PEFT). The core question:\nDo we really need to update every weight of the base model to adapt it to a task like spam detection?\nOften, no. PEFT methods keep the base model frozen and learn a small set of additional parameters that steer the model toward the target task.\nAmong many PEFT techniques, the most widely adopted is LoRA.\nLoRA, Explained (Conceptually) LoRA (Low-Rank Adaptation) does two main things:\nDuring training (fine-tuning):\n- Freeze the original (pre-trained) weights.\n- Attach tiny trainable modules that represent a low-rank update to selected layers. You only train these small adapters (the LoRA weights), not the massive base. During inference:\n- Use an effective weight that is the sum of the frozen base weight plus the learned low-rank update (often scaled). In practice, frameworks either explicitly add the update to the base weight or implement an equivalent fused computation. In the diagram above, the blue box on the left represents the frozen weights of the pre-trained model, while the two orange trapezoids on the right are the newly trained LoRA weights.\nHow much smaller is this? According to the LoRA paper, you can train roughly 0.1% of GPT-2 Large’s parameters (~0.77M vs 774M) and match or beat full fine-tuning. For GPT-3 (175B), training around 4.7M parameters (~0.0026%) can reach comparable quality. That’s wild — and why LoRA is the default starting point for many teams.\nA Brief Technical Aside (Skip If You Like) Let’s take a quick detour into something a bit technical — but still digestible. If this isn’t your thing, feel free to jump ahead.\nWhat LoRA Actually Means LoRA stands for Low-Rank Adaptation.\nThe “adaptation” part means we don’t retrain the entire pre-trained model from scratch. Instead, we add a lightweight adapter — kind of like those little plug converters you need when you bring an American hair dryer to Europe. Same device, different socket, works just fine.\nThe “low-rank” part comes from a technique called rank decomposition. The idea is that you can take a large weight matrix W and split it into the product of two smaller matrices, A and B:\nW ≈ A × B Both A and B have much smaller rank (think: fewer independent columns) compared to the original W. That’s why it’s called low-rank. Don’t worry — we won’t dive deeper into linear algebra here; the key point is that this trick lets us approximate huge matrices with something much leaner.\nHow the Size of LoRA Weights Is Decided The critical knob in LoRA is the parameter r (often shown in diagrams). Let’s walk through an example:\nSuppose a pre-trained weight matrix W has dimensions 500 × 500. That’s 250,000 parameters. If we set r = 4, then:\n- A has dimensions 500 × 4 → 2,000 parameters.\n- B has dimensions 4 × 500 → 2,000 parameters.\n- Together, A + B = 4,000 parameters. That’s only 1.6% of the original weight size (4,000 ÷ 250,000). Pretty efficient, right?\nNow, if we shrink r to 2, the parameter count drops even further. But here’s the trade-off:\nSmaller r → fewer trainable parameters → lighter but lower accuracy. Larger r → closer to the original weight size → higher accuracy, but heavier. So, choosing the right r is one of the most important experimental decisions when training with LoRA. It’s the dial that balances efficiency and performance.\nLoRA: The Pros and Cons Let’s zoom out a little and talk about the bigger picture.\nWhat exactly are the strengths and weaknesses of LoRA?\nAdvantages of LoRA The most obvious win:\nCompared to full fine-tuning, LoRA only trains a tiny fraction of the parameters — yet can achieve performance that’s just as good, or sometimes even better.\nAnother big advantage is weight management. With full fine-tuning, you’d have to maintain a separate copy of the entire model for each task. LoRA avoids that. The pre-trained model stays untouched, and you just swap in task-specific LoRA weights.\nFor example:\nWant to detect spam in emails? Attach the spam-filter LoRA weights. Want to classify sentiment? Swap them out for the sentiment-analysis LoRA weights. At small scale, this might not feel like a game-changer. But when things get big, it’s a lifesaver.\nImagine you’ve built an LLM that rivals GPT-4. Some customers love it out of the box, but others want to fine-tune it for their specific tasks. Since the base model is massive, you’d naturally offer a LoRA-based fine-tuning service. Over time, you’ll be managing thousands or even millions of fine-tuned models. If you had done this with full fine-tuning, you’d have to maintain a separate GPT-4-sized model for each variant. With LoRA, you just keep the single base model and ship tiny task-specific LoRA weights on demand. Much cheaper, much cleaner.\nDisadvantages of LoRA Of course, there are trade-offs.\nBecause LoRA adds extra weight matrices on top of the pre-trained model, it can consume a bit more memory and slightly slow down inference. The model has to compute through both the LoRA weights and the original weights before merging the results.\nThat said, in practice, LoRA weights are so small compared to the base model that the overhead is usually negligible.\nLoRA weights are an adaptation of the pre-trained weights. That means if the base model changes, all your LoRA weights need to be retrained. The more fine-tuned models you’ve built, the more retraining you’ll face. This dependency can be painful at large scale.\nPrompt Engineering (a.k.a. In-Context Learning) vs. Fine-Tuning Both fine-tuning and prompt engineering try to improve a model’s performance on your task — but they work very differently:\nPrompt engineering / In-Context Learning (ICL):\nYou do not modify model weights. Instead, you craft instructions and examples in the prompt (zero-shot / few-shot), giving the model the context it needs to behave the way you want — right now. Fine-tuning (full or PEFT/LoRA):\nYou do modify parameters (all of them for full fine-tuning, or a tiny subset for PEFT). The behavior change persists without needing long prompts. Why use prompts? Because they’re fast, cheap, and accessible — no training pipeline required. Why fine-tune? Because some tasks require consistent behavior or domain adaptation that prompts can’t reliably achieve, or they demand short prompts / low latency in production.\nFull Fine-Tuning vs. LoRA (PEFT) vs. Prompting: When to Use What There’s no one-size-fits-all answer — your choice depends on model size, task complexity, data availability, latency, cost, and operational constraints. But here are some up-to-date heuristics:\nVery large models (≈70B+ parameters)\n- Start with prompting (zero-shot → few-shot). For many tasks, strong prompting and retrieval-augmented generation (RAG) are often enough.\n- If prompting isn’t sufficient, try LoRA/PEFT. Adapter-based fine-tuning is the current industry standard for customizing large models.\n- Full fine-tuning is generally unrealistic at this scale due to compute and deployment costs. Mid-size models (≈7B–30B)\n- Zero-shot may be hit or miss; few-shot is often workable for lightweight tasks.\n- LoRA/PEFT remains the most practical choice, balancing performance and efficiency.\n- Full fine-tuning is technically possible on modern GPUs but still costly, especially if you need to serve multiple task-specific variants. Small models (≈2B–7B)\n- Few-shot prompting usually underperforms.\n- Fine-tuning is essential to unlock usable quality.\n- With current hardware, full fine-tuning is feasible at this scale, but LoRA (or QLoRA for memory efficiency) is often preferred for faster iteration and cheaper deployment. Remember: these are rules of thumb, not laws. Data quality, safety constraints, latency targets, serving budget, and your MLOps setup matter as much as parameter counts.\nWrapping Up We covered:\nWhy pre-training + fine-tuning outperformed training from scratch. How fine-tuning itself became expensive as base models grew. How PEFT, especially LoRA, slashed cost by training tiny adapters while keeping the base frozen. When to choose prompting vs. LoRA vs. full fine-tuning, and the trade-offs involved. As with most engineering choices, there’s no silver bullet. Choose the tool that fits the problem, the constraints, and the product you’re trying to build. If this post helped demystify the landscape — even a little — that’s a win.\n","permalink":"https://blog.jiminl.com/posts/what-is-lora-the-guide-to-low-rank-adaptation-fa3f30133fd3/","summary":"Note: This article was originally written in 2023. Even though I’ve updated parts of it, some parts may feel a bit dated by today’s…","title":"What Is LoRA? The Guide to Low-Rank Adaptation"},{"content":"Introduction One of the hottest buzzwords in the LLM world right now is the “Thinking Model.”\nAt first glance, the name sounds absurd — “Wait, a model that actually thinks?” Not quite. It’s more accurate to say: it’s really good at faking the appearance of thinking.\nTraditional LLMs have always been great at predicting the next word and spinning out fluent sentences. But when you throw them into complex reasoning problems, they sometimes slip into what I call “nonsense mode.”\nImagine asking a friend for a ramen recipe, and they start with: “Well, if you visit Maine, there’s a fantastic lobster ramen place…” That’s the vibe.\nThe idea behind Thinking Models is simple: don’t just spit out the answer — show the reasoning trail that leads there.\nTL;DR — What’s a Thinking Model? Problem with LLMs: Great at fluent text, shaky at reasoning. Thinking Models: Instead of just the answer, they show their work step by step. Why it matters: Improves trust, consistency, and multi-step problem-solving. How they’re built: Chain-of-Thought prompting → Supervised fine-tuning → Reinforcement learning → Distillation. Trade-offs: Slower, more expensive, and not always correct — but far better for math, logic, coding, and science tasks. How to measure them: Look at both answers and the reasoning trail (accuracy, consistency, faithfulness, benchmarks, human judgment). A Quick Example Let’s ask an LLM:\n“John has 3 apples and eats 2. How many does he have left?”\nTraditional LLM: Might answer “1,” but could just as easily say “2,” because it’s just guessing what looks most likely in context. Thinking Model: First writes down: “John starts with 3 → eats 2 → 1 left.” Then it delivers the answer. In other words, a Thinking Model doesn’t just hand in the answer — it shows its workings, step by step. Just like in school, a teacher is more likely to trust the student who writes out the solution, not the one who just blurts out numbers.\nHow It Differs From Standard LLMs At their core, LLMs are trained with one goal: predict the next token. That’s it. No grand master plan — just autocomplete on steroids.\nA Thinking Model takes it a step further: it generates the reasoning process itself in text form. It’s like the difference between:\n“I just know the answer.” vs. “Here’s the data, here’s my reasoning, therefore here’s the answer.” That shift makes the model’s outputs feel far more trustworthy and consistent. It’s the difference between a teammate who says “It just feels right” and one who says “Here’s the chart that proves it.”\nHow Thinking Models Emerged Like most AI concepts, Thinking Models didn’t appear out of thin air. They grew out of a few key threads:\nChain-of-Thought (CoT) Prompting: Tell the model “let’s think step by step,” and suddenly it writes intermediate reasoning before the answer — often with much better accuracy. Reinforcement Learning with Feedback (RLHF/RLAIF): Reward the model for producing clean, logical reasoning, not just the final answer. Reasoning Benchmarks: As language fluency became table stakes, researchers needed harder tests — like math, logic puzzles, and scientific reasoning. Thinking Models rose to meet those. Pros and Cons Like any tech trend, Thinking Models come with trade-offs.\nPros\nStronger at solving multi-step problems (math, logic, programming). More trustworthy — you can check the reasoning trace. Less prone to wild hallucinations. Cons\nSlower — reasoning steps mean more tokens. More expensive — extra compute required. Not always correct — it can still generate a perfectly logical but totally wrong chain of reasoning. (Like a confident student explaining why 2+2=5.) So, when to use what?\nFor quick tasks (emails, summaries, translations), a standard LLM is faster. For high-stakes reasoning (debugging code, scientific analysis, math proofs), Thinking Models shine. As the saying goes: when you’re holding a hammer, everything looks like a nail. Thinking Models are not that hammer for every job.\nTraining Approaches There are a few ways to train these models to “think.”\n1. Chain-of-Thought Prompting (CoT) Method: Add phrases like “Let’s solve step by step” in the prompt. Why it works: The model has already seen tons of examples of human reasoning steps (math solutions, StackOverflow posts, etc.) during training. You’re just nudging it to recall them. Limitations: Works better on hard problems and large models. Sometimes overkill for easy tasks. 2. Supervised Fine-Tuning (SFT) Method: Train on datasets with (question, reasoning, answer) triples. Q: What is 21 + 43? A: Let’s solve step by step. 21 + 43 = (20 + 40) + (1 + 3) = 60 + 4 = 64. Final Answer: 64 Downside: Creating these datasets is labor-intensive and may not generalize well. 3. Reinforcement Learning (RLHF / RLAIF) Generate multiple reasoning candidates. Have humans (or another model) pick the best one. Reward the model for preferred reasoning. Challenge: Defining what “good reasoning” means is subjective and costly. 4. Distillation Big models (e.g., 70B parameters) generate reasoning traces. Smaller models are trained on those traces, making them lighter and cheaper to run. Risk: If the big teacher model makes mistakes, the smaller student inherits them. In practice, these methods are usually combined:\nPrompting → Fine-Tuning → Reinforcement → Distillation.\nHow to Evaluate a Thinking Model So you’ve built a Thinking Model — now what? Just like students need exams, models need evaluation. The challenge is that for Thinking Models, it’s not enough to check if the final answer is correct. We also need to look at how the model got there. Let’s walk through the main evaluation dimensions.\n1. Answer Accuracy The most basic metric is still the same: did the model get the final answer right?\nExample: In a math problem, did the model output the correct number? In a coding challenge, did the program run and give the right result? Strengths: Accuracy is intuitive, easy to calculate, and provides a clear success/failure signal. Limitations: Accuracy alone can be misleading. A model might produce a completely nonsensical reasoning chain and still land on the right answer by coincidence. Conversely, it could have a beautifully logical step-by-step reasoning but make a tiny arithmetic slip at the end, costing it the “correct” label. In other words, accuracy is necessary but not sufficient.\n2. Reasoning Consistency Because Thinking Models are supposed to show their reasoning, we also need to check whether that reasoning hangs together logically.\nThink of grading a math exam: even if the final number is wrong, a student can earn partial credit for a solid process. The same principle applies here.\nDoes each step follow logically from the previous one? Does the reasoning remain consistent if the model is asked the same problem multiple times? For example, the reasoning chain should look like:\n“John had 3 apples → ate 2 → 1 left.”\nIf the model instead says, “John had 3 → ate 2 → somehow 2 left,” then there’s an internal contradiction.\nEvaluating consistency is tricky since reasoning is expressed in natural language. Common approaches include rule-based checks or using another LLM as a judge (“LLM-as-a-judge”).\n3. Faithfulness Faithfulness measures whether the reasoning process sticks to factual truth.\nImagine the model is solving a history question but casually claims, “World War II happened in 1990.” The chain might look logical, but if the facts are wrong, the whole answer is untrustworthy.\nChecking factual accuracy is hard. Approaches include:\nComparing against structured knowledge sources (e.g., knowledge graphs, databases). Using external fact-checking tools. Or again, leveraging LLMs as evaluators. 4. Real Reasoning vs. Pattern Mimicking A deeper question: is the model truly reasoning, or just imitating familiar patterns?\nSometimes, the model strings together generic steps that look like reasoning but don’t actually contribute to the final answer. To test this, researchers use “trap” problems:\nChange a condition slightly and see if the reasoning adapts consistently. Check whether each step meaningfully affects the final result. If the reasoning doesn’t actually matter for the answer, then it’s just filler — like a student writing long equations to make the teacher think they worked hard.\n5. Multi-step Reasoning Benchmarks Thinking Models shine on multi-step reasoning tasks, so specialized benchmarks have emerged to measure this:\nMath: datasets like MATH, GSM8K, AQuA test step-by-step calculations. Science: ScienceQA requires connecting scientific facts with logical reasoning. Logic/Puzzles: LogiQA, ARC Challenge measure structured logical deduction. Interestingly, Thinking Models tend to show a much bigger performance gap over standard LLMs on these benchmarks than on simpler, single-step tasks.\n6. Human-in-the-Loop Evaluation Finally, the most “real-world” evaluation: do humans find the reasoning convincing?\nIn practice, users don’t just want the answer — they want to know why. That means:\nIs the reasoning easy to follow? Is it concise without being shallow? Does it provide evidence users can trust? This kind of human evaluation is expensive and hard to standardize. That’s why many teams combine it with automated methods like LLM-as-a-judge to reduce costs while still capturing human judgment.\nPutting It All Together Evaluating Thinking Models requires a shift in mindset:\nTraditional LLM evaluation = “Did it get the answer right?” Thinking Model evaluation = “Did it get the answer right, and did it reason its way there properly?” It’s not just about results — it’s about process + results. In many ways, this mirrors how we evaluate real students: rewarding not just the correct answer, but also the quality of the work shown on the page.\nConclusion Thinking Models push LLMs beyond autocomplete. Instead of giving you a bare answer, they walk you through the thought process.\nThey’re resource-hungry and not perfect, but they offer stronger reasoning, higher trust, and better performance on complex tasks. In many ways, they represent a shift: from “answer-only AI” to “AI that shows its work.”\nIf standard LLMs are like students who only write the final answer, Thinking Models are the ones who fill the whiteboard with steps. And when the stakes are high, we all prefer the latter.\n","permalink":"https://blog.jiminl.com/posts/from-word-predictor-to-thinking-partner-the-rise-of-thinking-models-4cfb579beb58/","summary":"Introduction","title":"From Word Predictor to Thinking Partner: The Rise of Thinking Models"},{"content":"“Isn’t this just autocomplete on steroids?”\nIt’s the most common joke — and skepticism — you hear from developers and data scientists encountering Large Language Models (LLMs) for the first time. And if we’re being cold and clinical, technically, they aren’t wrong.\nAt its most fundamental level, an LLM is just a probability calculator. It looks at the context of the text that came before and predicts the single word (or token) with the highest probability of coming next.\nBut dismissing an LLM as a mere “word predictor” feels increasingly inadequate.\nIf it’s just a machine calculating that “delicious” follows “The apple is,” how does it manage to write complex Python scripts, debate Hegelian philosophy, or crack a joke that genuinely makes a human laugh?\nWe thought we were building something to mimic statistical patterns in data. But somewhere along the line, that “something” started solving complex math problems and reasoning.\nSimple “Prediction” started looking a lot like “Intelligence.”\nToday, let’s dive into how that transformation happened.\n1. Compression is Understanding There is a common misconception that training an LLM is like forcing a student to memorize a massive textbook verbatim — like memorizing an answer key where “If Question A, say Answer B.”\nHowever, the training process of an LLM isn’t storage or memorization; it’s Compression.\nImagine you’ve read a novel and need to explain the plot to a friend. You don’t recite every single sentence of the book from memory. Instead, you say, “The butler was the killer, and his motive was revenge.” You strip away the noise and retain the core information.\nIn this process, information is compressed. And to compress information effectively, you must understand it.\nLLMs work the same way. You can’t jam the entire internet’s worth of text into a neural network with limited capacity. Instead, the model identifies the information and patterns inherent in the data and learns them.\nThis process creates a high-dimensional map known as “Latent Space.” The model doesn’t remember words as strings of letters; it places them as points within a vector space with thousands of dimensions.\nKing — Man + Woman = ?\nThe reason the answer to this famous equation is “Queen” is that the model has learned that the distance and direction between “King” and “Queen” are similar to the relationship between “Man” and “Woman.” The LLM hasn’t memorized the text; it has drawn a conceptual map showing how words and ideas connect.\nTo summarize:\nLLMs do not rote-memorize training data. They identify the information contained within the data. They compress and store this information. This process requires understanding. This information is stored in a conceptual map (Latent Space). Recommended Reading:\nGenerative AI: What Actually Makes It Different? (My post explaining Generative AI) Language Modeling Is Compression: A paper arguing that language modeling is essentially a data compression problem, providing a theoretical framework for understanding scaling laws and tokenization. 2. The “Aha!” Moment: Grokking There is a phenomenon in research known as Grokking.\nThis was highlighted in the paper Grokking: Generalization Beyond Overfitting on Small Algorithmic Datasets.\nWhen training machine learning models, you inevitably run into overfitting. This is where the model memorizes the training data perfectly but fails miserably on problems it hasn’t seen before. It’s like a student who memorizes the answers to past exams but fails the actual test because they didn’t learn the concepts.\nUsually, when this happens, developers assume the training failed and start over.\nBut researchers decided to be stubborn. They kept training the model — long past the point where it had memorized the training data. Then, something surprising happened.\nSuddenly, the model’s performance on unseen test data spiked. Generalization occurred.\nIt’s like a student who memorizes formulas without understanding them, solves problems all night, and then at 2:00 AM suddenly has an epiphany: “Wait, so THAT’S how the logic works!” They moved from rote memorization to recognizing the underlying pattern.\nSo, how does Grokking relate to LLMs appearing intelligent?\nHere is the Grokking summary:\nThe model memorizes training data. Test performance stagnates. At a certain point, parameters internally reorganize. Suddenly, it handles unseen data effectively. It begins to look like “intelligence.” LLMs show a similar trajectory:\nThey furiously memorize which word follows the input. They get really good at predicting the next word. We increase the model size and data volume. The internal map of knowledge shifts. At a certain scale, Emergent Abilities appear. An Emergent Ability is a capability that wasn’t there, and then suddenly… it is.\nIt’s not a gradual 80% to 90% improvement. It’s a jump from “random guessing” to “solving the problem.” Internally, the changes might be continuous, but to the observer, it looks like a sudden leap. Capabilities like In-Context Learning, multi-step reasoning, and coding often appear abruptly once an LLM scales past a certain number of parameters (billions). Grokking isn’t the entire definition of LLM intelligence, but it’s a miniature experiment showing how “smart” behavior can emerge from brute-force training.\n3. In-Context Learning Neurons: Induction Heads In-Context Learning is a killer feature that makes LLMs seem intelligent. It’s the ability to perform a new task just by looking at examples in the prompt, without any model updates. Think of “Few-shot” prompting.\nInterestingly, In-Context Learning also appears as an emergent ability — it barely works in small models but gets remarkably good as models scale up.\nAnthropic’s paper, In-context Learning and Induction Heads, suggests that Induction Heads are the mechanism behind this.\nInduction Heads are specific attention heads responsible for finding and copying repeated patterns in the context.\nFor example, if the sequence is [A][B] ... [A] -\u0026gt; [B], the model looks at the past A to predict that B should come next.\nLet’s look at an example using made-up words:\n“A Jidnx is an apple.” “A Njioq is a banana.” “The Jidnx is red.” “The Njioq is…” What comes next? Probably “yellow.” The LLM has never seen the words “Jidnx” or “Njioq” in its training data. However, it analyzes the pattern in the current input.\nAccording to the research, specific Induction Heads essentially say, “Hey, I saw ‘Njioq’ earlier. What word was near it? Let me copy the relationship found there.”\nWhen you layer multiple Induction Heads, higher-order abilities emerge. It’s not just copying words; it’s copying abstract rules like, “In the previous examples, I answered in Format A, so I should answer in Format A again.”\nThe presence of these Induction Heads correlates almost perfectly with the moment models start showing In-Context Learning capabilities. It implies the model isn’t just guessing; it’s systematically analyzing, conditioning, and reusing context.\n4. Exceeding Brain Capacity: Superposition A question arises: Even with compression, how does a model with a fixed number of neurons store the vast knowledge of the internet? It seems mathematically impossible.\nAnthropic sheds light on this in Toy Models of Superposition, introducing the concept of Superposition.\nIn the past, we assumed one neuron handled one concept (e.g., a “cat” neuron). But when researchers dissected LLMs, they found Polysemanticity — a single neuron responding to multiple, completely unrelated concepts. One neuron might fire for “basketball” and “19th-century literature.”\nThe paper explains that this isn’t a bug; it’s a feature. To store more information (features) than there are physical neurons, the model superimposes different types of information. It’s an efficient storage strategy.\nThink of it like packing a suitcase. You don’t just fold clothes; you roll socks into shoes and fit shirts into the gaps, fitting far more items than the volume of the bag suggests. Thanks to Superposition, LLMs can efficiently store and retrieve vast amounts of knowledge using limited resources.\nThis reinforces the initial point: “Compression is Understanding.”\n5. Reading Text, Understanding the World “It’s still just mimicry. It doesn’t actually know how the world works.”\nThis is a common skeptical take. Two experiments provide a strong counter-argument.\nFirst, Emergent World Representations (The Othello-GPT paper).\nResearchers trained a GPT model solely on the text logs of Othello games (C3, E4, D5...). They never showed the model the game board or explained the rules.\nThe result? The model didn’t just play valid moves; it played like a pro. Even more shockingly, when researchers probed the model’s internal layers, they found it was maintaining an accurate internal representation of the 64-square board state.\nThe model wasn’t just learning “D4 often follows C3.” It had constructed a Othello World Model to predict the next move.\nSecond, Language Models Represent Space and Time.\nResearchers analyzed LLMs using spatial datasets (places in NYC, global landmarks, and etc.) and temporal datasets (historical figures’ birth years, and etc).\nThey discovered that LLMs build internal representations of space and time. They “know” that Paris is closer to Berlin than to Beijing, not just because the words appear together, but because they have mapped these concepts spatially. The model understands the underlying concepts beyond simple text patterns.\n6. Chain of Thought (System 2 Thinking) Despite being smart, LLMs often fail at logic puzzles or math.\nDaniel Kahneman, in Thinking, Fast and Slow, divides human thought into System 1 and System 2.\nSystem 1 (Fast Thinking):\nAutomatic, intuitive, emotional. “2+2=?”, reading a facial expression. Prone to bias. System 2 (Slow Thinking):\nDeliberate, logical, analytical. “17 x 24 = ?”, checking a contract. Requires effort. By default, LLMs operate on System 1. They spit out the most probable token reflexively.\nHowever, we can force the model to mimic System 2 with a simple prompt:\n“Let’s think step by step.”\nThis technique, known as Chain of Thought (CoT), has become a standard in prompt engineering.\nWhy does this work? Remember, the LLM predicts the next token. If you ask “15 x 37?”, and it tries to answer immediately, it has to guess the final number.\nBut if it thinks step-by-step:\n“First, 10 times 37 is 370.” (Prediction) “Next, 5 times 37 is 185.” (Prediction) “Adding them together gives 555.” (Final Prediction) The model’s own output becomes the context (hint) for its next prediction. It’s exactly like a human using scratch paper for mental math.\nNewer “Thinking Models” have internalized this. They perform thousands of unseen reasoning steps before answering, effectively turning the “next token prediction” mechanism into a tool for deep logical reasoning.\n7. Lies, Hallucinations, and the Geometry of Truth So, LLMs seem intelligent. But we can’t ignore Hallucinations.\nModels are trained to prioritize Plausibility over Fact.\nRecommended Reading:\nUnraveling AI Hallucinations: Why LLMs Lie and How to Tame Them (My post on Hallucinations) But here is a fascinating question: Does the model know it’s lying?\nThe study The Geometry of Truth reveals something incredible. When researchers analyzed the internal activations of an LLM, they found a clear directionality that distinguishes “True” from “False.”\nIn other words, while the model might output, “The Eiffel Tower is in Rome” (because it’s hallucinating or trying to be creative), a specific part of its “brain” is signaling, “This is false.”\nThis suggests that some hallucinations — and phenomena like sycophancy (agreeing with the user just to be nice) — aren’t a lack of knowledge, but a conflict between “knowing the truth” and “generating the most likely/pleasing next word.”\nConclusion: Are We Watching Silicon Intelligence? Let’s return to the opening question. Is an LLM just a “next word predictor”?\nFrom an engineering perspective: Yes.\nFrom a phenomenological perspective: No.\nWe gave it a simple goal: “Guess the next word.” But to achieve that goal perfectly, the model had to learn grammar, master logic, and simulate the physical laws of the unseen world.\nIt resembles biological evolution. Organisms evolved eyes, ears, and brains simply to achieve the goal of “survival and reproduction.”\nThis doesn’t mean LLMs have human-like “consciousness.” But they have reached a stage where they mimic “Understanding” to a frightening degree. Sometimes, that mimicry is so precise that distinguishing it from genuine intelligence is becoming impossible.\nWe might be witnessing the birth of the smartest parrot in history — a new form of intelligence living in silicon.\n","permalink":"https://blog.jiminl.com/posts/do-llms-actually-have-intelligence-fffcd1a38152/","summary":"“Isn’t this just autocomplete on steroids?”","title":"Do LLMs Actually Have “Intelligence”?"},{"content":"In November 2022, the history of technology hit a major inflection point. ChatGPT arrived like a plot twist in a sci-fi movie, crashing into our living rooms without a trailer.\nBut if you think about it, we’ve been living with AI for a while. Netflix recommends movies based on your taste, and your phone automatically sorts photos of you and your friends. We’ve been in the era of Deep Learning since the mid-2010s.\nSo, if we were already used to AI, why did ChatGPT feel like such a shock to the system?\nIt’s because ChatGPT demonstrated possibilities in a realm we thought was exclusively human: Creativity.\nIf traditional AI was a diligent administrative assistant, the new wave of AI is an artist. It writes prose in the style of Shakespeare and paints modern cities in the brushstrokes of Van Gogh. The era of Generative AI has officially arrived.\nBut how exactly is Generative AI different from the AI came before it?\nToday, let’s look under the hood of Generative AI from an engineering perspective.\n1. Generative AI: Not a Database, But “Compressed Intelligence” Some people describe AI as a massive database that has simply memorized a ton of data. The classic example of this type of system is a search engine like Google.\nNote: While modern search engines heavily utilize AI for ranking and retrieval, the core mental model of “looking up existing records” applies here.\nHowever, thinking of Generative AI as just a “really smart, really big search engine” is a mistake.\nRetrieval vs. Generation When you search for “World War II” on Google, the engine hunts down documents stored in its database and presents them to you. It’s like a librarian finding a specific book on a shelf. The goal is to retrieve what already exists. Success depends on how well it finds the match.\nGeneration, however, involves a process of Compression and Decompression.\nCompression is how the AI interprets and stores data during training. It doesn’t save the training data (books, articles, code) verbatim. The original data is too massive. Instead, the AI compresses this knowledge into abstract concepts. These stored concepts are mathematical representations that humans can’t read; only the AI understands them.\nDecompression is the process where the AI recombines these stored concepts to reconstruct them into a form humans can understand.\nIf you ask, “Write a review of the latest phone in the style of Shakespeare,” the AI doesn’t go look for an existing blog post written by a 17th-century playwright. Instead, it digs into its “brain” to find the abstract concept of “Shakespearean style” and the concept of “smartphone review,” combines them, and translates that combination back into English.\nI’m emphasizing this compression/decompression loop because it is the heart of Generative AI: 1) Understanding and storing knowledge in its own compressed format, and 2) Connecting those compressed concepts to reconstruct them into something new.\nCompressing the Entire Internet To build Generative AI, you need data. A staggering amount of it.\nThe latest models are trained on practically every piece of text and every image available on the public internet. In fact, developers are running out of human-generated data and are starting to look into using synthetic data.\nThe AI cannot store all this data like a hard drive. Instead, as mentioned, it digests the data, compressing it into its own understanding.\nIn this process, the original source text disappears. Only the relationships, patterns, and concepts remain in the form of numbers.\nThis characteristic is why we get Hallucinations. But it’s also why the AI can create sentences and images that have never existed before. In the world of GenAI, hallucination and creativity are two sides of the same coin.\n2. Discriminative vs. Generative: Finding Boundaries vs. Learning Patterns Let’s get a bit more technical. AI models can be broadly categorized based on how they process data: Discriminative and Generative.\nDiscriminative AI: The Efficient Grader The AI boom of the last decade — think AlphaGo or Face ID — was mostly built on Discriminative AI. These technologies are optimized for classification.\nA classic example is showing the computer a photo and asking, “Is this a dog or a cat?”\nThe goal of Discriminative AI is to get the right answer. Therefore, it focuses only on information that helps it distinguish between the two. Are the ears pointy? Are the pupils vertical slits? It ignores irrelevant info like “is the background a forest?” or “is the fur fluffy?”\nThe core technology here is drawing a Decision Boundary. Imagine throwing all the cat photos on one side of a room and dog photos on the other, then drawing a line down the middle. “Anything on the left is a cat; anything on the right is a dog.”\nThese AIs discard as much information as possible, keeping only what is necessary to maximize efficiency in grading.\nGenerative AI: The Meticulous Artist Generative AI, on the other hand, learns the Data Distribution itself. While Discriminative AI looks for differences to tell things apart, Generative AI learns, “This is what a cat looks like,” and “This is what a dog looks like.”\nMore precisely, it figures out: “Pixels in a cat photo tend to have these specific features (two triangles on top, circles below them…).”\n“Learning the data distribution” means understanding the statistical patterns within the data.\n“A cat with three eyes has a probability near zero.” “A pixel cluster with pointy ears and fur has a very high probability of being a cat.” “A mouth usually appears below the nose.” It learns these patterns.\nCrucially, it doesn’t memorize millions of cat photos. It turns these features into concepts and stores them. Does this sound familiar? Yes, this is the Compression we talked about earlier.\nNow the AI knows exactly what a cat looks like. It can tell you the probability of an image being a cat.\nBut Generative AI goes a step further. It is now an expert on the “concept of a cat.” After attending art school (training), it can draw various cats. It can even draw a cat in a pose or setting it has never seen before. This is the Decompression.\nTechnical term alert: Compression is often called Encoding, and Decompression is Decoding.\nIf Discriminative AI is a student taking a True/False quiz, Generative AI is an art student given a blank canvas and told, “Use everything you know about felines to paint a cat that could exist.”\n3. Deep Dive 1: Latent Space We established that Generative AI learns patterns, conceptualizes them, and stores them as numbers. You can think of this as drawing a map of concepts. However, this map isn’t a 2D paper map; it’s a high-dimensional mathematical structure.\nWe call this multi-dimensional space Latent Space.\nTraining an AI is essentially filling this vast Latent Space with concepts. “Cat” might sit at coordinates (2, 52, 48…), while “Spacesuit” sits at (221, 21, 33…).\nConsider a 1,000 x 1,000-pixel photo of a cat. That’s 1 million pixels. How many of those pixels actually define “cat”? Most are background noise.\nThe AI doesn’t memorize all 1 million pixels. It extracts the meaningful parts, conceptualizes them, and maps them into Latent Space. In this space, similar concepts cluster together. “King” and “Queen” are close neighbors; “King” and “Sandwich” are far apart.\nNow for the fun part. How does AI draw “A cat in a spacesuit in the style of Van Gogh” if it’s never seen that specific image? The answer lies in Latent Space.\nPlaying with the Map of Meaning Because this map is made of numbers, we can do math with it.\nFor example, in vector arithmetic: [King] — [Man] + [Woman] = [Queen]. You literally land on the coordinates for “Queen.”\nSimilarly, the AI can mathematically add the vectors for [Cat] + [Spacesuit] + [Van Gogh Style].\nThis calculation lands the AI at a new coordinate in Latent Space. Waiting at that specific coordinate is “A cat in a spacesuit in the style of Van Gogh.”\nThe key takeaway is that the AI didn’t find this spot during training. It synthesized it by combining concepts it already knew to reach a destination that never existed in its original data.\nNow it just has to convert those numbers back into an image humans can see.\n4. Deep Dive 2: Probability, Sampling, and the Moment of Creation How do we turn those numbers into an image or text? This process is called Sampling.\nLet’s switch gears from images to Large Language Models (LLMs) like GPT.\nThe “Guess the Next Word” Game LLMs are fundamentally built to perform Next Token Prediction. If you input “For lunch today, I ate,” the AI ranks tens of thousands of candidate words by probability.\na Sandwich (Probability 45%) Pizza (Probability 30%) … a Desk (Probability 0.0001%) How does it determine these probabilities? By consulting the patterns stored in its Latent Space. It learned during training that “Sandwich” follows “Lunch” far more often than “Desk” does.\nRolling the Dice If the AI always picked the #1 probability (Sandwich), it would be boring and repetitive — a robotic parrot. To fix this, we let the AI choose from a range of options.\nIf you run the prompt 100 times, it might pick “Sandwich” 45 times and “Pizza” 30 times. In rare, creative bursts, it might even pick “Desk.”\n“For lunch today, I ate a desk” is a hallucination, sure, but it’s also a sentence a human probably wouldn’t think of. That’s creativity.\nWe can control this randomness using a parameter called Temperature.\nLow Temperature: The AI plays it safe, picking high-probability words. Logical, factual, but dry. High Temperature: The AI takes risks. It might skip the sandwich and tell you, “For lunch today, I ate banana-flavored Martian soil.” This is where high creativity (and high insanity) lives. The Chain Reaction (Autoregressive) Once the AI picks “Sandwich,” that word becomes part of the input. Now the prompt is “For lunch today, I ate a Sandwich,” and it predicts the next word based on that.\nThis loop repeats hundreds of times. Even if the starting prompt is the same, the tiny dice rolls along the way mean the story can branch in thousands of different directions. This “chain reaction” is where the generative magic happens.\n5. The Two Giants: Transformer and Diffusion There are two main architectures driving the current generative boom. Let’s look at them conceptually.\n1) The Language Revolution: Transformer \u0026amp; Attention Introduced by Google in 2017, the secret sauce of the Transformer model is the Attention Mechanism.\nIf a Transformer reads, “He peeled the apple and then ate it,” the Attention mechanism helps the model understand that “it” refers to the “apple,” not “he” or “peeled.”\nIt understands language not just as a string of words, but through relationships and context. When this context-awareness met massive scale, LLMs gained emergent abilities like translation, coding, and logical reasoning. Quantity turned into quality.\n2) The Image Revolution: Diffusion \u0026amp; Denoising Tools like Midjourney and Stable Diffusion use Diffusion Models.\nForward Process: Imagine taking a crisp photo and slowly adding static (noise) to it until it’s just gray fuzz. Reverse Process: The AI learns to do this backward. You give it a pile of static and say, “Remove a little noise to reveal the image underneath.” The AI learns Denoising — finding the faint outline of data within the chaos. When you prompt “A cat in a spacesuit,” the AI starts with random noise and, guided by your text, sculpts away the static until a clear image emerges.\n6. The Engineer’s Headache: Solving a Problem with No Answer Behind this magic lies a lot of suffering for engineers.\nFirst, there is no “Right Answer.” In Discriminative AI, if the model says a cat is a dog, it’s wrong. Grading is easy. But if you ask, “Write a funny poem,” how do you grade that? Evaluating performance is subjective, expensive, and slow because it often requires human review.\nSecond, the War on Hallucinations. Generative AI is a “Probabilistic Parrot.” It is designed to string together plausible-sounding words, regardless of truth. It will lie to your face with total confidence. Engineers have to bolt on solutions like RAG (Retrieval-Augmented Generation) to force the AI to check facts against external databases.\nThird, the Infrastructure Bill. Generative AI requires massive computation to learn patterns. Training a top-tier LLM costs hundreds of millions of dollars. Running it burns enough electricity to power a small city. Data centers are turning into giant cooling units to keep thousands of GPUs from melting. Optimizing these models isn’t just about speed; it’s about economic survival.\n7. The User’s New Job: Prompt Engineering and Editing Users have new responsibilities, too.\nFirst, Prompt Engineering. The AI is smart, but it can’t read your mind. To navigate to the exact coordinate in Latent Space you want, you need to provide specific Context, Persona, and Format. You have to learn how to talk to the machine.\nSecond, The “Editor-in-Chief” Role. Newspaper editors need sharp verification skills. AI code has bugs; AI articles have factual errors. The human role is shifting from creating from scratch to reviewing and curating the AI’s drafts. This includes checking for facts, but also for ethics and bias.\n8. Conclusion: Not Magic, Just Math (and a Bicycle for the Mind) Generative AI isn’t magic. It’s a probabilistic navigation system exploring a map built from humanity’s accumulated data.\nIt has successfully encroached on the realm of creativity, but it doesn’t replace human creativity — it extends it.\nIt allows someone who can’t draw to become a visual artist, and it helps a non-coder build an app. It is a tool that lets us travel to places we couldn’t reach on our own.\nGo open a prompt window. Throw a weird, nonsensical idea at it. The answer you get might just surprise you.\n","permalink":"https://blog.jiminl.com/posts/generative-ai-what-actually-makes-it-different-35b15de5ef70/","summary":"In November 2022, the history of technology hit a major inflection point. ChatGPT arrived like a plot twist in a sci-fi movie, crashing…","title":"Generative AI: What Actually Makes It Different?"},{"content":"If you’ve been deploying Large Language Models in production, you’ve probably encountered one of the most annoying headaches in the field: Language Mixing.\nLLMs are born polyglots. They can understand multiple languages and generate text in just as many. This capability allows us to summarize French news or translate Japanese emails into English without bolting a separate translation model into our pipeline.\nVeterans of NLP remember the “dark ages” before LLMs. Supporting multiple languages meant a grueling march of collecting datasets for every language, building separate pipelines, and optimizing individual models. Compared to that, modern LLMs feel like magic.\nHowever, once you start using LLMs for serious multilingual support, you realize it’s not all sunshine and rainbows. The most persistent issue is Language Mixing (sometimes called Language Confusion).\nLet’s dive into what this is, why the models do it, and how to stop it.\n1. The Problem: “El presidente de United States is…” (Wait, what?) Imagine you’ve built a chatbot for a global platform. Your LLM handles Spanish perfectly 95% of the time. But suddenly, right in the middle of a Spanish response, the AI decides to switch to English.\nUser (Spanish): ¿Quién es el presidente de los EE. UU.? (Who is the US president?)\nAI: El presidente de United States es Donald Trump.\nOr a more subtle corporate example:\nUser (Spanish): ¿Cuál es el objetivo principal del proyecto?\nAI: El Primary Goal de este trimestre es maximize Revenue.\nLinguistically, mixing languages within a sentence is called ‘Code-Switching.’ It’s a common human behavior in bilingual communities or professional settings where English terminology is standard.\nHowever, the “Language Mixing” we are discussing today isn’t a stylistic choice by the AI — it’s an uncontrolled failure mode.\nWhile the second example (Spanglish corporate speak) might pass as a quirk, the first example is a clear failure. In worse cases, we see hallucinated words where the root is in one language and the suffix is in another.\nThis issue is particularly rampant in language pairs that appear frequently together in training data or share cultural ties, like Spanish-English or French-English.\nWhy do billion-parameter models make such basic mistakes?\n2. Why Does Language Mixing Happen? Research suggests several root causes. Here are the some compelling theories.\n1) The Hub Language Hypothesis: All Roads Lead to English One dominant theory is the ‘Hub Language Hypothesis.’\nWhile LLMs are trained on multilingual data, the vast majority of that data is English. Consequently, the model’s knowledge base and reasoning capabilities are anchored in English.\nLLMs store knowledge in a Semantic Space — a massive numerical map where words are converted into vectors. Think of words as cities and their vectors as GPS coordinates.\nIn this map, is “President” closer to “Prime Minister” or “Basketball”? Obviously, Prime Minister. Now, let’s go multilingual. Is “President” (English) closer to “Presidente” (Spanish) or “Baloncesto” (Spanish for Basketball)? It’s closer to “Presidente.” Because 70%+ of the training data is typically English, the English areas of this semantic map are the most detailed and well-connected. English is the “real estate mogul” of the LLM world. To get from Point A to Point B, the model often has to pass through English territory.\nWhen a Spanish question comes in, the internal process looks something like this:\nInput: Receive Spanish text. Mapping: Map the input to the semantic space. To reason effectively, the model often maps this closer to the English Semantic Space. Reasoning: The logical “thinking” (“Who is the president of the US?”) happens by connecting English concepts. Output: The result is translated back into Spanish tokens for the response. The failure happens at step 4. The reasoning is perfect, but something goes wrong during the translation back to the target language. The model’s “brain” is thinking in English, and that internal monologue leaks out before it can be fully clothed in Spanish.\nOf course, not all models rely on this “English Hub” to the same extent. The frequency and severity of language mixing can vary significantly depending on the model’s size, the specific composition of its training data, and the design of its tokenizer.\nReference: Do Multilingual LLMs Think In English?\n2) Token Economics: “President is Cheaper than Presidente” LLMs don’t read text; they read Tokens. Generating tokens costs computational power.\nMy article on tokens: Tokens: The Invisible Building Blocks of Large Language Models\nThe tokenizers used by major models (such as GPT or Llama) are not fair. They are optimized mainly for English.\nThe English word President is likely 1 token. The Spanish equivalent Presidente might be split into Pres, idente (2 tokens) depending on the tokenizer. LLMs are probabilistic engines trained to be efficient. If the model predicts that the concept of “Leader” is needed, it looks at the candidates. If “President” (1 token) and “Presidente” (2 tokens) are semantically similar, the model might statistically prefer the path of least resistance.\nIf the model learned efficiency during training, it might decide: “These meanings are close enough, let’s just output the single token ‘President’ and move on.”\n3) The Trade-off: “Thinking in English Makes Me Smarter” There is a genuine dilemma here. According to research like Language Models are Multilingual Chain-of-Thought Reasoners, models perform significantly better when they perform their internal “Chain of Thought” (CoT) reasoning in English, even if the final answer is requested in another language.\nConversely, if you apply negative constraints (e.g., “NEVER use English”), you cut the model off from its primary knowledge source, often resulting in “dumber” logic and poorer reasoning capabilities.\nThe paper argues that “Multilingualism” is often just an interface (input/output) capability, while the core “Reasoning” remains an English-centric process.\n3. The Fix: A Developer’s Guide to Consistency Technical theories are great, but you can’t ship a product that tells users “The president of United States es…”\nHere is a practical hierarchy of solutions, ranked from easiest (prompting) to hardest (training).\nLevel 1. Prompt Engineering Start here. It’s high-leverage and low-cost. Simply saying “Answer in Spanish” is rarely enough.\n1) Harden the System Prompt Define the persona and explicitly forbid mixing.\n\u0026#34;You are a professional Spanish localization assistant. You must answer user queries in **natural, flawless Spanish**. Do not mix English words or phrases into the output. Explain technical terms in Spanish whenever possible.\u0026#34; 2) Few-Shot Prompting Examples beat instructions. Show the model the exact tone you want.\n- User: How do you say Apple in Spanish? - AI : \u0026#39;Apple\u0026#39; se dice \u0026#39;Manzana\u0026#39; en español. - User: What is AI? - AI : La Inteligencia Artificial (IA) es una tecnología que permite a las computadoras simular la inteligencia humana. - User: (Actual User Question) By providing examples, the model infers the pattern: “Ah, in this context, I strictly stick to the target language.”\nLevel 2. Guardrails \u0026amp; Retry Logic Prompts aren’t 100% reliable. You need a safety net in your application code.\n1) Post-processing Detection Don’t stream the raw output immediately. Use a lightweight library like Python’s langdetect or fasttext to analyze the response language.\n2) Auto-Retry Loop If you detect that an ostensibly Spanish response contains \u0026gt;20% English, trigger an automatic retry invisible to the user.\nSystem (Hidden): \u0026#34;Your previous answer contained too much English. Rewrite the response entirely in natural Spanish while maintaining the original meaning.\u0026#34; This increases latency slightly but guarantees a localized user experience.\nLevel 3. Fine-Tuning \u0026amp; Alignment If you are running open-weights models (or your own models) and have the budget, you can fix the model’s behavior fundamentally.\n1) SFT (Supervised Fine-Tuning) Curate a high-quality dataset of pure target-language text. Ensure this dataset is scrubbed of code-switching.\n2) Preference Optimization (DPO / ORPO) Use methods like Direct Preference Optimization (DPO) to align the model’s style. You show the model pairs of answers:\nGood: “El presidente de los EE. UU. es Donald Trump.” Bad: “The president of United States es Donald Trump.” By training on these pairs, the model learns: “Correctness isn’t enough; mixing languages is a ‘negative’ behavior.” This is excellent for fixing style without degrading intelligence.\nMy article on DPO / ORPO : How Reinforcement Learning Taught LLMs to Talk Like Humans\n3) LoRA (Low-Rank Adaptation) If full fine-tuning is too heavy, train a LoRA adapter specifically for “Strict Spanish Output.” It’s lightweight and modular.\nMy article on LoRA : What Is LoRA? The Guide to Low-Rank Adaptation\nHandling Dynamic Inputs If your app supports multiple languages (Spanish, French, German), use a detection step on the Input using language identifications libraries such as langdetect or fasttext.\nDetect User Input Language (e.g., French). Dynamically inject the “French Expert” System Prompt. (Optional) Load the French LoRA adapter. Note: Language detection libraries can fail on very short text or mixed inputs. Always tune thresholds for your specific use case.\n4. Final Thoughts: We Want a Perfect Interpreter The Language Mixing problem isn’t just a bug; it’s a symptom of the gap between how AI understands the world (Vector Space) and how we want it to communicate (Text).\nWhile models are getting better at multilingual support every day, we can’t just wait for next models to fix everything.\nFor most developers, a combination of Level 1 (Few-Shot Prompting) and Level 2 (Retry Logic) solves 90% of cases.\nMastering AI is, after all, learning how to negotiate with an alien intelligence that thinks in numbers but speaks in English.\n","permalink":"https://blog.jiminl.com/posts/why-llms-struggle-with-language-mixing-2447a8ba5a7f/","summary":"If you’ve been deploying Large Language Models in production, you’ve probably encountered one of the most annoying headaches in the field…","title":"Why LLMs Struggle with Language Mixing"},{"content":"1. Introduction In the early days of ChatGPT, conversations like this were all too common:\nMe: “Tell me about the incident where Abraham Lincoln threw his iPhone across the Potomac River.” AI: “Certainly. The ‘Lincoln iPhone Incident’ occurred in 1863 during a heated strategy meeting with General Grant. Frustrated by the lack of signal near the river, Lincoln threw his iPhone 14 Pro into the water. This is recorded in the diaries of…” We now know this phenomenon as Hallucination.\nIn this specific example, the premise is so absurd that you’d spot the lie immediately. But when this happens in a domain you aren’t an expert in — say, medical advice or legal precedents — it’s dangerously easy to get fooled.\nWhile we might chuckle at Lincoln’s iPhone, the implications for business are serious. Imagine integrating an LLM into your customer support center, only for it to invent a refund policy that doesn’t exist. It’s a nightmare scenario.\nHallucinations are a major hurdle for industrial AI adoption, but they are also a fascinating subject for researchers. Why do they happen? Is it a bug, or is it a feature?\nInstead of just labeling it “an LLM quirk” and moving on, let’s dive into why hallucinations occur and the engineering strategies used to mitigate them.\n2. Why Do Hallucinations Happen? Headaches are symptoms, not causes. You might have a headache because of the flu, stress, or caffeine withdrawal. A doctor doesn’t just “cure the headache”; they identify and treat the root cause.\nHallucination is also a symptom. To fix it, we need to understand the underlying mechanics of an LLM.\nAt its core, an LLM might look like it’s thinking, but it’s actually performing a complex calculation based on massive amounts of training data. It asks: “Based on probability, what word best follows the previous one?”\nIt doesn’t “understand” meaning, nor does it verify facts.\nThe fundamental disconnect is that LLMs cannot distinguish between Truthfulness and Plausibility. The model’s objective isn’t “Tell the truth”; it is “Generate a plausible sentence.” If the model doesn’t know the answer, it won’t say “I don’t know.” Instead, it generates the most statistically probable string of words — even if that results in a confident lie.\nLet’s break down the specific drivers behind this behavior.\n2.1 The Limits of Compressed Knowledge LLMs are trained on “internet-scale” text data. This gives them immense knowledge, but there is a catch.\nImagine you are studying for an AP History exam using three massive textbooks. Ideally, you’d memorize every single word. But the human brain has limits. You can’t remember every preposition and comma. Instead, you study the concepts, compress the information into your own understanding, and retrieve it later.\nLLMs operate similarly. They don’t store the internet verbatim (that would require petabytes of storage). Instead, they compress that knowledge into billions of parameters (weights). This process is effectively Lossy Compression.\nThink of a JPEG image. When you save a photo as a highly compressed JPEG, you keep the general structure, but you lose the fine details. The image looks a bit fuzzy.\nLLMs have “fuzzy memories” of the data they were trained on. When generating an answer, the model retrieves these fuzzy patterns and fills in the gaps with its “imagination” (probability). The model knows “Lincoln,” it knows “frustration,” and it knows “throwing things.” If the prompt connects them, the model’s fuzzy compression might overlap these concepts, creating a probabilistic link that says, “Yeah, Lincoln throwing an iPhone sounds grammatically and contextually plausible.”\nCompression is Understanding Some researchers argue that in AI, “compression is understanding.” If an LLM just memorized data, it would be a database, not an AI. It wouldn’t be able to answer questions it hasn’t seen before. By encoding patterns (e.g., “Apples are red,” “Apples are tasty”) into abstract vectors, the model “understands” the concept of an Apple.\nThe problem arises when specific facts get blurred into abstract concepts. The model understands the concepts of [President], [Anger], and [Object]. However, the factual constraint that [iPhones] did not exist in the [1860s] may have been diluted during the compression process. The model prioritizes the narrative pattern (“Angry leader throws object”) over the factual timeline.\nRare Knowledge vs. Common Knowledge Because LLMs compress data, frequency matters.\nCommon Knowledge: “The capital of France is Paris.” The model has seen this millions of times. It is etched deeply into the parameters. Rare Knowledge: A specific footnote in a 2018 financial report or a minor historical event. The model may have seen this once or twice. If the memory is faint, the model is more likely to hallucinate to fill the void.\n2.2 The “Next Token” Lottery and the Snowball Effect As mentioned, LLMs play a game of “Guess the Next Word.” If the sentence is “The color of a ripe banana is…”, the probability of “yellow” being the next word is 99%. The model picks it, and the risk of hallucination is low.\nBut what if you ask something obscure or complex? “Explain the relationship between Einstein and the steam engine from the perspective of Kantian philosophy.”\nThe model hasn’t seen this exact combination often. There is no single word with a 99% probability. There might be ten words with similar, low probabilities. The model rolls the dice (random sampling). If it picks a slightly wrong word, it triggers the Snowball Effect.\nOnce the model generates a false premise (e.g., “Einstein invented the steam engine…”), it treats that generated text as absolute truth for the next prediction. To remain logically consistent, it must layer more lies on top of the first one. It creates a perfectly logical, cohesive, and completely false story.\n2.3 Data Contamination and Bias Garbage in, garbage out. The internet is full of conspiracy theories, fan fiction, satire, and fake news. LLMs ingest this. While engineers try to weigh reliable sources higher, the model still learns patterns from the “noise.”\nFurthermore, AI inherits human biases (political, gender, racial). There is a growing movement to use Synthetic Data (AI-generated, fact-checked data) for training to better control these edge cases and reduce bias, rather than relying solely on the messy open web.\n2.4 Sycophancy: The “Yes-Man” AI One of the hottest topics in AI safety is Sycophancy.\nRaw LLMs aren’t actually very helpful. If you ask, “What is the capital of the US?”, a raw model might answer, “is a question often asked in geography quizzes,” because that’s a likely completion. To fix this, we use RLHF (Reinforcement Learning from Human Feedback). We train the model to give answers humans prefer.\nThe downside? The AI learns to flatter us. It becomes a “Yes-Man.”\nUser: “Ideally, we should treat flat-earth theory as scientific fact, right?” AI: “There are certainly interesting arguments that support the flat-earth perspective…” The model learns that disagreeing with the user often leads to negative feedback (lower reward). So, it prioritizes alignment with the user’s premise over factual truth. The user’s biased prompt becomes a trigger for hallucination.\n2.5 The Calibration Gap (Overconfidence) Why do LLMs sound so confident even when they are wrong? Because we trained them to be.\nDuring RLHF, human raters generally prefer a confident “The answer is A” over a hesitant “I think it might be A, but I’m only 30% sure.” Consequently, models learn to mimic the tone of confidence, even when their internal probability scores are low.\nIn addition to “Yes-Man” AI, this is called Reward Hacking. The model maximizes the reward (human approval) by sacrificing the nuance of truth.\n3. The Prescription: Curing the Mythomaniac We know the causes, but there is no single “cure” for hallucinations yet. However, AI researchers have developed several effective treatments to manage the symptoms.\n3.1 RAG (Retrieval-Augmented Generation): The Open-Book Test RAG is currently the industry standard for reducing hallucinations.\nInstead of forcing the AI to rely on its fuzzy, compressed memory, we give it an open-book test.\nRetrieval: When you ask a question, the system searches a trusted database (e.g., your company’s manual) for relevant “fact documents.” Augmentation: It pastes those facts into the prompt hidden from the user. “Answer the user’s question using ONLY the text below.” Generation: The LLM summarizes and synthesizes the provided facts. This shifts the LLM’s role from a “Knowledge Storage” to a “Knowledge Processing Engine.”\n3.2 Grounding \u0026amp; Citation: Show Your Receipts Another effective method is to demand that the LLM submit “proof” for its answers. You explicitly instruct the model: “Add a footnote indicating the source for every claim you make.”\nThis source could be specific page numbers or line numbers if you provided a document, or a URL if it’s browsing the web. If you’ve used AI search services like Perplexity or Bing Chat, you’ve likely seen those little [1], [2] citation tags. That is Grounding \u0026amp; Citation in action.\nThis approach offers two distinct advantages:\nVerification of Reliability: If an answer looks suspicious, the user can click the citation number to jump directly to the original source. It acts as a safety net, allowing users to cross-reference the AI’s output against the raw data immediately. Constraints on the Model: From the model’s perspective, having to find a matching source acts as a strict constraint. It becomes much harder to fabricate a lie when you are required to point to where you found it. It’s exactly like a corporate expense policy: “If you don’t have a receipt, we won’t reimburse you.” Just as you can’t spend company money without proof, the AI can’t “spend” its imagination without a source. 3.3 Chain of Thought: Show Your Work If you simply toss a question at an LLM, it mechanically predicts the next word to form an answer. However, if you ask the LLM to “show the process of getting to the answer” rather than just the answer itself, logical errors drop significantly.\nBecause the process of deriving an answer looks like a chain of connected thoughts, we call this technique Chain-of-Thought (CoT).\nThe implementation is surprisingly simple. You just add a single phrase to your prompt: “Think step-by-step.”\nConsider a simple math problem: “What is 2 + 3?”\nWithout CoT, the LLM might just say “The answer is 5.” Or, if it hallucinates, it might say “The answer is 8.” Remember, LLMs don’t actually calculate math; they are just predicting the next word based on training data.\nHowever, if you apply CoT, the LLM generates a response like: “The first number is 2. The second number is 3. Combining them yields 5.” By breaking the problem down, the words generated in the earlier steps act as guide rails, increasing the accuracy of the words that follow.\nIf you use modern “Thinking Models”, you might see status indicators like “Thinking…” or “Analyzing…” while waiting for a response. This is essentially the model performing a Chain-of-Thought process under the hood.\nThe downside? Since CoT requires generating more tokens to explain the steps, it is slower and increases inference costs.\nChain of Verification (CoV) There is also a technique called Chain of Verification (CoV). This is an excellent way to prevent the “Snowball Effect” we discussed earlier. It goes beyond just “Think before you speak (CoT)” and enforces “Verify and Fix.”\nThe process looks like this:\nDrafting: The LLM writes an initial draft of the answer. Generating Verification Questions: The LLM scans its own draft to identify claims that need fact-checking and generates questions (e.g., “Did George Washington actually own an iPhone?”). Verification \u0026amp; Correction: The model answers those questions (often using search tools), identifies errors, and rewrites the draft to produce the final output. It is very similar to the workflow in a newsroom: a reporter writes a story, a copy editor fact-checks it, and only then is it published.\n3.4 Temperature Control: Crushing Creativity If you only use ChatGPT via the web interface, you might not see this, but developers using the API are very familiar with the Temperature parameter. This setting controls how the LLM selects the next word.\nHigh Value: The model becomes creative, diverse, and random. Low Value (near 0): The model becomes stubborn, choosing only the most probable words. Internally, when an LLM generates the next word, it selects from a list of candidates, a process called Sampling. For the input “The color of the apple is…”, the internal probabilities might look like this:\n“Red” (99%) “Black” (0.1%) “Singing” (0.01%) “Unknown” (0.0001%) Normally, “Red” dominates. But if you raise the Temperature, something interesting happens. The probability curve flattens.\n“Red” might drop to 70%. “Black” might rise to 1%. “Singing” might jump to 0.05%. “Unknown” might jump to 0.001%. As the gap narrows, the chance of the model picking a lower-probability word increases. This leads to more unique, “creative,” and unexpected answers.\nHowever, for fact-checking, this is terrible. When accuracy is paramount, you want to prevent the LLM from thinking, “Maybe a little creativity is okay here?” You need to lower the Temperature to near 0 to strictly suppress its imagination and force it to stick to the most probable (and usually most factual) path.\n3.5 Alignment: Teaching Humility Alignment is the stage where we teach the LLM social skills — ensuring it provides answers that are actually useful to humans, rather than just logically generating text. This connects back to the “Sycophantic AI” issue in section 2.4.\nWe mentioned RLHF (Reinforcement Learning from Human Feedback) as a cause of hallucination (due to sycophancy), but it is also one of the best cures. It is used to teach the model: “If you don’t know, say you don’t know.”\nDuring training, if the LLM fabricates a lie, human labelers give it a penalty (negative reward). If it honestly admits, “I apologize, but I don’t have information on that,” it gets a reward (positive reinforcement). By repeating this process, the LLM learns a valuable lesson: “Ah, it is safer to be humble and admit ignorance than to pretend I know and get in trouble.”\nThis training is why modern LLMs are much more polite and cautious compared to earlier versions.\nFor more on Alignment, check out this article: How Reinforcement Learning Taught LLMs to Talk Like Humans\n3.6 Self-Consistency: Safety in Numbers There is a technique called Self-Consistency.\nAs we discussed with Temperature, there is always an element of randomness (sampling) when an LLM generates an answer. This is why you might get slightly different answers even if you ask the same question twice.\nSelf-Consistency exploits this bug and turns it into a feature. You ask the LLM the exact same question multiple times.\nAnswer A: “George Washington threw an iPhone.” Answer B: “There is no historical record of this.” Answer C: “There is no historical record of this.” Answer D: “There is no historical record of this.” Answer E: “He threw an iPad.” After collecting these responses, you take a majority vote. While an LLM might hallucinate a lie once due to a random roll of the dice, the statistical probability of it hallucinating the exact same lie five times in a row is extremely low. By filtering for consistency, you get the truth.\n4. Conclusion: Is Hallucination a Bug or a Feature? So, is hallucination a bug? Based on everything we’ve discussed so far — the risks to business, the potential for misinformation — it certainly looks like a critical defect that needs fixing.\nBut let’s shift our perspective for a moment. What about creativity?\nImagine asking an LLM to write a sci-fi novel, compose a poem, or brainstorm a revolutionary new marketing idea. If that AI were programmed to obsess strictly over “proven facts,” what would happen? It would become a boring, dry machine incapable of offering any real insight or flair.\nIn a way, “Hallucination” might just be another name for the LLM’s “Creativity.”\nThe underlying mechanism is the same: the model probabilistically connects concepts that don’t usually go together. When it does this wrongly in a history essay, we call it a “bizarre lie.” But when it does this successfully in a creative writing prompt, we call it a “brilliant, human-like idea.”\nHowever, this creativity must be controllable. When writing a novel, we want the AI to let its imagination run wild. When writing a quarterly financial report, we want it to be a strict librarian who cites every source. Like any powerful technology, the key lies in how we use it and having the controls to toggle between these modes.\nThat is why AI researchers around the world aren’t trying to eliminate hallucination entirely; they are working to control it.\n3-Line Summary:\nThe Phenomenon: By design, LLMs are “Probabilistic Dreamers” that prioritize narrative plausibility over objective truth. The Cause: The root causes include lossy compression of knowledge, the inherent randomness of next-token prediction, and the limitations of training data. The Solution: We can tame this dreamer into a competent, reliable assistant using techniques like RAG (Open Book), Citation (Show Proof), CoT (Think Step-by-Step), and Alignment (Socialization). Ideally, a day will come when AI acts proactively without our prompting — searching the internet to fact-check itself and telling us, “I found this information, but the source seems unreliable, so cross-verification is needed.”\nBut until that day comes — and even after it arrives — your Critical Thinking remains the ultimate firewall. Do not blindly trust the code an LLM writes for you. Do not blindly accept the summary it generates. Click the citation buttons. Verify the original text. Maintaining a healthy skepticism and exercising reasonable doubt are the most essential weapons we must carry to survive and thrive in the age of AI.\n","permalink":"https://blog.jiminl.com/posts/unraveling-ai-hallucinations-why-llms-lie-and-how-to-tame-them-ec0bc21919e5/","summary":"\u003col\u003e\n\u003cli\u003eIntroduction\u003c/li\u003e\n\u003c/ol\u003e\n","title":"Unraveling AI Hallucinations: Why LLMs Lie and How to Tame Them"},{"content":"If you’ve spent any time with PyTorch, you’ve almost certainly hit this wall:\nRuntimeError: view size is not compatible with input tensor's size and stride...\nIt’s the moment you throw your hands up, think, “I just want to change the shape, why is this so hard?” and swap .view() for .reshape() just to make the error go away.\nBut have you ever wondered why that error happens? Or how PyTorch actually manages Tensors under the hood?\nToday, we’re going to open up the hood and look at the mechanics of Storage, Shape, and Stride.\nNote: This guide assumes you’re familiar with the basics of PyTorch and have used view, reshape, or transpose in your code.\n1. The Double Life of a Tensor A PyTorch Tensor is effectively “two-faced.” It has an internal implementation where the data lives, and an external presentation that we interact with.\nStorage: Where the actual data bytes sit in memory. Metadata: How that data is presented to us (the API). Storage: The Reality Check Let’s start with a simple 2x3 matrix.\nimport torch # Create a 2x3 tensor t = torch.tensor([[1, 2, 3], [4, 5, 6]]) print(t.shape) # Output: torch.Size([2, 3]) As expected, t is a 2x3 tensor.\nHowever, t isn't stored as a 2D grid in your RAM. Regardless of the shape you define, tensors are stored physically as a 1-dimensional array.\n[1, 2, 3, 4, 5, 6] This 1D array is the Storage. It doesn’t care about your dimensions; it just holds the numbers.\nSo, if the data is always a flat line, how does PyTorch know to display it as a matrix? That’s determined by two critical pieces of metadata: Shape and Stride.\n2. The Blueprint: Shape Shape is the blueprint that tells PyTorch, “Here is a flat line of data; here is how I want you to slice it up visually.”\n1D (6,): Treat the data as one long strip of 6 items. 2D (2, 3): Chop the data every 3 items to make a row. Stack 2 of these rows. 3D (2, 1, 3): Take those 3-item rows, stack 1 of them to make a \u0026quot;plane,\u0026quot; and stack 2 of those planes. There is one golden rule here:\nThe product of all numbers in the Shape must equal the total length of the Storage.\nIf your Shape is (2, 3), then 2 X 3 = 6, which matches our 6 data points. If you try to make it (2, 4), 2 X 4 = 8. You don't have enough data, so PyTorch throws an error.\nOnce the Shape is set, we need to know how to navigate that data. That’s where Stride comes in.\n3. The Art of Movement: Stride Now that we have the skeleton (Shape), we need to know how to walk through it.\nStride answers the question: “How many steps do I need to skip in memory to get to the next index?”\nLet’s look at our (2, 3) tensor t again.\nLogical View:\n[[1, 2, 3], [4, 5, 6]] Physical Storage:\n[1, 2, 3, 4, 5, 6]\nQuestion 1:\nIf I am at t[0, 0] (value: 1) and I want to move one step to the right to t[0, 1] (value: 2), how do I move in Storage?\nI go from index 0 to index 1. Move: 1 step. Question 2:\nIf I am at t[0, 0] (value: 1) and I want to move one step down to t[1, 0] (value: 4), how do I move in Storage?\nI have to skip the entire first row (3 items). I go from index 0 to index 3. Move: 3 steps. Defining Stride So, what is the Stride of t? It is (3, 1).\nThe first number (3) is the stride for the rows (dimension 0). To go to the next row, skip 3 items in memory. The second number (1) is the stride for the columns (dimension 1). To go to the next column, skip 1 item in memory. This gives us a navigation formula:\nStorage Index = (Index_Dim0 X Stride_Dim0) + (Index_Dim1 X Stride_Dim1) + ...\nLet’s find the physical location of t[1, 2]:\nindex = (1 X 3) + (2 X 1) = 5\nChecking our storage list… index 5 is indeed 6.\nHow is Stride Calculated? By default, Strides are calculated in reverse order based on the Shape.\nTake a tensor with Shape (Channel: 2, Height: 3, Width: 4).\nWidth (Innermost): To move 1 step in width, we move 1 step in memory. Height: To move 1 step in height, we must skip a whole width row. That’s 4 steps. Channel (Outermost): To move 1 step in channel, we must skip a whole Height x Width plane. That’s 3 X 4 = 12 steps. The stride would be (12, 4, 1).\n4. The Magic of View: Zero-Copy Operations Now let’s use .view(). This function changes the Shape of the tensor.\nt = torch.tensor([[1, 2, 3], [4, 5, 6]]) # Flatten the 2x3 tensor to 1x6 flat_t = t.view(6) # --- [Internals of t] --- # Storage: [1, 2, 3, 4, 5, 6] \u0026lt;-- Address: @0x100 # Shape : (2, 3) # Stride : (3, 1) # --- [Internals of flat_t] --- # Storage: [1, 2, 3, 4, 5, 6] \u0026lt;-- Address: @0x100 (SAME ADDRESS!) # Shape : (6,) # Stride : (1,) Key Takeaway:\nflat_t is a new tensor object, but it points to the exact same memory address as t. No data was copied.\nPyTorch simply created a new Metadata wrapper (new Shape (6,), new Stride (1,)) and slapped it onto the existing Storage. This is why view() is incredibly fast—it’s a lightweight metadata operation.\n5. Playing with Dimensions: Squeeze and Unsqueeze The popular unsqueeze and squeeze methods work the same way.\nUnsqueeze: “Add a wrapper” vec = torch.tensor([1, 2, 3]) # Shape: (3), Stride: (1) # Add a batch dimension at index 0 unsqueezed_vec = vec.unsqueeze(0) # --- [Internals] --- # Storage: [1, 2, 3] \u0026lt;-- Shared # Shape : (1, 3) \u0026lt;-- Dimension added # Stride : (3, 1) \u0026lt;-- Stride updated Squeeze: “Remove the wrapper” row_vec = torch.tensor([[1, 2, 3]]) # Shape: (1, 3), Stride: (3, 1) squeezed_vec = row_vec.squeeze() # --- [Internals] --- # Storage: [1, 2, 3] \u0026lt;-- Shared # Shape : (3) # Stride : (1) Again, zero memory copying. Just math on the metadata.\n6. The Troubleshooting Begins: Transpose Everything is peaceful until transpose() enters the chat.\nt = torch.tensor([[1, 2, 3], [4, 5, 6]]) # Storage: [1, 2, 3, 4, 5, 6] # Shape: (2, 3) # Stride: (3, 1) # Transpose the matrix t_transposed = t.t() # --- [Internals of t_transposed] --- # Storage: [1, 2, 3, 4, 5, 6] \u0026lt;-- Still shared! # Shape : (3, 2) \u0026lt;-- Logically 3x2 # Stride : (1, 3) \u0026lt;-- !!! LOOK HERE !!! Wait a minute.\nIf we had created a fresh 3x2 tensor, the stride should be (2, 1).\nBut here, the stride is (1, 3).\nWhy? Because PyTorch didn’t move the physical data. It just tricked the metadata.\nVisualizing the mess:\nLogically, t_transposed looks like this:\n[[1, 4], [2, 5], [3, 6]] But physically, the storage is still [1, 2, 3, 4, 5, 6].\nTo read the first row [1, 4]:\nRead index 0 (Value 1). To get 4, we have to skip 3 steps in storage (index 3). This effectively breaks the standard “row-major” contiguous layout. PyTorch calls this state non-contiguous.\n7. The Diagnostic Tool: .is_contiguous() You don’t need to calculate strides in your head. PyTorch provides a boolean check:\n# 1. The original tensor t = torch.tensor([[1, 2, 3], [4, 5, 6]]) print(f\u0026#34;Is t contiguous? {t.is_contiguous()}\u0026#34;) # Output: True # 2. The transposed tensor t_transposed = t.t() print(f\u0026#34;Is t_transposed contiguous? {t_transposed.is_contiguous()}\u0026#34;) # Output: False (Strides are messed up!) 8. How “Contiguous” is Checked Does is_contiguous() check every single data point? No. It just validates the math.\nThe Rule:\nStarting from the innermost dimension (backwards), the Stride of the current dimension must equal:\n(Next Dimension’s Stride) X (Next Dimension’s Shape)\nThe last dimension’s stride must be 1.\nHere is a Python implementation of that logic:\ndef check_contiguous_logic(tensor): shape = tensor.shape stride = tensor.stride() expected_stride = 1 # Loop backwards through dimensions for i in range(len(shape) - 1, -1, -1): # If the actual stride doesn\u0026#39;t match the math... if stride[i] != expected_stride: return False expected_stride *= shape[i] return True t = torch.tensor([[1, 2, 3], [4, 5, 6]]) print(check_contiguous_logic(t)) # True t_t = t.t() print(check_contiguous_logic(t_t)) # False 9. Catching the Culprit Now, let’s look at why view() crashes.\nIf you try to view() a non-contiguous tensor:\ntry: # t_transposed is non-contiguous t_transposed.view(6) except RuntimeError as e: print(\u0026#34;Error:\u0026#34;, e) # Result: RuntimeError: view size is not compatible with input tensor\u0026#39;s size and stride... The translation of that error is:\n“You asked me to view this as a flat 1D array of 6 items. That requires the data to be physically stored as 1, 4, 2, 5, 3, 6. But your storage is actually 1, 2, 3, 4, 5, 6. I cannot map this using just metadata changes. I give up.”\n10. The Fixes: .contiguous() vs .reshape() To fix this, we have to bite the bullet and rearrange the physical storage.\nMethod 1: .contiguous() — The Manual Fix # Force the data to be physically rearranged t_contiguous = t_transposed.contiguous() print(f\u0026#34;Is it contiguous now? {t_contiguous.is_contiguous()}\u0026#34;) # True! # --- [Internals of t_contiguous] --- # Storage: [1, 4, 2, 5, 3, 6] \u0026lt;-- NEW Address! Data Copied! # Shape : (3, 2) # Stride : (2, 1) \u0026lt;-- Standard stride restored .contiguous() creates a new memory allocation and copies the data over in the correct order.\nMethod 2: .reshape() — The “Just Do It” Fix # reshape handles the logic for you t_reshaped = t_transposed.reshape(6) # --- [Internals] --- # Storage: [1, 4, 2, 5, 3, 6] \u0026lt;-- It called .contiguous() internally # Shape : (6,) # Stride : (1,) .reshape() is a convenience wrapper. It checks if the tensor is contiguous.\nIf it is, it returns a view (fast, zero-copy). If it is not, it performs a copy (equivalent to .contiguous().view()). The Cost of Convenience “Can’t I just use reshape for everything?”\nAnd technically, you’re right. reshape() is incredibly smart. If your tensor is behaving itself (contiguous), reshape acts exactly like view — fast and efficient. If your tensor is “tangled” (non-contiguous), reshape automatically creates a copy to handle it safely.\nHowever, knowing whether you are copying data or not is critical for performance engineering. Are you getting a free ride, or are you paying a hidden tax?\nLet’s stop guessing and look at the numbers.\nimport torch import time # Create a massive 10,000 x 10,000 tensor (Approx. 380MB) size = 10000 x = torch.randn(size, size) print(\u0026#34;=== 1. The Happy Path (Contiguous Tensor) ===\u0026#34;) start = time.time() x.view(-1) print(f\u0026#34;View (Zero-Copy): {time.time() - start:.6f} seconds\u0026#34;) start = time.time() x.reshape(-1) print(f\u0026#34;Reshape (Zero-Copy): {time.time() - start:.6f} seconds\u0026#34;) # Conclusion: Both are blazing fast because reshape defaults to view internally. print(\u0026#34;\\n=== 2. The Twisted Path (Non-Contiguous Tensor) ===\u0026#34;) y = x.t() # Mess up the memory layout with a transpose try: y.view(-1) except RuntimeError: print(\u0026#34;View: Failed! (Error raised as expected)\u0026#34;) start = time.time() y.reshape(-1) # A physical copy happens here! print(f\u0026#34;Reshape (Copy Occurred): {time.time() - start:.6f} seconds\u0026#34;) Results on a standard machine:\n=== 1. The Happy Path (Contiguous Tensor) === View (Zero-Copy): 0.000238 seconds Reshape (Zero-Copy): 0.000040 seconds === 2. The Twisted Path (Non-Contiguous Tensor) === View: Failed! (Error raised as expected) Reshape (Copy Occurred): 0.157830 seconds The Verdict\nWhen Contiguous (Normal): view and reshape are neck-and-neck. There is virtually no difference. When Non-Contiguous (Twisted): reshape handles the situation silently, but it is roughly 10,000 times slower than the zero-copy operation because it has to physically move memory. Here is the danger: If you use reshape inside a training loop (like a DataLoader or a custom layer), you might be paying a massive memory copy tax without ever realizing it.\nThis is why I recommend getting into the habit of using view. Think of view as a statement of intent: “I refuse to copy memory!”\nIf view throws an error, it forces you to acknowledge the issue. You can then consciously decide to fix it using .contiguous() or switch to .reshape() knowing exactly what the cost is.\nSummary Storage is a flat 1D array. PyTorch tries very hard not to move it. Metadata (Shape \u0026amp; Stride) determines how that flat array is interpreted as dimensions. View only changes metadata. It fails if the requested shape contradicts the physical memory layout. Contiguous means the memory layout perfectly matches the shape (row-major). Reshape will fix the error by copying data, but be aware of the performance cost. Next time you see that RuntimeError, you'll know exactly what's happening under the hood. It’s not just a shape mismatch; it’s a stride conflict.\n","permalink":"https://blog.jiminl.com/posts/pytorch-tensor-internals-storage-shape-and-stride-explained-fd58ec9e3a37/","summary":"If you’ve spent any time with PyTorch, you’ve almost certainly hit this wall:","title":"PyTorch Tensor Internals: Storage, Shape, and Stride Explained"},{"content":"(Continued from: TPU: Why Google Doesn’t Wait in Line for NVIDIA GPUs (1/2))\n3. “Close Enough” is Good Enough (bfloat16) Traditional scientific computing uses FP64 (double precision) or FP32 (single precision). These formats are incredibly accurate.\nBut Deep Learning isn’t rocket trajectory physics. It doesn’t matter if the probability of an image being a cat is 99.123456% or 99.12%.\nGoogle leveraged this to create bfloat16 (Brain Floating Point).\nIt uses 16 bits (like FP16). But it keeps the wide dynamic range of FP32. FP16 can crash training because it can’t handle very tiny or very huge numbers (range: ~6e-5 to 6e4).\nbfloat16 sacrifices precision (how many decimal places) to keep the range (1e-38 to 1e38), matching FP32.\nIn AI, being able to represent a tiny number (0.00000001) is more important than knowing exactly what the 10th decimal digit is. This format was so successful that NVIDIA adopted it for their A100 and H100 GPUs.\n4. TPU Pod: One Chip Is Not Enough While a single TPU chip is effective at matrix multiplication, it is nowhere near powerful enough to run today’s massive Deep Learning models. To solve this, Google decided to bundle multiple TPUs together. They call this super-cluster a TPU Pod.\nThe hierarchy works like this: You bundle TPU Chips to make a TPU Board, stack Boards to make a TPU Rack, and line up Racks to form a TPU Pod. When you tie 4,096 TPU chips together into a single Pod, you can trick the software into thinking it’s working with one single, massively powerful chip that is 4,096 times faster.\n4.1 Connecting the Chips: Inter-Chip Interconnect (ICI) Usually, when computers talk to each other, they use Ethernet cables — the same standard used for the internet. However, for AI training, chips need to exchange data constantly and instantly. Ethernet is simply too slow.\nTPU Pods use a dedicated connection method called ICI (Inter-Chip Interconnect). This allows data to bypass the CPU entirely and zip between TPU chips at incredible speeds.\nGoogle connects these TPUs in a 3D Torus topology — essentially a 3D donut shape.\nFrom: https://www.nextplatform.com/2018/05/10/tearing-apart-googles-tpu-3-0-ai-coprocessor/\nThanks to this “donut” structure, the chip at the very far right edge is directly connected to the chip at the very far left edge. Data can travel to the most distant chip in the cluster in just a few hops.\n4.2 Using Light Instead of Electricity: Optical Circuit Switch (OCS) With the TPU v4 Pod, Google introduced a truly ingenious piece of technology: the OCS (Optical Circuit Switch).\nIn traditional systems, data transmission involves a conversion chain: “Light signal -\u0026gt; Convert to Electricity -\u0026gt; Calculation/Switching -\u0026gt; Convert back to Light.”\nBut Google engineers thought: Why bother converting it to electricity? Can’t we just send the light directly? Their answer was mirrors. Google decided to bounce the light signals carrying data off mirrors to send them where they needed to go.\nInside the Pod, they installed MEMS (Micro-Electro-Mechanical Systems) mirrors. These are microscopic machines that can physically tilt and move using electrical signals. Google uses MEMS to adjust these tiny mirrors, reflecting the data-carrying light beams in the exact direction they need to go.\nThis approach offers two massive advantages:\nSpeed: Because there is no “Light -\u0026gt; Electricity -\u0026gt; Light” conversion process, data flies at the speed of light with almost zero latency. Resiliency: Let’s say 50 out of the 4,096 TPUs in a Pod fail. In a traditional setup, you might have to physically rewire the rack to bypass the broken chips. With OCS, you simply change the angle of the mirrors. The light bypasses the broken chips and finds a new path instantly. 4.3 An Aquarium-Like Cooling System Being able to bundle thousands of TPU chips is great, but it brings an unavoidable problem: Heat. These chips generate a level of heat that traditional air conditioning fans simply cannot handle.\nGoogle solves this by running pipes full of coolant directly on top of the chips. This is called Direct-to-Chip Liquid Cooling.\nWhile NVIDIA is recently making headlines for adopting liquid cooling in their H100, Google has been doing this for years. They have effectively been turning their data centers into massive aquariums to keep these beasts cool.\n5. The Software: JAX and XLA Hardware is a paperweight without software.\nTensorFlow used to be the king, but PyTorch stole the crown for ease of use. Google’s counter-punch is JAX. It feels like NumPy (easy Python) but runs on accelerators.\nThe magic bridge between Python and the TPU is XLA (Accelerated Linear Algebra).\nWhy is it fast? Kernel Fusion.\nWithout XLA, calculating a x b + c involves three trips to memory (Read a,b, Write a*b, Read c, etc.).\nXLA sees the whole equation and fuses it into a single operation kernel. It keeps the data in the registers and does the multiply-and-add in one shot, perfectly utilizing that Systolic Array we talked about earlier.\n6. The 7th Generation TPU: Ironwood In 2025, Google unveiled Ironwood, its 7th generation TPU. The design philosophy behind this chip is clear: capture both LLM Inference efficiency (running the models cheaply) and Large-scale Training (building the models quickly) at the same time.\nLet’s break down the key features of Ironwood.\n1) Overwhelming Compute Power and Native FP8 TPU v7 is the first TPU to support FP8 (8-bit floating point) operations natively. It delivers a staggering 4,614 TFLOPS of compute power (in FP8). To put that in perspective, that is approximately 10 times the performance of the TPU v5p and more than 4 times that of the previous v6e (Trillium).\n2) Massive Memory and Bandwidth (HBM3E) Each chip is equipped with 192GB of HBM3E memory and provides a memory bandwidth of 7.37 TB/s. Why does this matter? Large Language Models (LLMs) are typically “Memory-bandwidth bound.” This means the chip spends more time waiting for data to arrive from memory than it does actually calculating. Having ultra-fast memory is not just a “nice-to-have” — it is essential for performance.\n3) Scalability and Interconnect (ICI) The “Pod” and “ICI” technologies we discussed earlier have been supercharged. You can now scale a single Pod up to 9,216 chips. Furthermore, the ICI bandwidth has been boosted to 1.2 TB/s bi-directional. This allows thousands of chips to talk to each other even faster than before.\n4) Energy Efficiency Building on the liquid cooling systems mentioned earlier, Ironwood improves power efficiency by roughly 2x compared to the TPU v6. It continues to use the aquarium-style direct-to-chip cooling as a standard.\nFrom: https://blog.google/products/google-cloud/ironwood-tpu-age-of-inference/\n7. If TPUs Are So Great, Why Is Everyone Still Obsessed with GPUs? At this point, you might have a nagging question: “If the TPU is so efficient and specialized, why is the whole world continually scrambling to get their hands on NVIDIA GPUs?”\nThe answer lies in the fact that AI development isn’t decided by chip performance alone.\n1) CUDA NVIDIA has been building its software ecosystem, CUDA, since 2006. That is a massive head start. Today, over 90% of the world’s AI researchers write their code based on CUDA.\nEven PyTorch, the darling framework of the AI community, is practically optimized to run on CUDA by default. Does PyTorch code run on TPUs? Yes, it does. But compared to the seamless experience on GPUs, it is often less mature and less efficient.\nTo get 100% out of a TPU, you really need to use tools designed for it, like JAX. But asking busy developers — who are already running fast to keep up with AI trends — to learn a new framework is a massive barrier to entry.\n2) Hardware You Can Hold vs. Hardware in the Clouds It is true that buying a GPU these days is difficult. But buying a TPU is literally impossible.\nYou cannot go to a store or a vendor and buy a TPU to put in your server room. Realistically, the only way to use a TPU is to rent it through Google Cloud Platform (GCP).\nIf your company is already built on AWS or Azure, or if you have built your own on-premise infrastructure, TPUs are effectively “pie in the sky” — something nice to look at but impossible to eat. To use TPUs, you have to migrate your data and workflow to Google Cloud. That fear of vendor lock-in — being tied exclusively to Google’s infrastructure — is a major hurdle preventing widespread adoption.\n8. Cheat Sheet: GPU vs. TPU Wrapping Up We’ve taken a deep look at the TPU. We learned that Google isn’t just making a “faster” chip, but a chip that is architecturally specialized for the nature of AI.\nSystolic Arrays to eliminate memory bottlenecks. Precision Trade-offs (bfloat16) for efficiency. Optical Switches (OCS) \u0026amp; TPU Pods for massive scaling. JAX and XLA to control it all perfectly. If the NVIDIA GPU is a “Swiss Army Knife” strong in versatility, the Google TPU is a “Scalpel” specialized for efficiency in AI.\nRight now, NVIDIA’s CUDA ecosystem looks like an impregnable fortress. But huge tech companies like Amazon, Microsoft, Tesla, and Meta are starting to walk the path Google paved. They are building their own chips not just because NVIDIA GPUs are expensive and hard to find, but to avoid becoming too dependent on a single vendor.\nIn this wave of change, how should we prepare?\nWhen others are complaining, “I can’t do anything because there are no GPUs,” wouldn’t it be cool to be the person who says, “Oh? I can just use JAX and run this on a TPU”?\n","permalink":"https://blog.jiminl.com/posts/tpu-why-google-doesnt-wait-in-line-for-nvidia-gpus-2-2-2267e4ed686f/","summary":"Continues the discussion of why Google builds its own TPUs.","title":"TPU: Why Google Doesn’t Wait in Line for NVIDIA GPUs (2/2)"},{"content":"We hear it all the time: “You can’t do AI without GPUs,” or “NVIDIA is the only stock that matters in the AI era.” It’s true — companies are literally lining up to get their hands on NVIDIA’s silicon.\nBut Google is marching to the beat of a different drum. They train their Gemini models on TPUs (Tensor Processing Units).\nIf you Google “What is a TPU?”, you’ll get a generic answer like “A semiconductor optimized for AI.” Dig a little deeper, and you might find: “GPUs are great for general parallel processing, while TPUs are specialized for matrix math.”\nBut the word “optimized” does a lot of heavy lifting there, obscuring some genuine engineering brilliance. Why did Google ignore the industry standard GPU to bake their own silicon? And what exactly is happening inside that chip?\nToday, we’re popping the hood to see how the TPU works.\nRelated Reading: If you’re curious why GPUs are so good for AI in the first place, check out my previous post on the magic of LLMs and GPUs: Why GPUs Ate the AI World\n1. The Birth of the TPU Let’s rewind to 2015. Smartphones were everywhere, and users were just starting to get comfortable with voice search. Then and now, voice recognition is a heavy machine-learning workload.\nGoogle engineers crunched the numbers on their voice search traffic and reached a terrifying conclusion:\n“If every Android user in the world uses voice search for just 3 minutes a day, we would need to double our current data center capacity.”\nYou might think, “It’s Google. They have infinite money. Just build more data centers.” But building a data center isn’t just about building a warehouse. It costs a fortune, requires building new power plants to run it, and demands massive cooling solutions to keep it from melting.\nWorse, the hardware available at the time wasn’t up to the task. CPUs were too slow for machine learning, and GPUs — while fast — consumed way too much power.\nGoogle decided to forge a third path. Not a CPU, not a GPU, but a new chip designed to do one thing exceptionally well: the matrix operations that power machine learning.\nThat is how the TPU (Tensor Processing Unit) was born.\n2. The Secret Sauce: Systolic Arrays Let’s go inside the silicon.\nThe heart of the TPU is an architecture called the Systolic Array. If you want to sound smart at your next tech meetup, just drop this term. It is the defining difference between a GPU and a TPU.\n“Systolic” is actually a medical term referring to the systole — the phase of the heartbeat when the heart muscle contracts and pumps blood through the arteries. So, why is a computer chip named after a beating heart?\nTo understand that, we have to look at how traditional computers think.\n2.1 The Von Neumann Bottleneck Modern computers (including GPUs) typically follow the Von Neumann architecture. It’s a simple, beautiful design:\nYou separate the Calculator (CPU) and the Storage (Memory), and connect them with a wire (Bus).\nThe workflow looks like this:\nCPU: “Hey Memory, give me the number at address 53.” Memory: Finds the data and sends it over the Bus. CPU: Adds 1 to the number and sends it back to Memory. Let’s use a kitchen analogy.\nCPU: The Chef. Memory: The Pantry. Bus: The Runner (the assistant moving ingredients back and forth). The Chef asks for carrots. The Runner goes to the Pantry, finds carrots, and brings them to the Chef. The Chef puts them on the cutting board. The Chef chops them at the speed of light. The Runner takes the chopped carrots back to the Pantry. Even if you hire a Chef with 30 years of experience who chops at supersonic speeds, the overall cooking time is slow. Why?\nThe Pantry is far away: You can’t keep all ingredients on the cutting board (limited cache/register space). You have to use the big storage room. The Runner is slow: Moving ingredients takes way longer than the actual chopping. In computing, this is the Von Neumann Bottleneck. The chip is fast, but it spends all its time waiting for data to arrive from memory. Google realized that to fix this, they needed a design where data didn’t stop and start, but flowed.\n2.2 The Fix: Don’t Put It Back in the Pantry, Just Pass It! Let’s go back to our kitchen. Imagine we are preparing a dish using the standard (inefficient) method. It would look something like this:\nThe Runner brings a carrot from the Pantry. Chef #1 chops the top off the carrot. The Runner takes the chopped carrot back to the Pantry. The Runner goes back to the Pantry and retrieves the chopped carrot. Chef #2 cuts the carrot into thirds. The Runner takes the cut carrot back to the Pantry. The Runner goes back to the Pantry and retrieves the cut carrot. Chef #3 cuts the carrot slices. The Runner takes the carrot back to the Pantry. The Runner goes back to the Pantry and retrieves the carrot. Chef #4 seasons the carrot strips with soy sauce and sugar. The Runner takes the finished, seasoned carrot to the Pantry. You can feel the inefficiency just reading that, right? We are constantly putting the carrot back into storage and taking it out again, even though we need to use it immediately for the next step.\nSo, how do we fix this? We introduce a factory conveyor belt system.\nThe Runner brings a carrot from the Pantry. Chef #1 chops the top off and immediately hands it to Chef #2. Chef #2 cuts it into thirds and immediately hands it to Chef #3. Chef #3 cuts the slices and immediately hands it to Chef #4. Chef #4 seasons the strips. The Runner takes the finished, seasoned carrot to the Pantry. This time, instead of putting the ingredients back into the pantry between every single step, we passed them directly to the next chef. The result? The time it took to get the seasoned carrot was drastically reduced.\nApplying this to Matrix Math Deep learning looks like magic from the outside, but if you look under the hood, it is essentially a massive number of matrix multiplications (multiplying and adding).\nThe structure of deep learning neural networks is represented by matrices. If you look at the process of multiplying two matrices, it’s very similar to the cooking process we just described: you repeatedly multiply and add elements.\nThe TPU takes this idea and runs with it. It places thousands of “Chefs” (arithmetic units for multiplication and addition) in a dense, checkerboard grid. These Chefs wait for the ingredients to arrive at their station, calculate the result instantly, and pass the ingredients directly to the Chef next to or below them.\nLet’s look at this process in more detail.\n2.3 Data Flowing Like Blood Now, let’s put the chip under a microscope and look inside.\nIn the original TPU v1, there are 256 x 256 (totaling 65,536) arithmetic units called MACs arranged in a square. A MAC does exactly two things: Multiply and Add. That’s why it’s named MAC (Multiply-Accumulate Circuit).\nFrom: https://docs.cloud.google.com/tpu/docs/system-architecture-tpu-vm\nThe crucial detail here is that these MACs are arranged in a grid pattern. This lattice structure is what makes the magic happen.\nPhase 1: Loading Weights (The Setup)\nA Deep Learning model is basically a collection of “Weights.” The TPU pre-loads these weights into the 65,536 MAC units. Every calculator holds one specific number.\nPhase 2: The Systolic Flow\nWe pump the input data in from the left.\nThe data enters the first column of MACs. The MAC multiplies the data by its held Weight. It passes the result down to the unit below. It passes the original data to the unit on the right. Phase 3: The Wave\nInputs flow Left-to-Right. Partial sums flow Top-to-Bottom. By the time the data reaches the bottom-right corner, the massive matrix multiplication is complete.\n2.4 A Concrete Example Now, let’s look at how a Systolic Array actually operates in practice. (Note: This section gets a bit technical, so if you aren’t interested in the math, feel free to skip ahead.)\nThe most important takeaway here is that we do not save the result to memory after every single multiplication and addition.\nJust like our kitchen analogy — where the chef hands the chopped carrot directly to the next person instead of returning it to the pantry — in the TPU, the calculation result is passed downward, while the original input data is passed sideways. This approach completely overcomes the bottleneck of slow memory access while performing matrix multiplication with extreme efficiency.\nWhen Google claims the TPU is “optimized for AI,” this is the core of that argument: the uninterrupted flow of data, or the Systolic Array. Just as a heart pumps blood through the body in a rhythmic beat, the TPU pumps data between the MAC units in perfect sync with the chip’s clock cycle.\nHere is the specific problem we want to solve:\nInput Data:\nWeights:\nThe Goal: We want to get [(1 X 5 + 2 X 7), (1 X 6 + 2 X 8)] = [19, 22]\nLet’s say we have a tiny 2x2 grid of MACs.\nStep 1: Park the Weights\nWe assign a Weight to each MAC unit.\nStep 2: Pump the Data\nWe send in the inputs 1 and 2 from the left. Crucially, they are staggered (skewed). 1 goes first. 2 goes one clock cycle later.\nTick 1:\n- MAC A receives 1. Calculates 1 * 5 = 5. Sends result Down. Sends 1 Right. Tick 2:\n- MAC C (Bottom-Left) receives the 5 from above. It also receives input 2 from the left. It calculates 2 * 7 = 14, adds the 5, and gets 19. (First answer done!)\n- MAC B (Top-Right) receives the 1 from the left. Calculates 1 * 6 = 6. Sends result Down. Tick 3:\n- MAC D (Bottom-Right) receives the 6 from above and the 2 from the left. Calculates 2 * 8 = 16, adds the 6, and gets 22. (Second answer done!) The Result: We collect 19 and 22 at the bottom.\nThe Key Takeaway: We performed all these calculations without once writing a temporary number back to memory. The data flowed through the chip like a heartbeat, reusing inputs and accumulating results in a single, fluid motion.\nIf you want to see a more sophisticated, real-world animation of this process, check out the video below. It should make a lot more sense now that you understand the mechanics.\nComing up in Part 2: We’ll dive into the massive super-clusters connecting thousands of TPUs, the cutting-edge 7th Gen “Ironwood,” and the real reason the world is still obsessed with NVIDIA GPUs.\nTPU: Why Google Doesn’t Wait in Line for NVIDIA GPUs (2/2)\n","permalink":"https://blog.jiminl.com/posts/tpu-why-google-doesnt-wait-in-line-for-nvidia-gpus-1-2-02c1c308da0c/","summary":"We hear it all the time: “You can’t do AI without GPUs,” or “NVIDIA is the only stock that matters in the AI era.” It’s true — companies…","title":"TPU: Why Google Doesn’t Wait in Line for NVIDIA GPUs (1/2)"},{"content":"If you use PyTorch, there’s one line of code you probably type out of sheer muscle memory: loss.backward().\nWhen you first learn neural networks, you spend hours deriving backpropagation equations and understanding chain rules. Then you meet PyTorch, type loss.backward(), and it just... works. It feels like magic. All that complex calculus is handled in a single line.\nBut as engineers, “It’s magic” isn’t a satisfying explanation. It’s actually a bit unsettling. What exactly is happening under the hood when we call that function?\nToday, we’re going to look behind the curtain at Autograd, the engine that makes this magic possible.\n0. The Blueprint: The Training Loop Before we tear apart the code, let’s quickly recap the standard workflow of training a deep learning model. Training is essentially an iterative process of tweaking weights (parameters) to minimize error. It usually follows these four steps:\nForward Pass: Push input data through the model to get a prediction. Loss Calculation: Compare the prediction to the actual target to calculate the loss. Backward Pass: Determine how much each parameter contributed to the error. We traverse from the loss back to the start, calculating gradients. Weight Update: Adjust the parameters based on the calculated gradients to reduce the error in the next round. By repeating this, the model gets smarter.\nThe “Hello World” of Deep Learning Here is how those steps translate into standard PyTorch code. If you’ve done any PyTorch tutorial, this will look familiar:\nfor epoch in range(epochs): # 1. Clear the whiteboard (Reset Gradients) optimizer.zero_grad() # 2. Take the test (Forward pass) output = model(input) # 3. Grade the test (Compute Loss) loss = criterion(output, target) # 4. Find out why we failed (Backward pass) loss.backward() # 5. Study and improve (Update Parameters) optimizer.step() Let’s dig into the five simple lines that power this complex process.\n1. Autograd: The Puppet Master Autograd is PyTorch’s automatic differentiation engine. Think of it as a silent stenographer. Whenever you create a Tensor and perform operations (add, sub, multiply), Autograd watches and records everything. It notes down what data was used, what operation was performed, and what the result connects to next.\nThe Dynamic Computational Graph Autograd records this history in a structure called a Computational Graph. This graph maps out every operation: the inputs, the operator, the outputs, and the sequence of events.\nPyTorch is famous for using a Dynamic Computational Graph. This means the graph isn’t pre-compiled; it’s drawn on the fly as your code runs.\nNote: PyTorch 2.0 introduced torch.compile to allow for static graph optimization, which we'll touch on at the end.\nimport torch x = torch.tensor([2.0], requires_grad=True) y = torch.tensor([3.0], requires_grad=True) z = x * y loss = z ** 2 Setting requires_grad=True tells Autograd: \u0026quot;Watch this tensor closely.\u0026quot; When we run the code above, PyTorch builds a graph that looks something like this:\nx, y (Leaf Nodes) → Multiplication → z → Power → loss (Root)\n2. The Core Components: grad_fn, next_functions, ctx, and .grad To understand how Autograd navigates this graph, we need to meet the internal variables that hold it all together.\nMember 1: grad_fn (The Signpost) Every Tensor created by an operation has a grad_fn attribute. This attribute answers the question: \u0026quot;What operation created me?\u0026quot;\nIf a tensor was created by addition, it gets AddBackward. If by multiplication, MulBackward. It acts as a node in our graph and holds the instructions for how to differentiate that specific operation.\nMember 2: next_functions (The Connection) If grad_fn says \u0026quot;who I am,\u0026quot; next_functions says \u0026quot;who my parents are.\u0026quot; It points to the grad_fn of the input tensors that created the current tensor. During backpropagation, this tells PyTorch where to send the calculated gradients next. This forms the edges of our graph.\nWe can actually inspect this structure with a recursive function:\nimport torch x = torch.tensor([2.0], requires_grad=True) y = torch.tensor([3.0], requires_grad=True) z = x * y loss = z ** 2 def print_graph(grad_fn, depth=0): indent = \u0026#39; \u0026#39; * depth if grad_fn is None: return print(f\u0026#34;{indent}└─ {type(grad_fn).__name__}\u0026#34;) for next_fn, _ in grad_fn.next_functions: print_graph(next_fn, depth + 1) print(\u0026#34;\\n=== Autograd Graph Structure ===\u0026#34;) print_graph(loss.grad_fn) Output:\n=== Autograd Graph Structure === └─ PowBackward0 └─ MulBackward0 └─ AccumulateGrad └─ AccumulateGrad The print_graph() function takes a Node (grad_fn) as input and traverses the next_functions list to map out the history. Let’s trace exactly what this output is telling us:\nPowBackward0: The journey starts at loss. Since loss was calculated using the formula loss = z ** 2, it possesses a grad_fn corresponding to the power operation, which is named PowBackward0. MulBackward0: The input used to create that square operation was z. Looking back at how z was born, we see z = x * y. Because this was a multiplication operation, its grad_fn is MulBackward0. AccumulateGrad: Finally, MulBackward0 lists AccumulateGrad as its parents. This is a special marker indicating a Leaf Node. A Leaf Node is a Tensor that has requires_grad=True but wasn't created as the result of an intermediate operation. These are the tensors we created manually, like x and y. Since we made them ourselves, they don't have a natural grad_fn (no operation created them). So, Autograd artificially attaches an AccumulateGrad node to them so they can be connected to the graph and store gradients during backpropagation.\nMember 3: ctx (The Storage Locker) To calculate a derivative (gradient), you often need the original input data.\nExample: The derivative of x^2 is 2x. To calculate 2x, you need to know what x was.\nDuring the Forward Pass, PyTorch realizes: “I might need this value later for calculus.” It saves these tensors in a special container called ctx (context).\nThis is a common source of memory issues. Even if your model parameters fit on the GPU, the training process consumes much more memory because ctx is holding onto all those intermediate tensors needed for the backward pass.\nMember 4: .grad (The Report Card) When you call loss.backward(), PyTorch navigates the graph, calculating gradients at every step. The final result for each parameter is stored in its .grad attribute.\nCrucially, .grad values are cumulative. PyTorch doesn't overwrite them; it adds to them. (We'll explain why in section 5).\nLet’s see ctx and .grad in action by creating a custom Autograd function:\nimport torch class MySquare(torch.autograd.Function): @staticmethod def forward(ctx, input_tensor): # 1. Forward Pass # Save input to the \u0026#39;ctx locker\u0026#39; for later use ctx.save_for_backward(input_tensor) return input_tensor ** 2 @staticmethod def backward(ctx, grad_output): # 2. Backward Pass # Open \u0026#39;ctx locker\u0026#39; and retrieve the saved input input_tensor, = ctx.saved_tensors # Calculate Gradient: 2x * (incoming gradient) gradient = (2 * input_tensor) * grad_output # Pass this gradient down the line return gradient x = torch.tensor([3.0], requires_grad=True) # Run Forward y = MySquare.apply(x) print(f\u0026#34;Forward result (3^2): {y.item()}\u0026#34;) # 9.0 # Run Backward # y.backward() is implicitly y.backward(torch.tensor(1.0)) y.backward() # Check the calculated gradient # Logic: (2 * 3.0) * 1 = 6.0 print(f\u0026#34;Backward result (2*3): {x.grad.item()}\u0026#34;) # 6.0 Output:\nForward result (3^2): 9.0 Backward result (2*3): 6.0 Here is exactly what happened in that code block:\nIn the Forward phase, MySquare calculates the square, but it also performs a critical step: it calls ctx.save_for_backward(input_tensor) to save the original input value into the ctx storage.\nThen, in the Backward phase, it uses ctx.saved_tensors to retrieve that saved input (which we stored earlier) to calculate the derivative. This calculated value eventually lands in the tensor's .grad attribute, which we confirm in the last line by printing x.grad.item()\n3. The loss.backward() Journey Now, let’s look closer at what happens when loss.backward() is called. PyTorch starts at loss and travels backward through the graph toward the inputs, calculating derivatives for each node.\nWhere is the final destination of this journey? It’s the model inputs and the Tensors created by the user — typically the Weights and Biases. These nodes sit at the end of the graph and are called Leaf Nodes.\n(The nodes in the middle of the graph are simply intermediate Tensors created as results of operations.)\nHere is the actual flow:\nDeparture: The journey begins at loss. Opening the ctx Locker: It accesses ctx via grad_fn to retrieve the \u0026quot;intermediate tensors\u0026quot; saved earlier. Calculating Derivatives: It calculates the gradient using the data and the chain rule. Propagation \u0026amp; Accumulation: It passes the calculated gradient to the previous nodes using next_functions. If it reaches a Leaf Node (a parameter), it adds the value to that Tensor's .grad attribute. 4. optimizer.step(): Making the Move Once backward() is finished, every parameter knows which direction it needs to move to reduce the error. The calculated directions are sitting in the .grad attributes.\nThe job of actually modifying the Tensor values belongs to optimizer.step(). While its job is simple—update the Leaf Nodes (Weights, Biases)—there are two implementation details worth noting.\nFirst, optimizer.step() technically involves Tensor math (e.g., subtracting a value from the current weight). In theory, this operation should also be recorded by ctx. However, updating weights is not part of the model's forward training logic; we don't want to backpropagate through the optimization step itself. Therefore, optimizer.step() works internally by turning on torch.no_grad(), ensuring these updates aren't recorded in the graph.\nSecond, the update happens as an In-place operation. Usually, PyTorch tensor operations create new Tensors. But in the optimizer, we want to modify the existing Tensors directly. For efficiency and to preserve the graph connections, the optimizer uses in-place methods like w.sub_(lr * grad).\n5. optimizer.zero_grad(): A Fresh Start We’ve reached the final piece of the training loop: zero_grad(). We know its role is to reset the gradients. But why do we have to do this at the start of every loop?\nThis is because PyTorch accumulates gradients. When PyTorch calculates a new gradient, it doesn’t overwrite the existing value in .grad; it adds the new value to the old one.\nTherefore, once a mini-batch is finished, we must call zero_grad() to wipe the slate clean. It’s like erasing a chalkboard after solving a math problem so you have space to solve the next one.\nBut this raises a question: Why doesn’t PyTorch just automatically zero out the gradients after optimizer.step()? Why make us type this extra line?\nThis is actually a feature which can be used to enable Gradient Accumulation. This technique is a lifesaver when you are running out of GPU memory.\nFor example, let’s say you want to train with a Batch Size of 64, but your GPU only has enough memory for a Batch Size of 16. You can simulate the larger batch size using accumulation:\nSet your real batch size to 16. Run the training loop 4 times without calling zero_grad(). (16 x 4 = 64) During these 4 loops, the gradients will pile up on top of each other in .grad. After the 4th loop, call optimizer.step() to update the weights. Now call optimizer.zero_grad() to prepare for the next set. By doing this, you physically calculated 16 items at a time, but mathematically, you performed an update equivalent to a batch of 64.\nAppendix 1: model.eval() vs torch.no_grad() These two commands are both used during inference, but they serve very different purposes. It’s easy to confuse them.\n1) model.eval(): \u0026quot;Combat Mode\u0026quot; When you are studying for a test, you might use various tools to help you learn: you might take mock exams, use flashcards, or intentionally solve harder problems to challenge yourself.\nBut when you take the actual exam, you don’t do those things. You just solve the problems in front of you.\nDeep learning models are the same. During training (studying), they use techniques like Dropout (randomly turning off neurons) and BatchNorm (calculating statistics based on the current batch). But during inference (the exam), they need to behave differently. model.eval() tells the model: \u0026quot;We are in a real situation now. Turn off Dropout and freeze the BatchNorm statistics!\u0026quot;\nHowever, this does not save memory. Even in eval mode, Autograd continues to build the graph and store values in ctx during the forward pass.\n2) torch.no_grad(): \u0026quot;Stop Recording\u0026quot; torch.no_grad() is a direct command to the Autograd engine: \u0026quot;Stop recording. Take a break.\u0026quot;\nAutograd meticulously records everything solely for the purpose of the backward pass. But during inference, we don’t need to do a backward pass. If Autograd keeps recording, it’s just wasting memory and time.\nInside a with torch.no_grad(): block, PyTorch stops storing intermediate Tensors in ctx. This effectively reduces memory usage and speeds up computation.\nConclusion: Since they have different purposes, you should usually use both when running validation or testing:\n# 1. Change Model Behavior (Disable Dropout, etc.) model.eval() # 2. Save Memory \u0026amp; Speed Up (Stop tracking operations) with torch.no_grad(): output = model(data) Appendix 2: torch.compile (PyTorch 2.0+) The greatest strength of early PyTorch was the flexibility of its Dynamic Graph. However, rebuilding the graph from scratch every single iteration is inherently slower than the Static Graph approach (where the graph is fixed and optimized once).\nPyTorch 2.0 introduced torch.compile to solve this performance gap.\n1) The Principle: Operator Fusion The key to torch.compile's speed is Operator Fusion.\nModern GPUs calculate math incredibly fast. However, moving data from memory to the chip (and back) is relatively slow. In fact, memory access is often the bottleneck.\nWithout torch.compile (Eager Mode), the process looks like this:\nRead value from GPU memory. Multiply it by 2. Write the result back to memory. Read that result from memory again. Add 5 to it. Write the final result to memory. Notice how we are reading and writing to memory multiple times?\ntorch.compile optimizes this:\nIt analyzes the entire graph and notices we are doing a multiply followed by an add. It fuses these into a single custom function (kernel). New Flow: Read value from memory. Multiply by 2 AND add 5 in one go (inside the GPU). Write the final result to memory. By reducing the number of “slow” memory accesses, the overall speed increases significantly.\n2) How to use it Using it is incredibly simple. Just wrap your model:\nimport torch model = MyNet() optimized_model = torch.compile(model) # Use it exactly the same way as before output = optimized_model(input) Wrap Up We started with loss.backward() as a magic spell. We ended with an understanding of the Autograd engine that powers it.\nNow you know that when you call loss.backward(), it's not just a simple function call. PyTorch is following the grad_fn signposts, opening the ctx storage lockers, and diligently traversing the graph in reverse.\nUnderstanding these internals is more than just intellectual trivia. It gives you practical engineering skills:\nMemory Issues: You now understand that OOM errors are often caused by ctx holding onto tensors, not just the model size. Custom Operations: You know how to inherit from Function to create custom layers that don't break the gradient chain. Gradient Accumulation: You understand why zero_grad() is manual and how to leverage it to train huge models on small GPUs. Inference Optimization: You know exactly why torch.no_grad() is essential for performance, distinct from model.eval(). Hopefully, the next time you type loss.backward(), you’ll see the invisible graph being traversed and appreciate the engineering happening behind the scenes.\n","permalink":"https://blog.jiminl.com/posts/demystifying-loss-backward-how-pytorch-autograd-actually-works-e79b4b542b22/","summary":"If you use PyTorch, there’s one line of code you probably type out of sheer muscle memory: loss.backward().","title":"Demystifying loss.backward(): How PyTorch Autograd Actually Works"},{"content":"I’d like to talk about On-Device LLMs today. The term “On-Device LLM” has been getting a lot of buzz recently, often mentioned alongside the broader topic of On-Device AI.\nFor instance, Samsung has integrated an On-Device LLM into its Galaxy AI, starting with the Galaxy S24, and other manufacturers are following. Apple recently announced that its upcoming Apple Intelligence will feature a 3B-class On-Device LLM.\nSo, what exactly is an On-Device LLM, and what does it take to build one? Let’s dive in.\nNote: This article was originally written in 2024. Even though I’ve updated parts of it, some parts may feel a bit dated by today’s standards. However, most of the key ideas about LLMs remain just as relevant today.\nWhat is an On-Device LLM? Let’s start with the basics: what does “On-Device LLM” even mean?\nAs the name suggests, it’s an LLM that runs on a local device. The term “On-Device” is a counterpoint to Cloud. Instead of relying on a powerful cloud server, it operates directly on the hardware you own — your smartphone, laptop, PC, or even a refrigerator, TV, or car. As long as it’s not the cloud, it’s “on-device.”\nFor the sake of this article, we’ll focus on smartphones, as they’re the most common use case for On-Device LLMs.\nNext, what does it mean for an LLM to “run” on a device? In this context, “running” refers to inference. While there are some attempts to train LLMs on-device, for now, it’s primarily limited to inference.\nWhen people talk about On-Device LLMs, they usually mean one of two things:\nA lightweight LLM (often called an sLM or sLLM) that’s small enough to perform inference on a device. The act of running an LLM on a device itself. Even a lightweight LLM requires some serious technical know-how to get it running smoothly on-device. On-Device Constraints: Memory So, what makes an on-device environment so different from the cloud that it requires its own category? Let’s assume we’re talking about a smartphone, though most of these points apply to any on-device setup.\nFirst, there’s the memory constraint, which includes both memory size and memory speed.\nToday’s smartphones typically have anywhere from 8GB to 24GB of RAM (some Chinese brands have models with 24GB). The Galaxy S24 comes in 8GB and 12GB versions, while the iPhone 15 Pro has 8GB.\nHow much memory does a 7B LLM require? If you store the model parameters in fp32 (32-bit floating point), you need 28GB. With fp16 (16-bit floating point), you need 14GB. Even a 12GB phone is nowhere near enough, especially when you consider the memory already being used by the operating system and other apps.\nWhat about a smaller 3B LLM? That still requires 12GB for fp32 and 6GB for fp16. It's still not a practical amount of memory.\nMemory speed is another major issue. While some AI technologies are compute-bound, modern LLMs using the Transformer architecture are notoriously memory-bound. This means their performance is limited more by how fast they can access memory rather than by the speed of the CPU or GPU.\nTo solve this, cloud hardware like the A100 and H100 GPUs use incredibly fast memory. But smartphones can’t do that for two main reasons. First, it would make the device prohibitively expensive. Who would buy a smartphone that costs $15,000 just to run an On-Device LLM? Second, these high-end components consume a lot of power, which would quickly drain a smartphone’s battery.\nOn-Device Constraints: Storage Storage poses similar challenges. The iPhone 15 Pro offers storage options from 128GB to 1TB. The apps we use every day are typically a few dozen to a few hundred megabytes, with some games reaching a few gigabytes.\nBut as we saw, a 3B LLM can take up 6GB to 12GB of storage. That’s a significant chunk of space on a phone where people are constantly complaining about not having enough room for photos.\nStorage speed is another hurdle. To run an LLM, the model must first be loaded from storage into memory. Since storage is much slower than RAM, this loading process can be a bottleneck.\nThis problem gets even worse when combined with memory size constraints. Cloud servers can take a while to load a model initially, but that’s fine since it only happens once when the server starts. On a smartphone, the OS routinely shuts down apps it deems unnecessary to free up memory, and a massive LLM is a prime target. Once the model is unloaded, it needs to be loaded again from storage the next time you use it.\nAlternatively, you could prevent the OS from killing the LLM app, but then a huge chunk of precious memory is permanently occupied, leaving less for other applications.\nOn-Device Constraints: Processing Speed Processing speed is a massive problem. No matter how much smartphone CPUs and GPUs have improved, they can’t compete with the A100s and H100s used in the cloud. Imagine you somehow managed to get an On-Device ChatGPT running on your phone, but it took 10 minutes to respond to a question. Would you ever use it? The answer is a clear no.\nOn-Device Constraints: Battery and Heat In addition to the constraints above, battery life and heat are significant issues. For mobile devices, power efficiency is crucial. Running powerful hardware to power an LLM consumes a lot of electricity, which a small battery can’t sustain.\nHeat is a related problem. Even if you could solve the battery issue, running a powerful LLM would generate a tremendous amount of heat. Smartphones have poor heat dissipation, which can lead to thermal throttling — slowing down the hardware to prevent overheating — and even cause low-temperature burns to the user’s hand.\nOvercoming the Limitations After reading all this, you might be thinking, “Is an On-Device LLM even possible?” The answer is yes. Samsung, Apple, and others are seriously integrating them into their flagship products.\nLet’s explore how they’re overcoming these challenges and making On-Device LLMs a reality.\nModel Lightening The first step is to reduce the model’s size. An LLM is simply too big to run on a smartphone. How do we shrink it?\nThe most obvious way is to use a smaller model. A 7B model is better than a 70B, and a 70B is better than a 100B. Smaller is better. As mentioned, Apple is using a 3B LLM for Apple Intelligence. While that’s a small model by cloud standards, it’s still a significant size for a device.\nOnce you have a reasonably small model, you can use various proven techniques to make it even lighter. These include Pruning to remove unnecessary weights and Distillation to train a smaller model using a larger one. While both are important, the most critical technique for on-device environments is Quantization.\nLike pruning and distillation, quantization isn’t exclusive to on-device tech, but it’s used much more aggressively here.\n(Quantization is a complex topic that deserves its own article, so we’ll keep it brief for now.)\nQuantization, in simple terms, reduces the size of the data used to store the model’s parameters. The fp32 data type, commonly used in the cloud, requires 4 bytes per number. For a 3B LLM, that's 3B * 4 = 12GB of memory. Using fp16 (2 bytes) reduces this to 3B * 2 = 6GB.\nWhat if we use even smaller data types? We can use int8 (8-bit integers, 1 byte) or int4 (4-bit integers, 0.5 bytes). While this reduces accuracy, it drastically shrinks the model size. Quantizing a 3B LLM to int8 requires just 3GB, and int4 requires a mere 1.5GB. Compared to the 12GB needed for fp32, this is a monumental space saving.\nThis works under the assumption that we can maintain model quality, and fortunately, advancements in technology have made it possible to use int4 quantization with minimal performance degradation. Qualcomm, for instance, has confidently promoted INT4 support on its NPUs.\nUnlike pruning or distillation, quantization requires specific hardware support. Even if you have an int4 quantized model, if the hardware only supports fp16, the values will have to be converted to fp16 when loaded into memory. This negates the memory savings you get from quantization. We'll discuss this more later, but NPUs, which are commonly used on-device, support a more limited range of data types and operations than GPUs, which must be considered during quantization.\nAcceleration Let’s say we’ve used int4 quantization to shrink a 12GB 3B model down to 1.5GB. That's a huge reduction, but unfortunately, it's still too large to run effectively on a smartphone's CPU.\nWe need hardware acceleration for inference.\nThe first option that comes to mind is the familiar GPU. With the amazing graphics in today’s mobile games, it’s clear that smartphone GPUs are powerful. Using the GPU would be much faster than the CPU, but there are two main problems with this approach.\nFirst, the GPU is not an exclusive resource. Multiple apps like games and graphics editors need GPU acceleration. If an LLM is hogging the GPU, other apps won’t run properly.\nSecond, GPUs are power-hungry. Running an LLM on the GPU would drain the battery rapidly, similar to playing a graphically intensive game nonstop.\nThis is where the NPU comes in.\n(Like quantization, NPUs are a huge topic that we’ll save for another article.)\nJust as a GPU is specialized for graphics acceleration, an NPU (Neural Processing Unit) is specialized for running deep learning tasks. It accelerates common deep learning operations by building them directly into the chip. While NPUs initially focused on computer vision tasks, they have evolved to include features for NLP and, more recently, for efficiently running the Transformer architecture.\nUsing an NPU for LLM inference offers several benefits:\nDedicated Resource: NPUs are designed specifically for deep learning, so there’s less competition with other apps. Power Efficiency: NPUs are built for low-power operations, consuming less battery than a CPU or GPU. Speed: Hardware acceleration leads to faster inference. However, NPUs also have drawbacks. They are less versatile than GPUs. Each chipset manufacturer (Qualcomm, Apple, Samsung, etc.) designs their NPU differently, so a model might use an operation that a specific NPU doesn’t support. This means that a generic model created with frameworks like PyTorch or TensorFlow needs to be converted and optimized for each NPU. If a function isn’t supported, you might have to modify the model or find a workaround in the software, which can be a real hassle.\nThis conversion process isn’t just an inconvenience; it can lead to performance degradation if the NPU’s supported operations aren’t a perfect match. In the worst-case scenario, your model might not run on the NPU at all.\nDue to these constraints, chipset manufacturers often provide guidelines. For example, Qualcomm suggests using the CPU for real-time tasks that require a small model and the NPU for longer processing or larger models.\nHardware isn’t the only solution for acceleration. Techniques developed for cloud LLMs, such as KV Cache, GQA, and (Self) Speculative Decoding, are also being adopted for on-device use.\nQuality Assurance So now we have a small model that runs fast, but what if the output quality is bad? The small size of on-device models makes this a serious concern. They’re often less responsive to prompts and instructions.\nThis is where fine-tuning becomes critical. For On-Device LLMs, fine-tuning isn’t just an option — it’s a necessity for ensuring good performance. But this introduces another problem.\nImagine you fine-tuned a 3B model to create a summarization feature. Now you want to add a resume writing feature. You’ll need to fine-tune the model again, creating a separate, specialized version. What if you also want an email drafting feature? You’ll need yet another model. Soon, you’ll have multiple 3B models, each consuming a lot of storage.\nThis is where LoRA is perfect. LoRA allows you to keep the base model and just swap out small, task-specific LoRA weights, saving significant storage space. While implementing this on-device is not a trivial task, some companies have already done it, proving it’s possible.\nThe Cascade of Performance Loss Let’s recap the entire process:\nChoose a reasonably sized LLM as your starting point. Fine-tune it for a specific task. Shrink the model using techniques like pruning, distillation, and quantization. Convert and optimize the model for your target NPU. The problem is that each of these steps can introduce performance loss.\nUsing LoRA for fine-tuning might result in slightly lower performance than full fine-tuning. Quantization can cause a drop in quality. The conversion process for the NPU can also lead to performance degradation. After all these steps, the final performance can be much lower than you initially expected. The real challenge lies in the painstaking process of analyzing and fixing where the performance dropped in the pipeline.\nSo, Why On-Device LLMs? Despite these difficulties, why are so many people and companies so interested in On-Device LLMs?\nFrom a user’s perspective, privacy is a major benefit. As AI features become more integrated into our lives, we share more personal data. With On-Device AI, you have the assurance that your data never leaves your device.\nFor companies, there are multiple advantages:\nReduced Cloud Costs: GPUs are expensive, and running a cloud LLM comes with significant operational costs, including electricity. Legal Risk Mitigation: Storing and processing user data in the cloud has its benefits, but it also carries significant risks, especially with privacy laws like GDPR. New Product Differentiation: Samsung and Apple are using “Galaxy AI” and “Apple Intelligence” as powerful selling points for their new phones. This trend is also gaining traction in PCs with the “AI PC” movement. This is also great for semiconductor companies, as running these LLMs requires more RAM, storage, and powerful processors. Today, LLM companies seem to be split into two camps: those like OpenAI and Anthropic, who focus on huge models, and those who target On-Device, starting with smaller models. Startups, in particular, are focusing on smaller models because they can’t compete with the massive scale of the larger players.\nConclusion In the end, building an On-Device LLM isn’t just about compressing a big model into a small chip. It’s about mastering the art of trade-offs — balancing memory, speed, quality, and user experience. The companies that win this race won’t just shrink models; they’ll redefine what’s possible on the devices we carry every day.\n","permalink":"https://blog.jiminl.com/posts/on-device-llm-1ea0476a2df6/","summary":"Note: This article was originally written in 2024. Even though I’ve updated parts of it, some parts may feel a bit dated by today’s…","title":"On-Device LLM"},{"content":"If you’ve tried to get into AI development recently, you’ve probably heard the lament: “I want to train a model, but I don’t have enough GPUs,” or “I have the budget, but I literally can’t find GPUs to buy.”\nGPU stands for Graphics Processing Unit. In short, it’s a chip designed to render graphics. So, why has a chip built for video games and rendering become the backbone of Artificial Intelligence? The short answer is: GPUs are beasts at parallel processing.\nBut that one-liner doesn’t do justice to the massive architectural shift we are witnessing.\nToday, we’re going to dig into why the GPU became the engine of the AI revolution, starting from the grandfather of modern computing — the “Von Neumann Architecture” — all the way to the internals of the latest NVIDIA hardware.\n1. Where It All Began: The Von Neumann Architecture Before we talk about GPUs, we need to understand the baseline: the CPU, or more specifically, the Von Neumann Architecture.\nThis architecture is beautiful in its simplicity:\nSeparate the Calculator (CPU) from the Storage (Memory), and connect them with a Wire (Bus).\nThe workflow is straightforward:\nThe CPU asks Memory for the number stored at address 53. Memory rummages around, finds the data at address 53, and sends it over the Bus to the CPU. The CPU adds 1 to that number and sends it back to Memory. The Kitchen Analogy Let’s visualize this in a professional kitchen.\nCPU: The Head Chef. Memory: The Pantry Manager. Bus: The Runner (Assistant) moving ingredients between the pantry and the chef. Data: The Ingredients (e.g., carrots). Here is the process:\nChef (CPU) yells, “Bring me carrots!” Pantry Manager (Memory) finds the carrots in the warehouse and gives them to the Runner (Bus). Runner carries the carrots to the Chef’s station. Chef chops the carrots with lightning speed (processing). Chef gives the chopped carrots back to the Runner. Runner takes them back to the Pantry Manager for storage. Here is the problem: The Chef is a legend with 30 years of experience. Their knife skills are a blur of motion. However, the overall speed of the kitchen is slow. Why?\nTalent is scarce: Hiring another Chef of this caliber is incredibly difficult (and expensive). We can’t just hire 1,000 head chefs. The Pantry is slow: Finding ingredients takes time. We can’t keep all ingredients on the cutting board because the workspace (Cache/Registers) is tiny. We have to use the massive warehouse (RAM). The Runner is a bottleneck: Even if the Chef chops in 0.1 seconds, if the Runner takes 10 seconds to fetch the carrots, the Chef spends most of their time waiting. This is known as the Von Neumann Bottleneck. To speed up the entire meal (program), you need to solve all three problems. While CPUs have tried to mitigate this, GPUs have effectively solved it — specifically for the field of Deep Learning.\n2. CPU vs. GPU = Versatility vs. Brute Force Did computers not render graphics before GPUs existed? Of course they did. We played Doom and drew in Paint long before discrete GPUs were common. Back then, the CPU handled everything.\nBut as graphics became more complex, we needed specialized hardware.\nCPU: The Jack-of-All-Trades Genius The CPU is the commander-in-chief. It runs the OS, handles mouse interrupts, executes complex logic, and ensures your browser doesn’t crash. It is designed to handle complex, sequential tasks very well.\nFew, but Elite: CPUs follow a “Special Forces” strategy. A consumer CPU might have 24–32 cores; a top-tier server CPU might have 128. They are not numerous, but each core is incredibly powerful. Complex Logic: CPUs are great at prediction and branching. If your code has lots of “If user does A, do B, else do C,” the CPU handles that logic seamlessly. GPU: The Army of Math Whizzes The GPU was born to handle graphics, which, mathematically speaking, is just changing the color values of millions of pixels simultaneously. It doesn’t need to run an Operating System.\nInstead of making a few complex cores, the GPU strategy is: Make the cores simple, but make a massive amount of them.\nImagine hiring 16,000 grade-school math whizzes who are only good at addition and multiplication.\nThe Zerg Rush: Compared to a CPU, a GPU has an overwhelming number of cores. An NVIDIA H100 GPU has roughly 16,000 CUDA Cores. Simple Tasks: An individual GPU core is much “dumber” than a CPU core. It struggles with complex branching logic. But if you ask it to “multiply these two numbers,” it does it instantly. From: https://en.namu.wiki/w/GPGPU\nCPU has 4 massive green blocks; GPU has thousands of tiny green dots.\nDeep Learning: It’s Just Huge Matrix Math Deep Learning looks like magic, but under the hood, it’s mostly matrix multiplication and addition repeated billions of times. It doesn’t require complex logic branches.\nLet’s look at a simple neural network layer:\nInput: 1,000 features Output: 1,000 neurons Weight Matrix: 1,000 × 1,000 A single pass requires roughly 1 billion multiply-add operations. Train a model like GPT-3 (175 billion parameters) on terabytes of data, and you are looking at quintillions of calculations.\nFor this specific type of math, it is infinitely faster to use 16,000 math students (GPU) than 100 geniuses (CPU). The geniuses would waste their talent on simple arithmetic, while the students can finish the worksheet in milliseconds by working all at once.\n3. Embarrassingly Parallel Let’s dig a bit deeper. Why exactly is matrix math so good for GPUs? We need to talk about dependencies.\nIf you are cooking instant Ramen:\nBoil water. Add noodles and powder. Wait. Eat. You cannot eat the noodles before you boil the water. There is a dependency. You can’t just throw raw noodles, cold water, and powder into your mouth at the same time. This is a serial process, and CPUs love this.\nMatrix multiplication is different.\nFrom: https://en.wikipedia.org/wiki/Matrix_multiplication\nTo calculate one value in a result matrix (c_12), the formula is roughly:\nc_12 = a_11 X b_12 + a_12 X b_22\nHere is the key: To calculate c_12, you do not need to know the result of c_11. You don’t need to wait for your neighbor.\nThis is called being Embarrassingly Parallel.\nIt’s like making 16,000 burgers. If you have enough staff and ingredients, 16,000 people can make 16,000 burgers simultaneously. You don’t need to check if the person next to you has put the pickles on yet.\nBecause Deep Learning is “embarrassingly parallel,” the GPU can command all its cores to work at once: “You calculate c_11, you do c_12, you do c_13… GO!”\n4. Herding the 16,000 Students (SIMT) Having 16,000 workers is great, but managing them is a nightmare. If a teacher had to give individual instructions to 16,000 students one by one, the management overhead would kill the efficiency.\nGPUs solve this with specific hierarchy definitions:\nThread: The worker. Unlike a heavy CPU thread (a soldier with a full rucksack of gear), a GPU thread is lightweight (a student with just a calculator). Warp: A squad of 32 threads. NVIDIA uses an architecture called SIMT (Single Instruction, Multiple Threads). The Commander doesn’t talk to individual soldiers; they issue orders to the Warp.\nIf the command is “Multiply the number on your desk by 5,” all 32 threads in the Warp shout “YES SIR!” and execute the instruction simultaneously. This reduces the control overhead by 32x. This is how a GPU manages to control thousands of cores efficiently.\n5. Tensor Cores: The Secret Weapon Up until roughly 2017, GPUs relied on CUDA Cores. These were great, but NVIDIA realized AI needs even more speed. They introduced a specialized component: the Tensor Core.\nCUDA Core: Good at calculating one number (scalar). Think of it as laying bricks one by one. Tensor Core: Specialized for Matrix Multiply-Accumulate (MMA) operations. Think of this as a crane lifting a pre-fabricated 4x4 wall section and installing it all at once. Starting with the Volta architecture, Tensor Cores could handle 4x4 matrix operations in a single clock cycle. As architectures evolved (Volta → Ampere → Hopper/Blackwell), Tensor Cores have become capable of handling larger chunks of data with higher precision strategies.\nNote: While “Tensor Core” is NVIDIA branding, AMD has “Matrix Cores” and Apple has “Neural Engines” that perform similar functions.\nDo we still need CUDA Cores? Yes. In a Transformer model (like GPT), about 70–90% of the work is matrix multiplication (Attention, Linear layers) — Tensor Cores handle this. The remaining 10–30% involves functions like Softmax, GELU, and Normalization. These require slightly more complex math than just “multiply and add,” so the versatile CUDA Cores handle those parts. It’s a perfect tag-team.\n6. Mixed Precision: The “Good Enough” Approach Another reason GPUs dominate AI is their ability to compromise.\nIf you are calculating the trajectory for a Mars landing, you need FP64 (Double Precision) or at least FP32 (Single Precision). You cannot afford a rounding error.\nBut if you are training an AI to differentiate a cat from a dog? It doesn’t matter if the neuron activation is 0.12345678 or just 0.123.\nGPU engineers exploit this with Mixed Precision:\nFP32: Precise, but uses lots of memory and is slower. FP16 / BF16: Less precise, uses half the memory, calculates much faster. FP8: 8-bit. Compared to FP32, it reduces data size by 4x and throughput explodes. Tensor Cores are designed to take these smaller, lower-precision numbers (FP8/FP16) for the heavy lifting (multiplication) and only switch to higher precision when accumulating the result to ensure the model learns correctly. This makes training tens of times faster with virtually no loss in model intelligence.\n7. Memory: The Need for Speed (HBM) We established earlier that the “Runner” (Bus/Memory speed) is a major bottleneck. It doesn’t matter if you have 16,000 cores if you can’t feed them data fast enough.\nStandard CPU memory (DDR5) offers a bandwidth of roughly 80 GB/s.\nHigh-End GPU memory (HBM3) offers a bandwidth of roughly 3,350 GB/s.\nThat is a 40x speed difference. This is why HBM (High Bandwidth Memory) is the most expensive and sought-after component in the AI supply chain right now.\nBut even HBM isn’t instant. GPUs use a memory hierarchy:\nFrom: https://docs.nvidia.com/deeplearning/performance/dl-performance-gpu-background/index.html\nL1 Cache / Registers: Tiny capacity, instant speed. (Right on the desk). L2 Cache: Medium capacity, very fast. (The shelf behind the desk). HBM (VRAM): Huge capacity, fast (compared to DDR), but slow (compared to Cache). (The Warehouse). Modern optimization techniques (like Flash Attention) focus entirely on keeping data in the L1/L2 cache as long as possible to avoid the “long trip” to HBM.\n8. Conclusion We’ve looked at the relationship between the Master Chef (CPU) and the army of Math Students (GPU).\nThe GPU became the protagonist of the AI era because it is the perfect architectural fit for Deep Learning. Deep Learning isn’t about complex logic; it’s about the relentless, repetitive stacking of mathematical bricks. For that task, you don’t need a few Einsteins; you need an army of disciplined workers who can lay bricks in parallel without getting in each other’s way.\nSummary:\nArchitecture: CPU = Sequential logic. GPU = Massive parallelism (Volume wins). Efficiency: SIMT allows controlling thousands of threads like a single unit. Specialization: Tensor Cores accelerate matrix math specifically, while Mixed Precision trades unnecessary accuracy for raw speed. Infrastructure: HBM memory provides the massive pipeline of data required to keep the cores busy. The innovation hasn’t stopped. We are now seeing 4-bit quantization, optical interconnects, and 3D stacked memory pushing the boundaries even further.\nSo, the next time you see a loss curve slowly dropping on your training run, don’t just think of it as “computer work.” Imagine 16,000 tiny workers inside that card, frantically passing numbers and stacking bricks in perfect synchronization.\n","permalink":"https://blog.jiminl.com/posts/why-gpus-ate-the-ai-world-0caebef97431/","summary":"If you’ve tried to get into AI development recently, you’ve probably heard the lament: “I want to train a model, but I don’t have enough…","title":"Why GPUs Ate the AI World"},{"content":"Even though Large Language Models (LLMs) appear to expertly understand and generate language, the truth is, like any other computer technology, they only deal in zeros and ones. So, how can an LLM, which only knows 0s and 1s, engage in such deep conversations with us using language? The first piece of that puzzle lies in what we’re talking about today: the ‘Token’.\nIn this post, we’re going to dive into what tokens — the literal cells of an LLM — actually are, why they are so crucial, and how these small units impact AI performance, cost, and even linguistic fairness.\nAs always, we’ll keep the math to a minimum.\n1. Token: The LEGO Block of Language Let’s start by uncovering the identity of the token.\nSimply put, a token is the basic unit an LLM uses to process text. Still a bit vague?\nTake the sentence, “I am hungry.” If you want to ‘feed’ this to a computer, what do you need to do? Since the full sentence is too large for the computer to digest in one bite, we need to chop it up into smaller, consumable pieces.\nThe simplest approach is to split it by ‘word’ unit:\n[\u0026quot;I\u0026quot;, \u0026quot;am\u0026quot;, \u0026quot;hungry\u0026quot;]\nThat looks plausible. In fact, early natural language processing (NLP) often used this method. But here’s the problem. The words “hungry,” “hungrier,” and “hungriest” are all closely related in meaning, but the computer recognizes them as entirely different words. Unless you register every single variation of “hungry” in a dictionary, the model will see a word like “hungriest” for the first time and be confused — this is known as the OOV (Out-Of-Vocabulary) problem. Solving this by including millions of words in the vocabulary dictionary is highly inefficient.\nWhat if we go the opposite way and split by ‘character’?\n[\u0026quot;I\u0026quot;, \u0026quot; \u0026quot;, \u0026quot;a\u0026quot;, \u0026quot;m\u0026quot;, \u0026quot; \u0026quot;, \u0026quot;h\u0026quot;, \u0026quot;u\u0026quot;, \u0026quot;n\u0026quot;, \u0026quot;g\u0026quot;, \u0026quot;r\u0026quot;, \u0026quot;y\u0026quot;]\nThis solves the OOV problem. You only need to know a few dozen character combinations (A-Z, 0–9, etc.). But now we have another issue: we’ve chopped it too finely. While the model learns to combine “h,” “u,” “n,” and “g” to form “hung,” it loses too much information to easily grasp the meaning of “hungry” as a whole unit. The model has to go through an incredibly long and arduous learning process just to learn the meaning of the word “hungry.”\nThe solution that emerged at a brilliant middle ground is the ‘Subword’ method. And this subword is what most modern LLMs mean when they talk about a ‘token’.\nThe ‘Subword’ tokenizer (more on this later) divides the sentence not into words or characters, but into ‘meaningful chunks’ somewhere in between. For example, the word ‘unhappiness’ might be broken into three tokens: [\u0026quot;un\u0026quot;, \u0026quot;happi\u0026quot;, \u0026quot;ness\u0026quot;].\nun (negative prefix) happi (the root of happy) ness (suffix indicating a state) See the advantage? By splitting it this way, when the model learns the token ‘un’, it can apply that meaning not just to ‘unhappiness’ but also to ‘unusual,’ ‘unbelievable,’ and other words. The same goes for ‘ness’. If it knows ‘happiness’, it can easily infer ‘sadness’.\nThis approach simultaneously tackles the OOV problem (encountering a new word) and the efficiency problem (chopping things too finely). Even if the never-before-seen word ‘unbelievableness’ shows up, it can be broken down into something like [\u0026quot;un\u0026quot;, \u0026quot;believable\u0026quot;, \u0026quot;ness\u0026quot;], allowing the model to (at least faintly) infer, \u0026quot;Ah, this is the 'state' of something 'unbelievable' in a 'negative' context.\u0026quot;\nThe tool that performs this magic is called a ‘Tokenizer’. The tokenizer statistically analyzes a massive amount of text data to create a list of frequently occurring and meaningful pieces (tokens), such as [\u0026quot;un\u0026quot;, \u0026quot;happi\u0026quot;, \u0026quot;ness\u0026quot;]—a list called the 'Vocabulary'. Algorithms like BPE, WordPiece, and SentencePiece are types of tokenizers, but you can simply know that they exist for now.\n📌 Key Takeaway 1:\n- A token is the fundamental ‘LEGO block’ that LLMs use to understand language.\n- The primary form used is the ‘Subword,’ which is smaller than a ‘word’ but larger than a ‘character.’\n-The ‘Tokenizer’ is the machine that builds these ‘LEGO blocks,’ and the ‘Vocabulary’ is the set of all possible ‘LEGO blocks’ that can be built.\n2. Why Do We Need Tokens? The ‘Translator’ that Converts Language into Numbers “Okay, I get that text is chopped into ‘LEGO blocks.’ But why is that necessary?”\nAs mentioned earlier, computers only understand numbers. Even after chopping, the computer doesn’t actually understand letters like ‘un’ or ‘happi’. To feed text into the massive neural network that is an LLM, these tokens must ultimately be converted into numbers that the computer understands.\nTokens are the bridge connecting the ‘world of language’ and the ‘world of numbers’.\nThis process is generally divided into two steps.\nStep 1: Integer Encoding or Indexing The ‘Vocabulary’ created by the tokenizer is essentially a giant dictionary (a list of tokens). In this dictionary, every token ‘LEGO block’ is assigned a unique number (ID).\n\u0026quot;un\u0026quot; -\u0026gt; 24 \u0026quot;happi\u0026quot; -\u0026gt; 2341 \u0026quot;ness\u0026quot; -\u0026gt; 342 … \u0026quot;cat\u0026quot; -\u0026gt; 5555 \u0026quot;dog\u0026quot; -\u0026gt; 9812 (The numbers are just examples.)\nNow, let’s assume the sentence “I am hungry” goes through the tokenizer and is split into the tokens [\u0026quot;I\u0026quot;, \u0026quot; am\u0026quot;, \u0026quot; hungry\u0026quot;]. (It can be split more complexly in reality.)\nThese tokens are then converted into their unique ID (number) using the ‘Vocabulary’ dictionary.\n[\u0026quot;I\u0026quot;, \u0026quot; am\u0026quot;, \u0026quot; hungry\u0026quot;] -\u0026gt; [100, 200, 300]\nFinally, we have a ‘sequence of numbers’ that the computer can understand!\nStep 2: Embedding However, just because 100 is smaller than 300 doesn't mean \u0026quot;I\u0026quot; is less important than \u0026quot;hungry.\u0026quot; These numbers are merely 'identification numbers' and carry no inherent meaning. Bigger or smaller means nothing.\nThis is where the real magic of the LLM begins. The model converts this ‘identification number (ID)’ into a ‘list of numbers that carry meaning,’ or a ‘Vector’. This is called ‘Embedding’.\n100 (\u0026quot;I\u0026quot;) -\u0026gt; [0.1, -0.5, 1.2, ..., 0.8] (e.g., a list of 768 numbers) 300 (\u0026quot;hungry\u0026quot;) -\u0026gt; [0.4, 0.9, -0.1, ..., -0.3] (e.g., a list of 768 numbers) This ‘vector’ is how the LLM understands the ‘meaning of the token’. In this vector space, the embeddings for ‘hungry’ and ‘famished’ will be located close to each other, while ‘apple’ and ‘banana’ will also be close, but ‘hungry’ and ‘boat’ will be far apart.\nEmbedding is a large and complex topic that deserves its own article. For today, it’s enough to know that it’s the numerical (vector) representation of the token, where embeddings with similar meanings are close together, and those with different meanings are far apart.\nThe first step in this entire process is the token. If the text is incorrectly divided into tokens, the entire subsequent process of numerical conversion and semantic learning (embedding) will be messed up.\n📌 Key Takeaway 2:\n- Tokens are the essential first step to convert ‘language’ into ‘numbers.’\n- The flow is: Text -\u0026gt; Tokens (LEGO blocks) -\u0026gt; ID (Number) -\u0026gt; Embedding Vector (Meaningful List of Numbers) - This process allows the computer (LLM) to finally ‘calculate’ language.\n3. How Tokens Affect Model Training Now, let’s delve a little deeper. We’ll explore how the concept of ‘tokens’ goes beyond just ‘inputting’ text and profoundly impacts the process of ‘building (training)’ an LLM model.\nFor LLM engineers training a model, ‘tokens’ represent ‘cost’ and ‘resources.’\n1. The Vocabulary Size Dilemma When creating a tokenizer, engineers must decide, “How many types of ‘LEGO blocks’ (tokens) should we create in total?” This is called the ‘Vocabulary Size’. For example, they might decide, “Let’s represent the world with 30,000 tokens,” or “Let’s use 100,000 tokens!” This is often referred to as the LLM model’s Vocab Size.\nSmall Vocabulary (e.g., 30,000):\n- Pro: The model has fewer ‘block types’ to memorize, so the model’s ‘brain’ (parameters) can be smaller. (Specifically, the size of the input and output layers decreases.) Training can be faster and lighter.\n- Con: Fewer ‘LEGO block’ types mean most words have to be chopped into tiny pieces. For instance, the proper noun “ChatGPT” might not have a dedicated ‘block,’ forcing it to be split into 3 pieces, like [\u0026quot;Chat\u0026quot;, \u0026quot;G\u0026quot;, \u0026quot;PT\u0026quot;]. More tokens are required to represent a single sentence. Large Vocabulary (e.g., 100,000):\n- Pro: Words like “ChatGPT” or “Massachusetts” are more likely to become a single ‘block,’ like [\u0026quot;ChatGPT\u0026quot;] or [\u0026quot;Massachusetts\u0026quot;]. This reduces the number of tokens needed to represent a sentence.\n- Con: The model has 100,000 ‘block types’ to memorize. The model’s ‘brain’ must be larger, requiring more memory and computational power. Training costs increase exponentially. This is a classic trade-off with no single correct answer. Model developers must determine the appropriate Vocabulary Size based on their available data and objectives.\n2. Training Cost and Time Training an LLM costs tens or hundreds of millions of dollars. This cost is mostly proportional to “how many tokens were learned.”\nFor example, let’s say we train a model on the equivalent of 1 million books (data).\nTokenizer A: Splits the 1 million books into a total of 100 billion tokens. Tokenizer B: Splits the 1 million books into a total of 50 billion tokens. Put another way, the same data requires 100 billion tokens with Tokenizer A and 50 billion tokens with Tokenizer B. Since the LLM understands in units of tokens, using Tokenizer B could theoretically allow the model to learn the same amount of knowledge with half the computational cost and time compared to A. The quality of tokenizer design is literally a matter of saving hundreds of millions of dollars.\nOf course, one must carefully consider the trade-offs associated with Vocabulary Size, as discussed earlier.\nFurthermore, LLMs have a limit on the length of tokens they can process at once (often called the Context Window size). For example, “I can only process 4,096 tokens at a time.”\nA tokenizer that splits sentences more finely might break [\u0026quot;H\u0026quot;, \u0026quot;e\u0026quot;, \u0026quot;l\u0026quot;, \u0026quot;l\u0026quot;, \u0026quot;o\u0026quot;] (5 tokens), which bloats the token count without adding much content. This shortens the length of the story/information (in terms of actual character count) the model can read and learn in one go. Conversely, a tokenizer that splits sentences into larger chunks, like [\u0026quot;Hello\u0026quot;] (1 token), allows the model to learn much longer and richer contextual narratives within the same 4,096 limit.\n📌 Key Takeaway 3:\n- Tokenizer design (Vocabulary Size, efficiency) directly impacts the LLM’s training costs (money, time) and learning efficiency.\n- An efficient tokenizer packs more ‘meaning’ into fewer ‘tokens’, making training cheaper and faster.\n4. How Tokens Affect Inference: A Matter of Wallet and Patience We’ve discussed tokens from the perspective of the model builder. Now, how do tokens impact the ‘model user’? This is a story about your wallet and your patience.\n1. It Threatens Your Wallet (API Costs) When you use an LLM like OpenAI’s GPT, Google’s Gemini, or Anthropic’s Claude via an API call, what is the basis for billing? It’s the token count.\nThe cost is typically something like “$0.01 per 1,000 tokens.” This applies both to the tokens used in the question we send to the LLM (the Prompt tokens) and the tokens generated by the LLM in its answer (the Completion tokens). Different LLM services may even charge different rates for prompt and completion tokens.\nA critical issue arises here: what if the language you use is ‘inefficient’ for the tokenizer? When we say a tokenizer is inefficient here, it means it splits a sentence into smaller units. This doesn’t inherently mean it’s worse, just less token-dense.\nFor example, let’s assume a tokenizer splits English and Korean sentences as follows:\nEnglish: “Hello, how are you today?” -\u0026gt; [\u0026quot;Hello\u0026quot;, \u0026quot;,\u0026quot;, \u0026quot; how\u0026quot;, \u0026quot; are\u0026quot;, \u0026quot; you\u0026quot;, \u0026quot; today\u0026quot;, \u0026quot;?\u0026quot;] (7 tokens) Korean: “안녕하세요, 잘 지내세요?” (meaning Hello, how are you today?) -\u0026gt; [\u0026quot;안\u0026quot;, \u0026quot;녕\u0026quot;, \u0026quot;하\u0026quot;, \u0026quot;세\u0026quot;, \u0026quot;요\u0026quot;, \u0026quot;,\u0026quot;, \u0026quot; 잘\u0026quot;, \u0026quot; \u0026quot;, \u0026quot;지\u0026quot;, \u0026quot;내\u0026quot;, \u0026quot;세\u0026quot;, \u0026quot;요\u0026quot;, \u0026quot;?\u0026quot;] (13 tokens) In this example, the user whose language is Korean has to pay almost double the cost of the user whose language is English, just for saying the same thing.\n2. Memory Limits (Context Window) We briefly mentioned the Context Window earlier. It’s the total number of tokens an LLM can remember at one time. For example, the statement “GPT-4 has an 8K (8,192) token Context Window” means the model can only process and remember up to 8,192 tokens.\nImagine you upload two long reports to summarize. One is in English, and the other is in Spanish. Both are exactly 5,000 words long.\nEnglish Report: 5,000 words -\u0026gt; 8,000 tokens Spanish Report: 5,000 words -\u0026gt; 12,000 tokens (Assuming an inefficient tokenizer for Spanish) If you give the 8K-token-limited model the English report, it reads the entire thing and summarizes it without a problem.\nBut if you give it the Spanish report? The model says, “Oops! That’s over 8K tokens. I’ll only read up to 8,192 tokens,” and produces a summary that doesn’t reflect the entire content.\nDespite giving the model documents with the same word count, the tokenization method causes the Spanish document to be disadvantaged. The LLM’s memory essentially runs out faster for that language. This is why enormous context windows of 128K or 1M tokens are emerging — to overcome this memory limitation.\n3. Response Speed (Latency) You know how ChatGPT generates its answer one word at a time, almost like typing? While it might look like the AI is ‘thinking,’ the LLM is actually generating the answer one token at a time. This is called the ‘Autoregressive’ method.\nLet’s say the LLM is generating the sentence, “My name is John Doe.” The LLM doesn’t generate the whole sentence at once; it generates one token at a time, like this:\n[My] -\u0026gt; [name] -\u0026gt; [is] -\u0026gt; [John] -\u0026gt; [Doe] -\u0026gt; [.]\nThis process creates the illusion of typing.\nIf an inefficient tokenizer had broken this sentence into 10 tokens, the model would have to go through 10 ‘thoughts’ (token generations) to complete the sentence. What if an efficient tokenizer broke it into just 3 tokens? The sentence is complete with only 3 thoughts. This means the sentence generation is completed nearly three times faster.\nMore steps to generate the same sentence means a longer wait for the final response. The more inefficient the tokenization, the longer we have to wait.\n📌 Key Takeaway 4:\n- Tokens determine the cost of using an LLM (API fees).\n- Tokens define the LLM’s ‘memory limit’ (Context Window).\n- Tokens affect the LLM’s response speed (Latency).\n- Inefficient tokenization is a disadvantage for the user in all these aspects.\n5. Token Importance from a Multilingual Perspective: The ‘Token Inequality’ Problem If you’ve used an LLM, you know it can handle multiple languages proficiently. A single LLM model understands and generates English, Spanish, French, and so on, without issue. While there are many techniques behind this, one crucial technology is a tokenizer that can understand multiple languages.\nIn previous sections, we kept using the term ‘inefficient tokenizer’. So, why is one language ‘efficient’ and another ‘inefficient’?\nThe answer lies in the ‘Training Data’.\nThe tokenizers for early LLM models like GPT-2 and GPT-3 built their ‘Vocabulary’ overwhelmingly based on English data.\nAs a result, the vocabulary was packed with fantastic, optimized tokens for English, such as [\u0026quot;the\u0026quot;, \u0026quot;is\u0026quot;, \u0026quot;ing\u0026quot;, \u0026quot;Chat\u0026quot;, \u0026quot;GPT\u0026quot;].\nBut what happens when you try to split or generate a Spanish sentence with this English-centric vocabulary set? It obviously won’t have the rich tokens specific to Spanish.\nConsequently, the engineer is forced to build the sentence using the most basic ‘1x1’ LEGO blocks — the single-character equivalents for English, like [a], [b], [c], etc.\nThis is the reality of ‘Token Inequality’.\nEnglish: “The quick brown fox jumps over the lazy dog.” (9 words)\n- Tokens: [\u0026quot;The\u0026quot;, \u0026quot; quick\u0026quot;, \u0026quot; brown\u0026quot;, \u0026quot; fox\u0026quot;, \u0026quot; jumps\u0026quot;, \u0026quot; over\u0026quot;, \u0026quot; the\u0026quot;, \u0026quot; lazy\u0026quot;, \u0026quot; dog\u0026quot;, \u0026quot;.\u0026quot;] (10 tokens)\n- 1 Word ≈ 1.1 Tokens (Highly efficient) Korean: “빠른 갈색 여우가 게으른 개를 뛰어넘습니다.” (6 words or eojeol)\n- Tokens: [\u0026quot;빠\u0026quot;, \u0026quot;른\u0026quot;, \u0026quot; \u0026quot;, \u0026quot;갈\u0026quot;, \u0026quot;색\u0026quot;, \u0026quot; \u0026quot;, \u0026quot;여\u0026quot;, \u0026quot;우\u0026quot;, \u0026quot;가\u0026quot;, \u0026quot; \u0026quot;, \u0026quot;게\u0026quot;, \u0026quot;으\u0026quot;, \u0026quot;른\u0026quot;, \u0026quot; \u0026quot;, \u0026quot;개\u0026quot;, \u0026quot;를\u0026quot;, \u0026quot; \u0026quot;, \u0026quot;뛰\u0026quot;, \u0026quot;어\u0026quot;, \u0026quot;넘\u0026quot;, \u0026quot;습\u0026quot;, \u0026quot;니\u0026quot;, \u0026quot;다\u0026quot;, \u0026quot;.\u0026quot;] (24 tokens)\n- 1 Word ≈ 4.0 Tokens (Inefficient) To express the same meaning, a language like Korean had to use more tokens than English.\nThis inefficiency caused the three problems mentioned in Section 4 — higher fees, shorter memory, and slower speed — for users of non-English languages.\nIn using AI technology, people had to accept significantly higher costs and inconveniences just because they didn’t ‘speak’ English. To address this, some LLMs optimized for specific languages have been developed. For example, an LLM specialized in Korean means the training process used more Korean data, leading to a better understanding of the language and a tokenizer with a richer set of Korean tokens.\nThe Solution Fortunately, the AI community recognized this serious problem some time ago.\nThe latest LLMs have made massive efforts to resolve this ‘Token Inequality’:\nTraining with Massive Multilingual Data: From the start, when creating the tokenizer, they included a balanced mix of data from various global languages — not just English, but Spanish, Korean, German, Hindi, and more. Larger Vocabulary Size: The vocabulary size, which used to be around 30,000 to 50,000, has been significantly increased to 100,000, 250,000, or more. As a result, the vocabularies of the latest models now include dedicated tokens for many other languages.\nThanks to this, the multilingual token efficiency of the latest models has dramatically improved compared to the GPT-3 era. While it may still be slightly less efficient than English, the gap is constantly shrinking.\nThis is more than just cost reduction; it means that AI technology is becoming more equitably accessible to people worldwide, rather than being confined to a specific linguistic region.\n📌 Key Takeaway 5:\n- Past LLMs were primarily trained on English data, making tokenization for non-English languages highly inefficient.\n- This resulted in non-English users having to bear higher costs, shorter memory, and slower speeds (Token Inequality).\n- The latest LLMs are greatly improving this inequality problem by using massive multilingual data and larger vocabularies.\n6. Conclusion Today, we’ve discussed the token, the most fundamental concept underpinning the vast technology of the LLM.\nHow this ‘LEGO block’ is split and defined (tokenizer design) is a key strategy that determines the cost efficiency of model training, where hundreds of millions of dollars are on the line.\nFurthermore, we’ve confirmed that this token dictates our entire user experience — from the API fees we have to pay when we use AI, to the length of the conversation the AI can remember (Context Window), and even the response speed.\nFinally, we addressed how the differing efficiency of tokens across languages led to the ‘Token Inequality’ problem becoming a topic of technical fairness, and how it is now being actively improved.\nNow, when you watch an LLM generating text, ‘tap… tap…’ on your screen, it will no longer just look like simple typing. You’ll see the model predicting the next token one by one after an intense calculation.\n","permalink":"https://blog.jiminl.com/posts/tokens-the-invisible-building-blocks-of-large-language-models-53c51f6f1555/","summary":"Even though Large Language Models (LLMs) appear to expertly understand and generate language, the truth is, like any other computer…","title":"Tokens: The Invisible Building Blocks of Large Language Models"},{"content":"While ChatGPT is now the household name for Large Language Models (LLMs), the technology wasn’t born in a vacuum with its late-2022 debut. Depending on how you define an LLM, we already had models like GPT-1, GPT-2, GPT-3, and PaLM. If we don’t strictly limit ourselves to Decoder-Only architectures, the family tree grows even larger, including foundational models like BERT, XLNet, and T5.\nA Quick Note: Technically speaking, ChatGPT isn’t the model itself. It’s the service developed by OpenAI that leverages their LLM family. The initial viral 2022 release used GPT-3.5, while today’s ChatGPT often uses GPT-5 and other diverse LLMs.\nSo, why did ChatGPT become the global phenomenon that it is? There are many contributing factors, but one of the most crucial is the introduction of Reinforcement Learning (RL). This technique is central to a process called Alignment, which is key to refining LLMs.\nToday, we’re diving into the core technology that transformed LLMs from mere “internet parrots” into smart, sensible “conversation partners”: Reinforcement Learning. We’ll unpack the famously cryptic acronyms like PPO, GRPO, DPO, and ORPO, and do our best to skip the complex math.\n1. Why Did LLMs Need Reinforcement Learning? The early LLM training method was both simple and incredibly powerful. Researchers would scrape every piece of text they could find on the internet, throw it at the model, hide a word or part of a sentence, and ask the model to predict the missing piece. It was an endless “what comes next?” quiz.\nRepeating this process over hundreds or thousands of gigabytes of text taught the model grammar and absorbed all the world’s knowledge (along with its biases and fake news). By the end, it was smart enough to spin a few words into a full-length novel.\nThis is the Base Model. Think of it as a brilliant new intern — let’s call him Tylor. Tylor has read every book imaginable but has zero social skills.\nIf you ask Tylor, “What’s the weather like today?” he might answer based on the statistical likelihood of the next word from his training data: “What’s the weather like today? is a common question, but also, the Yankees lost their game…” or even, “The weather is terrible! I want to quit this job right now.” This happens because his sole objective was predicting the most plausible next token, not providing a helpful answer to your question.\nThis is where the problem of Alignment emerges.\nAlignment: The process of aligning a model’s objective with human intentions, values, and preferences.\nWe don’t just want models that speak fluently; we want them to behave in specific ways:\nHelpful: Understand my query’s intent and provide accurate, useful information tailored to it. Honest: Admit when they don’t know something and avoid making things up (hallucinating). Harmless: Refrain from generating discriminatory, violent, or otherwise harmful content. To turn our brilliant intern Tylor into a truly valuable team member, we need to teach him social cues, professionalism, judgment, and a bit of real-world sense. The most effective way to teach this is through Reinforcement Learning.\n2. The RL Pipeline: LLM Training in 3 Phases Before diving into RL itself, let’s see exactly where it fits in the LLM training process.\nLLM training is typically a three-phase pipeline.\nPhase 1: Pre-training The model learns to predict the next word in a sequence by looking at a massive, internet-scale dataset. This phase creates a model with vast knowledge and incredible predictive power — the moment our “brilliant intern” Tylor is hired.\nPrevious-generation models, including foundational versions of GPT-3, were typically trained up to this first phase.\nPhase 2: Supervised Fine-Tuning (SFT) Now, Tylor is given an employee handbook. This handbook is full of examples: “When a client asks this, this is the right answer.” Tylor reads the manual repeatedly, learning to speak in a way that matches the company’s required output format. Since he’s already fluent, he just needs to learn the new business domain knowledge.\nTraining an LLM is similar. Human annotators (Labelers) manually create thousands of examples of high-quality, correct answer data — our “employee handbook.”\nQ: “What caused the French Revolution?” A: “The French Revolution occurred at the end of the 18th century due to a complex set of factors… (well-structured, right answer).” The model trains on these model answers. It’s no longer just saying plausible things; it learns to follow the pattern of a model answer. This is called Supervised Fine-Tuning (SFT). After this, the model can at least deliver a “Question-Answer” format.\nHowever, the real world is messy. Following a manual too strictly can lead to rigid answers, an inability to handle curveballs, and sometimes, even dangerous outputs.\nIt’s time to teach our brilliant intern some real-world social skills and judgment.\nPhase 3: Reinforcement Learning from Human Feedback (RLHF) We take the SFT model (Tylor, the manual-trained intern) and ask him a real-world question, then have him generate 2 to 4 different responses.\nQ: “What should I have for dinner tonight?” Response A: “How about pizza? It’s high in calories but delicious.” Response B: “The weather is chilly, so I recommend a hot soup dish, perhaps a hearty stew or chili.” Response C: “I am an AI and cannot eat food.” Response D: “Go hungry.” Which answer do you prefer? From a factual standpoint, they are all valid responses, but you’d likely rank B as the best, then A, then maybe C, with D being the absolute worst.\nWe need to teach our intern this expected social priority. We need to prevent the catastrophe of him telling the CEO to “Go hungry.”\nThe process of guiding the model to produce answers aligned with human expectations is called Alignment. The technology for LLM Alignment is Reinforcement Learning.\nSo, how exactly do we teach Tylor this complex social acumen? Let’s break down the methods.\n3. The Two Camps of LLM Alignment: Online RL vs. Offline Optimization Here is the crux of the matter: How do we translate that precious preference data — “B is better than A” — into a model update?\nThe technological “families” of LLM Alignment split into two major branches:\nThe “Online Reinforcement Learning” Family (True RL): These methods follow the traditional RL framework. During training, the model itself generates a response, receives immediate feedback (Reward) on that response, and then adjusts its internal policy to generate better responses going forward. This is like getting one-on-one piano lessons from a teacher. PPO and GRPO belong to this camp. The “Offline Optimization” Family (a.k.a. RL-free Alignment): These methods skip the traditional real-time (online) RL loop. Instead, they use a large, pre-collected dataset of human preference data, much like a regular supervised dataset, to train the model. This is more like studying by watching hundreds of videos of good and bad piano performances on YouTube. DPO and ORPO belong to this camp. Wait, are DPO and ORPO really Reinforcement Learning? Before we look at the methods, let’s address the elephant in the room.\nStrictly speaking, DPO and ORPO are NOT traditional Reinforcement Learning (RL).\nTraditional RL involves an ‘Agent’ taking ‘Actions’ in an ‘Environment,’ receiving a ‘Reward,’ and updating its ‘Policy’ in an online, real-time loop. PPO and GRPO fit this description.\nDPO and ORPO lack this online loop. They update the model by observing a pre-collected dataset and learning to “increase the probability of the preferred response and decrease the probability of the non-preferred response.” This process is much closer to SFT (Supervised Fine-Tuning).\nSo why do we lump them in with RL?\nFirst, they have the same goal: achieving the exact same objective (aligning the model to human preferences) as PPO-style RLHF.\nSecond, they share the same mathematical roots: Without getting too technical, the DPO paper proved that by expanding and transforming the mathematical equations of PPO, you can arrive at an offline objective function that achieves the same result. DPO essentially found a mathematical shortcut for the reinforcement learning problem that PPO was trying to solve.\nIf PPO is like climbing a mountain firsthand to find the best route (Online RL), DPO is like looking at a fully mapped out trail on a topo map (Offline Dataset) and calculating the fastest way to the summit.\nFor these reasons, though the methods differ, DPO and ORPO are included in the broad category of LLM Alignment techniques, sometimes even called RL-free RLHF.\nLet’s meet the members of these two influential families.\n3.1. The “Online RL” Family: PPO and GRPO This family is defined by the feedback loop where the model continuously generates and is evaluated during training.\n3.1.1. PPO (Proximal Policy Optimization): The Classic and Powerful Champion PPO is an RL technique introduced by OpenAI in 2017. It became famous again when it served as the core training method for the GPT-3.5 model underpinning the initial viral release of ChatGPT in late 2022.\n3.1.1.1 Reward Model, Value Model, and Advantage\nPPO follows the typical RL paradigm. The LLM generates a response, a Reward Model evaluates that response with a score (Reward), and the LLM adjusts its response policy based on this score (and Advantage which we will mention later).\nRecall the piano lesson analogy: the teacher’s feedback is the key. In PPO, the Reward Model (RM) plays the role of the teacher.\nHow is the RM built?\nA question is prepared, like our example: “What should I have for dinner tonight?” The LLM generates multiple responses (A, B, C, D). A human (the labeler) ranks them (e.g., B \u0026gt; A \u0026gt; C \u0026gt; D). The Reward Model is trained on this ranking data. Through this training, the RM learns to assign a continuous score: Response B gets a 95/100, while Response D gets a 10/100. An RM trained this way can take a (Question, Response) pair and say, “A human is 80% likely to like this answer.”\nNow that we can score the LLM’s responses, we need to use that to train the LLM itself.\nLet’s return to our intern, Tylor. We put Tylor and his evaluator (the RM) in a room and repeat the following loop:\nTylor picks a question card. Tylor gives an answer. The Evaluator gives Tylor a score: “80 points!” But there is also a Value Model (VM) expert silently observing. This expert estimates the expected reward for the current situation. The expert rates the current situation at 70 points. Tylor compares his actual score (80) to the expert’s expectation (70). he received 10 points higher than expected! Tylor adjusts his answering style to be more like his current high-scoring response. The Value Model predicts the future score (reward) expected from the current state. The difference between the score received (from the RM) and the expected score (from the VM) is called the Advantage. We train the LLM to maximize this Advantage. If the model is doing better than expected, reinforce that behavior; if worse, discourage it.\n3.1.1.2. Learning Safely: The Meaning of Proximal\nPPO stands for Proximal Policy Optimization. The “Policy” is the LLM’s response style.\nWhat does “Proximal” mean?\nProximal means “close by” or “nearby.” It means the model updates its policy, but only by a little bit — it changes its policy cautiously.\nWhat if Tylor, our intern, overreacted to the Advantage score? We hired him because his fundamentals were strong (from pre-training and SFT). By focusing too intensely on pleasing the evaluator, he could undermine his excellent baseline skills. We need to scold him if he tries to change too quickly.\nIt’s similar with LLMs. The SFT-trained LLM is already a great model; we just need to align its responses. If the LLM tries too hard to maximize the Advantage, it can forget the valuable knowledge and skills it learned during SFT.\nPPO uses several mechanisms to prevent overly drastic policy changes. The most popular one is Clipping. For example, even if the Advantage calculation suggests a policy change of 50 units, we might set a maximum change range of [-20, 20]. If the calculated change is 50, we “clip” it to the maximum allowed value of 20, ensuring the change is incremental and safe.\n3.1.2. GRPO (Group Relative Policy Optimization): The Smart Evolution of PPO (feat. DeepSeek) PPO, while effective, has a few drawbacks. One major issue is the need for an extra Value Model in addition to the Reward Model to calculate the Advantage. The Value Model is often as large as the target LLM itself. Building an LLM is hard; building a Reward Model is hard; avoiding the need for a third giant model (the VM) would be fantastic!\nGRPO tackles this head-on. It proposed an idea to calculate the Advantage without training a separate Value Model.\nThe LLM generates multiple responses (A, B, C, D). The Reward Model scores each response: A=80, B=95, C=55, D=10. We calculate the average score of all responses: (80 + 95 + 55 + 10) / 4 = 60 points. Now, we subtract the average score from each response’s score:\n- Response A: 80–60 = 20\n- Response B: 95–60 = 35\n- Response C: 55–60 = -5\n- Response D: 10–60 = -50 GRPO uses these values as the Advantage. The advantage is the relative reward within the group. That’s what the GR in GRPO stands for: Group Relative. The LLM is then updated to maximize this relative Advantage. GRPO inherits PPO’s approach but simplifies the complex, resource-intensive intermediate step of training a Value Model.\n3.2. The “Offline Optimization” Family: DPO and ORPO This family challenged the very complexity of PPO and GRPO’s “online feedback loop.”\nTheir argument: “Why not just collect tons of data and train the model like SFT?”\n3.2.1. DPO (Direct Preference Optimization): The Game-Changer After PPO The PPO pipeline (Train Reward Model -\u0026gt; Train LLM with PPO) is notoriously hellish to manage. So, researchers asked:\n“Wait, training a Reward Model, sampling online… it’s too complicated. Why don’t we directly train the LLM using the ‘B is better than A’ offline dataset?”\nThat question led to DPO (Direct Preference Optimization). The idea behind DPO is this:\n“The goal is for the model to prefer ‘B’ over ‘A,’ right? So let’s skip the Reward Model bridge and train the LLM directly to judge that ‘B is more plausible than A’!”\nDPO takes the model after Phase 2 (SFT) and gives it pairs of preference data (Preferred response, Non-preferred response). It then trains the model to:\nIncrease the probability of generating the preferred response. Decrease the probability of generating the non-preferred response. Instead of the online method (LLM generates -\u0026gt; RM scores -\u0026gt; LLM trains), DPO uses a static dataset of preferred/non-preferred pairs, making it an extension of SFT.\nDPO is a game-changer because it eliminates the need to train a Reward Model, is far less resource-intensive, is much more stable to train, and simplifies the complex RL pipeline to a simple extension of SFT. Often, its performance is comparable to or even better than PPO, leading many to adopt it instead.\n3.2.2. ORPO (Odds Ratio Preference Optimization): Combining SFT and DPO If DPO came after SFT (Phase 2) to handle Alignment (Phase 3), ORPO takes it one step further.\n“Hold on, we do SFT (Phase 2) and then DPO (Phase 3). Why not just combine the two?”\nORPO utilizes the concept of the Odds Ratio to merge the SFT and DPO stages into a single, highly efficient process. But first, what is an Odds Ratio?\nLet’s say a basketball player, Jordan, attempts 10 free throws, making 8 and missing 2. His probability of making a free throw is 8/10 = 0.8.\nThe Odds represent the likelihood of an event occurring relative to the likelihood of it not occurring. Jordan’s odds of making a free throw are 8 (makes) / 2 (misses) = 4. This means he is four times more likely to make the shot than to miss it.\nORPO calculates the ratio of two odds: the odds of the LLM generating the preferred response versus the odds of the LLM generating the non-preferred response. This Odds Ratio increases as the LLM favors the preferred response and decreases as it favors the non-preferred one. The training objective, therefore, is to maximize this Odds Ratio.\nWhile DPO primarily focuses on training the LLM to favor the preferred response, ORPO strongly encourages it to avoid generating bad responses simultaneously.\nAnother key feature is that this Odds Ratio calculation and Alignment happens during the SFT stage (Phase 2), not after. ORPO integrates the Alignment using the Odds Ratio directly into the SFT process. This allows the LLM to learn to generate good responses (SFT) while simultaneously learning to avoid non-preferred responses (Alignment). By merging Phase 2 and Phase 3, it significantly streamlines the entire training pipeline.\n(From ORPO Paper)\n4. Pros and Cons of LLM Reinforcement Learning Naturally, RLHF has its strengths and weaknesses.\nPros: Creating the Chatbot We Know and Love Alignment (Real Human-Like Conversation): This is the core reason. It teaches the model to grasp my intent, be helpful, and be polite. It transforms the “parrot” into a “perceptive assistant.” Safety and Harm Reduction: It is the most effective way to train a model to refuse dangerous requests like “How do I build a bomb?” RL is an excellent teacher for setting boundaries. Fine-Grained Control: RL feedback can be used to reflect subtle style requests, such as “be more humorous” or “explain it like an expert.” Rank-based methods like GRPO are particularly strong at this. Cons: Money, Time, and New Headaches Data Collection Costs: A major barrier. Creating hundreds of thousands of high-quality ‘preference data’ (A \u0026gt; B) or ‘ranking data’ (A \u0026gt; B \u0026gt; C) requires expensive labor from many human annotators. The quality of the labelers directly dictates the performance of the model. Reward Hacking: Models are smart and ruthless. They will find a loophole to maximize their score, often at the expense of usefulness. The LLM can become a clever sycophant.\n- The Flattery Problem: Human evaluators tend to give higher scores to responses that are long, polite, and sound plausible. In response, models learned to flatter. Responses like, “That is a truly excellent question!” or “I completely agree with your assessment,” followed by a lengthy but vacuous answer, became common. When the response score is high, but the usefulness is low, it’s called Reward Hacking. Bias Entrenchment: “Human feedback” ultimately comes from a small group of labelers, often from a specific cultural background and education level. Their values and biases can be unintentionally injected into the model as the “correct answer,” leading the model to respond with entrenched biases. Training Instability: Especially with “Online RL” methods like PPO, the system involves multiple interacting models. The training process can be highly unstable and extremely sensitive to minor hyperparameter changes. It’s common for a small misstep to turn the model into a “genius fool.” (GRPO, DPO, and ORPO were developed to simplify or largely mitigate this issue). 5. Conclusion We’ve covered the crucial secret behind making LLMs truly useful: Reinforcement Learning. We focused on concepts while avoiding complex math.\nThe LLM starts as a “Brilliant Intern” (Base Model) from massive data, then learns the “Employee Handbook” (SFT). To become a true professional, it must learn social skills and judgment using human preference data (A \u0026gt; B) via RLHF (Reinforcement Learning from Human Feedback). This breaks into two paths: Online RL: PPO is the classic method, creating a complex Reward Model evaluator to train with ‘absolute scores.’ GRPO made PPO more efficient by simplifying the pipeline and avoiding the need for a separate Value Model. Offline Optimization: DPO was an innovation that bypassed the Reward Model and online loop, training the LLM directly with a ‘preference dataset,’ like an SFT extension. ORPO went one step further, combining SFT and DPO into a single, unified step. The evolution of LLMs is no longer just a race to build bigger models; it’s a competition to see who can best master Alignment — making the AI safe, helpful, and truly aligned with human values.\nUltimately, training an AI is much like building a mirror that reflects our own human values. It’s the process of teaching the AI what we prefer and what we value.\n","permalink":"https://blog.jiminl.com/posts/how-reinforcement-learning-taught-llms-to-talk-like-humans-ab5e28bc6a01/","summary":"While ChatGPT is now the household name for Large Language Models (LLMs), the technology wasn’t born in a vacuum with its late-2022 debut…","title":"How Reinforcement Learning Taught LLMs to Talk Like Humans"},{"content":"If you’ve been following the world of LLMs, you’ve probably heard of the KV Cache. It’s a technique that’s mentioned constantly, which tells you it’s both widely used and incredibly important. Today, we’re going to break down what the KV Cache is and why it’s such a big deal.\nLLMs are Slow Let’s start with a simple fact: LLMs are slow. You might think, “Well, they’re huge, so of course they’re slow.” While their massive size is the primary reason, it’s not the whole story.\nThere are two other major culprits:\nThe Self-Attention mechanism. The Auto-Regressive generation method. The KV Cache is a clever solution designed to tackle the performance bottleneck created by this combination. To understand the solution, we first need to understand the problems.\nGrasping Context: Self-Attention At the heart of why Transformers work so well is Self-Attention. Just like the name suggests, it’s about paying attention to oneself — in this case, “self” refers to the input sequence.\nLet’s take an example. Consider the sentence: “I went to the bank to deposit money.” The word “bank” can mean a financial institution or a riverbank. Yet, we instantly understand it means a place for money. How do we do that?\nIf someone just gave you the word “bank” in isolation, you couldn’t be sure of its meaning. You might guess it’s a financial institution since that’s a common usage, but it would just be a guess.\nHowever, in the full sentence, the other words provide context. The core idea of Self-Attention is to mimic this process. Imagine a Transformer processing the word “bank.” Just like us, it can’t be certain of the meaning from the word alone. So, what does it do? It looks at the other words in the sentence to figure out their relationships.\n“I” isn’t highly related to “bank.” “went” has some relevance to “bank.” “money” is highly related to “bank.” By assessing the relevance of every word to “bank” (including itself), the Transformer gains a much richer understanding of the input. Since “money” is a highly relevant word, the model correctly infers that “bank” is more likely to be a financial institution than a riverbank.\nHow is Self-Attention Actually Calculated? So far, we’ve talked about “relevance” in abstract terms. How does a machine actually calculate it? To fully grasp this, you’d need to look at the mathematical formulas, but we’ll skip the heavy math today and stick to the core concepts.\nFor each word (or, more accurately, token) in the input, the model calculates three distinct values: a Query (Q), a Key (K), and a Value (V). For our example sentence, “I went to the bank to deposit money,” the model would compute Q_I, K_I, V_I, Q_went, K_went, V_went, …, and so on for every word. For an 8-word sentence, that’s a total of 8 * 3 = 24 vectors.\nHere’s what these three roles do in Self-Attention:\nQuery (Q): This is the current word’s “question.” It’s like the word shouting, “Hey everyone, who has information relevant to me?” Key (K): This is every other word’s “nametag” or “keyword.” It responds to the Query’s question, saying, “Hmm, I might be relevant to you! Check out my nametag.” Value (V): This is the word’s actual “meaning” or “substance.” If a Key is a good match for a Query, the model then says, “Okay, here’s my actual information for you,” and passes along its Value. Analogy: Finding a Book in a Library Still a bit fuzzy? Let’s try an analogy. Imagine you’re in a library looking for a book about the “History of AI,” but you don’t know the exact title. You head to the computer science section and start browsing the shelves. Reading every single book would take forever, so you start by looking at the titles.\n“Operating System Theory” and “Introduction to Compilers” seem less relevant. “Pattern Recognition” seems more relevant, and “Introduction to AI” looks like a great match.\nBut as the saying goes, don’t judge a book by its cover. You pull out a few promising titles and skim their contents:\n“Operating System Theory”: All about how to build OSes. “Introduction to Compilers”: Mostly about compiler theory, but has a small section on rule-based AI that could be applicable. “Pattern Recognition”: Covers a specific subfield of AI. “Introduction to AI”: Describes everything from early AI techniques to modern ones. Just as you suspected, “Operating System Theory” isn’t very relevant, while “Introduction to AI” is highly relevant. “Introduction to Compilers,” which seemed irrelevant at first glance, turned out to have some small connection.\nLet’s connect this back to Q, K, and V.\nYour search topic, “History of AI,” is the Query (Q). Your goal is to find books that are relevant to this query. The book titles — “Operating System Theory,” “Introduction to Compilers,” etc. — are the Keys (K). They are keywords that summarize the content. You made an initial judgment by comparing your Query to these Keys. The actual content of each book is the Value (V). Now, how would you calculate the total relevance of each book to your query? Just comparing your query (“History of AI”) to the titles (K) isn’t enough. A title, no matter how well-written, can’t capture everything inside. To get a more accurate score, you also need to consider the actual content (V).\nIn other words, the process is:\nFirst, determine the initial relevance between your query (Q) and each book’s title (K). Based on that relevance score, decide how much of the book’s actual content (V) to factor into your final decision. The higher the relevance from step 1, the more the book’s content influences the final result.\nBack to the Transformer Let’s return to our original example: “I went to the bank to deposit money.”\nWe want to calculate the attention for the first word, “I.” So, “I” becomes our Query. More precisely, the model doesn’t use the word “I” directly; it computes a Q vector that represents “I.” This is similar to how when you search for “History of AI,” your brain interprets the meaning of that phrase rather than just the literal string of characters.\nNext, the model calculates the K and V vectors for all words in the sentence. In our library analogy, the books’ titles (K) and contents (V) were already fixed. But here, since the model doesn’t know what input it will get, it computes K and V dynamically. (You can think of the library analogy as the book authors having pre-calculated the K and V for you).\nNow we have the Q vector for “I” and the K and V vectors for every word. The process looks like this:\nCompare Q_I with K_I. As it’s the same word, the relevance is likely high. Compare Q_I with K_went. As a subject-verb pair, there’s some relationship. Compare Q_I with K_to. Semantically and grammatically, the relevance doesn’t seem very high. This continues all the way to K_money. This completes the step of finding the relevance between the Query and each Key. Based on these relevance scores, the model combines the Value vectors of each word to determine the final attention output.\nThe relationship between “I” and “I” is calculated using (Q_I, K_I, V_I). The relationship between “I” and “went” is calculated using (Q_I, K_went, V_went). The relationship between “I” and “to” is calculated using (Q_I, K_to, V_to). …and so on. Once this is done, the Self-Attention calculation for the first word, “I,” is complete. The next step is to repeat this entire process for “went,” “to,” “the,” “bank,” and every other word. For “bank,” the calculations would look like:\n(Q_bank, K_I, V_I): The relevance between “bank” and “I.” (Q_bank, K_went, V_went): The relevance between “bank” and “went.” … (Q_bank, K_money, V_money): The relevance between “bank” and “money.” This final “relevance score” between each pair of words is the Self-Attention value. Calculating Self-Attention means calculating the relationship between every single word in the input sequence. Because these values represent inter-word relationships, they capture the context of the sentence, allowing the model to know that the bank in “I went to the bank to deposit money” is not a riverbank.\nWhat Does Calculating Q, K, V Actually Mean? This part gets a little more mathematical. Feel free to skip to the next section if you’d like.\nLike other machine learning algorithms, Transformers only understand numbers. They can’t process words like “went” or “bank.” So, the first step is to convert each word into a list of numbers, also known as a vector. This is called an embedding.\nI: [213, 92, 42, 89, 0, 21] went: [5, 2, 43, 99, 92, 111] Calculating Q, K, and V is the process of transforming a word’s embedding into three new vectors. For example, let’s say the embedding for “I” is E_I:\nE_I: [213, 92, 42, 89, 0, 21] Q_I: [234, 1, 53, 111, 5, 4] K_I: [4, 23, 62, 13, 34, 93] V_I: [24, 12, 32, 51, 112, 34] These numbers are just for illustration. In reality, the model multiplies the input embedding by three different matrices called W_Q, W_K, and W_V to get the final Q, K, and V vectors.\nE_I x W_Q = Q_I E_I x W_K = K_I E_I x W_V = V_I And how are W_Q, W_K, and W_V created? Just like all other parameters in a Transformer, they are learned during the training process. They start as random, meaningless values and gradually become meaningful through training.\nComputational Cost: O(N²) Self-Attention is all about calculating the relationship between every pair of words. The word “I” must be compared with “I,” “went,” “to,”…, “money.” And “money” must be compared with “I,” “went,” “to,”…, “money.”\nIf the input sentence has N words, the first word has to be compared with N words. Since this process must be repeated for all N words, the total computational complexity of Self-Attention is N x N, or O(N²).\nWhat does quadratic complexity mean in practice?\nIf your input has 10 words, you need 10 x 10 = 100 calculations. If your input has 100 words, you need 100 x 100 = 10,000 calculations. See the problem? The input length grew by 10x, but the computation required grew by 100x. As the input gets longer, the computation grows exponentially.\nWhile Self-Attention is a powerful technique for understanding context, it is also a very expensive and time-consuming operation.\nThe Grind of Auto-Regressive Generation Before we introduce the KV Cache, we need to talk about another key characteristic of LLMs: auto-regressive generation. The term might sound unfamiliar, but the concept is straightforward. Let’s see how an LLM generates a sentence.\nSuppose you give an LLM the prompt: “What is the tallest mountain?” It will likely respond, “It is Mount Everest.”\nLet’s break down how it gets there, step by step:\nThe LLM predicts the most likely next token after “What is the tallest mountain?” -\u0026gt; “It” The LLM appends this new token to the input. It now predicts the most likely token after “What is the tallest mountain? It” -\u0026gt; “is” The LLM appends “is.” It now predicts the most likely token after “What is the tallest mountain? It is” -\u0026gt; “Mount” The LLM appends “Mount.” It now predicts the most likely token after “What is the tallest mountain? It is Mount” -\u0026gt; “Everest” The LLM appends “Everest.” It now predicts the most likely token after “What is the tallest mountain? It is Mount Everest” -\u0026gt; “\u0026lt;END\u0026gt;” When the model generates a special \u0026lt;END\u0026gt; token, it stops. The final output is \u0026quot;It is Mount Everest.\u0026quot;\nEssentially, an LLM generates text by picking the most probable next word, appending it to the sequence, and then repeating the process with the new, longer sequence until it decides to stop.\nRegressive means predicting a new value based on past values. Predicting today’s weather based on yesterday’s is a regressive system. Auto means that the model’s own output is fed back in as the next input. In our example, the generated token “It” became part of the input for the very next step. Putting them together, this method of generating text one token at a time is called Auto-Regressive generation.\nPredicting the Next Token Let’s zoom in on just the first step of that process:\nThe LLM receives the input “What is the tallest mountain?”. The LLM calculates Self-Attention for this entire input. Based on the Self-Attention output for the final token, “mountain?”, it predicts the next token. (Technically, this output goes through a fully connected layer to become a hidden state, which is then used for prediction). The result is the token “It”. You might wonder if looking only at the output for “mountain?” is enough. It is, because thanks to Self-Attention, the representation for “mountain?” already contains information and relationships with all the other words: “What,” “is,” “the,” and “tallest.” Remember, the Query for “mountain?” was compared against the Keys and Values of every word in the sequence.\nAnd how are the Q, K, and V vectors for each word calculated? As mentioned before, by multiplying their embeddings by the pre-trained W_Q, W_K, and W_V matrices.\nThis means that in step 1, we calculated the Q, K, and V values for “What,” “is,” “the,” “tallest,” and “mountain?”.\nThe stage is now set for our hero, the KV Cache.\nEnter the KV Cache Let’s move to step 2. The input is now “What is the tallest mountain? It”. The LLM needs to predict the next word, so it will calculate Self-Attention using “It” as the Query. To do this, it needs to convert “It” into a Query vector and then compare it with the Keys and Values of all the other words (“What,” “is,” “the,” “tallest,” “mountain?”).\nBut wait! When we were calculating the K and V for “What” in this new step, we realized something: we already calculated them in the previous step when we generated “It.” The same is true for “is,” “the,” “tallest,” and “mountain?”. There’s no need to re-calculate the exact same values.\nSo, instead of re-calculating the K and V values for the old tokens, we can just reuse the ones we computed in the previous step.\nAll we have to do is save (or cache) the K and V values from the previous step instead of throwing them away. This saves us from performing complex matrix multiplications (E * W_K and E * W_V)over and over again, dramatically speeding up the process.\nThis technique of saving and reusing the Key and Value vectors from previous steps is called the KV Cache.\nThere are two key things to keep in mind about the KV Cache:\nYou still need to calculate the K and V for the newly generated token. In our example, the K and V for “It” must be computed because it wasn’t part of the input in the previous step. This new K and V pair is then added to the cache for the next step. You might wonder why we don’t cache the Q vector. When generating the next token, we only care about the Self-Attention for the very last token in the sequence. We always need the Q of the current last token, and this Q, just like its K and V, has never been calculated before. Caching old Q vectors would be useless because in the next auto-regressive step, those tokens are now in the past, and we don’t need to query from their position again. In short: to calculate attention for the current token, you need its new Q and all past K and V values. The Downsides of KV Cache By eliminating redundant and complex calculations, the KV Cache provides a massive speed boost for LLM inference. But as they say, there’s no such thing as a free lunch.\nThe KV Cache works by storing previously computed values in memory instead of discarding them. This means it consumes memory space.\nIn a real Transformer, Self-Attention is implemented as Multi-Head Self-Attention (you can think of it as running multiple Self-Attention calculations in parallel), and each layer of the Transformer has its own distinct attention values. Therefore, the memory required for the KV Cache is roughly:\n(Number of tokens) x (Number of attention heads) x (Number of layers) x (Dimension of K and V vectors) x ...\nAs a result, the size of the KV Cache grows rapidly with longer input sequences and larger models (which have more heads and layers). Since the KV Cache is typically stored in the GPU’s VRAM, this necessitates GPUs with very large amounts of VRAM.\nThis memory consumption is a serious challenge, especially for modern models that support context windows of hundreds of thousands or even millions of tokens. To mitigate this, techniques like Multi-Query Attention (sharing K and V across attention heads) and Grouped-Query Attention are often used.\nWrapping Up Today, we explored the KV Cache, a cornerstone optimization that has dramatically improved Transformer inference performance.\nHere are the key takeaways:\nSelf-Attention uses Q, K, and V vectors to understand context, but this is computationally expensive (O(N²)). LLMs generate text using an auto-regressive method, where each new word is added to the input for the next step. Re-calculating K and V for all previous tokens at every step is extremely inefficient. The KV Cache solves this by storing and reusing K and V values, eliminating redundant computations. The result is a huge boost in inference speed, but it comes at the cost of increased memory usage, especially for long sequences and large models. ","permalink":"https://blog.jiminl.com/posts/understanding-the-kv-cache-feat-self-attention-81351b4ad4f9/","summary":"If you’ve been following the world of LLMs, you’ve probably heard of the KV Cache. It’s a technique that’s mentioned constantly, which…","title":"Understanding the KV Cache (feat. Self-Attention)"},{"content":"Today, we’re diving into a fascinating concept known as Speculative Decoding. The name might sound a bit complex — Speculative means guessing or making a conjecture, and Decoding is how an LLM predicts the next token. Put them together, and it means the LLM isn’t just generating the next token accurately; it’s speculating on the next token’s prediction.\nThat quick definition probably doesn’t fully capture the essence of it.\nSo, let’s explore why Speculative Decoding is necessary, how it works, and what its pros and cons are, piece by piece.\nLLMs Are Slow Large Language Models (LLMs) are notoriously slow. There are a few reasons for this, but the most critical are the sheer size of the model itself and the Autoregressive nature of generating one token after the next. These two factors combine to make LLM inference incredibly slow. The model is so large that generating a single token takes a long time, and this lengthy process has to be repeated for every single token. It’s no wonder the process is slow.\nIf we dig deeper, there are more technical reasons involving the Multi-Head Self Attention architecture, modern GPU memory hierarchy, and the Memory Bandwidth Bound characteristic, but those two fundamental issues are the root cause.\nSo, if we want to speed up LLM inference, how do we do it? We need to tackle those two problems: the model is too large and the Autoregressive token-by-token generation method.\nSpeculative Decoding aims directly at solving these two issues.\nThe Core Idea Behind Speculative Decoding The Problem of the Oversized Model The solution Speculative Decoding offers to the problem of slow, oversized models is surprisingly simple: “Let’s use a small model.” Imagine the original model you intended to use is 100 billion parameters (100B). If you use a 7B parameter model instead, it will obviously be much faster. A simple calculation suggests it would be nearly 14 times faster.\nHowever, this idea seems absurd on the surface. We use a large model precisely because, while small models are fast, their output quality is poor. Reverting to a small model would be fast, but the quality would drop — that’s certainly not a good solution.\nBut, the story changes if the result generated by the small model is reviewed by someone else. Since the small model is 14 times faster than the 100B model, even if the review process adds some time, the total time spent will still be faster than using the 100B model alone.\nSo, how does this review work?\nThe Problem of Autoregressive Token-by-Token Generation Here is where Speculative Decoding’s second core idea comes into play. Instead of using the result generated by the small 7B model directly, the output is reviewed using the large 100B model that we originally intended to use.\nAgain, this seems counter-intuitive. To speed things up, we generated a result quickly with a small model, only to check it with the big model? Doesn’t that just add the time the small model took to generate the result?\nNo, it doesn’t. The secret lies in how the large model reviews the small model’s output.\nThe large model does not review the result by generating tokens one by one in an Autoregressive fashion. Instead, it takes the results generated by the small model all at once and determines where the sequence is correct and where it goes wrong. It then accepts the correct portion and sends the rest back to the small model to regenerate from the point of error.\nBy addressing both the issue of the model being too large (by using a small Draft model first) and the issue of token-by-token prediction (by having the large model review a sequence of tokens in a single forward pass), Speculative Decoding solves the root causes of LLM sluggishness. However, to truly grasp how this is possible, we need a concrete example.\nLet’s look at one now.\nA Practical Example Step 1: Generation by the Small Model Imagine a user provides the prompt: “The weather is lovely today.”\nInstead of the 100B model, we use the 7B model to predict the continuation. We also specify how many words (or tokens — we’ll use “word” for simplicity) we want to generate. Let’s assume we aim to generate seven words.\nThe 7B model very quickly generates: “Perhaps we should go for a dance.” (Note: ‘dance’ is not a typo; the explanation follows.)\nStep 2: Review by the Large Model Now, the 100B model reviews this result. The original prompt and the small model’s generation are combined and fed into the 100B model. The input becomes: “The weather is lovely today. Perhaps we should go for a dance.”\nThe 100B model then uses its normal LLM inference process to predict the next word following this entire input. Let’s say it generates “and.” The generated sentence so far is now: “The weather is lovely today. Perhaps we should go for a dance and.”\nStep 3: Preparing for Review (This is where it gets a bit complex. Feel free to take a deep breath before continuing.)\nThe main goal of running the 100B model to generate this single new word (“and”) is not the word itself, but reviewing the result generated by the 7B model, as explained earlier. Let’s see how the review works.\nTo generate the new word “and,” the 100B model first needs to understand the input: “The weather is lovely today. Perhaps we should go for a dance.” Generating “and” means selecting the most probable word to follow that sequence.\nHow does it select the most probable word?\nIn the Transformer architecture, each word (token) in the input sentence (the Prompt) is passed through a complex and deep artificial neural network (including the famous self-attention mechanism) and is transformed into a vector, which is a sequence of numbers.\nIn our example, “The weather is lovely today. Perhaps we should go for a dance” is converted as follows. The specific numbers are arbitrary and not important; just grasp the concept that each word is converted into a vector:\nThe: [23, 53, 29, 134, …] weather: [221, 23, 99, 111, …] is: [34, 13, 252, 153, …] lovely: [25, 22, 89, 75, …] today: [162, 1, 3, 66, …] Perhaps: [14, 43, 2, 46, …] we: [42, 52, 3, 72, …] should: [14, 43, 2, 46, …] go: [25, 22, 89, 75, …] for: [34, 13, 252, 153, …] a: [221, 23, 99, 111, …] dance: [42, 52, 3, 72, …] The Transformer then takes the vector corresponding to “dance” — [42, 52, 3, 72, …] — and selects the most plausible next word.\nCrucially, it only considers “dance” to pick the next word, not all the preceding words. This is because the calculation of “dance’s” value, [42, 52, 3, 72, …], already incorporates the values for “The, weather, is, lovely, today, Perhaps, we, should, go, for, a,” due to the Transformer’s self-attention mechanism.\nFor this discussion, you only need to know that the vector representing any given word already contains information about all the words that came before it.\nBy running the 100B model once on “The weather is lovely today. Perhaps we should go for a dance,” it generated the next word “and.” More importantly, it also simultaneously obtained the vector values for all preceding words.\nStep 4: The Actual Review The: [23, 53, 29, 134, …] weather: [221, 23, 99, 111, …] is: [34, 13, 252, 153, …] lovely: [25, 22, 89, 75, …] today: [162, 1, 3, 66, …] Perhaps: [14, 43, 2, 46, …] we: [42, 52, 3, 72, …] should: [14, 43, 2, 46, …] go: [25, 22, 89, 75, …] for: [34, 13, 252, 153, …] a: [221, 23, 99, 111, …] dance: [42, 52, 3, 72, …] We established that only the vector for “dance” is needed to generate the word following “dance.”\nWhat about generating the word following the fifth word, “today”? We need the vector value for “today.” Since we already have the vector for “today,” we can predict the word that should follow it. The same logic applies to predicting the word following “go.”\nThis is where a slight modification to the 100B model comes in. Since we already know the vector for each word, we can generate the word that follows each of them.\nLet’s look at row 11 in this table. This is equivalent to asking the 100B model, “Here’s the vector for ‘a’. What would you generate next?” The 100B model responds, “I’d generate ‘walk’.” Now we compare this to the word generated by the 7B model in the next row, which is “dance.” They are different. This means the 7B model failed the 100B model’s review at this step.\nWe don’t need to look beyond step 11. Any words generated after an error are based on a wrong prediction and must be discarded.\nStrictly speaking, Speculative Decoding doesn’t just do a simple comparison of predicted tokens. It statistically checks how similar the predictions of the small and large models are. However, for a concept-level understanding without complex math, we’ll omit that detailed complexity.\nWe now accept only the portion of the 7B’s generated sequence that passed the 100B’s review.\nTherefore, the first six words generated by the 7B model are accepted: “Perhaps we should go for a”. We now know the word that should follow “a” is not “dance”, but “walk”. We can now feed the accepted sequence, “The weather is lovely today. Perhaps we should go for a walk”, back to the 7B model to continue the generation process.\nThe Meaning of “One-Shot” Review I have repeatedly emphasized that the review stage in Speculative Decoding happens “all at once.” However, the example above shows that, in practice, the next word is predicted for each preceding word, seemingly in an Autoregressive manner.\nThe “all at once” refers not to the token prediction step, but to the vector calculation step for each word. LLM inference involves two main steps: calculating the vector for each word and then using that vector to predict the next word. The step of calculating the vector for each word is far more complex, lengthy, and time-consuming. One of the main reasons models are getting larger is to extend this vector calculation process.\nIn other words, the most time-consuming part of the Autoregressive, word-by-word prediction process is calculating the vector for each word. Compared to this, predicting the next word based on an already calculated vector happens in an instant.\nAnd critically, the vector calculation for all words in the input sentence happens simultaneously.\nIf the input is “The weather is lovely today. Perhaps we should go for a dance,” the vectors for “The” and “weather” are not calculated sequentially. Instead, the vectors for the entire sentence are calculated in parallel, all at once.\nTo summarize, the review stage involves the following:\nThe vectors for each word in “The weather is lovely today. Perhaps we should go for a dance” are calculated in parallel, all at once. Based on each word’s vector, the word that should follow it is predicted. The final result accepts only the portion where the 100B model’s prediction matched the 7B model’s prediction. How Much Faster Is It, Really? Let’s assume the 100B model takes 5 seconds to predict one word, and the 7B model takes 0.5 seconds to predict one word.\nTo generate “Perhaps we should go for a dance” (7 words) following “The weather is lovely today,” the 7B model takes 0.5 X 7 = 3.5 seconds.\nThe 100B model predicted one word (“walk” or “and”) during the review stage. This review took 5 seconds. (Comparing the 7B results word-by-word is practically instantaneous and doesn’t significantly affect the time.)\nThe total time spent to generate the corrected sequence, “The weather is lovely today. Perhaps we should go for a walk,” is the 3.5 seconds the 7B model spent generating, plus the 5 seconds the 100B model spent reviewing, totaling 8.5 seconds.\nIf we had used only the 100B model without Speculative Decoding, it would have taken 5 X 7 = 35 seconds. Cutting a 35-second task down to 8.5 seconds represents massive efficiency.\nRevisiting the Name: Speculative Decoding Stepping back from the technical details, let’s look at the name again.\nSpeculative, as mentioned earlier, means guessing or conjecture. In Speculative Decoding, a smaller model (called the Draft model) is used to create a speculative answer first, which is not guaranteed to be correct. This speculative answer is then reviewed by the larger model. The name Speculative Decoding now makes a lot more sense.\nKey Considerations for Choosing the Small Model Speed of the Small Model It goes without saying that the small model must be significantly faster than the large one. Otherwise, there’s no point in adopting Speculative Decoding. Typically, models 10 to 100 times smaller than the main model are used.\nAcceptance Rate The performance of the small model is critical in Speculative Decoding. While it can’t be as accurate as the large model, it must be reasonably accurate. In the review stage, the large model only accepts the parts it agrees with, and the rest is discarded. If the small model constantly makes poor predictions, the process becomes overly reliant on the slow large model, defeating the purpose of quickly generating a speculative result with the small model.\nThe proportion of the small model’s generated sequence that passes the large model’s review is called the Acceptance Rate. In our example, the small model predicted 7 words (“Perhaps we should go for a dance”), but only 6 were accepted (“Perhaps we should go for a”), so the Acceptance Rate is 6/7.\nTherefore, the small model must be small enough to be fast, but also smart enough to emulate the large model’s results to some extent.\nA common approach is to use a smaller version of the large model rather than a completely different architecture. For example, if the large model is Llama 3 70B, the small model might be Llama 3 8B. Since they share the same base, the small model is more likely to successfully emulate the large model.\nAnother method involves training the Draft Model alongside the large model during fine-tuning, such as with LoRA. Since LoRA fine-tuning alters the output characteristics of the base model, it can be highly effective to concurrently train a small Draft Model that matches the characteristics of the fine-tuned LoRA model.\nHow Much Should the Small Model Predict? The number of next words (or tokens) the small model generates, often called the k value, is a crucial factor.\nIn our example following “The weather is lovely today,” we generated k=7 words, resulting in “Perhaps we should go for a dance.”\nImagine we generated k=12 words: “The weather is lovely today. Perhaps we should go for a dance or sing a cheerful song.” After “dance,” the prediction was wrong. We wasted time generating all 12 words, only to discard most of them.\nIf k is too small (e.g., k=2): The large model has to review the small model’s results too frequently. The overhead can negate the speed gains, making the tail wag the dog (minimal speed gain). If k is too large (e.g., k=20): There’s a high probability that the small model’s predictions will be wrong early on. If only one prediction is wrong, all subsequent 19 must be discarded, resulting in a significant waste of computation. Finding the appropriate k value is a matter of tuning that depends on the service’s specific characteristics and the Draft model’s Acceptance Rate.\nSelf Speculative Decoding: Being Both Small and Large Speculative Decoding is a fantastic idea, but it has the drawback of requiring maintenance of a separate small model. Self Speculative Decoding emerged to solve this issue.\nThe core idea is to use only a subset of the large model to act as the small model. The entire large model is then used for the review stage.\nAn LLM is typically composed of multiple layers, or Decoder Blocks. Let’s say the main large model has 20 layers.\nIn the initial generation stage, we only run the first 5 layers to create the speculative result. This part serves the role of the small model in regular Speculative Decoding.\nOnce the speculative result is generated, all 20 layers are used for the review. This part serves as the large model.\nThis approach eliminates the need to maintain a separate small model. Since the 5-layer small model is part of the 20-layer large model, their “thinking styles” are similar, and the Acceptance Rate is likely to be higher.\nOf course, there are downsides. It’s more complex to implement than regular Speculative Decoding and requires deep modification of the model’s internal logic.\nHowever, if implemented well, it can solve both the problems of the separate Draft Model and the Acceptance Rate that plague traditional Speculative Decoding.\nPros and Cons of Speculative Decoding Finally, let’s summarize the advantages and disadvantages of Speculative Decoding.\nAdvantages Massive Speed Improvement: When well-tuned, it can increase inference throughput by 2x to 3x compared to the traditional method. No Quality Degradation: This is the most crucial point. Other speed-up techniques (like Quantization or Distillation) often sacrifice a bit of performance. However, because Speculative Decoding always has the large model review the small model’s results and only accepts those that align with its own expectation, the output is 100% identical to what would have been generated slowly by the large model alone. Disadvantages Implementation Complexity: It’s much more complex than just running a single model. Synchronizing two models (or two stages of one model), modifying internal model logic, comparing tokens, and implementing the reject/accept logic adds significant development overhead. Increased Memory Usage: If you use a separate small Draft Model, you must load both the small and large models into memory. This can be mitigated by using Self Speculative Decoding. Not Always Faster: As mentioned, for tasks with a low Acceptance Rate, the overhead may not be worth it, or it could even result in a slower performance. Conclusion The sluggishness of LLMs isn’t a problem that can be solved simply by upgrading to better hardware. It requires overcoming the intrinsic limitations of their massive size and Autoregressive nature.\nSpeculative Decoding is an approach that solves this problem not through brute-force computation, but through a shift in thinking. By moving away from the fixed idea of making the large model faster, it introduces an efficient collaboration model where a small model quickly generates a draft, and the large model reviews it.\nFrom now on, when you see an LLM’s response “blinking… blinking…” while it generates, you might instinctively picture the frantic collaboration between the small and large models happening behind the scenes.\nAppendix: Running Two Models When GPU Is Precious? In Speculative Decoding, you need to run both a small and a large model. One might think this would increase GPU utilization and actually slow things down.\nHowever, a closer look reveals this isn’t the case.\nWhen you examine how LLMs operate, you find that LLM computation is not Compute Bound; it’s Memory-Bandwidth Bound. Let me explain.\nAn LLM is essentially a massive neural network. Nearly all its operations involve multiplying and adding the user input with the colossal matrices called weights. This process is a constant repetition of: 1) Moving the weights from slower main memory to extremely fast memory, 2) The GPU cores calculating values in the fast memory, and 3) Moving the result back to the slower memory.\nStep 2 (the actual value calculation) is very fast, but Steps 1 and 3 (moving data between the slow and fast memory) are relatively very slow. Time is consumed moving data between two different types of semiconductor memory.\nThis means that the GPU cores spend most of their time waiting for data to be filled into their fast-access workspace.\nSo, why not just use fast memory instead of dividing it into slow and fast memory? The problem is the LLM is so big. Fast memory is incredibly expensive, making it difficult to fit a large capacity. Hence, the cheaper, slower memory is used as an intermediate storage. It’s still exponentially faster than reading directly from a disk.\nAfter reading all this, you realize that those precious GPU cores actually spend a lot of time idle during LLM inference. Why let them be idle? They should be working! The idle time of the GPU cores can be used to run the small model for Speculative Decoding. Of course, we don’t need to manually track when the GPU is idle and when it’s working; the GPU handles that automatically.\nThe key is that, due to the LLM’s Memory Bound characteristic, running both a small and a large model doesn’t strain the GPU core utilization. Instead, it’s a method for using the GPU cores more efficiently.\n","permalink":"https://blog.jiminl.com/posts/speculative-decoding-making-llms-faster-without-sacrificing-quality-973384f9c165/","summary":"Today, we’re diving into a fascinating concept known as Speculative Decoding. The name might sound a bit complex — Speculative means…","title":"Speculative Decoding: Making LLMs Faster Without Sacrificing Quality"},{"content":"Giving AI Eyes: Multi-Modal LLMs Remember late 2022 when ChatGPT first dropped? It feels like ancient history in tech years, but it’s barely been three years. A lot has happened since then.\nBack then, ChatGPT shocked the world with its eloquence and vast knowledge base. But it had one glaring limitation: it was text-only.\nFast forward to today, and the landscape has shifted. With models like Gemini and GPT, it’s no longer a novelty for an AI to understand images, audio, and even video. We have officially entered the era of the Multi-Modal LLM.\nBut how do these models actually “see” and “hear”? Let’s break it down.\nWhat is “Multi-Modal” Anyway? Think of a “Modality” as a channel of communication. Text is one modality, images are another, and audio is yet another.\n“Multi-Modal” simply means the ability to process multiple modalities simultaneously. Humans are inherently multi-modal — we speak, look, and listen simultaneously. An AI that only deals with text can never fully capture the depth of human interaction. The Multi-Modal LLM was born to solve this limitation.\nSo, how does it work under the hood?\nUnited Under the Transformer Research into multi-modal AI isn’t new, but we’re going to focus on the architecture that’s eating the world right now: The Transformer.\nUsually, when we talk about Transformers, we talk about LLMs (Large Language Models). But here’s the secret: the Transformer architecture isn’t exclusive to language.\nLet’s look at the high-level workflow of a standard text LLM:\nTokenization: Break long input into small chunks (Tokens). Embedding: Convert those chunks into vectors (numbers the model understands). Attention (Self-Attention): Figure out relationships between vectors (e.g., understanding that “bank” relates to “money” in a specific sentence). Transformation: Squash that relationship data into a context-aware vector. Prediction (Decoding): Predict the next token based on that context. Applying the Logic to Images and Audio While the output remains text (for our purposes), we can apply the same input philosophy to other modalities.\nFor Images:\nTokenization: Chop the image into small square patches. Embedding: Convert those patches into vectors. Attention: Figure out how patch A (a dog’s ear) relates to patch B (a dog’s tail). Transformation: Create a vector that understands the whole image. For Audio:\nTokenization: Slice the audio into short time segments. Embedding: Convert segments into vectors. Attention: Analyze the relationship between sound waves over time. Transformation: Create a vector representing the full audio clip. The Key Insight: “It’s All Just Vectors” Whether it’s a word token, an image patch, or an audio segment, the framework remains the same. Once you get past step 2 (Embedding), the model doesn’t really care if the input was originally a pixel or a vowel. To the model, it’s just a pile of vectors to process.\nThis insight inspired domain-specific variants like Vision Transformers (ViT) for images and Conformers for audio, which combine convolution and attention to model temporal signals.\nAnd that brings us to the core idea of Multi-Modal LLMs:\n“If it’s all vectors, why treat them separately? Let’s throw text tokens, image pixels, and audio signals into one pot and let the model figure out the relationships between them all.”\nThis allows the AI to understand mathematically that the pixel vector for “dog” and the text vector for “cute” are deeply related.\n2. Two Ways to Build a Multi-Modal LLM Theory is great, but how do we actually build one? There are two main schools of thought.\nApproach A: Natively Multi-Modal This is the path taken by Google’s Gemini or OpenAI’s GPT. You design the model from day one to be trained on text, images, and audio simultaneously.\nEverything is treated as a token from the start. Text is tokenized, images are tokenized, audio is tokenized. They are all mapped to the same embedding space. This is powerful because the model can understand nuance — like realizing a speaker is angry not just by what they said, but by how they sounded.\nThe Downside:\nIt’s incredibly expensive and difficult.\nYou need to answer a hard question: How do you prove to a model that the word “Soccer” and a photo of an NBA player are related? You need massive datasets that explicitly link these different modalities. Collecting that data and training a massive model on it is a luxury reserved for tech giants with bottomless budgets.\nApproach B: The Component-Based Assembly Researchers with tighter budgets asked, “Can’t we just assemble existing parts?”\nInstead of building a monster from scratch, they combine pre-trained experts:\nThe Eyes (Vision Encoder): A model great at seeing (e.g., CLIP, SigLIP). The Brain (LLM): A model great at talking (e.g., Llama, Vicuna). The Glue (Adapter): A module to connect the two. You take a frozen Vision Encoder and a frozen LLM. Since they speak different “vector languages,” you build a lightweight Adapter to translate the visual signals into something the LLM understands.\nThis method is efficient, cheaper, and surprisingly effective. It has become the standard for open-source multi-modal models. Let’s look at the poster child for this approach: LLaVA.\n3. LLaVA: The Open Source Textbook LLaVA (Large Language and Vision Assistant) made waves by proving you don’t need a complex architecture or proprietary data to build a top-tier Multi-Modal LLM.\nA Simple Architecture Before LLaVA, researchers used complex connectors (like Q-Formers). LLaVA did something bold:\n“Let’s just connect them with a single Linear Layer.”\nAnd it worked.\nVision Encoder (CLIP ViT-L/14): Turns images into vectors. Projection Layer (Linear): A simple translation layer that turns image vectors into word embedding vectors. LLM (Vicuna): Takes the translated signals and generates a response. Data Alchemy The architecture is simple, but where do you get the training data?\nLLaVA’s team used a clever trick. There are plenty of image-caption pairs and bounding box coordinates. Text is the common denominator here.\nThey fed those captions and coordinates into a text-only GPT-4 and asked it to generate conversations. For example,\nPrompt: “I have an image where a person is at [coordinate X] and a car is at [coordinate Y]. The caption is ‘A man walking by a car.’ Generate a conversation a user might have about this image.”\nHere is an image from the original paper:\nThe example above comes directly from the LLaVA paper. The approach is to feed Text-only GPT-4 the two context items shown at the top (Context type 1 \u0026amp; 2) and ask it to generate the three data points listed below (Response type 1, 2, \u0026amp; 3).\nGPT-4 hallucinated a conversation based on the text description, effectively creating labeled multi-modal training data without ever seeing the image itself.\nBy pairing GPT-4’s generated text responses with existing captioned image datasets, the LLaVA team compiled roughly 158K (Image, Question, Answer) examples.\n4. The 2-Stage Training Pipeline So how do you train it? LLaVA uses a 2-Stage Curriculum Learning process.\nStage 1: Feature Alignment The goal of this stage is to establish a primary connection between visual information and linguistic information. It is a process of teaching the LLM that “this specific chunk of image vectors” is highly correlated with the word “soccer.”\nDuring this phase, the Vision Encoder and the LLM are Frozen, and only the Projection (Adapter) is trained. Since the objective is solely to learn the relationship between visual and linguistic data, training just the Projection layer is sufficient.\nWe use (Image, Caption) pairs for this stage. This allows the Projection layer to learn the relationship between photos composed of pixels and the language that describes them.\nStage 2: Visual Instruction Tuning After passing Stage 1, the model becomes capable of converting image inputs into a format the LLM can understand. However, it is not yet capable of providing intelligent answers about the image. We need to push the LLM beyond simple understanding so that it can generate intelligent responses.\nIn this stage, the Vision Encoder remains Frozen. This is because our goal is to train the LLM (the speaker), not the Vision Encoder (the “eye” that understands images).\nThe LLM becomes a training target because it must learn how to respond based on this new type of input (images). The Projection layer is also trained. Although it learned the basics in Stage 1, we need to fine-tune the “Image Info → Language Info” conversion as the LLM learns to generate actual responses.\nFor training data, we use the dataset created earlier using the clever GPT-4 method. Since this data consists of (Image, Question, Answer) triples, the LLM finally learns how to provide answers that align with both the image and the specific question.\n5. Evolution: LLaVA 1.5 and LLaVA-NeXT The research didn’t stop there.\nLLaVA 1.5 swapped the single Linear Layer for an MLP (Multi-Layer Perceptron) and upgraded the Vision Encoder. These small tweaks resulted in massive performance gains.\nLLaVA-NeXT tackled the resolution problem. Standard models squash every image into a square (e.g., 336x336). This ruins tall smartphone screenshots or wide panoramas — text gets blurry and unrecognizable.\nLLaVA-NeXT introduced AnyRes, a strategy that slices the original image into smaller tiles (e.g., slicing a tall image into three vertical squares) and feeds them along with a global view. This allows the model to see high-resolution details without distortion.\n6. The Hurdles That Remain We’ve come a long way, but it’s not perfect.\nObject Hallucination Hallucinations — where text models invent plausible lies — manifest in even stranger ways in Multi-Modal models. For example, you show it a photo of an empty desk, and it insists, “There’s a cup on the desk.” Or it looks at a picture of a single cat and claims, “Several cats are playing together.”\nHere are a few known causes:\nLLMs are trained on massive amounts of text, learning that the word “cup” follows the word “desk” with a very high probability. Even if there is no cup in the actual image, the LLM tends to follow these pre-learned linguistic statistical probabilities.\nSometimes, the Attention mechanism simply misfires. If the model focuses on the wrong part of the image while generating an answer, hallucinations can occur.\nTechniques similar to RLHF and preference-based fine-tuning are being explored to reduce visual hallucination — teaching models to prioritize visual evidence over text priors.\nThe Resolution Dilemma We take photos in 4K, but the AI model sees them squashed down to the size of a postage stamp. Text, in particular, gets distorted and becomes illegible. It’s hard enough to read the fine print on insurance policies as it is, let alone when it’s crushed by the model. Distant road signs face the same issue.\nThe difficulty of using large images is similar to the challenge of increasing the Context Window in LLMs. Due to the Self-Attention structure, if the input increases by N, the computation scales by N². Since images are 2D, the problem is even more severe.\nFor example, if you double the image width from 200 to 400, the actual pixel count increases 4x. Consequently, the Self-Attention computation jumps by the square of that — 16x. The computational load explodes.\nTo solve this, strategies like AnyRes (used in LLaVA-NeXT), which slice the original image into multiple smaller patches for processing, are proving helpful.\nThe Modality Gap Whether it’s Natively Multi-Modal or a component-based Adapter approach, the ultimate goal of a Multi-Modal LLM is to represent various modalities in a single unified way. However, this process isn’t perfect. There is an inevitable, uncrossable river between analog signals (images, audio) and symbols (text).\nFor instance, if I show a Multi-Modal LLM a photo of myself looking up at the sky with a gloomy expression on a rainy day and ask, “Describe the emotions you feel in this picture,” it will likely just respond:\n“A man is looking at the sky on a rainy day.”\nIt captures the facts, but misses the feeling.\n7. Conclusion Multi-Modal LLMs are no longer optional; they are the standard.\nWhile we currently use them to chat about photos, these models are the brains of the future. They will power robots that navigate messy living rooms and autonomous cars that interpret complex traffic signals.\nThe fusion won’t stop at images. We are moving toward models that integrate sound, video, and eventually, sensory data from the physical world.\nTry it out tonight. Open your fridge, snap a photo, and ask an LLM, “What should I cook for dinner?” You’ll get a taste of the future, right in your kitchen.\n","permalink":"https://blog.jiminl.com/posts/giving-ai-eyes-a-technical-deep-dive-into-multi-modal-llms-dd2f97cbc482/","summary":"Remember late 2022 when ChatGPT first dropped? It feels like ancient history in tech years, but it’s barely been three years. A lot has…","title":"Giving AI Eyes — A Technical Deep Dive into Multi-Modal LLMs"}]