<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shawn on Medium]]></title>
        <description><![CDATA[Stories by Shawn on Medium]]></description>
        <link>https://medium.com/@xiaxiami?source=rss-94e461173820------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XNkpphl7hs5N1YXrk6GC7A.jpeg</url>
            <title>Stories by Shawn on Medium</title>
            <link>https://medium.com/@xiaxiami?source=rss-94e461173820------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:38:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xiaxiami/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Agentic Context Engineering: A Step-by-Step Guide for Machine Learning Engineers]]></title>
            <link>https://medium.com/@xiaxiami/agentic-context-engineering-a-step-by-step-guide-for-machine-learning-engineers-fa3647ee056c?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa3647ee056c</guid>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 23:57:51 GMT</pubDate>
            <atom:updated>2026-08-16T23:57:51.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klJefbSN96bSWis1STLcmA.jpeg" /></figure><p>If you have worked with large language models (LLMs), you have probably encountered a frustrating situation:</p><p>You give an agent a powerful model, a collection of tools, access to documentation, and a seemingly straightforward task — and it still produces a poor result.</p><p>The instinctive response is often:</p><blockquote><em>“We need a better model.”</em></blockquote><p>Sometimes that is true. But increasingly, the bottleneck is not the model itself. It is <strong>context</strong>.</p><p>An AI agent can only reason about the information available to it. If the right information is missing, irrelevant information dominates the context, previous decisions are forgotten, or tool results are poorly organized, even an excellent model can behave poorly.</p><p>This is where <strong>agentic context engineering</strong> becomes important.</p><p>Context engineering is the discipline of designing, constructing, managing, and continuously updating the information an AI model receives at each step of an agent’s execution.</p><p>The word <em>agentic</em> matters because an agent is not answering a single question once. It is repeatedly:</p><ol><li>Observing the environment</li><li>Retrieving information</li><li>Reasoning</li><li>Taking actions</li><li>Observing the results</li><li>Updating its context</li><li>Reasoning again</li></ol><p>In this article, we will build the concept from the ground up and develop a practical framework that machine learning engineers can use to design better LLM agents.</p><h3>1. Start With the Fundamental Question: What Is Context?</h3><p>Before talking about context engineering, we need to define context.</p><p>For an LLM, context is essentially the information available to the model when it generates its next output.</p><p>A simplified view is:</p><pre>Context → LLM → Output</pre><p>The context might contain:</p><ul><li>System instructions</li><li>User requests</li><li>Conversation history</li><li>Retrieved documents</li><li>Tool results</li><li>Database records</li><li>Previous agent actions</li><li>Intermediate reasoning state</li><li>Application state</li><li>Structured metadata</li></ul><p>For example, suppose we ask an agent:</p><blockquote><em>“Why did our image anomaly detector suddenly get worse this week?”</em></blockquote><p>The model cannot answer this question reliably from the prompt alone.</p><p>It might need:</p><pre>User question<br>      +<br>Model configuration<br>      +<br>Recent evaluation metrics<br>      +<br>Training dataset statistics<br>      +<br>Recent production images<br>      +<br>Deployment history<br>      +<br>Data distribution statistics<br>      +<br>Recent code changes<br>      ↓<br>    LLM<br>      ↓<br>Diagnosis</pre><p>The model may be extremely capable, but without these inputs it is essentially guessing.</p><p>This leads to an important principle:</p><blockquote><strong><em>The intelligence of an agent is constrained not only by the model’s capabilities, but also by the quality of the context supplied to it.</em></strong></blockquote><h3>2. Prompt Engineering Is Not Context Engineering</h3><p>These concepts are related, but they are not the same.</p><h3>Prompt engineering</h3><p>Prompt engineering focuses primarily on how we formulate instructions.</p><p>For example:</p><pre>You are an expert ML engineer.</pre><pre>Analyze the following anomaly detection results<br>and identify the most likely causes of the performance drop.</pre><p>We might improve the prompt by adding:</p><pre>Consider:<br>1. Data distribution shift<br>2. Model degradation<br>3. Label quality<br>4. Hardware changes<br>5. Preprocessing changes</pre><p>That is useful.</p><p>But suppose the model still does not have access to the actual production metrics.</p><p>The problem is no longer the wording of the prompt.</p><p>It is the <strong>context</strong>.</p><h3>Context engineering</h3><p>Context engineering asks:</p><blockquote><em>What information should the model have at this exact point in the agent’s execution?</em></blockquote><p>That is a much broader question.</p><p>Instead of merely designing a prompt, we design the information flow:</p><pre>                    ┌──────────────┐<br>                    │ User Request │<br>                    └──────┬───────┘<br>                           ↓<br>                    ┌──────────────┐<br>                    │ Agent State  │<br>                    └──────┬───────┘<br>                           ↓<br>              ┌────────────┴────────────┐<br>              ↓                         ↓<br>        Retrieval                    Tools<br>              ↓                         ↓<br>       Documentation             Metrics / DB<br>              └────────────┬────────────┘<br>                           ↓<br>                    ┌──────────────┐<br>                    │   Context    │<br>                    └──────┬───────┘<br>                           ↓<br>                         LLM<br>                           ↓<br>                        Action</pre><p>The prompt is only one component of this system.</p><h3>3. Why Context Becomes Hard for Agents</h3><p>A traditional chatbot might have a relatively simple interaction:</p><pre>User → LLM → Answer</pre><p>An agent looks more like:</p><pre>User<br> ↓<br>Agent<br> ↓<br>Search documentation<br> ↓<br>Read results<br> ↓<br>Call database<br> ↓<br>Analyze data<br> ↓<br>Call another tool<br> ↓<br>Observe result<br> ↓<br>Modify hypothesis<br> ↓<br>Search again<br> ↓<br>Take action<br> ↓<br>Final answer</pre><p>The amount of information can grow rapidly.</p><p>Imagine an agent performing a software debugging task.</p><p>After 15 tool calls, its context might contain:</p><ul><li>5,000 lines of logs</li><li>20 documentation pages</li><li>10 error messages</li><li>15 tool responses</li><li>Several failed hypotheses</li><li>Source-code snippets</li><li>Configuration files</li><li>User instructions</li><li>Previous actions</li></ul><p>Simply dumping everything into the context window is usually a bad strategy.</p><p>Why?</p><p>Because <strong>more context does not necessarily mean better context</strong>.</p><p>A useful analogy is human working memory.</p><p>If I give you:</p><blockquote><em>“Here are 500 pages of documentation. Find the three paragraphs relevant to this bug.”</em></blockquote><p>I have technically given you more information.</p><p>But I have not necessarily made the problem easier.</p><p>Good context engineering is therefore about <strong>selectivity, organization, compression, and state management</strong>.</p><h3>4. The Four Fundamental Context Problems</h3><p>For practical agent design, I find it useful to think about four major problems.</p><h3>Problem 1: Missing context</h3><p>The agent does not have the information it needs.</p><p>Example:</p><pre>Agent:<br>&quot;The model may be suffering from data drift.&quot;</pre><pre>Reality:<br>The model was recently changed from ViT-B to ViT-L.</pre><p>The agent cannot reason about a change it cannot see.</p><h3>Problem 2: Irrelevant context</h3><p>The agent receives too much information that does not matter.</p><p>For example, retrieving 50 documents when only two are relevant.</p><pre>Query<br> ↓<br>Vector database<br> ↓<br>50 documents<br> ↓<br>LLM</pre><p>This increases token usage and can make reasoning less reliable.</p><h3>Problem 3: Stale context</h3><p>The information was once correct but is no longer correct.</p><p>For example:</p><pre>Current production model:<br>anomaly-detector-v4</pre><pre>Old documentation:<br>anomaly-detector-v2</pre><p>An agent that retrieves the old documentation may confidently make the wrong recommendation.</p><h3>Problem 4: Poorly structured context</h3><p>The information is technically available but difficult for the model to use.</p><p>Compare:</p><pre>Accuracy: 0.91<br>Accuracy: 0.87<br>Accuracy: 0.84</pre><p>with:</p><pre>Model: anomaly-detector-v4<br>Dataset: Production<br>Metric: Image-level AUROC</pre><pre>Previous week: 0.91<br>Current week:  0.84<br>Change:       -7.7 percentage points</pre><pre>Deployment:<br>- Version: v4.2<br>- Date: 2026-08-12<br>- Preprocessing: resize=336</pre><p>The second representation gives the model a much stronger basis for reasoning.</p><h3>5. A Useful Mental Model: Context as a Data Pipeline</h3><p>Machine learning engineers already understand pipelines.</p><p>We can think about context in exactly the same way.</p><p>A conventional ML pipeline might be:</p><pre>Raw Data<br> ↓<br>Cleaning<br> ↓<br>Feature Extraction<br> ↓<br>Transformation<br> ↓<br>Model<br> ↓<br>Prediction</pre><p>An agentic context pipeline can be:</p><pre>Raw Information<br> ↓<br>Retrieval<br> ↓<br>Filtering<br> ↓<br>Ranking<br> ↓<br>Transformation<br> ↓<br>Compression<br> ↓<br>Context Assembly<br> ↓<br>LLM<br> ↓<br>Action<br> ↓<br>New Observation<br> ↓<br>Context Update</pre><p>This is a powerful way to think about agent design.</p><p>The question becomes:</p><blockquote><em>“What is the data pipeline that produces the model’s context?”</em></blockquote><p>Once you think this way, many familiar ML concepts become directly applicable.</p><h3>6. Step 1 — Define the Agent’s Objective</h3><p>Before designing retrieval or memory, define what the agent is trying to accomplish.</p><p>Consider an ML debugging agent.</p><p>Its objective might be:</p><blockquote><em>Identify the most likely cause of a production model’s performance degradation and recommend the next diagnostic experiment.</em></blockquote><p>This is much better than:</p><blockquote><em>“Analyze the model.”</em></blockquote><p>The objective determines what context is useful.</p><p>For example:</p><pre>Objective:<br>Diagnose production degradation</pre><p>Relevant context:</p><ul><li>Current metrics</li><li>Historical metrics</li><li>Dataset distribution</li><li>Deployment changes</li><li>Model versions</li><li>Recent code changes</li><li>Error examples</li></ul><p>Less relevant context:</p><ul><li>Entire company documentation</li><li>Unrelated models</li><li>Old project meeting notes</li></ul><p>Context engineering therefore starts with <strong>task definition</strong>.</p><h3>7. Step 2 — Identify the Context Sources</h3><p>Next, identify where useful information lives.</p><p>For our debugging agent:</p><pre>                  ML Debugging Agent<br>                          │<br>        ┌─────────────────┼─────────────────┐<br>        ↓                 ↓                 ↓<br>   Metrics DB        Git Repository      Experiment DB<br>        │                 │                 │<br>        ↓                 ↓                 ↓<br>   Performance         Code changes       Experiments<br>        │                 │                 │<br>        └─────────────────┼─────────────────┘<br>                          ↓<br>                       Context</pre><p>Other common context sources include:</p><h3>Documents</h3><ul><li>PDFs</li><li>Wikis</li><li>Technical documentation</li><li>Research papers</li><li>Design documents</li></ul><h3>Databases</h3><ul><li>SQL databases</li><li>NoSQL databases</li><li>Feature stores</li><li>Experiment tracking systems</li></ul><h3>Tools</h3><ul><li>Search engines</li><li>APIs</li><li>Python execution</li><li>Kubernetes</li><li>Cloud services</li><li>Monitoring systems</li></ul><h3>Memory</h3><ul><li>Previous conversations</li><li>Previous decisions</li><li>User preferences</li><li>Long-running task state</li></ul><h3>Environment</h3><ul><li>Current time</li><li>Current deployment</li><li>Current repository branch</li><li>Current system status</li></ul><p>The important insight is:</p><blockquote><strong><em>Context is not synonymous with documents.</em></strong></blockquote><p>A database query can be context.</p><p>A tool result can be context.</p><p>A previous action can be context.</p><p>Even the current environment can be context.</p><h3>8. Step 3 — Retrieve Only What Matters</h3><p>Now we reach one of the most important components: retrieval.</p><p>Suppose our agent needs information about an anomaly detection model.</p><p>A naïve RAG system might do:</p><pre>Question<br> ↓<br>Embedding<br> ↓<br>Vector DB<br> ↓<br>Top 10 chunks<br> ↓<br>LLM</pre><p>This works surprisingly well for simple applications.</p><p>But agents often need more sophisticated retrieval.</p><p>Consider the question:</p><blockquote><em>“What changed between the last successful deployment and the current deployment?”</em></blockquote><p>A semantic vector search might retrieve documentation about anomaly detection.</p><p>But the correct retrieval strategy should probably be:</p><pre>1. Find current deployment<br>2. Find previous deployment<br>3. Compare configurations<br>4. Retrieve associated code changes<br>5. Retrieve metric changes</pre><p>This is <strong>task-aware retrieval</strong>.</p><p>The agent isn’t merely asking:</p><blockquote><em>“Which documents are semantically similar?”</em></blockquote><p>It is asking:</p><blockquote><em>“What information do I need to solve this particular problem?”</em></blockquote><h3>9. Step 4 — Use Structured Context</h3><p>One of the easiest improvements you can make is to structure tool outputs.</p><p>Bad:</p><pre>The deployment happened recently and the model seems<br>to have lower performance and there were some preprocessing<br>changes and the new version uses 336 resolution...</pre><p>Better:</p><pre>{<br>  &quot;model&quot;: &quot;anomaly-detector-v4&quot;,<br>  &quot;deployment&quot;: &quot;v4.2&quot;,<br>  &quot;deployment_date&quot;: &quot;2026-08-12&quot;,<br>  &quot;image_size&quot;: 336,<br>  &quot;previous_image_size&quot;: 224,<br>  &quot;auroc_previous&quot;: 0.91,<br>  &quot;auroc_current&quot;: 0.84<br>}</pre><p>Why is this better?</p><p>Because structured information reduces ambiguity.</p><p>It also allows the agent to reason over explicit relationships.</p><p>For example:</p><pre>image_size:<br>224 → 336</pre><pre>AUROC:<br>0.91 → 0.84</pre><p>Now the agent can form a hypothesis:</p><blockquote><em>“The preprocessing change is temporally correlated with the performance degradation.”</em></blockquote><p>That does not prove causality — but it gives the agent a useful hypothesis to test.</p><h3>10. Step 5 — Separate Facts, Hypotheses, and Actions</h3><p>This is particularly important for agentic systems.</p><p>An agent should distinguish:</p><h3>Facts</h3><p>Things directly observed.</p><pre>Current AUROC = 0.84<br>Previous AUROC = 0.91<br>Image resolution changed from 224 to 336</pre><h3>Hypotheses</h3><p>Things inferred.</p><pre>Hypothesis:<br>The resolution change may have caused distribution mismatch.</pre><h3>Actions</h3><p>Things the agent has done or plans to do.</p><pre>Action:<br>Evaluate v4.2 on the previous preprocessing configuration.</pre><p>You can represent the state as:</p><pre>{<br>  &quot;facts&quot;: [<br>    &quot;AUROC dropped from 0.91 to 0.84&quot;,<br>    &quot;Image resolution changed from 224 to 336&quot;<br>  ],<br>  &quot;hypotheses&quot;: [<br>    {<br>      &quot;claim&quot;: &quot;Resolution change caused degradation&quot;,<br>      &quot;confidence&quot;: 0.65<br>    }<br>  ],<br>  &quot;actions_completed&quot;: [<br>    &quot;Compared deployment configurations&quot;<br>  ],<br>  &quot;next_action&quot;: &quot;Run controlled preprocessing experiment&quot;<br>}</pre><p>This is much more robust than allowing everything to accumulate in an unstructured conversation history.</p><h3>11. Step 6 — Compress Context</h3><p>Eventually, context becomes too large.</p><p>This is where context compression becomes important.</p><p>Suppose an agent performed 30 tool calls.</p><p>Instead of keeping every response, we might maintain a running summary:</p><pre>Investigation Summary</pre><pre>Objective:<br>Diagnose production AUROC degradation.</pre><pre>Observed:<br>- AUROC decreased 0.91 → 0.84.<br>- Deployment v4.2 introduced 336px preprocessing.<br>- Model weights unchanged.<br>- Data volume unchanged.</pre><pre>Ruled out:<br>- Model checkpoint change.<br>- Infrastructure failure.</pre><pre>Current hypothesis:<br>Preprocessing change may be responsible.</pre><pre>Next experiment:<br>Evaluate v4.2 using 224px preprocessing.</pre><p>The agent no longer needs 30 raw tool outputs.</p><p>It needs the <strong>information extracted from those outputs</strong>.</p><p>This is analogous to feature engineering.</p><p>Instead of feeding raw data directly into a model, we transform it into a representation that preserves useful information.</p><h3>12. Step 7 — Give the Agent a Working Memory</h3><p>A useful agent architecture separates different kinds of memory.</p><p>One practical design is:</p><pre>                 Agent Memory<br>                      │<br>       ┌──────────────┼──────────────┐<br>       ↓              ↓              ↓<br>  Working Memory   Long-Term      External<br>                   Memory          Knowledge<br>       │              │              │<br>       ↓              ↓              ↓<br> Current task     Past decisions   Documents<br> Current facts    User preferences Databases<br> Hypotheses       Past results     APIs</pre><h3>Working memory</h3><p>Contains information needed for the current task.</p><h3>Long-term memory</h3><p>Contains useful information that persists between tasks.</p><h3>External knowledge</h3><p>Information retrieved from external systems.</p><p>This distinction prevents a common mistake:</p><blockquote><em>Putting everything into one giant memory store.</em></blockquote><p>Not everything deserves permanent memory.</p><h3>13. Step 8 — Let the Agent Decide What Context It Needs</h3><p>This is where context engineering becomes genuinely <strong>agentic</strong>.</p><p>A static RAG pipeline looks like:</p><pre>Question<br> ↓<br>Retrieve<br> ↓<br>LLM<br> ↓<br>Answer</pre><p>An agentic context system can look like:</p><pre>Question<br> ↓<br>LLM<br> ↓<br>&quot;What information am I missing?&quot;<br> ↓<br>Retrieve<br> ↓<br>Observe<br> ↓<br>&quot;What else do I need?&quot;<br> ↓<br>Tool call<br> ↓<br>Observe<br> ↓<br>Update hypothesis<br> ↓<br>Retrieve again<br> ↓<br>Answer</pre><p>The agent is now actively managing its context.</p><p>For example:</p><blockquote><em>User: “Why did the model degrade?”</em></blockquote><p>Agent:</p><pre>I need:<br>1. Current metrics<br>2. Historical metrics<br>3. Recent deployments</pre><p>After retrieving those:</p><pre>I see a preprocessing change.</pre><pre>I now need:<br>4. Code/config diff<br>5. Evaluation by preprocessing version</pre><p>After retrieving those:</p><pre>The degradation occurs only on the new preprocessing path.</pre><pre>Hypothesis strengthened.</pre><p>This is very different from simply retrieving the top five documents.</p><h3>14. A Concrete Example: ML Debugging Agent</h3><p>Let’s put everything together.</p><p>Suppose you build an agent for an industrial visual inspection system.</p><p>The system detects cosmetic defects on manufactured components.</p><p>Your production metric suddenly changes:</p><pre>Image-level AUROC</pre><pre>Monday: 0.94<br>Tuesday: 0.93<br>Wednesday: 0.92<br>Thursday: 0.85</pre><p>A human engineer might investigate:</p><ol><li>Did the model change?</li><li>Did the data change?</li><li>Did preprocessing change?</li><li>Did camera configuration change?</li><li>Did labeling change?</li><li>Did production conditions change?</li></ol><p>We can encode this investigation into an agent.</p><h3>Initial context</h3><pre>Task:<br>Diagnose the AUROC degradation.</pre><pre>Current metric:<br>0.85</pre><pre>Previous metric:<br>0.92</pre><p>The agent determines that this is insufficient.</p><h3>Tool call 1: deployment system</h3><pre>Current model:<br>v4.2</pre><pre>Previous model:<br>v4.1</pre><p>Now it asks:</p><blockquote><em>Did model weights change?</em></blockquote><h3>Tool call 2: model registry</h3><pre>Weights:<br>v4.1 == v4.2</pre><p>The model itself did not change.</p><p>Next hypothesis:</p><blockquote><em>Maybe preprocessing changed.</em></blockquote><h3>Tool call 3: configuration service</h3><pre>Resize:<br>224 → 336</pre><pre>Normalization:<br>unchanged</pre><p>Now the agent has a strong candidate.</p><p>But it should not immediately conclude causality.</p><p>Instead:</p><h3>Tool call 4: evaluation service</h3><pre>v4.2 + 224px:<br>AUROC = 0.93</pre><pre>v4.2 + 336px:<br>AUROC = 0.85</pre><p>Now the evidence is much stronger.</p><p>The agent can produce:</p><pre>Finding:<br>The performance degradation is strongly associated with<br>the preprocessing change from 224px to 336px.</pre><pre>Evidence:<br>- Model weights unchanged.<br>- Deployment introduced 336px preprocessing.<br>- 224px evaluation restores AUROC to 0.93.<br>- 336px evaluation produces AUROC of 0.85.</pre><pre>Recommendation:<br>Roll back preprocessing to 224px while investigating<br>why the new preprocessing configuration causes degradation.</pre><p>Notice what made this possible.</p><p>It wasn’t simply a better prompt.</p><p>The agent had:</p><ul><li>Relevant context</li><li>Structured context</li><li>Tool access</li><li>Working memory</li><li>Hypothesis tracking</li><li>Iterative retrieval</li><li>Evidence-based decision making</li></ul><p>That is agentic context engineering in practice.</p><h3>15. Context Engineering and RAG</h3><p>If you already understand RAG, think of agentic context engineering as a broader generalization.</p><p>Traditional RAG:</p><pre>Query<br> ↓<br>Retriever<br> ↓<br>Documents<br> ↓<br>LLM</pre><p>Agentic context engineering:</p><pre>Goal<br> ↓<br>Agent<br> ↓<br>Determine missing context<br> ↓<br>Retrieve / Query / Execute<br> ↓<br>Evaluate results<br> ↓<br>Update state<br> ↓<br>Retrieve again<br> ↓<br>Compress<br> ↓<br>Assemble context<br> ↓<br>LLM<br> ↓<br>Action</pre><p>RAG is therefore one <strong>component</strong> of context engineering.</p><p>Other components include:</p><ul><li>Query planning</li><li>Tool selection</li><li>Context filtering</li><li>Memory</li><li>State management</li><li>Summarization</li><li>Context compression</li><li>Structured representations</li><li>Observation processing</li><li>Temporal state</li><li>Error recovery</li></ul><h3>16. Context Engineering Is Similar to Feature Engineering</h3><p>This analogy is especially useful for ML engineers.</p><p>In classical machine learning:</p><pre>Raw data<br> ↓<br>Feature engineering<br> ↓<br>Feature selection<br> ↓<br>Model<br> ↓<br>Prediction</pre><p>For an agent:</p><pre>Raw information<br> ↓<br>Context retrieval<br> ↓<br>Context filtering<br> ↓<br>Context transformation<br> ↓<br>Context selection<br> ↓<br>LLM<br> ↓<br>Decision</pre><p>The analogy is:</p><p>Classical MLAgentic AIRaw dataRaw informationFeaturesContextFeature engineeringContext engineeringFeature selectionContext selectionFeature storeMemory / knowledge storeModelLLMPredictionAgent actionFeedbackTool/environment observations</p><p>This suggests an important lesson:</p><blockquote><strong><em>Context should be treated as an engineered representation, not as a pile of text.</em></strong></blockquote><h3>17. Evaluating Context Quality</h3><p>One of the biggest challenges is evaluation.</p><p>A common mistake is to evaluate only the final answer.</p><p>But an agent can fail long before the final answer.</p><p>Consider this chain:</p><pre>Bad retrieval<br>     ↓<br>Bad context<br>     ↓<br>Bad reasoning<br>     ↓<br>Bad action<br>     ↓<br>Bad answer</pre><p>We should therefore evaluate multiple layers.</p><h3>Retrieval quality</h3><p>Did we retrieve the right information?</p><p>Metrics might include:</p><ul><li>Recall@K</li><li>Precision@K</li><li>MRR</li><li>NDCG</li></ul><h3>Context quality</h3><p>Was the information:</p><ul><li>Relevant?</li><li>Current?</li><li>Complete?</li><li>Consistent?</li><li>Correctly structured?</li></ul><h3>Reasoning quality</h3><p>Did the agent form a reasonable hypothesis?</p><h3>Action quality</h3><p>Did it select the correct tool or experiment?</p><h3>Final task success</h3><p>Did the agent actually solve the problem?</p><p>This gives us a much richer evaluation framework:</p><pre>Retrieval<br>   ↓<br>Context<br>   ↓<br>Reasoning<br>   ↓<br>Action<br>   ↓<br>Outcome</pre><h3>18. Common Mistakes</h3><h3>Mistake 1: “Just put everything in the prompt”</h3><p>More tokens are not automatically better.</p><p>Context has a cost.</p><p>Large amounts of irrelevant information can make it harder for the model to identify what matters.</p><h3>Mistake 2: Treating vector search as the entire solution</h3><p>Vector search is useful, but not every question is semantic.</p><p>For example:</p><blockquote><em>“What was the deployment immediately before v4.2?”</em></blockquote><p>This is better handled by structured metadata or a database query.</p><h3>Mistake 3: Keeping infinite conversation history</h3><p>Long conversations eventually become expensive and noisy.</p><p>Instead:</p><pre>Recent details<br>+<br>Compressed historical state<br>+<br>Relevant retrieved information</pre><p>is often better.</p><h3>Mistake 4: Mixing facts with guesses</h3><p>An agent saying:</p><blockquote><em>“The preprocessing change caused the problem.”</em></blockquote><p>is very different from:</p><blockquote><em>“The preprocessing change is the leading hypothesis, based on the controlled evaluation.”</em></blockquote><p>The second statement preserves uncertainty.</p><h3>Mistake 5: Ignoring temporal context</h3><p>In production systems, <em>when</em> something happened is often as important as <em>what</em> happened.</p><p>For debugging, context should frequently include:</p><pre>timestamp<br>version<br>deployment<br>experiment<br>data snapshot<br>environment</pre><p>Otherwise, the agent can accidentally compare incompatible states.</p><h3>19. A Practical Architecture for Your First Agent</h3><p>If you are a junior ML engineer building your first agent, don’t start with a complicated multi-agent system.</p><p>Start here:</p><pre>                 ┌──────────────┐<br>                 │    User      │<br>                 └──────┬───────┘<br>                        ↓<br>                 ┌──────────────┐<br>                 │    Agent     │<br>                 └──────┬───────┘<br>                        ↓<br>               ┌─────────────────┐<br>               │ Context Manager │<br>               └───────┬─────────┘<br>                       ↓<br>          ┌────────────┼────────────┐<br>          ↓            ↓            ↓<br>       Search        Database      Tools<br>          │            │            │<br>          └────────────┼────────────┘<br>                       ↓<br>                 Context Assembly<br>                       ↓<br>                      LLM<br>                       ↓<br>                     Action<br>                       ↓<br>                   Observation<br>                       ↓<br>                 Context Update</pre><p>You can implement a simple version using:</p><ul><li>Python</li><li>An LLM API</li><li>A vector database</li><li>SQL</li><li>A few Python tools</li><li>A state object</li></ul><p>The key component is not the framework.</p><p>It is the <strong>state and context design</strong>.</p><h3>20. Where Agentic Context Engineering Is Going</h3><p>As agents become more capable, context management will become increasingly important.</p><p>Future systems will likely have sophisticated mechanisms for:</p><ul><li>Dynamic memory</li><li>Personalized context</li><li>Hierarchical summaries</li><li>Tool-result compression</li><li>Context-aware retrieval</li><li>Long-term task state</li><li>Environment state</li><li>Automatic context evaluation</li><li>Learned retrieval strategies</li></ul><p>We may eventually think about an agent less as:</p><pre>LLM + Tools</pre><p>and more as:</p><pre>LLM<br>+<br>Memory<br>+<br>Retrieval<br>+<br>State<br>+<br>Tools<br>+<br>Environment<br>+<br>Context Management</pre><p>The LLM remains the reasoning engine, but context engineering determines what the reasoning engine can actually see.</p><h3>Conclusion</h3><p>Agentic AI is often described as:</p><blockquote><em>“An LLM that can use tools.”</em></blockquote><p>That definition is useful, but incomplete.</p><p>A more useful mental model is:</p><blockquote><strong><em>An agent is a system that continuously constructs the context it needs to accomplish a goal.</em></strong></blockquote><p>That makes context engineering a first-class engineering discipline.</p><p>The progression looks like this:</p><pre>Prompt Engineering<br>       ↓<br>RAG<br>       ↓<br>Memory<br>       ↓<br>Tool Use<br>       ↓<br>State Management<br>       ↓<br>Agentic Context Engineering</pre><p>For machine learning engineers, the concepts should feel familiar.</p><p>You already know how to:</p><ul><li>Select useful features</li><li>Build data pipelines</li><li>Handle noisy data</li><li>Monitor distributions</li><li>Evaluate models</li><li>Manage state</li><li>Design experiments</li></ul><p>Agentic context engineering applies many of the same principles to LLM systems.</p><p>The central idea is simple:</p><blockquote><strong><em>Don’t ask only, “What should I tell the model?” Ask, “What does the model need to know right now to make the next correct decision?”</em></strong></blockquote><p>That shift — from designing prompts to designing information flows — is one of the most important changes in modern agent engineering.</p><p>And for anyone building production AI systems, it may ultimately matter more than choosing between the latest LLM models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa3647ee056c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Terminal: Mastering Claude Code for Agentic AI Workflows]]></title>
            <link>https://medium.com/@xiaxiami/beyond-the-terminal-mastering-claude-code-for-agentic-ai-workflows-2e73eedd64d9?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e73eedd64d9</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 05:31:46 GMT</pubDate>
            <atom:updated>2026-04-27T05:31:46.479Z</atom:updated>
            <content:encoded><![CDATA[<p>The era of “copy-pasting code into a chat box” is officially dead. As we move through 2026, the distinction between a “coder” and an <strong>AI Orchestrator</strong> has narrowed, thanks largely to the evolution of <strong>Claude Code</strong>.</p><p>If you’re still using Claude just for snippets, you’re using a Ferrari to drive to the mailbox. As an AI expert and contributor to the Medium engineering community, I’ve spent months stress-testing the latest Q1 2026 updates — including <strong>AutoDream</strong>, <strong>Multi-Agent Dispatch</strong>, and the redesigned <strong>Ultraplan</strong> interface.</p><p>This is your definitive guide to mastering Claude Code for high-level software and ML engineering.</p><h3>1. The Foundation: The “Agentic” Configuration</h3><p>To make Claude effective, you must stop treating it as a guest and start treating it as a resident. This begins with the CLAUDE.md file—your project’s &quot;Source of Truth.&quot; In 2026, Claude Code uses this file as an <strong>active memory buffer</strong> rather than just a static style guide.</p><h3>Pro-Level Example for an ML Repo:</h3><p>Markdown</p><pre># CLAUDE.md - Research Alpha Project</pre><pre>## Tech Stack<br>- Python 3.12, PyTorch 2.6, Hydra for config.<br>- Ruff for linting, Pytest for testing.</pre><pre>## Core Architecture<br>- All models reside in `src/models/`.<br>- We use the Strategy Pattern for different optimization schedulers.</pre><pre>## Workflow Rules<br>- **Memory:** If you fix a CUDA memory leak, log the pattern in `.claude/memory.json`.<br>- **Testing:** Always run `pytest tests/unit` before committing.<br>- **LaTeX Standards:** Document all loss functions using LaTeX in docstrings.<br>  Example: $\mathcal{L}_{total} = \alpha \mathcal{L}_{MSE} + \beta \mathcal{L}_{KL}$</pre><h3>2. Skill: Autonomous Refactoring with “AutoDream”</h3><p>One of the most powerful 2026 features is <strong>AutoDream</strong> (/dream). Unlike standard refactoring, AutoDream allows Claude to &quot;simulate&quot; the execution path and prune its own internal memory before writing a single line.</p><h3>Scenario: The “Memory Sleep Cycle”</h3><p>As sessions grow, the .claude/memory/ directory can become bloated with &quot;context drift&quot; (e.g., if you switched from Auth0 to Clerk mid-project).</p><ul><li><strong>Command:</strong> /dream --consolidate auth</li><li><strong>What happens:</strong> Claude scans all memory files, identifies the stale Auth0 references, and updates your project’s “Active Architecture” index.</li></ul><h3>Scenario: Modularizing Messy Scripts</h3><p>If you have a 1,200-line train.py, use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ajb9LhLAnno8e7EMM_5bA.png" /></figure><p>Claude creates a task tree, checks if the new modular imports break dependencies, and executes a dry-run of the training loop to ensure the loss curve still initializes.</p><h3>3. Skill: Multi-Agent Orchestration (/agents)</h3><p>The most significant shift in 2026 is moving beyond a single terminal session. Using the .claude/agents/ configuration, you can trigger <strong>parallel specialized agents</strong> to work on separate parts of a feature simultaneously.</p><h3>The “Feature Sprint” Workflow</h3><p>Instead of one Claude building a whole feature, define a team in your project root.</p><p><strong>Subagent Config (</strong><strong>.claude/agents/qa-engineer.md):</strong></p><p>Markdown</p><pre>---<br>name: qa-engineer<br>description: Strictly for writing tests and verifying edge cases.<br>model: claude-sonnet-4-6<br>isolation: worktree<br>---<br>Goal: Achieve 90%+ coverage. If you find a bug, open a /issue; do NOT fix it.</pre><p><strong>The Lead Trigger:</strong></p><blockquote><em>“Lead, coordinate </em><em>frontend-dev and </em><em>qa-engineer. Implement the new Dashboard Analytics. Use </em><em>/ultraplan to show me the architecture first.&quot;</em></blockquote><p>The <strong>Lead Agent</strong> creates a task list, the <strong>Frontend Agent</strong> builds components, and the <strong>QA Agent</strong> (in an isolated git worktree) writes tests against the proposed API spec in parallel.</p><h3>4. Skill: Headless Debugging via “Dispatch” &amp; “Remote Control”</h3><p>Engineering happens everywhere. <strong>Claude Dispatch</strong> allows you to trigger tasks programmatically via API or CI/CD, while <strong>Remote Control</strong> lets you manage them from any device.</p><h3>The “Fix-on-Fail” Pipeline</h3><p>Imagine your GitHub Action fails at 3 AM. Your pipeline triggers Claude:</p><p>Bash</p><pre>claude dispatch --task &quot;Investigate the failure in integration_tests.py. Fix the race condition and submit a PR.&quot; --headless</pre><p><strong>Why this is a game-changer:</strong></p><ul><li><strong>Remote Control:</strong> You can open your Claude app on your phone while commuting and see the real-time <strong>Channels</strong> feed showing the terminal output as Claude hunts the bug.</li><li><strong>Computer Use:</strong> If the bug is UI-related, Claude spins up a headless browser, takes screenshots, and identifies CSS or z-index errors automatically.</li></ul><h3>5. The “Ultraplan” Interface</h3><p>For complex refactors, the terminal can be limiting. <strong>Ultraplan</strong> bridges the CLI and the Web.</p><ul><li><strong>Command:</strong> /ultraplan &quot;Migrate the data persistence layer to support multi-region failover.&quot;</li><li><strong>The Interface:</strong> Claude spawns an interactive browser window showing a rich UI of the proposed changes.</li><li><strong>The Power:</strong> You can inline-comment on specific logic blocks and then hit “Teleport to Terminal” to execute the approved plan locally.</li></ul><h3>6. Essential Claude Code Commands (2026 Edition)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPzBUxAfcWexOEqme2dhsQ.png" /></figure><h3>7. The Expert Workflow: A 10-Minute Feature</h3><p>To wrap up, here is how a master orchestrator implements a feature in record time:</p><ul><li><strong>Initialize Context:</strong> claude &quot;Explain the current auth flow in this repo.&quot;</li><li><strong>Define Goal:</strong> claude /ultraplan &quot;Add Google OAuth2 support using existing FastAPI middleware.&quot;</li><li><strong>Approve &amp; Execute:</strong> Review the interactive plan. Claude writes the logic, updates .env.example, and creates migration scripts.</li><li><strong>Verify:</strong> claude &quot;Write a README section for the flow and run the test suite via /monitor.&quot;</li><li><strong>Commit:</strong> claude &quot;Review my changes and commit them with a conventional commit message.&quot;</li></ul><h3>Final Thought</h3><p>In 2026, <strong>Claude Code is no longer a tool; it’s a teammate.</strong> The real skill isn’t just knowing the syntax — it’s knowing how to provide the right context and when to let the agentic features take the wheel. Stop being the one who writes every line; be the one who configures the agents and reviews the <strong>Ultraplan</strong>.</p><p><em>What’s the most complex refactor you’ve ever handed off to an AI agent, and did it handle the edge cases? Let’s discuss in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e73eedd64d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Prompt: The Rise of Automatic Prompt Engineering with DSPy, GEPA, and TextGrad]]></title>
            <link>https://medium.com/@xiaxiami/beyond-the-prompt-the-rise-of-automatic-prompt-engineering-with-dspy-gepa-and-textgrad-3292907c06f8?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/3292907c06f8</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 19:36:18 GMT</pubDate>
            <atom:updated>2026-04-25T19:36:18.452Z</atom:updated>
            <content:encoded><![CDATA[<p>The era of “vibes-based” prompting is coming to an end. For the past few years, AI engineers have spent countless hours manually tweaking adjectives, adding “think step-by-step,” or begging models to “be concise.” We treated prompts like magic spells rather than what they actually are: <strong>volatile software parameters.</strong></p><p>As we move into 2026, the industry is pivoting toward <strong>Prompt Science</strong>. Instead of humans writing prompts, we are building systems that <em>program</em> them.</p><p>In this deep dive, we’ll explore the frameworks leading this revolution — <strong>DSPy</strong>, <strong>GEPA</strong>, and <strong>TextGrad</strong> — and how they are turning prompt engineering into a rigorous optimization problem.</p><h3>1. DSPy: Programming, Not Prompting</h3><p>If you’re still hard-coding long strings of instructions into your Python scripts, you’re doing it the old way. <strong>DSPy (Declarative Self-improving Language Programs)</strong>, developed by the Stanford NLP group, is the framework that changed the paradigm.</p><h3>The Core Concept: Signatures and Teleprompters</h3><p>DSPy separates the <strong>logic</strong> of your program from the <strong>textual representation</strong> of the prompt.</p><ul><li><strong>Signatures:</strong> Instead of writing a prompt, you define a task (e.g., question -&gt; answer).</li><li><strong>Modules:</strong> You use pre-defined layers like ChainOfThought or ProgramOfThought.</li><li><strong>Teleprompters (Optimizers):</strong> This is the magic. A teleprompter takes your code, a few examples, and a metric, then iterates to find the best possible prompt and few-shot examples to maximize your score.</li></ul><p>The result? If you switch from GPT-4o to Llama-3, you don’t rewrite your prompts. You simply re-run the optimizer.</p><h4>Three Real-World DSPy Examples:</h4><ul><li><strong>Multi-hop Research (STORM):</strong> In systems designed to write Wikipedia-style articles from scratch, DSPy is used to optimize the “search query” phase. It learns which specific query formats result in the highest-quality citations, iteratively refining the search strategy based on the final article’s completeness.</li><li><strong>Precision Medical Extraction:</strong> In a pipeline processing PubMed abstracts, DSPy was used to optimize for two conflicting metrics: <strong>factual correctness</strong> and <strong>brevity</strong>. By using a MIPROv2 optimizer, the system automatically found a few-shot &quot;demonstration&quot; set that penalized verbosity while maintaining a 98% accuracy on clinical entities.</li><li><strong>Industrial Entity Resolution:</strong> For e-commerce giants managing messy SKU data, DSPy optimizes the “normalization” prompt. The system identifies that certain attributes (like “material”) are frequently missed and automatically injects specific “hard cases” into the few-shot prompt to teach the model how to resolve them.</li></ul><h3>2. GEPA: The Reflective Optimizer</h3><p>While DSPy provides the structure, <strong>GEPA (Genetic-Pareto)</strong> introduces a more sophisticated way to evolve instructions. Introduced as a high-efficiency alternative to standard reinforcement learning, GEPA treats prompts as evolving organisms.</p><h3>How it Works: Reflection-Driven Evolution</h3><p>Standard optimizers often rely on a single numerical score. GEPA goes deeper by using <strong>Natural Language Reflection</strong>.</p><ol><li><strong>Trajectory Sampling:</strong> The model attempts a task several times.</li><li><strong>Reflection:</strong> An “Analyzer” model looks at the failures and writes a textual critique (e.g., <em>“The model failed because it didn’t verify the legal jurisdiction before citing the law”</em>).</li><li><strong>Pareto Frontier:</strong> Instead of keeping just one “best” prompt, GEPA maintains a diverse pool of prompts that excel in different areas (e.g., one that is great at logic, one that is great at formatting).</li></ol><p>GEPA is particularly powerful for <strong>Agentic workflows</strong> where the “correct” answer isn’t always binary, and the model needs to understand <em>why</em> a multi-step plan failed.</p><h4>Three Real-World GEPA Examples:</h4><ul><li><strong>Niche Mathematical Reasoning:</strong> When solving complex logic puzzles — such as finding palindromes across multiple number bases — GEPA analyzes the model’s failed Python code. It generates a “Reflection” (e.g., <em>“The model fails to account for base-8 digit constraints”</em>) and rewrites the prompt to include a pre-computed logical plan for those specific constraints.</li><li><strong>Adversarial Medical Safety:</strong> In the “CounselBench” benchmark, models often fall for medical myths (e.g., presupposing a fake cure). GEPA was used to optimize safety prompts by identifying exactly which “rebuttal logic” worked best to debunk myths without causing the model to become overly cautious and refuse valid medical questions.</li><li><strong>Financial SEC Filing Analysis:</strong> For agents analyzing 10-K filings, GEPA maintains a <strong>Pareto Frontier</strong> of prompts. One prompt might be optimized for “speed” (short context), while another is optimized for “thoroughness” (exhaustive risk extraction). The system allows the user to toggle between these optimized versions depending on the budget.</li></ul><h3>3. TextGrad: Backpropagation for Words</h3><p>If DSPy is the framework and GEPA is the evolution, <strong>TextGrad</strong> is the calculus.</p><p>TextGrad treats the entire AI pipeline like a neural network. In a neural network, we use gradients to update weights. In TextGrad, we use <strong>textual feedback</strong> as a gradient to update prompts.</p><p>When a system produces an incorrect output, TextGrad “backpropagates” the error through the system. It identifies exactly which part of the prompt caused the hallucination and suggests a surgical edit. This is far more efficient than a total rewrite, as it preserves the parts of the prompt that are already working.</p><h4>Three TextGrad Examples:</h4><ul><li><strong>Example 1: Competitive Coding.</strong> When code fails a test case, TextGrad uses the error message to surgically update the prompt’s logic instructions.</li><li><strong>Example 2: Drug Discovery.</strong> Researchers use TextGrad to refine the textual descriptions of molecules based on their simulated “druglikeness” scores.</li><li><strong>Example 3: Radiation Treatment Planning.</strong> In oncology, TextGrad tunes the instructions for treatment-plan generators to optimize dosage while minimizing side effects.</li></ul><h3>4. Comparing the SOTA Methods</h3><p>Choosing the right optimizer depends on your specific use case and “token budget.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZnryFW-OoN4sSrwEXjMQw.png" /></figure><h3>5. Why Sample Efficiency is the New “Gold Standard”</h3><p>In the early days of Auto-Prompting, methods like <strong>APE (Automatic Prompt Engineer)</strong> required thousands of test runs to find a good instruction. In a production environment, that’s too expensive.</p><p>The 2026 generation of optimizers — led by GEPA — can achieve state-of-the-art results with <strong>35x fewer model calls </strong>than traditional reinforcement learning. By using “Reflection” instead of “Trial and Error,” we are making prompt optimization accessible to startups, not just tech giants.</p><h3>6. The Verdict: How to Start</h3><p>If you are building a production-grade AI application today, stop writing prompts in a vacuum.</p><ol><li><strong>Define a Metric:</strong> You cannot optimize what you cannot measure. Create a small “Golden Dataset” of 20–50 examples.</li><li><strong>Adopt a Framework:</strong> Use <strong>DSPy</strong> to structure your code. It’s the closest thing we have to an “Industry Standard.”</li><li><strong>Use an Optimizer:</strong> Start with a simple Bayesian optimizer like <strong>MIPROv2</strong>. If your task requires deep reasoning, look into implementing a <strong>GEPA</strong> loop.</li></ol><p>The goal isn’t to write the perfect prompt. The goal is to build a system that <em>finds</em> the perfect prompt for you.</p><p><em>Enjoyed this deep dive? Follow for more insights on the intersection of Machine Learning and Agentic Systems.</em></p><h3>References</h3><p>Agrawal, A., et al. (2025). Decoding the Behavior of LLMs as Scientific Reasoners. <em>Proceedings of the ICLR 2026 Workshop on Post-AGI Science</em>. Cited by: 12</p><p>Khattab, O., Singhvi, A., Maheshwari, P., Zhang, Z., Santhanam, K., Vardhamanan, S., Haq, S., Sharma, A., Joshi, T. T., Moazam, H., Miller, H., Zaharia, M., &amp; Potts, C. (2023). DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines. <em>arXiv</em>. <a href="https://doi.org/10.48550/arxiv.2310.03714">https://doi.org/10.48550/arxiv.2310.03714</a> Cited by: 850</p><p>Opsahl-Ong, K., et al. (2024). MIPROv2: Multi-objective Instruction and Prompt REcovery. <em>Stanford NLP Technical Report</em>.</p><p>Pal, S., et al. (2026). Beyond the Answer: Decoding the Behavior of LLMs as Scientific Reasoners. <em>arXiv</em>. <a href="https://www.google.com/search?q=https://doi.org/10.48550/arXiv.2603.28038">https://doi.org/10.48550/arXiv.2603.28038</a></p><p>Yang, C., Wang, X., Lu, Y., Liu, H., Le, Q. V., Zhou, D., &amp; Chen, X. (2023). Large Language Models as Optimizers. <em>arXiv</em>. <a href="https://doi.org/10.48550/arXiv.2309.03409">https://doi.org/10.48550/arXiv.2309.03409</a></p><p>Yuksekgonul, M., Bianchi, F., Boen, J., Liu, S., Huang, Z., Guestrin, C., &amp; Zou, J. (2024). TextGrad: Automatic “Differentiation” via Text. <em>arXiv</em>. <a href="https://www.google.com/search?q=https://doi.org/10.48550/arxiv.2406.07496">https://doi.org/10.48550/arxiv.2406.07496</a> Cited by: 297</p><p>Zhou, Y., et al. (2022). Large Language Models are Human-Level Prompt Engineers. <em>arXiv</em>. <a href="https://www.google.com/search?q=https://doi.org/10.48550/arXiv.2211.01910">https://doi.org/10.48550/arXiv.2211.01910</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3292907c06f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VMamba: Rethinking Vision Architectures with State Space Models]]></title>
            <link>https://medium.com/@xiaxiami/vmamba-rethinking-vision-architectures-with-state-space-models-68e8bd065bc2?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/68e8bd065bc2</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 00:49:45 GMT</pubDate>
            <atom:updated>2026-01-02T00:49:45.555Z</atom:updated>
            <content:encoded><![CDATA[<p>For the past decade, Computer Vision (CV) has been dominated by two architectural giants: Convolutional Neural Networks (CNNs) and Vision Transformers (ViTs). CNNs gave us efficiency and translation invariance but struggled with long-range dependencies. Vision Transformers solved the global context problem with self-attention but at a quadratic computational cost (O(N2)), making them prohibitively expensive for high-resolution images.</p><p>VMamba (Visual Mamba) represents a paradigm shift. It adapts the <strong>State Space Model (SSM)</strong> — specifically the Selective Scan Mechanism from Mamba — to visual data. It promises the best of both worlds: the <strong>linear complexity (O(N))</strong> of CNNs and the <strong>global receptive field</strong> of ViTs.</p><p>In this deep dive, we will explore VMamba from first principles — starting with the math behind State Space Models — dissect its unique “Cross-Scan” architecture, and implement the core components in PyTorch.</p><h3>1. The Core Problem: The Quadratic Bottleneck</h3><p>To understand why VMamba exists, we must first revisit the limitation of Vision Transformers.</p><p>In a ViT, an image is split into patches. If you have an image of size H×W and patch size P, you get N=(H×W)/P^2 tokens. Self-attention requires every token to “look at” every other token.</p><p>Complexity∝N^2</p><ul><li><strong>224x224 Image:</strong> ≈196 tokens. Manageable.</li><li><strong>1024x1024 Image:</strong> ≈3136 tokens. 3136^2≈9.8 million interactions per layer.</li><li><strong>4K Image:</strong> Impossible on standard hardware.</li></ul><p>This quadratic scaling is the primary bottleneck for high-resolution tasks like medical imaging, remote sensing, and autonomous driving.</p><h3>2. Fundamentals: The State Space Model (SSM)</h3><p>To truly understand VMamba, we must first look under the hood at the engine powering it: <strong>Mamba</strong>, and its roots in Structured State Space Sequence Models (S4).</p><p>SSMs aim to be the “Holy Grail” of sequence modeling: <strong>Linear (O(N)) training speed</strong> like Transformers and <strong>Constant (O(1)) inference speed</strong> like RNNs.</p><h3>2.1 The Physical Intuition: Continuous Systems</h3><p>State Space Models originate from control theory. Imagine mapping a 1D input signal x(t) (e.g., a sequence of pixels) to an output y(t) through a latent state h(t).</p><p>In physics, we describe systems using differential equations:</p><p>h′(t)=Ah(t)+Bx(t)</p><p>y(t)=Ch(t)</p><ul><li><strong>h(t) (The State):</strong> A “summary” of the history of the input up to time t. In deep learning, this is a vector of size N.</li><li><strong>A (The Evolution Matrix):</strong> This matrix dictates how the state evolves. If designed correctly, it allows the state to “memorize” long-term history rather than forgetting it exponentially.</li><li><strong>B &amp; C:</strong> Projections that translate between the input/output dimension and the hidden state.</li></ul><h3>2.2 Discretization: Making it Computable</h3><p>Neural networks process discrete steps (token 1, token 2…), not continuous time. We must “discretize” the continuous parameters (A,B) into discrete ones (A,B) using a step size Δ (Delta). This transforms the differential equation into a recurrence (like an RNN):</p><p>ht​=A*ht−1​+B*xt​</p><p>yt​=C*ht​</p><p>During <strong>inference</strong>, this allows for incredibly fast, constant-time generation because you only need the previous state to calculate the next step.</p><h3>2.3 The Mamba Innovation: Selection Mechanism</h3><p>Standard SSMs (like S4) are <strong>Time-Invariant</strong>, meaning matrices A,B,C are fixed for every token. This is efficient (it can be computed as a convolution) but rigid — it treats every input token identically.</p><p>Mamba introduces <strong>Selectivity</strong>. It makes the parameters B,C,and Δ functions of the input xt​.</p><p>Bt​,Ct​,Δt​=Linear(xt​)</p><p>This allows the model to “selectively” remember or forget information:</p><ol><li><strong>High Δ:</strong> “Focus on this input, update the state heavily.”</li><li><strong>Low Δ:</strong> “Ignore this input (noise), keep the state as is.”</li><li><strong>Reset State:</strong> “The context has changed, clear the history.”</li></ol><p>Because this time-variance breaks the convolution trick used in S4, Mamba uses a hardware-aware <strong>Selective Scan </strong>algorithm (running in parallel on GPU SRAM) to maintain O(N) training speed.</p><h3>3. The Challenge of 2D Data</h3><p>Mamba is inherently 1D. It processes sequences causally from left to right. Images are 2D. They have spatial relationships (up, down, left, right) that are non-causal.</p><p>If you simply flatten an image into a 1D sequence (Raster Scan) and feed it to Mamba, you lose critical spatial locality. A pixel at (i,j) might be very close to (i,j+1) in the sequence, but very far from (i+1,j). Furthermore, a standard 1D scan only sees the pixels “before” it, blinding it to the context in the bottom-right of the image.</p><h3>4. The VMamba Solution: CS-SSM (Cross-Scan State Space Model)</h3><p>VMamba introduces the <strong>Cross-Scan Module (CSM)</strong> to solve the 2D directionality problem while maintaining linear complexity.</p><p>Instead of a single scan, VMamba scans the image in <strong>four directions</strong>:</p><ol><li>Top-left to Bottom-right (Standard Raster)</li><li>Bottom-right to Top-left (Reverse Raster)</li><li>Top-right to Bottom-left</li><li>Bottom-left to Top-right</li></ol><h3>4.1 How It Works</h3><p><strong>1.Input:</strong> An image feature map of size H×W×C.</p><p><strong>2. Unfold:</strong> The image is unfolded into four distinct sequences corresponding to the four scan directions.</p><p><strong>3. Parallel Processing:</strong> Each sequence is processed independently by a Selective Scan SSM (S6).</p><ul><li>Since S6 is efficient, running it 4 times is still O(N).</li></ul><p><strong>4. Merge:</strong> The four output sequences are reshaped back into H×W feature maps and merged.</p><p>This ensures that <strong>every pixel integrates information from all four directions</strong>, effectively achieving a global receptive field without the quadratic cost of attention.</p><h3>5. Architecture Deep Dive (With Code)</h3><p>Let’s dissect the components of VMamba and implement a simplified version of the Cross-Scan mechanism in PyTorch.</p><h3>5.1 The VSS Block</h3><p>The fundamental building block of VMamba is the <strong>VSS Block</strong>. It mimics the structure of a Transformer block or ConvNeXt block but replaces the Attention layer with the <strong>2D-Selective-Scan (SS2D)</strong> module.</p><p>Structure: Input -&gt; LayerNorm -&gt; Linear -&gt; Depthwise Conv -&gt; SS2D -&gt; LayerNorm -&gt; Linear -&gt; Residual -&gt; Output</p><h3>5.2 Implementing the Cross-Scan Mechanism</h3><p>We will implement the logic for unfolding an image into the 4 scan directions. <em>Note: In production, this is implemented in CUDA for speed. We will use pure PyTorch for understanding.</em></p><p>Python</p><pre>import torch<br>import torch.nn as nn<br><br>class CrossScan(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>    def forward(self, x: torch.Tensor):<br>        &quot;&quot;&quot;<br>        x: (B, C, H, W)<br>        Returns: 4 sequences representing the 4 scan directions<br>        &quot;&quot;&quot;<br>        B, C, H, W = x.shape<br>        <br>        # 1. Top-left to Bottom-right (Standard)<br>        scan_1 = x.view(B, C, -1) # Shape: (B, C, H*W)<br>        <br>        # 2. Bottom-right to Top-left (Reverse)<br>        scan_2 = torch.flip(scan_1, dims=[-1])<br>        <br>        # 3. Top-right to Bottom-left<br>        # Transpose to scan across width first<br>        x_transposed = x.transpose(2, 3) # (B, C, W, H)<br>        scan_3 = x_transposed.reshape(B, C, -1)<br>        <br>        # 4. Bottom-left to Top-right<br>        scan_4 = torch.flip(scan_3, dims=[-1])<br>        <br>        # Stack them for parallel processing in the SSM<br>        # Shape: (B, 4, C, L)<br>        return torch.stack([scan_1, scan_2, scan_3, scan_4], dim=1)<br>class CrossMerge(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>    def forward(self, scans: torch.Tensor, H: int, W: int):<br>        &quot;&quot;&quot;<br>        scans: (B, 4, C, L) - The outputs from the SSM<br>        Merges them back into an image<br>        &quot;&quot;&quot;<br>        B, K, C, L = scans.shape<br>        <br>        scan_1, scan_2, scan_3, scan_4 = scans.unbind(dim=1)<br>        <br>        # Invert the transforms done in CrossScan<br>        out_1 = scan_1.view(B, C, H, W)<br>        out_2 = torch.flip(scan_2, dims=[-1]).view(B, C, H, W)<br>        out_3 = scan_3.view(B, C, W, H).transpose(2, 3)<br>        out_4 = torch.flip(scan_4, dims=[-1]).view(B, C, W, H).transpose(2, 3)<br>        <br>        # Element-wise Summation (Standard merge strategy)<br>        return out_1 + out_2 + out_3 + out_4</pre><h3>5.3 The Full SS2D Module Logic</h3><p>The SS2D module integrates the scanning with the actual Mamba inner core.</p><p>Python</p><pre>class SS2D(nn.Module):<br>    def __init__(self, d_model, d_state=16):<br>        super().__init__()<br>        self.d_model = d_model<br>        <br>        # Projections<br>        self.in_proj = nn.Linear(d_model, 2 * d_model)<br>        self.out_proj = nn.Linear(d_model, d_model)<br>        <br>        # Scanning Modules<br>        self.cross_scan = CrossScan()<br>        self.cross_merge = CrossMerge()<br>        <br>        # Note: The actual selective scan parameters (A, B, C, dt) <br>        # would be initialized here.<br>def forward(self, x):<br>        # x shape: (B, H, W, C)<br>        B, H, W, C = x.shape<br>        x = x.permute(0, 3, 1, 2) # (B, C, H, W)<br>        <br>        # 1. Scan (Get 4 views of the image)<br>        scans = self.cross_scan(x) # (B, 4, C, L)<br>        <br>        # 2. Process with SSM<br>        # Flatten batch and scan dimensions to parallelize: (B*4, C, L)<br>        scans_flat = scans.view(B * 4, C, -1)<br>        <br>        # --- SSM Core Operation ---<br>        # In a real implementation, this calls the selective_scan_cuda kernel<br>        # y = selective_scan(scans_flat, ...)<br>        y_flat = scans_flat # Placeholder pass-through<br>        # --------------------------<br>        <br>        # Reshape back<br>        y = y_flat.view(B, 4, C, -1)<br>        <br>        # 3. Merge (Combine 4 views back to image)<br>        out = self.cross_merge(y, H, W) # (B, C, H, W)<br>        <br>        # 4. Final Projection<br>        out = out.permute(0, 2, 3, 1) # (B, H, W, C)<br>        return self.out_proj(out)</pre><h3>6. Performance &amp; Benchmarks</h3><p>VMamba is not just theoretical; it delivers state-of-the-art results with significantly lower resource usage.</p><h3>6.1 ImageNet Classification</h3><ul><li><strong>VMamba-Tiny</strong> achieves <strong>82.2%</strong> Top-1 accuracy.</li><li>This is comparable to <strong>ConvNeXt-T</strong> (82.1%) and <strong>Swin-T</strong> (81.3%).</li><li><strong>Key Advantage:</strong> It uses <strong>75% less FLOPs</strong> than Swin Transformer for similar performance.</li></ul><h3>6.2 Object Detection (COCO)</h3><ul><li>At high resolutions (1280×800), VMamba outperforms ResNet-50 and Swin-T.</li><li>The linear complexity allows it to handle the large feature maps required for detecting small objects without the memory explosion typical of Transformers.</li></ul><h3>7. Applications and Future Directions</h3><p>The implications of VMamba extend far beyond standard benchmarks.</p><h3>7.1 Medical Imaging</h3><p>Medical scans (MRI, CT) are massive (e.g., 4096×4096).</p><ul><li><strong>Current State:</strong> We downsample images to 256×256 to fit them into ViTs, losing diagnostic details.</li><li><strong>VMamba:</strong> Can process the <strong>full resolution</strong> image. “U-Mamba,” a recent adaptation, integrates VMamba blocks into U-Net for biomedical segmentation, achieving SOTA with a lower memory footprint.</li></ul><h3>7.2 Remote Sensing</h3><p>Satellite imagery is gigapixel-scale. VMamba allows for sliding windows that are significantly larger than traditional CNNs, capturing broader geographical context (e.g., tracing river systems or road networks spanning hundreds of miles).</p><h3>7.3 Video Understanding</h3><p>Video is 3D data (T×H×W). While VMamba focuses on 2D, the SSM principle naturally extends to the temporal dimension. <strong>VideoMamba</strong> adapts the architecture to treat time as just another scan dimension, enabling efficient long-video processing.</p><h3>8. Conclusion</h3><p>VMamba proves that <strong>Attention is Not All You Need</strong>.</p><p>By revisiting the fundamentals of sequence modeling and adapting the State Space Model to 2D domains via the Cross-Scan Mechanism, VMamba offers a compelling alternative to Vision Transformers. It retains the global modeling capabilities that made Transformers famous but discards the quadratic anchor weighing them down.</p><p>For the ML Engineer, VMamba represents a new tool in the arsenal — one that is particularly potent when compute is constrained or input resolution is high.</p><p><strong>References:</strong></p><ul><li>Liu et al., “VMamba: Visual State Space Model”, 2024.</li><li>Gu &amp; Dao, “Mamba: Linear-Time Sequence Modeling with Selective State Spaces”, 2023.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68e8bd065bc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Prompt to Product: A Comprehensive Guide to Building LLM Applications with LangChain]]></title>
            <link>https://medium.com/@xiaxiami/from-prompt-to-product-a-comprehensive-guide-to-building-llm-applications-with-langchain-d576ab53bb3f?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/d576ab53bb3f</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 00:49:58 GMT</pubDate>
            <atom:updated>2025-12-31T00:49:58.298Z</atom:updated>
            <content:encoded><![CDATA[<p>The release of ChatGPT was an iPhone moment for Artificial Intelligence. Suddenly, the power of Large Language Models (LLMs) was accessible to everyone.</p><p>But for developers, the initial excitement quickly turned into a practical engineering challenge. Playing in ChatGPT’s web interface is one thing; building a robust, reliable application powering a business process is entirely different.</p><p>Raw LLMs have significant limitations:</p><ol><li><strong>They are disconnected:</strong> They don’t know about your private data, documents, or real-time information.</li><li><strong>They are stateless:</strong> They don’t remember past conversations unless you feed the history back to them every time.</li><li><strong>They lack agency:</strong> They can output text, but they cannot natively execute code, browse the web, or interact with APIs.</li></ol><p>Enter <strong>LangChain</strong>.</p><p>LangChain has rapidly become the de facto orchestration framework for developing applications powered by LLMs. It provides the “glue” code to connect language models to external data sources, computational tools, and conversational memory.</p><p>In this deep dive, we will move from the basic building blocks of LangChain to constructing a production-ready application that can “chat” with your private documents.</p><blockquote><strong><em>Prerequisites:</em></strong><em> This guide assumes basic knowledge of Python and possession of an OpenAI API key.</em></blockquote><h3>Part 1: The Building Blocks (Core Components)</h3><p>At its heart, LangChain is an abstraction layer. It allows you to swap out different LLM providers (OpenAI, Anthropic, Hugging Face) and different vector databases without rewriting your entire codebase.</p><p>Let’s look at the foundational atoms of LangChain.</p><h3>1. Models (The Engines)</h3><p>LangChain distinguishes between two main types of models:</p><ul><li><strong>LLMs:</strong> Older style models that take a string in and return a string out (e.g., text-davinci-003).</li><li><strong>Chat Models:</strong> Newer models optimized for conversation. They take a list of messages as input and return a single AI message (e.g., gpt-3.5-turbo, gpt-4).</li></ul><p>In modern development, you will almost exclusively use Chat Models.</p><p>Python</p><pre># First, set your API key environment variable<br># import os<br># os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;your-api-key-here&quot;</pre><pre>from langchain_openai import ChatOpenAI</pre><pre># Initialize the Chat Model<br># temperature=0.0 means deterministic outputs (good for data extraction)<br># temperature=0.7 means creative outputs (good for chatbots)<br>chat_model = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;, temperature=0.7)</pre><pre># We can invoke it directly with a string (LangChain handles conversion)<br>response = chat_model.invoke(&quot;Explain quantum computing in one sentence.&quot;)<br>print(response.content)<br># Output: Quantum computing uses the principles of quantum mechanics to perform calculations at speeds unattainable by classical computers.</pre><h3>2. Prompts (The Instructions)</h3><p>You rarely send raw strings to an LLM in production. You need parameterized, reusable templates.</p><p>PromptTemplate (for raw LLMs) and ChatPromptTemplate (for chat models) allow you to define the structure of an interaction and dynamically inject variables.</p><p>A Chat Prompt consists of different roles:</p><ul><li><strong>SystemMessage:</strong> High-level instructions setting the behavior of the AI.</li><li><strong>HumanMessage:</strong> The user’s input.</li><li><strong>AIMessage:</strong> Previous responses from the model (for context).</li></ul><p>Python</p><pre>from langchain_core.prompts import ChatPromptTemplate</pre><pre># Define a reusable template structure<br>template = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are a helpful assistant that translates English into {language}.&quot;),<br>    (&quot;human&quot;, &quot;{text}&quot;),<br>])</pre><pre># Format the prompt with specific data<br>formatted_prompt = template.invoke({&quot;language&quot;: &quot;French&quot;, &quot;text&quot;: &quot;Hello, how are you today?&quot;})</pre><pre># Send the formatted messages to the model<br>response = chat_model.invoke(formatted_prompt)<br>print(response.content)<br># Output: Bonjour, comment allez-vous aujourd&#39;hui ?</pre><h3>3. Output Parsers (Structuring the Response)</h3><p>LLMs output unstructured text. But your application — a frontend UI or a database — usually needs structured data, like JSON. Output Parsers are responsible for taking the text output and transforming it into a usable format.</p><p>Let’s ensure the model always gives us a comma-separated list.</p><p>Python</p><pre>from langchain_core.output_parsers import CommaSeparatedListOutputParser<br>from langchain_core.prompts import PromptTemplate</pre><pre># Initialize parser<br>output_parser = CommaSeparatedListOutputParser()<br>format_instructions = output_parser.get_format_instructions()</pre><pre># Create a prompt that includes the formatting instructions<br>prompt = PromptTemplate(<br>    template=&quot;List five distinct {subject}.\n{format_instructions}&quot;,<br>    input_variables=[&quot;subject&quot;],<br>    partial_variables={&quot;format_instructions&quot;: format_instructions}<br>)</pre><pre># The &quot;manual&quot; way of linking them (we will improve this shortly)<br>_input = prompt.format(subject=&quot;ice cream flavors&quot;)<br>output = chat_model.invoke(_input)<br>parsed_output = output_parser.invoke(output)</pre><pre>print(parsed_output)<br>print(type(parsed_output))<br># Output: [&#39;Vanilla&#39;, &#39;Chocolate&#39;, &#39;Strawberry&#39;, &#39;Mint Chocolate Chip&#39;, &#39;Cookie Dough&#39;]<br># Output type: &lt;class &#39;list&#39;&gt;</pre><h3>Part 2: The “Chain” in LangChain</h3><p>Individually, these components are useful. But the real power comes from combining them into sequences, or “Chains.”</p><p>Historically, LangChain used classes like LLMChain. However, modern LangChain (v0.1.0 and beyond) uses <strong>LCEL (LangChain Expression Language)</strong>.</p><p>LCEL uses the Unix pipe operator (|) to chain components together seamlessly. It makes code incredibly readable and automatically handles streaming, async calls, and batching.</p><p>The basic flow is: Prompt | Model | OutputParser</p><p>Let’s rewrite our translation example using LCEL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sd6FBP4VRI0Y3ceFzy7k-A.png" /></figure><p>Python</p><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser</pre><pre># 1. Define components<br>model = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;)<br>prompt = ChatPromptTemplate.from_template(&quot;Tell me a joke about {topic}&quot;)<br>output_parser = StrOutputParser() # Cleans up the message object to just the string content</pre><pre># 2. Create the chain using pipes (|)<br># The dictionary input at invoke time is passed to the first element (the prompt)<br>chain = prompt | model | output_parser</pre><pre># 3. Run the chain<br>response = chain.invoke({&quot;topic&quot;: &quot;programmers&quot;})<br>print(response)<br># Output: Why do programmers prefer dark mode? Because light attracts bugs!</pre><p>This is elegant. The output of the prompt becomes the input of the model, and the output of the model becomes the input of the parser.</p><h3>Part 3: Giving the Model Memory</h3><p>If you run the chain above twice, the model has no recollection of the first joke. It is stateless.</p><p>To build a chatbot, we need “Memory” — a mechanism to store conversation history and inject it back into the prompt on every new turn.</p><p>In the LCEL paradigm, we handle memory by wrapping our chain with a generic runnable that manages history. We use RunnableWithMessageHistory.</p><p>Python</p><pre>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br>from langchain_core.runnables.history import RunnableWithMessageHistory<br>from langchain_community.chat_message_histories import ChatMessageHistory<br>from langchain_openai import ChatOpenAI<br>from langchain_core.output_parsers import StrOutputParser</pre><pre>model = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;)</pre><pre># We need a prompt that expects history<br># MessagesPlaceholder points to where the history will be injected<br>prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are a helpful assistant. Answer briefly.&quot;),<br>    MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>    (&quot;human&quot;, &quot;{input}&quot;),<br>])</pre><pre>chain = prompt | model | StrOutputParser()</pre><pre># Create a dictionary to store persistent histories for different session IDs<br>store = {}</pre><pre>def get_session_history(session_id: str):<br>    if session_id not in store:<br>        store[session_id] = ChatMessageHistory()<br>    return store[session_id]</pre><pre># Wrap the chain with message history functionality<br>chain_with_message_history = RunnableWithMessageHistory(<br>    chain,<br>    get_session_history,<br>    input_messages_key=&quot;input&quot;,<br>    history_messages_key=&quot;chat_history&quot;,<br>)</pre><pre># Turn 1<br>response1 = chain_with_message_history.invoke(<br>    {&quot;input&quot;: &quot;Hi, my name is Mark.&quot;},<br>    config={&quot;configurable&quot;: {&quot;session_id&quot;: &quot;user_123&quot;}}<br>)<br>print(f&quot;AI: {response1}&quot;)</pre><pre># Turn 2 (The model should remember my name)<br>response2 = chain_with_message_history.invoke(<br>    {&quot;input&quot;: &quot;What is my name?&quot;},<br>    config={&quot;configurable&quot;: {&quot;session_id&quot;: &quot;user_123&quot;}}<br>)<br>print(f&quot;AI: {response2}&quot;)</pre><pre># Output Turn 1: AI: Hello Mark.<br># Output Turn 2: AI: Your name is Mark.</pre><h3>Part 4: Retrieval Augmented Generation (RAG) — Connecting to Data</h3><p>This is currently the most popular use case for LangChain. You have a PDF, a Notion database, or a company wiki, and you want ChatGPT to answer questions based <em>only</em> on that data.</p><p>We cannot fine-tune the model on this data (it’s too slow and expensive, and data changes too fast). Instead, we use <strong>RAG</strong>.</p><h3>The RAG Recipe:</h3><ul><li><strong>Load Data:</strong> Import your documents (PDFs, HTML, text).</li><li><strong>Split/Chunk:</strong> Break large documents into smaller, manageable pieces.</li><li><strong>Embed:</strong> Convert these text chunks into vector representations (lists of numbers representing semantic meaning) using an Embedding Model.</li><li><strong>Store:</strong> Save these vectors in a Vector Database (like Chroma, Pinecone, or FAISS).</li><li><strong>Retrieve:</strong> When a user asks a question, convert the question to a vector, find the most similar chunks in the database.</li><li><strong>Generate:</strong> Pass the retrieved chunks + the user question to the LLM to generate an answer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eXLAAoOwPWpx9q7dbSBIw.png" /></figure><p>Let’s build a RAG system based on a sample PDF. For this example, assume you have a file named sample_policy.pdf in your directory.</p><h3>Step 1–4: Ingestion (Loading, Splitting, Embedding, Storing)</h3><p>We need a few extra libraries: pip install pypdf chromadb tiktoken</p><p>Python</p><pre>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.vectorstores import Chroma</pre><pre># 1. Load the PDF<br>loader = PyPDFLoader(&quot;sample_policy.pdf&quot;)<br>docs = loader.load()</pre><pre># 2. Split the documents into chunks<br># We use overlap to ensure context isn&#39;t lost at the edges of chunks<br>text_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=1000,<br>    chunk_overlap=200,<br>    add_start_index=True<br>)<br>all_splits = text_splitter.split_documents(docs)</pre><pre># 3 &amp; 4. Embed and Store<br># We use OpenAI&#39;s embedding model and ChromaDB as our local vector store<br>embedding_model = OpenAIEmbeddings()</pre><pre># This creates a local folder &#39;./chroma_db&#39; to store the vectors<br>vectorstore = Chroma.from_documents(<br>    documents=all_splits, <br>    embedding=embedding_model, <br>    persist_directory=&quot;./chroma_db&quot;<br>)</pre><pre>print(f&quot;Successfully stored {len(all_splits)} document chunks.&quot;)</pre><h3>Step 5–6: Retrieval and Generation Chain</h3><p>Now that our data is indexed in ChromaDB, we create a chain that queries it.</p><p>We use a special LCEL component called RunnablePassthrough. This allows us to pass the user&#39;s question unmodified to the prompt, while simultaneously using that same question to fetch relevant context from the retriever.</p><p>Python</p><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough</pre><pre># Initialize model<br>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo-0125&quot;, temperature=0)</pre><pre># Create a retriever interface from the vectorstore we created earlier<br>retriever = vectorstore.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 6})</pre><pre># Define the RAG prompt<br>template = &quot;&quot;&quot;Answer the question based only on the following context:<br>{context}</pre><pre>Question: {question}<br>&quot;&quot;&quot;<br>rag_prompt = ChatPromptTemplate.from_template(template)</pre><pre># The magic happens here with LCEL<br># 1. RunnablePassthrough passes the input question to the &quot;question&quot; key.<br># 2. The retriever takes the input question, fetches docs, and passes them to the &quot;context&quot; key.<br>rag_chain = (<br>    {&quot;context&quot;: retriever, &quot;question&quot;: RunnablePassthrough()}<br>    | rag_prompt<br>    | llm<br>    | StrOutputParser()<br>)</pre><pre># Run it!<br># (Replace this with a question relevant to your specific PDF contents)<br>response = rag_chain.invoke(&quot;What is the policy on remote work?&quot;)<br>print(response)</pre><p>You have just built a system that reads your document and answers questions based solely on its content.</p><h3>Part 5: Agents (Giving the Model Tools)</h3><p>Chains are predetermined sequences. RAG is fetching data. But what if the steps needed to solve a problem aren’t known ahead of time?</p><p>If I ask: <em>“Who is the current CEO of Microsoft, and what is their age multiplied by 2.5?”</em></p><p>An LLM alone cannot answer this. It might know the CEO instantly, but its math is unreliable. It needs to:</p><ul><li>Search Google for the CEO.</li><li>Search Google for their age.</li><li>Use a calculator for the math.</li></ul><p><strong>Agents</strong> are systems where the LLM acts as the reasoning engine to decide which “Tools” to use and in what order. It enters a loop of: <em>Thought -&gt; Action -&gt; Observation -&gt; Thought…</em> until it arrives at an answer.</p><p>To run this, we need a search tool. We’ll use SerpAPI (you need a free API key from serpapi.com). pip install google-search-results numexpr</p><p>Python</p><pre># os.environ[&quot;SERPAPI_API_KEY&quot;] = &quot;your_serpapi_key&quot;</pre><pre>from langchain_openai import ChatOpenAI<br>from langchain.agents import AgentExecutor, create_tool_calling_agent<br>from langchain_community.tools import SerpAPIWrapper<br>from langchain_core.tools import Tool<br>from langchain_core.prompts import ChatPromptTemplate</pre><pre># Initialize the model (must be a model capable of reliable tool calling, like gpt-3.5 or gpt-4)<br>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo-0125&quot;, temperature=0)</pre><pre># --- Define Tools ---<br>search = SerpAPIWrapper()<br># We wrap the search functionality in a Tool object with a clear description<br># The LLM uses the description to decide when to use this tool.<br>search_tool = Tool(<br>    name=&quot;Search&quot;,<br>    func=search.run,<br>    description=&quot;useful for when you need to answer questions about current events or facts you don&#39;t know.&quot;<br>)</pre><pre># A simple tool for math so the LLM doesn&#39;t try to do it itself<br>from langchain_community.tools import WikipediaQueryRun<br>from langchain_community.utilities import WikipediaAPIWrapper<br>math_tool = Tool(<br>    name=&quot;Calculator&quot;,<br>    func=lambda x: eval(x), # Warning: eval() is risky in prod, use libraries like numexpr instead<br>    description=&quot;Useful for when you need to answer questions about math.&quot;<br>)</pre><pre>tools = [search_tool, math_tool]</pre><pre># --- Create Agent ---<br># We use a pre-made prompt optimized for tool calling agents<br>prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are a helpful assistant. Make sure to use the search tool for information and the calculator for math.&quot;),<br>    (&quot;human&quot;, &quot;{input}&quot;),<br>    (&quot;placeholder&quot;, &quot;{agent_scratchpad}&quot;), # Crucial: where the agent&#39;s intermediate thought steps go<br>])</pre><pre># Construct the agent<br>agent = create_tool_calling_agent(llm, tools, prompt)</pre><pre># Create the executor (the runtime for the agent)<br>agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)</pre><pre># Run it<br>response = agent_executor.invoke({&quot;input&quot;: &quot;Who is the current CEO of Microsoft, and what is their age multiplied by 2.5?&quot;})</pre><pre>print(response[&quot;output&quot;])</pre><p>When you run this with verbose=True, you will see the amazing process of the AI &quot;thinking,&quot; deciding to search, getting search results, realizing it needs age, searching again, and finally deciding to use the calculator.</p><h3>Part 6: The Final Application — A Conversational “Chat with PDF” Bot</h3><p>Let’s put it all together. We will build the “Hello World” of real-world AI apps: A system that allows you to have a back-and-forth conversation with a PDF document.</p><p>This is harder than standard RAG because follow-up questions often rely on previous context.</p><p>If I ask: “What does the doc say about vacation?” and then follow up with “Does that apply to contractors?”, a standard retrieval system will fail because the second query doesn’t contain the word “vacation”.</p><p>We need a two-step process:</p><ul><li><strong>Condense:</strong> Take the chat history and the latest follow-up question, and condense them into a standalone search query.</li><li><strong>Retrieve &amp; Generate:</strong> Use that standalone query to perform standard RAG.</li></ul><p>Here is the complete code for the final application.</p><p>Python</p><pre>from langchain_openai import ChatOpenAI, OpenAIEmbeddings<br>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough, RunnableBranch<br>from langchain_community.vectorstores import Chroma<br>from langchain_core.runnables.history import RunnableWithMessageHistory<br>from langchain_community.chat_message_histories import ChatMessageHistory</pre><pre># --- Setup (Assuming vectorstore is already populated from Part 4) ---<br>embedding_model = OpenAIEmbeddings()<br># Reload the existing vectorstore<br>vectorstore = Chroma(persist_directory=&quot;./chroma_db&quot;, embedding_function=embedding_model)<br>retriever = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 5})<br>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo-0125&quot;, temperature=0)</pre><pre># --- Step 1: The Query Transforming Chain ---<br># This chain reformulates follow-up questions into standalone queries<br>query_transform_prompt = ChatPromptTemplate.from_messages([<br>    MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>    (&quot;human&quot;, &quot;{input}&quot;),<br>    (&quot;system&quot;, &quot;Given the above conversation, generate a search query to look up in order to get information relevant to the conversation. If the input is a simple greeting or not a question requiring info, just return the input verbatim.&quot;)<br>])</pre><pre>query_transform_chain = query_transform_prompt | llm | StrOutputParser()</pre><pre># --- Step 2: The RAG Chain ---<br>rag_prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;Answer the user&#39;s questions based on the below context:\n\n{context}&quot;),<br>    MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>    (&quot;human&quot;, &quot;{input}&quot;),<br>])</pre><pre># We use a &quot;Branch&quot; to decide: do we need history to understand the question?<br># If chat history exists, transform the query first. If not, use the raw input.<br>query_router = RunnableBranch(<br>    (<br>        lambda x: len(x.get(&quot;chat_history&quot;, [])) &gt; 0,<br>        query_transform_chain,<br>    ),<br>    RunnablePassthrough.assign(output=lambda x: x[&quot;input&quot;]) | (lambda x: x[&quot;output&quot;]),<br>)</pre><pre># The final retrieval chain<br>conversational_rag_chain = (<br>    RunnablePassthrough.assign(<br>        context=query_router | retriever # Use transformed query to retrieve docs<br>    )<br>    | rag_prompt<br>    | llm<br>    | StrOutputParser()<br>)</pre><pre># --- Step 3: Add Memory Management ---<br>store = {}<br>def get_session_history(session_id: str):<br>    if session_id not in store:<br>        store[session_id] = ChatMessageHistory()<br>    return store[session_id]</pre><pre>final_app = RunnableWithMessageHistory(<br>    conversational_rag_chain,<br>    get_session_history,<br>    input_messages_key=&quot;input&quot;,<br>    history_messages_key=&quot;chat_history&quot;,<br>)</pre><pre># === Running the Application ===</pre><pre>session_id = &quot;user_session_555&quot;</pre><pre># Turn 1<br>print(&quot;--- Turn 1 ---&quot;)<br>response1 = final_app.invoke(<br>    {&quot;input&quot;: &quot;What are the main points of this document?&quot;},<br>    config={&quot;configurable&quot;: {&quot;session_id&quot;: session_id}}<br>)<br>print(f&quot;AI: {response1}\n&quot;)</pre><pre># Turn 2 (A vague follow-up question)<br>print(&quot;--- Turn 2 ---&quot;)<br># The system will internally rewrite this to something like &quot;details about [point mentioned in turn 1]&quot; before retrieving.<br>response2 = final_app.invoke(<br>    {&quot;input&quot;: &quot;Tell me more about the second point.&quot;},<br>    config={&quot;configurable&quot;: {&quot;session_id&quot;: session_id}}<br>)<br>print(f&quot;AI: {response2}&quot;)</pre><p>You now have a sophisticated, context-aware RAG application running locally.</p><h3>Conclusion &amp; The LangChain Ecosystem</h3><p>We have journeyed from sending a simple string to an LLM to building a complex, multi-step reasoning engine with memory and data retrieval capabilities.</p><p>LangChain’s power lies in its composability using LCEL. Once you understand the flow of data through pipes, you can build incredibly complex workflows.</p><p>However, building with LLMs is inherently non-deterministic. Things break. Prompts stop working as models get updated. That is why the broader LangChain ecosystem is vital:</p><ul><li><strong>LangSmith:</strong> A platform for debugging, testing, and monitoring your chains. You can trace every step of an agent’s thought process to see exactly where it went wrong or why a RAG retrieval failed.</li><li><strong>LangServe:</strong> A library that helps you deploy your LangChain runnables as a production-ready REST API instantly.</li></ul><p>The field of Generative AI is moving at breakneck speed. LangChain is currently the best framework available to tame that chaos and build genuinely useful applications today. Start with the building blocks, master the LCEL syntax, and soon you will be architecting systems that seemed like science fiction just two years ago.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d576ab53bb3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting LLMs — From Fundamentals to Scaled Production (with Hands-On Tutorial)]]></title>
            <link>https://medium.com/@xiaxiami/hosting-llms-from-fundamentals-to-scaled-production-with-hands-on-tutorial-6598d16810e0?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/6598d16810e0</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 00:08:54 GMT</pubDate>
            <atom:updated>2025-12-17T00:08:54.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hosting LLMs — From Fundamentals to Scaled Production (with Hands-On Tutorial)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6glwj9o0ohPbxWIb8MUIGg.png" /></figure><p>In traditional machine learning deployment, serving a model is often a stateless, compute-bound task. You receive a vector, perform a forward pass, and return a prediction. Large Language Models (LLMs) fundamentally break this paradigm. They are stateful, memory-bound, and require complex scheduling mechanisms to run efficiently at scale.</p><p>For platform engineers and ML architects, “hosting an LLM” is not merely about wrapping a Python script in a Docker container. It is an exercise in managing high-bandwidth memory, optimizing GPU kernel execution, and balancing the opposing forces of <strong>throughput</strong> (total tokens generated per second) and <strong>latency</strong> (time to first token).</p><p>This guide serves as a technical reference and a practical handbook for deploying LLMs in production. We will move from the first principles of transformer inference to a complete, code-driven deployment tutorial.</p><h3>1. Introduction</h3><h3>What “Hosting an LLM” Really Means</h3><p>Hosting an LLM involves managing the lifecycle of a request that may persist for seconds or minutes. Unlike a ResNet inference which takes milliseconds, an LLM generation is an iterative process. The system must manage <strong>KV (Key-Value) caches</strong> — large memory structures that preserve the context of the conversation — and perform dynamic batching to keep the GPU saturated without causing Out-Of-Memory (OOM) errors.</p><h3>The Key Constraints</h3><ul><li><strong>Latency (TTFT &amp; TPOT):</strong> Users perceive two types of latency: Time to First Token (TTFT) and Time Per Output Token (TPOT). TTFT is dominated by processing the prompt; TPOT is dominated by memory bandwidth.</li><li><strong>Throughput:</strong> The number of concurrent requests the system can handle. This is generally strictly limited by Video RAM (VRAM) capacity.</li><li><strong>Cost:</strong> GPU compute is expensive. Inefficient hosting burns capital on idle cycles.</li><li><strong>Reliability:</strong> Long-running requests are susceptible to network timeouts and hardware preemption.</li></ul><h3>The Serving Stack Overview</h3><p>A modern LLM stack consists of:</p><ol><li><strong>Hardware Layer:</strong> GPUs (H100, A100, A10g) or specialized accelerators (TPU, AWS Inferentia).</li><li><strong>Runtime Engine:</strong> The low-level software managing memory and kernels (vLLM, TensorRT-LLM).</li><li><strong>Serving Layer:</strong> API handling, queuing, and protocol management (FastAPI, Ray Serve).</li><li><strong>Orchestrator:</strong> Container management and scaling (Kubernetes).</li></ol><h3>2. Fundamentals of LLM Inference</h3><p>To optimize hosting, one must understand the underlying mechanics of the Transformer architecture.</p><h3>Transformer Inference Mechanics &amp; Autoregression</h3><p>LLM inference is <strong>autoregressive</strong>. To generate the t-th token wt​, the model requires the history of all previous tokens w1:t−1​.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWCXgzk-WJn2ofa-hvKojg.png" /></figure><p>This process occurs in two distinct phases:</p><ol><li><strong>Prefill (The Prompt Phase):</strong> The model processes all input tokens in parallel. This phase is <strong>compute-bound</strong>. The GPU tensor cores are fully utilized calculating attention scores for the existing context.</li><li><strong>Decode (The Generation Phase):</strong> The model generates one token at a time. To generate token N+1, it relies on the state of token N. This phase is <strong>memory-bandwidth bound</strong>.</li></ol><h3>Why Inference is Memory-Bound</h3><p>In the decode phase, for every single token generated, the entire set of model weights must be moved from High Bandwidth Memory (HBM) to the compute units. If a model has 70 billion parameters (FP16), it is roughly 140GB in size. To generate <em>one</em> token, you must transfer 140GB of data. If your memory bandwidth is 2TB/s (like an A100), your maximum theoretical speed is limited, regardless of how many TFLOPS of compute you have.</p><h3>The KV Cache</h3><p>To avoid recalculating attention for all previous tokens at every step, we cache the Key and Value matrices. The size of this cache grows linearly with sequence length (L) and batch size (B).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YE_0Bg0ILbLUnseQAzGBPA.png" /></figure><p>Managing this cache memory is the single most critical aspect of high-throughput LLM serving.</p><h3>3. Model Selection and Hosting Strategies</h3><p>Before provisioning hardware, you must select the model architecture, as this dictates infrastructure requirements.</p><h3>Model Archetypes</h3><ul><li><strong>Dense Models (e.g., Llama 3 70B):</strong> Every parameter is active for every token. Predictable latency, but high VRAM requirements.</li><li><strong>Mixture of Experts (MoE) (e.g., Mixtral 8x7B):</strong> Only a fraction of parameters (active parameters) are used per token. This allows for faster inference (lower latency) relative to the total parameter count, but the VRAM requirement remains high because all weights must be loaded.</li></ul><h3>Hosting Strategies</h3><ul><li><strong>Managed APIs (OpenAI, Anthropic):</strong> Zero infra overhead. Best for validation and low-volume use cases. Trade-off: Data privacy and cost scaling.</li><li><strong>Fully Self-Hosted (On-Prem/Cloud VPC):</strong> Full control over data and weights. Requires engineering team to manage. Best for high-volume, privacy-sensitive, or fine-tuned use cases.</li><li><strong>Hybrid:</strong> Use managed APIs for general queries and small, self-hosted models for specific, narrow tasks (e.g., PII redaction).</li></ul><h3>4. Inference Engines and Runtimes</h3><p>Standard PyTorch code (model.generate()) is insufficient for production because it allocates memory statically and handles requests serially.</p><h3>PagedAttention &amp; vLLM</h3><p>Traditional attention algorithms require contiguous memory blocks for the KV cache. This leads to massive fragmentation and wasted VRAM (internal fragmentation). <strong>vLLM</strong> introduced <strong>PagedAttention</strong>, inspired by OS virtual memory paging. It breaks the KV cache into non-contiguous blocks, allowing the engine to fill almost every byte of VRAM. This typically increases throughput by 2x-4x over naive implementations.</p><h3>Continuous Batching</h3><p>In static batching, the GPU waits for the <em>slowest</em> sequence in the batch to finish before returning. <strong>Continuous Batching</strong>(or iteration-level scheduling) allows the engine to eject finished sequences and insert new requests into the running batch at every token generation step. This creates a “cellular automaton” style of processing where the GPU is permanently saturated.</p><h3>Key Runtimes</h3><ul><li><strong>vLLM:</strong> The current open-source standard. Excellent throughput, PagedAttention, easy-to-use Python API.</li><li><strong>TensorRT-LLM (NVIDIA):</strong> Highly optimized for NVIDIA hardware. Compiles the model into a specific engine plan. often faster than vLLM but harder to debug and deploy.</li><li><strong>TGI (Text Generation Inference):</strong> Maintained by Hugging Face. Robust, features semantic caching and tensor parallelism.</li><li><strong>llama.cpp:</strong> optimized for CPU and Apple Silicon. Best for edge/local, not typically for high-scale server production.</li></ul><h3>5. Hardware Considerations</h3><h3>GPU Selection Guide</h3><ul><li><strong>NVIDIA H100 (80GB):</strong> The king of throughput. Features FP8 support (transformer engine). Expensive, short supply.</li><li><strong>NVIDIA A100 (80GB):</strong> The industry workhorse. High memory bandwidth.</li><li><strong>NVIDIA A10g (24GB):</strong> Good for smaller models (7B-13B) or development. Low memory bandwidth compared to A100.</li></ul><h3>Parallelism Strategies</h3><p>When a model doesn’t fit on one GPU:</p><ul><li><strong>Pipeline Parallelism:</strong> Layers are split across GPUs (GPU 1 does layers 1–10, GPU 2 does 11–20). Increases latency (bubbles in pipeline) but simple to reason about.</li><li><strong>Tensor Parallelism (TP):</strong> Individual matrix multiplications are split across GPUs. Requires ultra-fast interconnect (NVLink) because synchronization happens at every layer. This is the standard for serving 70B+ models.</li></ul><h3>6. Model Optimization Techniques</h3><h3>Quantization</h3><p>Reducing the precision of weights (and activations) from FP16 (16-bit) to INT8 or INT4.</p><ul><li><strong>GPTQ / AWQ:</strong> Post-training quantization methods that modify weights to minimize error in output.</li><li><strong>Impact:</strong> Running a Llama-3–70B in INT4 reduces VRAM usage from ~140GB to ~40GB, allowing it to fit on a single A6000 Ada or two consumer 3090s/4090s.</li><li><strong>Trade-off:</strong> Minimal perplexity degradation for significant throughput gains.</li></ul><h3>Speculative Decoding</h3><p>This technique uses a small “draft” model (e.g., 7B) to guess the next K tokens, and the large “target” model (e.g., 70B) verifies them in parallel. If the draft is accurate, you generate multiple tokens for the cost of one forward pass of the large model.</p><h3>7. Serving Architecture Design</h3><h3>Streaming &amp; Protocols</h3><p>LLM responses are slow. Waiting 10 seconds for a full JSON response is bad UX. You must use <strong>Server-Sent Events (SSE)</strong> or <strong>gRPC streaming</strong> to push tokens to the client as they are generated.</p><h3>Load Balancing</h3><p>Standard Round-Robin is dangerous for LLMs because request variance is huge (generating 10 tokens vs 1000 tokens).<strong>Least-Outstanding-Requests</strong> or <strong>Queue-Depth-Based</strong> routing is preferred. The load balancer should be aware of the “KV cache pressure” on the workers.</p><h3>8. Deployment Approaches</h3><ul><li><strong>Docker:</strong> The standard unit. Images are large (10GB+) due to CUDA dependencies.</li><li><strong>Kubernetes (K8s):</strong> The standard orchestrator. Requires the <strong>NVIDIA GPU Operator</strong> to expose GPU resources to pods.</li><li><strong>Model Versioning:</strong> Do not bake model weights into the Docker image. Use an <strong>InitContainer</strong> or a networked volume (PVC) to mount weights at runtime. This allows faster rolling updates of the code without re-downloading 100GB of weights.</li></ul><h3>9. Scaling LLM Hosting</h3><h3>Autoscaling Metrics</h3><p>CPU usage is a useless metric for LLM autoscaling. Scale based on:</p><ol><li><strong>Average Queue Latency:</strong> How long a request waits before processing begins.</li><li><strong>GPU KV Cache Utilization:</strong> If cache usage &gt; 90%, scale up immediately to prevent request rejection.</li></ol><h3>Cold Starts</h3><p>Loading a 70B model into GPU memory takes time (30s to minutes). Over-provisioning or “warm pools” are necessary for latency-sensitive applications.</p><h3>10. Observability and Monitoring</h3><p>You cannot optimize what you do not measure.</p><ul><li><strong>Generation Throughput:</strong> Tokens/second across the fleet.</li><li><strong>TTFT (Time To First Token):</strong> Critical for perceived responsiveness.</li><li><strong>Token Ratio:</strong> Input tokens vs. Output tokens. This changes the dynamics of compute-bound vs. memory-bound.</li><li><strong>Finish Reason:</strong> Track how often models hit context limits (length) vs. natural completion (stop).</li></ul><h3>11. Security, Privacy, and Governance</h3><ul><li><strong>Prompt Injection:</strong> Assume all input is malicious. Sanitize inputs, but acknowledge that LLMs are inherently susceptible to social engineering (jailbreaking).</li><li><strong>Data Isolation:</strong> In multi-tenant systems, ensure the KV cache of User A cannot bleed into User B. Engines like vLLM handle this at the memory page level, but application-level logic must ensure strict separation.</li></ul><h3>12. Applications of Hosted LLMs</h3><ul><li><strong>RAG (Retrieval Augmented Generation):</strong> High ratio of input tokens (documents) to output tokens. Optimization focus: Prefill speed and long-context performance.</li><li><strong>Agents:</strong> Recursive loop of generation. Latency stacks up quickly. Requires fast inference to feel interactive.</li></ul><h3>13. Cost Modeling</h3><p>Cost is usually calculated per 1k tokens.</p><p>Cost≈Avg Tokens Per Second×3600Hourly GPU Rate​</p><p>To reduce cost, maximize batch size. If your batch size is 1, you are paying for memory bandwidth you aren’t using. If your batch size is 64, you are amortizing the cost of reading weights across 64 requests.</p><h3>14. Failure Modes and Lessons Learned</h3><ul><li><strong>The “ EOS” Trap:</strong> If a model doesn’t emit the End of Sequence token, it will generate until it hits the max limit, wasting compute and money.</li><li><strong>Fragmentation:</strong> Without paged attention, long-running servers eventually fragment memory, leading to OOMs even with “free” memory displayed in nvidia-smi.</li></ul><h3>15. Hands-On Tutorial: Hosting an LLM End-to-End</h3><p>We will build a production-ready inference service for <strong>Llama-3–8B-Instruct</strong> using <strong>vLLM</strong>, <strong>FastAPI</strong>, and <strong>Docker</strong>.</p><h3>15.1 Local LLM Hosting</h3><p><strong>Prerequisites:</strong> NVIDIA GPU with at least 16GB VRAM (e.g., RTX 3090, A10g, T4), Python 3.10+, CUDA 12.1.</p><p>First, let’s install vLLM.</p><p>Bash</p><pre>pip install vllm</pre><p>Here is a minimal script to load the model and generate text offline.</p><p>Python</p><pre>from vllm import LLM, SamplingParams</pre><pre># Initialize the engine<br># trust_remote_code is needed for some architectures<br>llm = LLM(model=&quot;meta-llama/Meta-Llama-3-8B-Instruct&quot;, trust_remote_code=True)</pre><pre>prompts = [<br>    &quot;Hello, my name is&quot;,<br>    &quot;The capital of France is&quot;,<br>]</pre><pre># Set sampling parameters<br>sampling_params = SamplingParams(temperature=0.8, top_p=0.95, max_tokens=100)</pre><pre># Generate<br>outputs = llm.generate(prompts, sampling_params)</pre><pre>for output in outputs:<br>    prompt = output.prompt<br>    generated_text = output.outputs[0].text<br>    print(f&quot;Prompt: {prompt!r}, Generated text: {generated_text!r}&quot;)</pre><h3>15.2 Building an LLM Inference API</h3><p>We need a web server to handle requests. We will use FastAPI and handle streaming responses.</p><p><strong>app.py</strong></p><pre>import os<br>from fastapi import FastAPI, Request<br>from fastapi.responses import StreamingResponse<br>from vllm import AsyncLLMEngine<br>from vllm.engine.arg_utils import AsyncEngineArgs<br>from vllm.sampling_params import SamplingParams<br>import json<br>import uuid</pre><pre>app = FastAPI()</pre><pre># Configuration<br>MODEL_NAME = os.getenv(&quot;MODEL_NAME&quot;, &quot;meta-llama/Meta-Llama-3-8B-Instruct&quot;)</pre><pre># Initialize Async vLLM Engine<br>engine_args = AsyncEngineArgs(<br>    model=MODEL_NAME,<br>    tensor_parallel_size=1, # Change based on GPU count<br>    trust_remote_code=True<br>)<br>engine = AsyncLLMEngine.from_engine_args(engine_args)</pre><pre>@app.post(&quot;/generate&quot;)<br>async def generate_stream(request: Request):<br>    req_data = await request.json()<br>    prompt = req_data.get(&quot;prompt&quot;)<br>    stream = req_data.get(&quot;stream&quot;, False)<br>    <br>    sampling_params = SamplingParams(<br>        temperature=req_data.get(&quot;temperature&quot;, 0.7),<br>        max_tokens=req_data.get(&quot;max_tokens&quot;, 512)<br>    )</pre><pre>    request_id = str(uuid.uuid4())<br>    results_generator = engine.generate(prompt, sampling_params, request_id)</pre><pre>    if stream:<br>        return StreamingResponse(<br>            stream_results(results_generator), <br>            media_type=&quot;text/event-stream&quot;<br>        )<br>    <br>    # Non-streaming fallback logic here...<br>    final_output = None<br>    async for request_output in results_generator:<br>        final_output = request_output<br>    <br>    return {&quot;text&quot;: final_output.outputs[0].text}</pre><pre>async def stream_results(results_generator):<br>    async for request_output in results_generator:<br>        text = request_output.outputs[0].text<br>        # In vLLM, text is cumulative. We might need to diff it <br>        # depending on client expectation, but simplest is sending full text<br>        yield f&quot;data: {json.dumps({&#39;text&#39;: text})}\n\n&quot;</pre><h3>15.3 Dockerizing the LLM Service</h3><p>We need a CUDA-enabled base image.</p><p><strong>Dockerfile</strong></p><pre>FROM nvidia/cuda:12.1.0-devel-ubuntu22.04</pre><pre>WORKDIR /app</pre><pre># Install Python and pip<br>RUN apt-get update &amp;&amp; apt-get install -y python3 python3-pip git</pre><pre># Install vLLM and dependencies<br># Pinned version for stability<br>RUN pip3 install vllm==0.4.0 fastapi uvicorn[standard]</pre><pre>COPY app.py /app/app.py</pre><pre># Expose port<br>EXPOSE 8000</pre><pre># Environment variables<br>ENV MODEL_NAME=&quot;meta-llama/Meta-Llama-3-8B-Instruct&quot;</pre><pre># Use python3 directly<br>CMD [&quot;python3&quot;, &quot;-m&quot;, &quot;uvicorn&quot;, &quot;app:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><h3>15.4 Deploying to Kubernetes</h3><p>To schedule this on K8s, you must request GPU resources.</p><p><strong>deployment.yaml</strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: llm-inference<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: llm-inference<br>  template:<br>    metadata:<br>      labels:<br>        app: llm-inference<br>    spec:<br>      containers:<br>      - name: llm-server<br>        image: my-registry/llm-server:latest<br>        resources:<br>          limits:<br>            nvidia.com/gpu: 1  # Requests 1 GPU<br>        env:<br>        - name: HUGGING_FACE_HUB_TOKEN<br>          valueFrom:<br>            secretKeyRef:<br>              name: hf-secret<br>              key: token<br>        volumeMounts:<br>        - name: model-cache<br>          mountPath: /root/.cache/huggingface<br>      volumes:<br>      - name: model-cache<br>        emptyDir: {} # Ideally use a PersistentVolume here</pre><h3>15.5 Performance Optimization Tips</h3><ul><li><strong>Batch Size Tuning:</strong> In your AsyncEngineArgs, set max_num_seqs. Start at 256. Increase until latency spikes.</li><li><strong>KV Cache quantization:</strong> vLLM supports FP8 KV cache, which reduces memory usage by 50%, allowing for larger batch sizes.</li></ul><h3>15.6 Basic Monitoring</h3><p>Integrate Prometheus. You want to wrap the generate function to time how long it takes to yield the first chunk (TTFT) and the total time divided by tokens (TPOT). Log these metrics with dimensions for model_name and batch_size.</p><h3>16. Future Directions</h3><p>The landscape is shifting rapidly.</p><ul><li><strong>Serverless Inference:</strong> Platforms like Modal or RunPod are abstracting the K8s layer entirely.</li><li><strong>Hardware Co-design:</strong> Chips like Groq LPU are moving away from HBM-bottlenecked GPUs to SRAM-based architectures for ultra-low latency.</li><li><strong>On-Device:</strong> Apple and Qualcomm are pushing for NPU-based inference, likely offloading “small” tasks to the edge to save cloud costs.</li></ul><h3>17. Conclusion</h3><p>Hosting LLMs is a discipline of trade-offs. You are constantly balancing <strong>memory</strong> (which limits throughput) against <strong>compute</strong> (which limits latency).</p><ul><li><strong>For high throughput/public chatbots:</strong> Use vLLM, continuous batching, and maximize batch size.</li><li><strong>For low latency/copilots:</strong> Use aggressive speculative decoding and keep utilization lower to avoid queue times.</li><li><strong>For cost optimization:</strong> Quantize models to INT4/INT8 to fit on cheaper, older generations of GPUs.</li></ul><p>The code provided above is a starting block. The real engineering begins when you scale to handling thousands of concurrent users, where the subtle interactions between the OS scheduler, the GPU kernel, and the network topology determine success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6598d16810e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Prompt: The Definitive Engineering Guide to Retrieval-Augmented Generation (RAG)]]></title>
            <link>https://medium.com/@xiaxiami/beyond-the-prompt-the-definitive-engineering-guide-to-retrieval-augmented-generation-rag-8e87c6d7433d?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e87c6d7433d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 00:29:51 GMT</pubDate>
            <atom:updated>2025-12-15T00:29:51.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBB3ko8fti9bPROb5bg9rA.png" /></figure><p>In the rapid evolution of Large Language Models (LLMs), few paradigms have shifted the engineering landscape as fundamentally as <strong>Retrieval-Augmented Generation (RAG)</strong>.</p><p>While the release of GPT-4 and Gemini dazzled the world with reasoning capabilities, practitioners quickly hit a hard wall: the <strong>knowledge cutoff</strong> and the <strong>hallucination</strong> problem. Models are frozen in time, and they are confident liars when pressed on obscure data.</p><p>RAG is the architectural bridge between the static, parametric memory of an LLM and the dynamic, massive scale of external data. It is not merely a feature; it is the dominant design pattern for enterprise AI today.</p><p>This article is a comprehensive deep dive into RAG. We will move beyond the basic tutorials and dissect the system architecture, mathematical underpinnings, advanced engineering techniques, and the real-world trade-offs — specifically comparing widely used tools like <strong>FAISS</strong> and <strong>Milvus</strong> — required to put RAG in production.</p><h3>1. Introduction: The Problem with Parametric Memory</h3><p>To understand RAG, we must first understand the limitation of the LLM itself.</p><p>An LLM stores knowledge in its weights (parametric memory). During training, the model compresses the internet into a dense vector space. However, this compression is lossy. When you ask a model about a specific document from your internal confluence page, it fails because:</p><ol><li><strong>It hasn’t seen it:</strong> The data is private.</li><li><strong>It forgot it:</strong> The compression prioritized more common patterns.</li><li><strong>It is stale:</strong> The model was trained six months ago.</li></ol><p>The naive solution is <strong>Fine-Tuning</strong>. You could retrain the model on your data. However, fine-tuning is expensive, slow, and notoriously bad at teaching models <em>new facts</em>. Fine-tuning is better suited for adapting <em>behavior</em> and <em>style</em>, not injecting knowledge.</p><p><strong>RAG offers a different path:</strong> Instead of teaching the model the information, we give the model access to an open-book test. We retrieve the relevant facts at inference time and inject them into the context window.</p><h3>2. Background: Foundations of RAG</h3><p>RAG is the convergence of two historical streams in AI: <strong>Information Retrieval (IR)</strong> and <strong>Generative AI</strong>.</p><h3>Non-Parametric Memory</h3><p>In traditional IR (like Google Search or Lucene), we index documents to retrieve specific matches. This is <strong>non-parametric memory</strong>. It is explicit, editable, and verifiable. If a document changes, you update the index, not the neural network.</p><h3>The Evolution</h3><ul><li><strong>1.0 Keyword Search:</strong> Systems like BM25 used frequency-based heuristics to find documents.</li><li><strong>2.0 Dense Retrieval:</strong> With the advent of BERT, we began representing text as dense vectors. Semantic search became possible.</li><li><strong>3.0 Neural RAG:</strong> The current era. We use a dense retriever to find content and a generative model (LLM) to synthesize the answer.</li></ul><p>The core premise is defined by the equation of generation probability. Instead of P(y∣x) (probability of answer y given input x), we model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rqOLJ2LVmY3bqh4t6rD5Q.png" /></figure><p>Where z is the retrieved document. We are marginalizing over the retrieved documents to generate the best answer.</p><h3>3. Core RAG Architecture</h3><p>A production RAG system is an <strong>Extract-Transform-Load (ETL)</strong> pipeline followed by an inference pipeline.</p><h3>The Pipeline Steps</h3><ol><li><strong>Ingestion &amp; Chunking:</strong> Documents are parsed and split into smaller segments.</li><li><strong>Embedding:</strong> A model (like OpenAI’s text-embedding-3 or bge-m3) converts text chunks into vector representations (e.g., 1536 dimensions).</li><li><strong>Indexing:</strong> Vectors are stored in a Vector Database (VDB) utilizing Approximate Nearest Neighbor (ANN) algorithms.</li><li><strong>Retrieval:</strong> The user query is embedded. The VDB finds vectors with high cosine similarity.</li><li><strong>Ranking:</strong> (Optional but recommended) A Cross-Encoder re-ranks the top K results for precision.</li><li><strong>Generation:</strong> The top results are stuffed into the LLM context window with a prompt, and the model generates the answer.</li></ol><h3>Failure Modes at the Core</h3><ul><li><strong>Retrieval failure:</strong> The answer exists in the database, but the retrieval step failed to find it (low recall).</li><li><strong>Synthesis failure:</strong> The retrieval found the correct document, but the LLM failed to reason over it or hallucinated despite the context.</li></ul><h3>4. Retrieval Methods: The Engine Room</h3><p>The quality of your RAG system is usually bottlenecked by retrieval, not generation. If you feed garbage context to GPT-4, you get a garbage answer.</p><h3>Sparse vs. Dense Retrieval</h3><ul><li><strong>Sparse (BM25/Splade):</strong> Matches exact keywords.</li><li><em>Pros:</em> Great for part numbers, acronyms, and names (e.g., “Error code 0x84f”).</li><li><em>Cons:</em> Fails at synonyms or conceptual matching.</li><li><strong>Dense (Embeddings):</strong> Matches semantic meaning.</li><li><em>Pros:</em> Handles “How do I reset the box?” matching with “System reboot instructions.”</li><li><em>Cons:</em> Can drift. “King” matches “Queen” highly, but if you need exact gender distinction, it might fail.</li></ul><h3>Hybrid Search</h3><p>The industry standard is <strong>Hybrid Search</strong>. You run both BM25 and Vector Search, then normalize the scores and combine them (often using Reciprocal Rank Fusion — RRF). This gives you the best of both worlds.</p><h3>The Critical Role of Re-Ranking</h3><p>Bi-encoders (embedding models) are fast but lose nuance because they compress query and document independently.</p><p>Score(Q,D)=Cosine(Embed(Q),Embed(D))</p><p><strong>Cross-Encoders</strong> take both the query and document as a single input and output a similarity score. They are much slower but vastly more accurate.</p><p>Score(Q,D)=BERT(Q∣∣D)</p><p><strong>Production Pattern:</strong> Retrieve 100 documents using fast vector search. Re-rank the top 100 using a slow Cross-Encoder (like Cohere Rerank or BGE-Reranker). Pass the top 5 to the LLM.</p><h3>5. Vector Databases and Indexing: FAISS vs. Milvus</h3><p>You cannot simply iterate through 10 million vectors to find the closest match. We use <strong>Approximate Nearest Neighbor (ANN)</strong> indexing. This is where the choice of your vector store becomes a critical architectural decision.</p><p>While there are many options (Weaviate, Pinecone, Chroma), <strong>FAISS</strong> and <strong>Milvus</strong> represent two distinct ends of the spectrum: the “embedded library” vs. the “cloud-native database.”</p><h3>FAISS (Facebook AI Similarity Search)</h3><p>FAISS is a C++ library with python bindings. It is not a server; it is a set of algorithms you run inside your own application process.</p><ul><li><strong>Best For:</strong> Researchers, offline batch processing, or extremely high-performance scenarios where you want to strip away network overhead.</li><li><strong>Architecture:</strong> It runs in-memory. If your Python script dies, your index is gone unless you manually serialize it to disk (faiss.write_index).</li><li><strong>Key Algorithms:</strong></li><li><strong>IndexFlatL2:</strong> Exact search (brute force). Perfect accuracy but slow.</li><li><strong>IVF (Inverted File Index):</strong> Clusters vectors into Voronoi cells. You only search the closest nprobe cells.</li><li><strong>PQ (Product Quantization):</strong> Compresses vectors (e.g., from floats to bytes) to fit massive indices in RAM, trading off some precision.</li></ul><h3>Milvus</h3><p>Milvus is a full-featured, open-source vector database built for scale. It is “cloud-native,” meaning it separates storage and compute.</p><ul><li><strong>Best For:</strong> Enterprise production systems, teams needing CRUD operations (insert, delete, update), and massive datasets (billions of vectors).</li><li><strong>Architecture:</strong> It runs as a distributed service (often on Kubernetes). It handles persistence, replication, and failover automatically.</li><li><strong>Key Features:</strong></li><li><strong>Hybrid Search:</strong> Native support for filtering by metadata (e.g., WHERE author_id = 123) alongside vector similarity.</li><li><strong>Tunable Consistency:</strong> You can choose “Strong” or “Eventually” consistent, impacting latency.</li><li><strong>Multiple Index Types:</strong> Milvus actually wraps FAISS (and HNSWLib/Annoy) under the hood, giving you access to HNSW, IVF_FLAT, and IVF_PQ through a unified API.</li></ul><h3>Comparative Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7GMjoyeZTVc_KQ3_O2ZJg.png" /></figure><h3>Engineering Insight</h3><p>If you are building a Proof of Concept (PoC) in a notebook, use <strong>FAISS</strong>. It is lightweight and fast. If you are building a microservice that needs to run 24/7, handle concurrent writes, and scale to 100M+ documents, use <strong>Milvus</strong>.</p><h3>6. Prompt Engineering for RAG</h3><p>Once retrieval is done, we must construct the prompt. This is not just string concatenation; it is architecture.</p><h3>The “Lost in the Middle” Phenomenon</h3><p>Research shows LLMs prioritize information at the <strong>beginning</strong> and <strong>end</strong> of the context window. Information buried in the middle is often ignored.</p><ul><li><em>Strategy:</em> Sort your retrieved documents by relevance score, placing the highest scored documents at the start and end of the context block.</li></ul><h3>Guardrails</h3><p>Your system prompt must be robust.</p><blockquote><em>“You are a helpful assistant. Answer the user query using ONLY the provided context. If the answer is not in the context, state that you do not know. Do not use outside knowledge.”</em></blockquote><h3>Instruction Hierarchy</h3><ol><li><strong>System Instructions:</strong> Define behavior and constraints.</li><li><strong>Retrieved Context:</strong> The data source.</li><li><strong>User Query:</strong> The specific question.</li></ol><p>By wrapping context in XML tags (e.g., &lt;context&gt;...&lt;/context&gt;), you help the model distinguish between instructions and data, reducing prompt injection risks.</p><h3>7. Advanced RAG Techniques</h3><p>Moving beyond “Naive RAG,” here are the patterns distinguishing top-tier systems.</p><h3>Query Transformations</h3><p>Users write bad queries. “My internet is broken” is a terrible vector search query.</p><ul><li><strong>Query Rewriting:</strong> Use an LLM to rewrite “My internet is broken” to “Troubleshooting steps for network connectivity issues.”</li><li><strong>HyDE (Hypothetical Document Embeddings):</strong> Ask the LLM to hallucinate a <em>perfect answer</em> to the question. Embed that hallucination and search for documents that look like it. This bridges the semantic gap between a question and an answer.</li></ul><h3>Multi-Hop RAG</h3><p>Some questions require combining info from Document A and Document B.</p><ul><li><strong>Iterative Retrieval:</strong> The LLM generates a partial answer, determines it needs more info, generates a new query, retrieves again, and updates the answer. This is the foundation of Agentic RAG.</li></ul><h3>GraphRAG</h3><p>Vector databases struggle with relationships. If you ask “How are the CEO of Company A and the Director of Company B connected?”, vector search fails. <strong>Knowledge Graphs</strong> map entities and relationships. GraphRAG combines vector search (for unstructured similarity) with graph traversal (for structured relationships).</p><h3>8. Training and Optimization</h3><p>While most RAG is “frozen,” you can optimize the components.</p><ol><li><strong>Fine-Tuning Embeddings:</strong> If you are in a niche domain (e.g., Law, Chemistry), standard OpenAI embeddings might fail. You can fine-tune a BERT model using <strong>Matryoshka Representation Learning</strong> to align the vector space with your domain jargon.</li><li><strong>Hard Negative Mining:</strong> When training retrievers, don’t just use random documents as negatives. Use documents that look similar to the query but are <em>wrong</em>. This forces the model to learn fine-grained distinctions.</li></ol><h3>9. Evaluation of RAG Systems</h3><p>How do you know if your RAG system is good? “It looks good to me” is not a metric.</p><h3>The RAG Triad</h3><p>We evaluate three distinct links:</p><ol><li><strong>Context Relevance:</strong> Did we retrieve the right stuff? (Metric: Precision@K, Recall@K).</li><li><strong>Faithfulness:</strong> Did the LLM stick to the retrieved context, or did it hallucinate? (Metric: LLM-as-a-judge).</li><li><strong>Answer Relevance:</strong> Did the answer actually address the user’s query?</li></ol><h3>Tools</h3><p>Use frameworks like <strong>Ragas</strong> or <strong>TruLens</strong>. These use a strong LLM (like GPT-4) to grade the output of your system.</p><ul><li><em>Example:</em> GPT-4 reads the context and the answer and calculates a “Faithfulness Score” from 0 to 1 based on how many claims in the answer can be attributed to the context.</li></ul><h3>10. Applications</h3><h3>Enterprise Knowledge Assistants</h3><ul><li><em>Use Case:</em> An internal chatbot for employees to query HR policies, IT support, and project documentation.</li><li><em>Challenge:</em> Permissions. You must filter search results based on the user’s Access Control List (ACL). A junior engineer shouldn’t retrieve the CEO’s salary document.</li></ul><h3>Legal &amp; Compliance</h3><ul><li><em>Use Case:</em> Analyzing thousands of contracts to find specific liability clauses.</li><li><em>Architecture:</em> Heavy use of <strong>Parent-Child indexing</strong>. Retrieve the specific clause, but provide the full contract section for context. High emphasis on <strong>Faithfulness</strong> — hallucination here is a liability.</li></ul><h3>Customer Support Copilots</h3><ul><li><em>Use Case:</em> Suggesting answers to human agents based on historical ticket data.</li><li><em>Challenge:</em> Latency. The retrieval must happen in &lt;200ms. Requires aggressive caching and optimized HNSW indices in Milvus.</li></ul><h3>11. Common Failure Modes &amp; Pitfalls</h3><h3>1. The “Pizza” Problem (Retrieval Noise)</h3><p>If you ask about “neural networks” and the retriever pulls a document about “pizza” because of a vector glitch, the LLM might try to force a connection (“Neural networks are like layers of cheese…”).</p><ul><li><em>Fix:</em> Set a <strong>Similarity Threshold</strong>. If the top result has a cosine similarity &lt; 0.7, return “I don’t know.”</li></ul><h3>2. Context Window Overflows</h3><p>Even with 128k context windows, cost and latency scale linearly.</p><ul><li><em>Fix:</em> Summarization chains. If retrieved documents are too long, run a map-reduce summarization step before the final generation.</li></ul><h3>3. Sycophancy</h3><p>The model tends to agree with the user’s premise, even if the context contradicts it.</p><ul><li><em>Fix:</em> Strong system prompts instructing the model to correct false premises in the query.</li></ul><h3>12. RAG vs. Alternatives</h3><h3>RAG vs. Long Context Windows (Gemini 1.5 Pro / GPT-4-Turbo)</h3><p>Google’s Gemini 1.5 has a 1M+ token window. Can’t we just dump the whole database into the prompt?</p><ul><li><strong>Cost:</strong> Input tokens cost money. Reading 1M tokens for every query is bankrupting.</li><li><strong>Latency:</strong> Processing 1M tokens takes seconds to minutes. RAG takes milliseconds.</li><li><strong>Focus:</strong> “Lost in the Middle” still applies to massive contexts.</li><li><strong>Verdict:</strong> Long Context is for <em>single-session heavy analysis</em> (e.g., “Read this entire book”). RAG is for <em>scale</em> (e.g., “Search this library”).</li></ul><h3>RAG vs. Agents</h3><p>Agents are systems that can use tools. RAG is essentially a tool.</p><ul><li><strong>Future:</strong> The distinction is blurring. “Agentic RAG” involves an agent that <em>decides</em> when to RAG, how to query, and when to stop.</li></ul><h3>13. Future Directions</h3><h3>Multimodal RAG</h3><p>We are moving beyond text. <strong>ColPali</strong> and CLIP models allow us to index images, PDFs, and charts directly.</p><ul><li><em>Scenario:</em> “Find the schematic for the landing gear.” The system retrieves the image of the blueprint, and the Vision-LLM explains it.</li></ul><h3>Adaptive Retrieval</h3><p>Systems that learn from user feedback. If a user clicks “Thumbs Down,” the system records the query and the retrieved documents as a “Negative Pair” to fine-tune the embedding model later.</p><h3>Memory &amp; Personalization</h3><p>RAG is usually stateless. Future systems will have a “User Memory” vector store, retrieving facts about <em>you</em> (your preferences, past projects) to contextualize the answer.</p><h3>14. Conclusion</h3><p>Retrieval-Augmented Generation is the bridge that turns a generic reasoning engine into a domain-expert oracle. It solves the two biggest hurdles of LLM adoption: <strong>Truthfulness</strong> and <strong>Freshness</strong>.</p><p>However, building a demo is easy; building a production RAG system is hard. It requires a shift from “Prompt Engineering” to <strong>“Flow Engineering.”</strong> You must obsess over your data pipeline, tune your chunking strategies, and ruthlessly evaluate retrieval metrics.</p><p>As models get smarter and context windows get longer, RAG will not disappear. It will evolve. It will become the long-term memory of the AI agents of the future.</p><h3>Next Step for You</h3><p>If you are building a RAG pipeline today, stop looking at the LLM. Look at your data. Run a baseline evaluation using <strong>BM25 vs. Vectors</strong>. Then, choose your vector engine: start with <strong>FAISS</strong> for experimentation, but plan your migration to <strong>Milvus</strong> early if you need production-grade scale and persistence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e87c6d7433d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide to Training LoRA Adapters for Vision–Language Models Using PyTorch]]></title>
            <link>https://medium.com/@xiaxiami/a-practical-guide-to-training-lora-adapters-for-vision-language-models-using-pytorch-0f64c74af7fa?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f64c74af7fa</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[model-training]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 23:02:15 GMT</pubDate>
            <atom:updated>2025-11-30T23:02:15.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVS3cjjYaBFGi6APyvydSQ.png" /></figure><p>Vision–Language Models (VLMs) are rapidly becoming core components of modern multimodal systems. Whether the goal is image captioning, visual inspection, or open-ended reasoning, these models integrate visual perception with linguistic generation. However, full fine-tuning of VLMs is often expensive. <strong>LoRA (Low-Rank Adaptation)</strong> offers a memory-efficient alternative that updates only a small subset of the model parameters, enabling fast iteration and lower compute overhead.</p><p>This guide walks through an end-to-end workflow for training LoRA adapters using PyTorch and Hugging Face libraries, based on a commonly used dataset: <strong>MS COCO Captions</strong>. It also explains how this workflow generalizes to more advanced multimodal architectures using a <strong>Q-former</strong>, as seen in MiniGPT-4 and LLaVA.</p><h3>1. Why LoRA?</h3><p>Training vision-language systems typically involves hundreds of millions of parameters spread across encoders, decoders, cross-attention, and projection layers. Updating the entire model is resource-intensive and risks destabilizing pretrained knowledge.</p><p>LoRA addresses these issues by:</p><ul><li>Injecting low-rank matrices into linear layers</li><li>Freezing the original weights</li><li>Learning only lightweight parameter updates</li><li>Reducing memory usage by 10–100× depending on configuration</li></ul><p>The result is a flexible, efficient fine-tuning method especially suitable for early exploration.</p><h3>2. Overview of the Approach</h3><p>This tutorial focuses on a direct <strong>encoder → decoder</strong> architecture using:</p><ul><li><strong>Vision encoder</strong>: ViT-based model</li><li><strong>Text decoder</strong>: GPT-style model</li><li><strong>Dataset</strong>: COCO Captions</li><li><strong>Libraries</strong>: pytorch, transformers, datasets, peft</li></ul><p>The pipeline consists of:</p><ol><li>Dataset loading and preprocessing</li><li>Loading a pretrained vision-to-text model</li><li>Adding LoRA adapters</li><li>Training using supervised captioning loss</li><li>Evaluating and saving LoRA weights</li><li>(Later) Extending to LLM + Q-former architectures</li></ol><p>This foundation mirrors the design of industrial captioning systems and is directly transferable to research prototypes.</p><h3>3. Step-by-Step Implementation</h3><p>Below is the full technical workflow, including code snippets.</p><h3>3.1 Dataset Loading and Preprocessing</h3><p>We use the COCO caption dataset via Hugging Face:</p><pre>from datasets import load_dataset<br>from transformers import AutoTokenizer, ViTFeatureExtractor<br><br># Load COCO captions<br>dataset = load_dataset(&quot;lmms-lab/COCO-Caption&quot;)<br><br>feature_extractor = ViTFeatureExtractor.from_pretrained(<br>    &quot;google/vit-base-patch16-224&quot;<br>)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;gpt2&quot;)<br><br>def preprocess(example):<br>    image = example[&quot;image&quot;]<br>    pixel_values = feature_extractor(<br>        images=image, return_tensors=&quot;pt&quot;<br>    ).pixel_values[0]<br>    <br>    caption = example[&quot;captions&quot;][0]  # choose the first caption<br>    tokens = tokenizer(<br>        caption, truncation=True, padding=&quot;max_length&quot;, max_length=64<br>    )<br>    return {<br>        &quot;pixel_values&quot;: pixel_values,<br>        &quot;labels&quot;: tokens[&quot;input_ids&quot;],<br>    }<br><br>dataset = dataset.with_transform(preprocess)</pre><p>This produces aligned pairs of image tensors and tokenized caption sequences.</p><h3>3.2 Loading a Pretrained Vision–Language Model</h3><p>For fast iteration, an off-the-shelf encoder-decoder model is ideal:</p><pre>from transformers import VisionEncoderDecoderModel<br><br>model = VisionEncoderDecoderModel.from_pretrained(<br>    &quot;nlpconnect/vit-gpt2-image-captioning&quot;<br>)</pre><p>This model includes cross-attention bridging the vision encoder and language decoder.</p><h3>3.3 Attaching LoRA Modules</h3><p>LoRA modules are added via the Hugging Face peft library.</p><pre>from peft import LoraConfig, get_peft_model, TaskType<br><br>lora_config = LoraConfig(<br>    r=8,<br>    lora_alpha=32,<br>    target_modules=[<br>        &quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;, &quot;fc1&quot;, &quot;fc2&quot;<br>    ],<br>    bias=&quot;none&quot;,<br>    task_type=TaskType.SEQ_2_SEQ_LM,<br>)<br><br>model = get_peft_model(model, lora_config)<br><br># Verify trainable parameter count<br>trainable_params = sum(<br>    p.numel() for p in model.parameters() if p.requires_grad<br>)<br>total_params = sum(p.numel() for p in model.parameters())<br>print(f&quot;Trainable params: {trainable_params:,} / {total_params:,}&quot;)</pre><p>Key points:</p><ul><li>Only specific linear projections are adapted</li><li>LoRA rank r controls update capacity</li><li>Encoder may remain fully frozen</li><li>Decoder attention + FFN layers receive LoRA adapters</li></ul><h3>3.4 Training Setup</h3><p>Using the Hugging Face Trainer:</p><pre>from transformers import TrainingArguments, Trainer, DataCollatorForSeq2Seq<br><br>training_args = TrainingArguments(<br>    output_dir=&quot;./lora-coco&quot;,<br>    per_device_train_batch_size=16,<br>    per_device_eval_batch_size=8,<br>    num_train_epochs=3,<br>    fp16=True,<br>    logging_steps=100,<br>    save_total_limit=3,<br>    evaluation_strategy=&quot;epoch&quot;,<br>    save_strategy=&quot;epoch&quot;,<br>)<br><br>data_collator = DataCollatorForSeq2Seq(<br>    tokenizer=tokenizer,<br>    model=model,<br>)<br><br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=dataset[&quot;train&quot;],<br>    eval_dataset=dataset[&quot;validation&quot;],<br>    data_collator=data_collator,<br>)<br><br>trainer.train()</pre><p>Training considerations:</p><ul><li>Mixed-precision (fp16) reduces memory</li><li>2–3 epochs are enough for initial experiments</li><li>Small LoRA modules converge rapidly</li><li>CIDEr is the most informative captioning metric</li></ul><h3>3.5 Evaluating and Saving LoRA Weights</h3><p>After training:</p><pre>model.save_pretrained(&quot;./lora-coco-adapter&quot;)</pre><p>This saves <strong>only LoRA adapter weights</strong>, not the full model.</p><p>During inference:</p><pre>from peft import PeftModel<br><br>base_model = VisionEncoderDecoderModel.from_pretrained(<br>    &quot;nlpconnect/vit-gpt2-image-captioning&quot;<br>)<br>model = PeftModel.from_pretrained(base_model, &quot;./lora-coco-adapter&quot;)</pre><h3>4. Engineering Notes</h3><ul><li>Module names differ across architectures; inspect model.named_modules() before selecting LoRA targets.</li><li>Visual inputs consume more memory than text; consider gradient accumulation.</li><li>Caption supervision requires careful handling of EOS tokens and label shifting.</li></ul><p>With this setup, an engineer can train custom VLMs efficiently even on modest hardware (e.g., single RTX 3090/4090).</p><h3>5. Extending the Workflow to an LLM + Q-Former Pipeline</h3><p>Modern multimodal systems — such as <strong>MiniGPT-4</strong>, <strong>LLaVA</strong>, and <strong>BLIP-2</strong> — use a more modular architecture. Instead of a single decoder attending directly to image features, these systems introduce an intermediary <strong>Q-former</strong> to transform visual representations into language-aligned embeddings.</p><p>Below is a high-level but actionable outline for adapting the LoRA workflow to these architectures.</p><h3>5.1 Architectural Differences</h3><h3>Traditional Encoder–Decoder</h3><ul><li>Decoder cross-attends directly to vision encoder features</li><li>Good for captioning, but limited for open-ended reasoning</li></ul><h3>Q-Former / MiniGPT-4 / LLaVA</h3><ul><li>Frozen vision encoder (e.g., CLIP ViT-L/14)</li><li>Trainable Q-former that:</li><li>— Learns a set of visual “query tokens”</li><li>— Merges visual embeddings with learnable queries</li><li>— Produces compact latent representations</li><li>Projection layer maps Q-former outputs into LLM embedding space</li><li>Frozen LLM (LLaMA/Vicuna), <em>optionally LoRA-tuned</em></li></ul><p>This architecture allows multimodal reasoning via LLM priors.</p><h3>5.2 Adapted Fine-Tuning Pipeline</h3><h3>Step A. Freeze the Vision Encoder</h3><p>Use CLIP or comparable pretrained models:</p><ul><li>Strong zero-shot performance</li><li>No need to retrain</li><li>Outputs visual embeddings for the Q-former</li></ul><h3>Step B. Train or Adapt the Q-Former</h3><p>The Q-former includes:</p><ul><li>Learnable query tokens</li><li>Cross-attention between image embeddings and queries</li><li>Self-attention for token refinement</li></ul><p>Training objectives may use:</p><ul><li>Captioning datasets</li><li>Visual instruction datasets</li><li>Conversation datasets with (image, question, answer) triplets</li></ul><h3>Step C. Project Q-Former Output into the LLM Space</h3><p>A linear projection aligns dimensions:</p><pre>Q-former hidden size → LLM hidden size</pre><p>These projected visual tokens serve as the prefix to the LLM.</p><h3>Step D. Apply LoRA to the LLM</h3><p>LoRA adapters can be added to:</p><ul><li>Self-attention (q_proj, k_proj, v_proj, o_proj)</li><li>Feed-forward layers (gate_proj, up_proj, down_proj)</li></ul><p>The training focuses on teaching the LLM to interpret the embedded visual tokens.</p><h3>Step E. Train with Instruction Fine-Tuning</h3><p>Use a simple next-token prediction framework:</p><pre>&lt;image_tokens&gt; USER: &quot;Describe the image.&quot; ASSISTANT: &quot;...&quot;</pre><p>Training datasets:</p><ul><li>LLaVA-style visual dialogues</li><li>BLIP-2 instruction data</li><li>VQA datasets</li><li>COCO captions (optional)</li></ul><h3>Step F. Evaluate on Multimodal Reasoning Tasks</h3><p>Relevant benchmarks:</p><ul><li>VQAv2</li><li>TextVQA</li><li>COCO Captioning (for grounding)</li><li>Multi-turn conversational evaluations</li></ul><p>LoRA adapters for both the Q-former and LLM are saved.</p><h3>6. Summary</h3><p>This article presented a complete, practical workflow for training LoRA adapters on vision-to-text models using PyTorch and Hugging Face tooling. The approach is efficient, requires minimal compute, and enables fast experimentation.</p><p>Key takeaways:</p><ul><li>LoRA is an effective parameter-efficient technique for VLM tuning.</li><li>MS COCO Captions provides a simple and well-supported starting dataset.</li><li>Encoder–decoder models allow straightforward captioning fine-tuning.</li><li>The same LoRA method extends naturally to modern Q-former + LLM multimodal pipelines.</li></ul><p>With these tools, machine learning engineers can begin exploring multimodal capabilities, experimenting with Vision-LLMs, and scaling toward more advanced reasoning systems such as MiniGPT-4 or LLaVA.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f64c74af7fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speculative Sampling in LLMs: Speeding Up Inference with Drafts, Verification & Parallelism]]></title>
            <link>https://medium.com/@xiaxiami/speculative-sampling-in-llms-speeding-up-inference-with-drafts-verification-parallelism-6d948d268a87?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d948d268a87</guid>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm-inference]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 06:46:10 GMT</pubDate>
            <atom:updated>2025-11-08T06:46:10.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Autoregressive large language models generate one token at a time: for each new token, the model must run a full forward pass using all previously generated tokens as context. This sequential process introduces inherent latency — especially for long generations or when the system cannot batch many tokens in parallel.</p><p><strong>Speculative Sampling</strong> (also called <em>speculative decoding</em>) is a family of techniques developed to reduce inference latency and improve throughput <em>without sacrificing output quality</em>. The core idea is to use a faster, smaller draft model (or lighter mechanism) to propose several tokens ahead, then have a more capable target model verify or accept those proposals in bulk rather than one by one. This lets you generate more tokens per forward pass of the target model, reducing total inference time under favorable conditions.</p><p>In this blog, we’ll cover:</p><ol><li>What speculative sampling is and why it’s useful</li><li>Core methods: draft-target model, draft heads, verification, acceptance criteria</li><li>Implementation details: how to coordinate models, how to handle errors, latency/throughput trade-offs</li><li>Advanced variants and recent research</li><li>Comparisons, pros &amp; cons, and when speculative sampling helps most</li><li>Example (pseudo-code) of how to integrate it into an inference pipeline</li><li>Practical tips and considerations</li></ol><h3>1. What is Speculative Sampling &amp; Why It Matters</h3><h3>1.1 Autoregressive generation’s bottleneck</h3><p>Autoregressive LLMs generate text by predicting the next token conditioned on all preceding tokens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-WUrJrn1MDbDeWBhO2vGQ.png" /></figure><p>To generate a sequence of length T, you typically run T forward passes through the model. Even if each pass is fast, there are fixed costs per pass: memory load, context switching, kernel launches, etc. This is particularly inefficient when batch sizes are small (common in real-time or streaming use), since GPU/TPU hardware is underutilized.</p><h3>1.2 Key idea of speculative sampling</h3><p>Speculative sampling addresses this by adding a <em>draft-then-verify</em> phase:</p><ul><li>Use a <strong>draft model</strong> (smaller or less expensive) to speculatively predict K future tokens (or short sequence).</li><li>Use the <strong>target model</strong> (the large/high-quality model) to <em>verify</em> those K draft tokens, ideally in parallel if possible.</li><li>Accept as many of those draft tokens as match what the target model would have produced (often the longest prefix that matches).</li><li>For rejected tokens, the target model replaces them and the process moves forward.</li></ul><p>The hope is that many or all of the draft tokens will be accepted, so that the target model only needs to be invoked occasionally (or one continuous chunk) instead of for every single token. This yields speed‐ups when the draft model is much cheaper than the target model, and when draft proposals are good enough that the target often agrees.</p><h3>2. Core Methods &amp; Mechanisms</h3><p>Let’s look at the main building blocks in speculative sampling: the models involved, verification, acceptance rules, and decoding loops.</p><h3>2.1 Draft Model &amp; Target Model</h3><ul><li><strong>Target model</strong>: High quality, large, accurate (e.g. 70B+ parameters). Every final token must be consistent with the target model’s behavior.</li><li><strong>Draft (or auxiliary) model</strong>: Smaller or more efficient model, used to generate drafts. It could be a smaller LLM, a smaller version of the same architecture, or a subset of its layers.</li></ul><p>Key requirements:</p><ul><li>Must share the same <em>vocabulary</em> (tokenization), so that draft tokens are interpretable by the target model.</li><li>Sometimes need to <strong>fine-tune alignment</strong> so that the draft model’s distribution approximates or correlates well with the target model’s next-token predictions.</li></ul><h3>2.2 Verification / Acceptance</h3><p>Once draft tokens are proposed, they must be checked. Approaches include:</p><ul><li>Forwarding the draft tokens with the target model in one batch: that is, feed the concatenation of accepted prefix + draft tokens into the target model; generate its output distribution for the next K tokens; compare with draft proposals.</li><li>Accepting the longest prefix of tokens that <em>match</em> what the target model’s greedy (or sampling) outputs would have produced.</li></ul><p>For example, suppose:</p><ul><li>Draft model proposes: [token1, token2, token3]</li><li>Target model, given the same prefix context, would produce [token1, token2, token_alt3]</li></ul><p>Then accepted prefix is [token1, token2], and token3 is rejected. The target model must output token3 (and any further tokens) correctly.</p><h3>2.3 Looping &amp; Decoding</h3><p>A speculative sampling decoding loop often proceeds as:</p><ol><li>Start with input context x_{&lt;t}.</li><li>Draft model proposes K tokens: d_{1..K}.</li><li>Target model verifies; accepts h tokens (longest prefix matching).</li><li>Append the accepted tokens to the context.</li><li>If h &lt; K, target contributes the replacement for d_{h+1}.</li><li>Repeat until generation is complete.</li></ol><h3>2.4 Rejection Sampling &amp; Preservation of Target Distribution</h3><p>An important property: The final output must be <strong>statistically identical</strong> (or nearly so) to what one would get by pure target model sampling, to avoid output quality degradation. That requires carefully designed acceptance rules and verification.</p><p>Some methods use <em>modified rejection sampling</em>, letting the draft model make proposals, but only accepting them if they satisfy certain criteria in the target model distribution.</p><h3>2.5 Draft-heads &amp; Multi-head / Multi-token Drafting</h3><p>Instead of using a separate draft model, some methods embed <em>draft heads</em> in the target model, which predict future tokens ahead of the primary next‐token head. Examples include <em>Medusa heads</em>:</p><ul><li>These are additional LM heads attached to intermediate or last layer hidden states, which predict tokens at position t+1, t+2, …, up to t+K.</li><li>These draft heads are trained to match the target model’s predictions with some loss, so that they can serve both as proposals and, with suitable verification, speed up inference.</li></ul><h3>3. Variants &amp; Recent Research</h3><p>There have been multiple variants and improvements on speculative sampling. I’ll cover several of them.</p><h3>3.1 “Accelerating Large Language Model Decoding with Speculative Sampling”</h3><p>This is one of the earlier works that formalized speculative sampling. It showed that one can get ~2–2.5× decoding speedups for large models like Chinchilla using a smaller draft model + target model scheme, preserving output quality.</p><h3>3.2 Medusa &amp; Medusa Heads</h3><p>Medusa is a framework that adds multiple extra LM heads (draft heads) which predict future tokens. It explores draft token trees (multiple possible paths), verifying them, and choosing accepted tokens. Useful when one wants to reduce the dependency on an external smaller draft model.</p><h3>3.3 EAGLE (Extrapolation Algorithm for Greater Language-model Efficiency)</h3><ul><li>EAGLE proposes speculative sampling but pushes further: using <em>feature uncertainty</em> and predictive certainty of the draft tokens, and improving efficiency in verification. It reportedly beats other speculative methods in speed while maintaining identical distributions.</li></ul><h3>3.4 FR-Spec</h3><ul><li>Focuses on LLMs with large vocabularies, where the target LM head over many tokens is expensive. FR-Spec constrains the draft candidate selection to a frequency-prioritized subset of the vocabulary (more probable tokens), thereby reducing the overhead from draft proposals (which often pick low-probability tokens).</li></ul><h3>3.5 S$⁴$C (Speculative Sampling with Syntactic and Semantic Coherence)</h3><ul><li>Recognizes editorial coherence (syntax and semantics) when generating drafts. It seeks to retain coherence while generating drafts, improving both quality and acceptance rate. It uses multi-head drafts and continuous verification trees. Reported acceleration is large (2.26×–2.60× in certain tasks).</li></ul><h3>3.6 Recursive Speculative Decoding (RSD)</h3><ul><li>Builds a <strong>draft token tree</strong> without replacement sampling, maximizing diversity among candidate draft paths, while also considering fixed computational budgets. Works particularly well when you want to balance quality, latency, and budget.</li></ul><h3>4. Trade-offs, Losses, and Performance Considerations</h3><p>Speculative sampling is powerful, but there are trade-offs and constraints to be aware of.</p><h3>4.1 Speed vs Accuracy</h3><ul><li>If draft model proposes tokens that are often <em>rejected</em>, the overhead of drafting + verifying + rejecting may outweigh benefits.</li><li>If the draft model is too weak, acceptance rate drops, speedups vanish. Draft model size must be chosen to balance speed (lightweight) and alignment (matching target).</li></ul><h3>4.2 Overhead Costs</h3><ul><li>Memory footprint: holding both draft and target models (or draft heads) in memory can increase memory usage.</li><li>Verification cost: Running target model on multiple draft tokens per iteration is more work per iteration. But if many tokens are accepted, per-token cost drops.</li></ul><h3>4.3 Latency vs Throughput</h3><ul><li>In some cases, speculative sampling increases <em>throughput</em> (tokens/sec), but adds latency for individual tokens or initial tokens. For streaming or interactive settings, latency matters.</li><li>If the user prompt is one token at a time, speculative sampling may not help as much.</li></ul><h3>4.4 Distribution Matching &amp; Output Quality</h3><ul><li>Draft model + verification must preserve the distribution of the target model (i.e. same token probabilities). Otherwise, you might introduce bias.</li><li>Rejection sampling, thresholds for acceptance, verification strategy are crucial.</li></ul><h3>4.5 Implementation Complexity</h3><ul><li>Synchronization between draft and target model pipelines.</li><li>Handling prefix context correctly.</li><li>Memory and caching: K-step drafts require managing context and caching efficiently.</li></ul><h3>5. Detailed Example &amp; Pseudocode</h3><p>Here’s a simplified pseudocode for <strong>Draft-Target speculative sampling</strong>:</p><pre>def speculative_decode(context, draft_model, target_model, K):<br>    output = []  # final tokens<br>    while not done:<br>        # 1. Use draft model to propose K tokens<br>        draft_tokens = draft_model.generate(context, max_length=K)<br><br>        # 2. Feed context + all draft_tokens to target_model in one forward pass<br>        target_output_probs = target_model.predict(context, draft_tokens)<br><br>        # 3. Determine how many of the draft_tokens match what the target_model would produce<br>        # For simplicity, use greedy or top-1 sampling in target<br>        accepted = 0<br>        for dtok, top_tok in zip(draft_tokens, target_output_probs):<br>            if dtok == top_tok:<br>                accepted += 1<br>            else:<br>                break<br><br>        # 4. Append accepted tokens to output and context<br>        output.extend(draft_tokens[:accepted])<br>        context.extend(draft_tokens[:accepted])<br><br>        # 5. If not all K accepted, target generates next token itself<br>        if accepted &lt; K:<br>            ttok = target_model.generate(context, max_length=1)  # one token<br>            output.append(ttok)<br>            context.append(ttok)<br><br>    return output</pre><p>This is simplified: real implementations handle sampling (not just greedy), token probability comparisons, caching, etc.</p><h3>6. Practical Performance &amp; When Speculative Sampling Helps</h3><p>Speculative sampling tends to help more in scenarios where:</p><ul><li>You have a fast draft model that’s significantly cheaper than the target.</li><li>The context is large, so the draft model’s per-token overhead is small relative to target.</li><li>Prompts where continuation is “predictable” (like code, completion, or when token distributions are peaky).</li><li>When GPU/TPU hardware tends to be under-utilized due to small batch or latency-oriented tasks.</li></ul><p>Empirical results:</p><ul><li>Several papers report <strong>2× to 3× speedups</strong> in token generation without degradation.</li><li>For large-vocabulary models (very big output token sets), FR-Spec shows improvements by limiting candidate search space.</li><li>S⁴C shows both syntactic &amp; semantic coherence improvement — higher acceptance rates, more valid tokens per draft.</li></ul><h3>7. System Design &amp; Implementation Details</h3><h3>7.1 Caching &amp; Key-Value Cache</h3><ul><li>LLMs use <strong>KV-cache</strong> in decoding to reuse attention computations for past tokens.</li><li>The draft model needs to maintain its own cache, or reuse parts of cache if draft model shares architecture with target (or if draft heads are attached).</li></ul><h3>7.2 Model Loading &amp; Memory</h3><ul><li>Both draft and target model (or draft heads) must be in memory. Memory footprint increases.</li><li>In resource constrained environments (e.g. limited GPU VRAM), this can be a bottleneck.</li></ul><h3>7.3 Parallelism &amp; Batching</h3><ul><li>Verification of multiple draft tokens ideally happens in a batch forward pass on the target model. This increases GPU utilization.</li><li>If many tokens are accepted, you save many model passes.</li></ul><h3>7.4 Handling Rejected Tokens &amp; Fallbacks</h3><ul><li>In chain of token generation, if draft token is wrong, you must correct using the target.</li><li>Ensuring output is identical to what the target alone would produce (up to sampling randomness) is critical.</li></ul><h3>7.5 Parameter Choices</h3><ul><li><strong>Draft token length </strong>K<strong>:</strong> How many tokens the draft model proposes ahead. Larger K gives more potential speedup, but risk more rejections.</li><li><strong>Draft model strength:</strong> Size, how trained, alignment to target model.</li><li><strong>Acceptance criterion:</strong> Greedy matching, probability thresholds, etc.</li></ul><h3>7.6 Variants: Tree vs Linear Drafting</h3><ul><li>Linear drafting: always propose a linear sequence of K.</li><li>Tree based: propose multiple possible continuations (paths) in a tree structure, verify multiple paths in parallel. More complex but can increase accepted token count. See <em>Recursive Speculative Decoding</em>, <em>Medusa</em>.</li></ul><h3>8. Advanced Variants &amp; Recent Research</h3><p>Here are some of the more recent or advanced works:</p><ul><li><strong>S⁴C</strong>: Adds syntactic &amp; semantic coherence constraints to improve acceptance and generation quality.</li><li><strong>FR-Spec</strong>: Optimizes draft candidate selection by frequency ranking, useful for large output vocabularies.</li><li><strong>EAGLE</strong>: Uses feature uncertainty and draft token prediction from nearly final layers, improving over simpler draft models.</li><li><strong>Recursive Speculative Decoding (RSD)</strong>: Tree-based generation without replacement; builds candidate drafts and validation paths in tree form.</li></ul><p>Also interesting are works like <em>Learning Harmonized Representations for Speculative Sampling (HASS)</em>, which align representations between draft and target to reduce overhead.</p><h3>9. Pros &amp; Cons</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Dt7wlfWzuzErDoCseQ6zQ.png" /></figure><h3>10. Example Use Case &amp; Pseudocode</h3><p>Let me give a more fully fleshed example in a modern ML inference system.</p><h3>Example Setup</h3><ul><li><strong>Target model (TM)</strong>: 70B parameters</li><li><strong>Draft model (DM)</strong>: 7B parameters</li><li><strong>Draft length</strong> K = 5 tokens per iteration</li><li><strong>Sampling method</strong>: Greedy (for simplicity) or top-1 sampling from both models</li></ul><h3>Pseudocode</h3><pre>def speculative_generate(prefix, DM, TM, K, max_len):<br>    context = prefix<br>    output = []<br>    while len(output) &lt; max_len:<br>        # 1. Draft model proposes up to K tokens<br>        draft_tokens = DM.generate(prefix=context, max_tokens=K)<br><br>        # 2. Use TM to verify in batch<br>        # Construct input: context + draft_tokens<br>        # Compute TM outputs for each draft position<br>        tm_preds = TM.predict_next_tokens(context, draft_tokens)<br><br>        # 3. Find how many draft tokens match TM&#39;s prediction<br>        accepted = 0<br>        for d, t in zip(draft_tokens, tm_preds):<br>            if d == t:<br>                accepted += 1<br>            else:<br>                break<br><br>        # 4. Append accepted tokens<br>        if accepted &gt; 0:<br>            output.extend(draft_tokens[:accepted])<br>            context.extend(draft_tokens[:accepted])<br><br>        # 5. If less than K, fallback: TM generates the next token<br>        if accepted &lt; K:<br>            tm_tok = TM.generate(prefix=context, max_tokens=1)<br>            output.append(tm_tok[0])<br>            context.append(tm_tok[0])<br><br>    return output</pre><h3>Metrics to track</h3><ul><li><strong>Acceptance rate</strong>: fraction of draft tokens accepted over total draft attempts.</li><li><strong>Speedup</strong>: (time generating with speculative sampling) / (time producing same text with pure target model).</li><li><strong>Quality metrics</strong>: perplexity, human evaluation, or any task-specific metrics to ensure no degradation.</li></ul><h3>11. Practical Tips &amp; Engineering Considerations</h3><ul><li><strong>Choose a good draft model</strong>: ideally somewhat aligned to the target, not too weak. Sometimes a model of 10–20% size of target works well.</li><li><strong>Tune </strong>K: larger K gives more potential speed but increases risk of rejections.</li><li><strong>Monitor acceptance rate</strong>: if low, speculative may be doing more work than gains.</li><li><strong>Memory management</strong>: ensure both models (or draft heads) fit, manage caches carefully.</li><li><strong>Parallelize verification</strong> properly: batch TM calls over draft tokens.</li><li><strong>Warm-up effects</strong>: early iterations may have more context overhead; speculative gains show up more in steady state.</li><li><strong>Domain / prompt adaptation</strong>: some prompts are more predictable (e.g. code generation, auto-completions), making speculative sampling more effective.</li></ul><h3>12. Future Opportunities</h3><ul><li><strong>Dynamic Draft Models</strong>: switching draft model strength depending on prompt complexity.</li><li><strong>Hybrid Methods</strong>: combining speculative sampling with retrieval, context reuse, attention sparsity.</li><li><strong>Better Acceptance Criteria</strong>: using probability thresholds, calibration to improve acceptance, or even learned acceptors.</li><li><strong>User-Facing Latency Optimizations</strong>: streaming speculative results, partial speculative parse.</li><li><strong>Speculative Sampling in Multimodal LLMs</strong>: images + text, video, etc.</li></ul><h3>13. Conclusion</h3><p>Speculative sampling is a powerful tool in the LLM toolkit: with thoughtful design, it offers real speedups in inference without sacrificing output quality. Its core strength is in decoupling token generation into a cheap, fast proposal phase and a more expensive but amortized verification phase.</p><p>When implemented well, speculative sampling helps reduce per-token latency, improve GPU utilization (especially in small batch settings), and make large models more usable in interactive and streaming contexts.</p><p>If you build or deploy LLM inference, speculative sampling should be on your radar. Test it carefully, measure acceptance rates, monitor quality, and optimize the balance between draft and target models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d948d268a87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPUs for Large Language Models: Kernels, Triton, Memory Coalescing, and the Execution Hierarchy]]></title>
            <link>https://medium.com/@xiaxiami/gpus-for-large-language-models-kernels-triton-memory-coalescing-and-the-execution-hierarchy-7aaa32dac5ae?source=rss-94e461173820------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aaa32dac5ae</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Shawn]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 23:29:14 GMT</pubDate>
            <atom:updated>2025-09-21T23:29:14.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DrXAteyOeQOnafLJo_n2A.png" /></figure><h3>Introduction</h3><p>Large Language Models (LLMs) like GPT-4, LLaMA, and Mixtral are computationally demanding. Their massive scale — billions or even trillions of parameters — necessitates highly parallelized hardware to achieve practical training and inference times. That hardware is almost always the <strong>GPU (Graphics Processing Unit)</strong>.</p><p>GPUs were originally built for rendering graphics but have evolved into massively parallel processors capable of accelerating matrix multiplications, convolutions, and tensor operations — the backbone of deep learning. In fact, the rise of transformer-based models directly coincided with advances in GPU architectures and software frameworks like CUDA, cuDNN, and more recently, Triton.</p><p>In this blog, we’ll unpack the technical foundations of how GPUs accelerate LLMs. We’ll dive into:</p><ul><li>GPU programming concepts (blocks, threads, warps, waves).</li><li><strong>Kernels</strong> and how they orchestrate computation.</li><li><strong>Memory coalescing</strong>, the key to efficient bandwidth usage.</li><li><strong>Triton</strong>, a modern kernel programming language for AI workloads.</li><li>Examples of how these concepts come together in training and inference of LLMs.</li></ul><p>By the end, you’ll have a deep understanding of why GPUs are the backbone of LLMs, and how software and hardware interact to maximize efficiency.</p><h3>1. GPU Basics: Why GPUs Are Ideal for LLMs</h3><p>LLMs rely heavily on <strong>linear algebra operations</strong>: matrix multiplications, dot products, layer normalizations, and tensor reshaping. Training involves both forward passes (computing activations) and backward passes (gradients), with vast amounts of matrix multiplications.</p><p>A GPU is fundamentally different from a CPU:</p><ul><li><strong>CPU:</strong> Few cores (e.g., 8–64), optimized for sequential, general-purpose tasks.</li><li><strong>GPU:</strong> Thousands of smaller cores, optimized for massively parallel tasks.</li></ul><p>Matrix multiplication is embarrassingly parallel: each output element can be computed independently by summing products of input pairs. This aligns perfectly with the GPU architecture.</p><h3>2. CUDA Programming Model</h3><p>At the heart of GPU programming is <strong>CUDA (Compute Unified Device Architecture)</strong>, NVIDIA’s programming interface. CUDA abstracts the GPU as a device where developers can write <strong>kernels</strong> that execute across thousands of threads simultaneously.</p><h3>2.1 Threads, Blocks, and Grids</h3><p>CUDA organizes computation hierarchically:</p><ul><li><strong>Thread:</strong> The smallest unit of execution. Each thread performs computation on one piece of data.</li><li><strong>Block:</strong> A group of threads (1D, 2D, or 3D). Threads in a block can cooperate via shared memory.</li><li><strong>Grid:</strong> A collection of blocks. Grids can also be multi-dimensional.</li></ul><p>For example:</p><pre>__global__ void vector_add(float *a, float *b, float *c, int N) {<br>    int idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; N) {<br>        c[idx] = a[idx] + b[idx];<br>    }<br>}</pre><p>Here:</p><ul><li>threadIdx.x → thread’s index inside the block.</li><li>blockIdx.x → block’s index inside the grid.</li><li>blockDim.x → number of threads per block.</li></ul><p>The <strong>global thread ID</strong> is computed as blockIdx.x * blockDim.x + threadIdx.x.</p><p>This design allows CUDA to scale: if you launch 1024 threads per block and 1000 blocks, you get <strong>1 million threads</strong> in parallel.</p><h3>2.2 Warps and Waves</h3><p>Threads are not executed independently. GPUs group <strong>32 threads into a warp</strong> (on NVIDIA hardware). All threads in a warp execute the same instruction at the same time (SIMT: Single Instruction, Multiple Threads).</p><p>If threads in a warp diverge (e.g., some take an if branch, others don’t), performance drops because the warp serializes execution. This is called <strong>warp divergence</strong>.</p><p>On AMD GPUs, the term <strong>wavefront</strong> (often 64 threads) is used instead of warp.</p><p>Understanding warps/waves is critical for writing efficient kernels.</p><h3>3. Kernels: The Workhorses of LLMs</h3><p>A <strong>kernel</strong> is a GPU function executed by many threads simultaneously. Deep learning frameworks like PyTorch, TensorFlow, and JAX rely on pre-optimized kernels (e.g., from cuBLAS, cuDNN) for heavy lifting.</p><p>For LLMs, the most critical kernels include:</p><ul><li><strong>Matrix multiplication (GEMM)</strong> — core of transformer attention and MLP layers.</li><li><strong>Softmax kernels</strong> — for attention probability normalization.</li><li><strong>Layer normalization kernels</strong> — stabilize training.</li><li><strong>Activation functions</strong> (ReLU, GeLU, SwiGLU, etc.).</li></ul><p>Each of these kernels is tuned at the hardware level to exploit GPU parallelism and memory hierarchy.</p><h3>4. Memory Hierarchy and Coalescing</h3><p>GPUs have a <strong>memory hierarchy</strong>:</p><ol><li><strong>Registers</strong> — private to each thread, fastest.</li><li><strong>Shared memory</strong> — shared across threads in a block, very fast (on-chip).</li><li><strong>Global memory (VRAM)</strong> — accessible to all threads, but slower (off-chip).</li></ol><p>Efficient GPU programming requires minimizing expensive global memory accesses.</p><h3>4.1 Memory Coalescing</h3><p>When a warp of 32 threads loads data, the GPU fetches memory in chunks (e.g., 128 bytes). If each thread accesses consecutive memory addresses, the requests are <strong>coalesced</strong> into one transaction.</p><p>Example:</p><ul><li>Good (coalesced): Threads 0–31 load A[0]..A[31] (consecutive).</li><li>Bad (non-coalesced): Threads 0–31 load A[0], A[1000], A[2000]… (scattered).</li></ul><p>Non-coalesced memory access wastes bandwidth, slowing performance.</p><p><strong>LLMs are particularly sensitive</strong> here because matrix multiplications and attention involve massive amounts of memory movement.</p><h3>5. Triton: A New Way to Write Kernels</h3><p>Traditionally, writing GPU kernels in CUDA is complex. Enter <strong>Triton</strong>, an open-source programming model developed by OpenAI. Triton lets you write custom GPU kernels in Python with performance close to hand-written CUDA.</p><p>Example: Matrix multiplication kernel in Triton:</p><pre>import triton<br>import triton.language as tl<br><br>@triton.jit<br>def matmul_kernel(a_ptr, b_ptr, c_ptr, M, N, K, stride_am, stride_ak,<br>                  stride_bk, stride_bn, stride_cm, stride_cn, BLOCK_SIZE: tl.constexpr):<br>    pid = tl.program_id(axis=0)<br>    m = pid // N<br>    n = pid % N<br>    a = tl.load(a_ptr + m * stride_am + tl.arange(0, BLOCK_SIZE) * stride_ak)<br>    b = tl.load(b_ptr + n * stride_bn + tl.arange(0, BLOCK_SIZE) * stride_bk)<br>    c = tl.sum(a * b, axis=0)<br>    tl.store(c_ptr + m * stride_cm + n * stride_cn, c)</pre><p>Why Triton matters:</p><ul><li>Higher productivity (Python API).</li><li>Explicit control over memory layout.</li><li>Integration with PyTorch 2.0 (torch.compile uses Triton).</li></ul><p>LLMs benefit because attention, normalization, and activation kernels can be tuned more easily with Triton.</p><h3>6. Putting It Together: GPU Execution in LLM Training</h3><p>Let’s walk through what happens when you train an LLM step-by-step on GPUs.</p><h3>6.1 Forward Pass</h3><ol><li><strong>Token embeddings</strong> loaded from memory.</li><li><strong>Matrix multiplications</strong> (Q, K, V projections in attention).</li><li><strong>Softmax kernel</strong> normalizes attention scores.</li><li><strong>Weighted sum</strong> computed via GEMM.</li><li><strong>MLP layers</strong>: large matrix multiplications with GeLU/SwiGLU activations.</li><li><strong>Layer normalization</strong>.</li></ol><p>Each step invokes optimized GPU kernels.</p><h3>6.2 Backward Pass</h3><ul><li>Requires storing intermediate activations (big memory cost).</li><li>Computes gradients using kernels (often similar to forward kernels).</li><li>Optimizer step updates weights.</li></ul><p>Backward is usually <strong>2–3× more expensive</strong> than forward, because gradients and optimizer states are involved.</p><h3>7. GPU Concepts Applied to LLMs</h3><p>Let’s connect the GPU fundamentals to LLM workloads.</p><h3>7.1 Parameters</h3><ul><li>Stored in GPU VRAM.</li><li>Accessed repeatedly during forward and backward passes.</li><li>Memory coalescing ensures high throughput when loading weights.</li></ul><h3>7.2 Activations</h3><ul><li>Stored during forward pass for use in backpropagation.</li><li>Often the <strong>largest memory consumer</strong>.</li><li>Activation checkpointing trades memory for compute.</li></ul><h3>7.3 Optimizer States</h3><ul><li>Adam stores <strong>two extra states per parameter</strong> (momentum and variance).</li><li>Triples memory usage relative to raw parameters.</li></ul><h3>7.4 Gradient Accumulation</h3><ul><li>Large models don’t fit full batches in memory.</li><li>Gradients accumulated over micro-batches before weight update.</li><li>Kernels handle partial gradient updates efficiently.</li></ul><h3>8. Advanced Optimizations</h3><h3>8.1 Mixed Precision</h3><ul><li>Use <strong>FP16/BF16</strong> for activations and weights.</li><li>Reduces memory footprint and doubles throughput.</li><li>Requires care with numerical stability.</li></ul><h3>8.2 Kernel Fusion</h3><ul><li>Combine multiple operations into one kernel (e.g., bias add + activation).</li><li>Saves memory bandwidth.</li><li>Triton is excellent for writing fused kernels.</li></ul><h3>8.3 Multi-GPU and Model Parallelism</h3><ul><li><strong>Tensor parallelism</strong> splits matrix multiplications across GPUs.</li><li><strong>Pipeline parallelism</strong> distributes layers across GPUs.</li><li>Requires careful synchronization of kernels and memory transfers.</li></ul><h3>9. Example: Memory Coalescing in LLM Attention</h3><p>Consider scaled dot-product attention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*cS2Dho6HOpcEvtlMfaf4lA.png" /></figure><ul><li><strong>QK^T</strong> is a huge matrix multiplication.</li><li>If Q and K are stored contiguously, threads can coalesce loads.</li><li>If stored in strided format, performance drops.</li></ul><p>Frameworks like PyTorch use layout optimizations (e.g., row-major, column-major) to ensure coalescing.</p><h3>10. The Future: Beyond CUDA</h3><ul><li><strong>Triton</strong> will likely replace many hand-written CUDA kernels.</li><li><strong>New GPU architectures</strong> (NVIDIA Hopper, AMD ROCm) are increasing tensor core efficiency.</li><li><strong>Specialized accelerators</strong> (TPUs, AWS Trainium, Cerebras) are competing.</li><li>However, GPUs remain dominant for LLM workloads today.</li></ul><h3>Conclusion</h3><p>GPUs are the workhorses of LLMs, enabling practical training and inference of massive models. Key takeaways:</p><ul><li><strong>Execution model:</strong> Threads, blocks, warps, and waves define parallelism.</li><li><strong>Kernels:</strong> Specialized functions handle tensor ops like GEMM, softmax, normalization.</li><li><strong>Memory:</strong> Coalescing is critical for performance.</li><li><strong>Triton:</strong> A new way to write high-performance kernels.</li><li><strong>LLM workloads:</strong> Dominated by matrix multiplications, requiring optimized GPU utilization.</li></ul><p>Understanding these details is not just academic — it directly informs how frameworks like PyTorch, JAX, and DeepSpeed achieve state-of-the-art performance, and how researchers push the boundaries of what’s computationally possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aaa32dac5ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>