<?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 Shubham Rathod on Medium]]></title>
        <description><![CDATA[Stories by Shubham Rathod on Medium]]></description>
        <link>https://medium.com/@laravelshubham?source=rss-162878262f1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XLZDRejCYFv_mODJst6R5A.jpeg</url>
            <title>Stories by Shubham Rathod on Medium</title>
            <link>https://medium.com/@laravelshubham?source=rss-162878262f1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:50:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@laravelshubham/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[KV Cache Explained: From Transformer Fundamentals to Efficient LLM Inference]]></title>
            <link>https://medium.com/@laravelshubham/kv-cache-explained-from-transformer-fundamentals-to-efficient-llm-inference-8329c2cad518?source=rss-162878262f1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8329c2cad518</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shubham Rathod]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 14:16:53 GMT</pubDate>
            <atom:updated>2026-12-02T14:16:53.181Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into how Large Language Models avoid redundant computation, accelerate token generation, and optimize memory during inference.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*R_v3cHo5q4hEW99PFu40cg.png" /><figcaption>Source: Google Images.</figcaption></figure><h3>1. Introduction</h3><p>Have you ever wondered how Large Language Models (LLMs) like GPT generate hundreds or even thousands of words within seconds?</p><p>When we ask an LLM a question, it may appear as though the model produces the entire response at once. Behind the scenes, however, the model generates text incrementally, predicting <strong>one token at a time</strong>. This process is known as <strong>autoregressive generation</strong>.</p><h3>1.1 How Do LLMs Generate Text?</h3><p>Consider a simple example where we provide the following input to an LLM:</p><blockquote>The cat</blockquote><p>The model generates the response through a series of steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*IfczOgQtkjqW9lir1Y5wtQ.png" /><figcaption>Source: My Notes</figcaption></figure><p>At every generation step, the newly predicted token is appended to the existing sequence and becomes part of the input for predicting the next token. This process continues until the model reaches a stopping condition, such as an end-of-sequence token or a maximum output length.</p><h3>1.2 Autoregressive Text Generation</h3><p>The term <em>autoregressive</em> describes a process in which each new output depends on previously observed or generated outputs. In LLMs, each new token is predicted from the preceding sequence of tokens.</p><p>In our running example, the initial prompt <em>The cat</em> is followed by the predicted tokens <em>sat</em>, <em>on</em>, <em>the</em> and <em>mat</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-OcPYZhzNV7CC_g5Cw4WQ.png" /><figcaption>Source: My Notes</figcaption></figure><h3>1.3 The Computational Problem</h3><p>As in the example above (The cat sat on the mat), the input sequence grows with every newly generated token. Without any optimization, the model would repeatedly process the <strong>entire</strong> sequence, including tokens it has already processed in earlier generation steps.</p><p>For example, when predicting the word <em>mat</em>, the model would process “<em>The cat sat on the”</em> again, even though most of these tokens have already been processed several times. This introduces a significant amount of <strong>redundant computation</strong>, particularly inside the self-attention mechanism of the Transformer.</p><p>This may not seem like a major problem for a short sentence. But imagine generating a response containing thousands of tokens, or processing a document with a context length of 100,000 tokens. As the sequence grows, so does the computational cost.</p><h3>1.4 Can We Avoid This Redundant Computation?</h3><p>Can we store some of the previously computed information and reuse it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*4YRhFWkPqpfrUsA5iI07TA.png" /><figcaption>Source: My Notes</figcaption></figure><p>The answer lies in an optimization technique known as <strong>Key-Value Caching</strong>, commonly called <strong>KV Cache</strong>.</p><p>KV Cache is one of the fundamental optimization techniques used in modern autoregressive LLM inference. It allows models to reuse previously computed Key and Value representations instead of recomputing them at every generation step.</p><h3>2. Where Does KV Cache Fit in the Transformer?</h3><p>Before diving into the mechanics of KV Cache, it is important to understand where it fits within the Transformer architecture.</p><p>The Transformer was introduced in 2017 in the paper “<em>Attention Is All You Need”</em>. The original architecture consists of two major components: an <strong>Encoder</strong> and a <strong>Decoder</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJoaC7tpBlKNW-EmBOsITA.png" /><figcaption>Source: Image Captioning with an End-to-End Transformer Network by Atul Ranjan</figcaption></figure><h3>2.1 Encoder vs. Decoder</h3><p>Although both components rely on attention, they serve different purposes.</p><p><strong>Encoder.</strong> The encoder processes an input sequence and produces contextual representations of its tokens. In a standard bidirectional encoder, each token can attend to tokens that appear both before and after it. The primary objective is to <em>understand and represent</em> the input.</p><p><strong>Decoder.</strong> The decoder is responsible for <em>generating</em> an output sequence. During autoregressive generation, it predicts the next token from the tokens that have already been provided or generated. Unlike a bidirectional encoder, the decoder uses <strong>causal self-attention</strong>, which prevents a token from attending to future tokens.</p><h3>2.2 Types of Transformer Architectures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*YJgO3BquOQ7o0GZjr6L8qw.png" /><figcaption>Source: My Notes</figcaption></figure><h3>2.3 Where Exactly Does KV Cache Exist?</h3><p>KV Cache operates <strong>inside the attention mechanism of each Transformer decoder layer</strong>. Within self-attention, token representations are transformed into three components: a <strong>Query (), a Key () and a Value ()</strong>.</p><p>KV caching is primarily used during autoregressive inference in <strong>decoder-only models</strong> such as GPT and Llama, or in the decoder of encoder-decoder models such as T5. Standard encoder-only models such as BERT process the whole input sequence together rather than generating tokens sequentially, so they do not need the conventional autoregressive KV Cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*rG98Zh3w65BPz3ZIa8qSPw.png" /><figcaption>Source: My Notes</figcaption></figure><h3>2.4 Training vs. Inference</h3><p><strong>During training,</strong> the target sequence is already available. Using causal masking, the model can process many token positions in parallel while preventing each position from seeing future tokens. Because the model does not need to generate the training sequence one token at a time, <strong>conventional autoregressive KV caching is generally unnecessary.</strong></p><p><strong>During inference,</strong> the future output tokens are unknown. The model must generate new tokens sequentially, with each prediction depending on the preceding sequence. Without KV Cache, previously processed token representations would be recomputed in later generation steps. With KV Cache, previously computed Keys and Values are reused, avoiding much of this redundant computation.</p><h3>3. Understanding Self-Attention</h3><p>Before understanding <em>why</em> we cache Keys and Values, we need to understand what Queries, Keys and Values actually are, how they are computed, and what role each plays in attention.</p><h3>3.1 From Text to Token Embeddings</h3><p>Neural networks cannot directly understand words, so before attention the model converts text into numbers in two steps:</p><ul><li><strong>Tokenization:</strong> converting text into a sequence of token IDs.</li><li><strong>Embedding:</strong> converting each token ID into a dense numerical vector.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*r8TF-0pkIUw05BWkSnWUYA.png" /><figcaption>Source: My Notes</figcaption></figure><h3>3.2 Why Do We Need Positional Information?</h3><p>The self-attention mechanism, by itself, does not inherently encode the order of tokens.</p><p>Consider the following two sentences:</p><blockquote><em>The cat chased the dog.</em></blockquote><blockquote><em>The dog chased the cat.</em></blockquote><p>Both sentences contain the same words, but their meanings are different because of the order in which those words appear.</p><p>Transformers incorporate positional information to help distinguish these relationships.</p><p>💡 Positional information is particularly important for KV Cache, because cached representations must remain consistent with their original token positions.</p><h3>3.3 What Are Queries, Keys and Values?</h3><p>Instead of directly comparing token embeddings, the attention mechanism projects each token representation into three different vectors:</p><ul><li><strong>Query (Q): </strong>What information am I looking for?</li><li><strong>Key (K):</strong> What information can I be matched against?</li><li><strong>Value (V):</strong> What information do I contribute if attended to?</li></ul><p>An intuitive analogy</p><p>Imagine searching for information in a library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*-59NymqaqLumctyB0BDSAg.png" /><figcaption>Source: My Notes</figcaption></figure><p>Your Query is compared against the available Keys to determine relevance. Based on that relevance, information is retrieved from the corresponding Values.</p><h3>3.4 How Are Q, K and V Computed?</h3><p>Queries, Keys and Values are produced by multiplying the input representations by three learnable weight matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*KqdIOWa9iKDYqD2Df5r2xg.png" /><figcaption>Source: My Notes</figcaption></figure><p>The weight matrices are learned during training and remain fixed during standard inference. The resulting Q, K and V vectors, however, depend on the input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*oAZVe0pW3aDYYywz0Iq-bg.png" /><figcaption>Source: My Notes</figcaption></figure><h3>3.5 Understanding Scaled Dot-Product Attention</h3><p>Now that we have computed Q, K and V, how do we actually use them?</p><p>The Transformer uses a mechanism called <strong>Scaled Dot-Product Attention</strong>, mathematically represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*YomDESfyhvl9qYBFiRTXAA.png" /><figcaption>Source: My Notes</figcaption></figure><p>Step 1: Calculate the attention scores — (QKᵀ)</p><p>Step 2: Scale the attention scores</p><p>Why is scaling necessary?</p><p>As the dimensionality of Query and Key vectors increases, their dot products can become large in magnitude.</p><p>Large attention scores can push softmax into regions where its output becomes extremely concentrated and its gradients become small, making training more difficult.</p><p>Dividing by <strong><em>√dₖ </em></strong>helps stabilize the magnitude of attention scores.</p><p>Step 3: Apply softmax</p><p>Softmax converts raw attention scores into non-negative attention weights that sum to one.</p><p>Step 4: Multiply the attention weights by Values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*lh4CzEP3euFpz8NYEyTjHw.png" /><figcaption>Source: My Notes</figcaption></figure><p>The resulting vector is a context-aware representation produced by the attention mechanism.</p><p>This highlights the fundamental distinction between Q, K and V:</p><p><strong>Queries and Keys determine how much attention to pay, while Values determine what information is collected.</strong></p><h3>3.6 Understanding Causal Masking</h3><p>In a decoder-only Transformer, a token must not have access to future tokens.</p><p>When predicting the next token, the model should only use information that is already available.</p><p><strong>Why is causal masking important for KV Cache?</strong></p><p>When a new token is appended, the previous tokens cannot attend to it because of causal masking.</p><p>Consequently, their contextual representations remain unchanged in a standard causal Transformer, assuming fixed model parameters, consistent positional handling and deterministic inference.</p><p>Since their input representations remain unchanged, their corresponding Key and Value representations also remain unchanged.</p><h3>4. What Exactly Is KV Cache?</h3><p>In the previous section, we observed that during autoregressive text generation, a Transformer repeatedly computes the representations of previously processed tokens, even though those representations remain unchanged.</p><p>We also established two important properties of causal self-attention:</p><ul><li>The Key and Value representations of previously processed tokens remain unchanged when a new token is appended.</li><li>Computing the attention output for the latest token does not require the Query representations of previous tokens.</li></ul><p>What if, instead of recomputing these representations during every forward pass, we simply stored them in memory and reused them whenever required?</p><p>This is the fundamental idea behind <strong>Key-Value Caching</strong>, commonly referred to as <strong>KV Cache</strong>.</p><h3>4.1 Text Generation Without KV Cache</h3><p>Consider our original input prompt:</p><blockquote><em>The cat</em></blockquote><p>Suppose the model generates the following sentence:</p><blockquote><em>The cat sat on the mat.</em></blockquote><p>Although the final sentence appears as a continuous piece of text, the model generates it through multiple forward passes.</p><p>During each forward pass, the model predicts the next token based on the existing sequence. The newly generated token is appended to the sequence, which is then processed again during the next forward pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*Drn349Yh7puv10AU8zNTcQ.png" /><figcaption>Source: My Notes</figcaption></figure><p>Without KV Cache, the model repeatedly computes the intermediate representations of previously processed tokens.</p><p>This raises three fundamental questions:</p><ul><li>Why are we recomputing the Keys and Values of previously processed tokens?</li><li>Why are we computing previous Queries when we only require the latest Query?</li><li>Can we store previously computed Keys and Values and reuse them during subsequent forward passes?</li></ul><h3>4.2 What Is KV Cache?</h3><p>KV Cache is an inference optimization technique that stores the previously computed Key and Value representations within each Transformer attention layer, allowing them to be reused during subsequent autoregressive generation steps.</p><p>Instead of processing the entire input sequence through the Transformer at every generation step, the model processes only the newly appended token during standard cached decoding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*6HyQtoUhJwSTk4cxr5q8Zg.png" /><figcaption>Source: My Notes</figcaption></figure><h3>4.3 What Exactly Does KV Cache Store?</h3><p>One common misconception is that KV Cache stores previously generated words, token embeddings or attention scores.</p><p>In reality, KV Cache stores the intermediate Key and Value tensors produced by the attention mechanism.</p><h3>4.4 Why Cache Keys and Values but Not Queries?</h3><p>This is one of the most interesting questions about KV Cache. If the Queries, Keys and Values of previous tokens all remain unchanged, why cache only Keys and Values?</p><p>Think of a Query as a question asked by a particular token. A Key describes how a token can be matched against that question, and a Value holds the information the token contributes. When a new token arrives, it asks a <em>new</em> question through its Query. To answer it, we need the Keys and Values of previous tokens, but we do not need to ask all the previous questions again: their attention outputs were already computed, and they cannot change when a new token is appended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*fZ8z-7YxSTO1aHgtiSIOiw.png" /><figcaption>Source: My Notes</figcaption></figure><p>Queries are temporary computations, while Keys and Values are reusable representations.</p><p>Caching previous Queries would consume additional memory without providing a benefit for conventional autoregressive decoding.</p><h3>4.5 Where Is KV Cache Stored Within the Transformer?</h3><p>A common misconception is that a Transformer maintains one global Key matrix and one global Value matrix.</p><p>In reality, each Transformer layer maintains its own Key and Value cache.</p><p>The output representation of one layer becomes the input representation of the next layer.</p><p>Each layer has its own learned projection matrices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*p96TWMm9IRcl7vdwdO2Vsw.png" /><figcaption>Source: My Notes</figcaption></figure><p>For example, a Transformer with 32 layers logically maintains:</p><ul><li>32 Key cache tensors.</li><li>32 Value cache tensors.</li></ul><h3>4.6 With vs. Without KV Cache</h3><p>Without KV Cache</p><p>At every generation step, the entire sequence is processed through the Transformer.</p><p>The total number of token positions processed is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*OXW5bJk9Mkb9XFErY2pRbw.png" /><figcaption>Source: My Notes</figcaption></figure><p><strong>[2+3+4+5=14]</strong></p><p>Notice that the first two tokens, The and cat, are processed four times, even though their causal representations remain unchanged.</p><h4>With KV Cache</h4><p>During prefill, the entire initial prompt is processed. During subsequent decode steps, only the newly generated token is processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*QvclbIaRttRZwHwa_0Q_Vg.png" /><figcaption>Source: My Notes</figcaption></figure><p>The total number of token positions processed is: [<strong> 2+1+1+1=5 ]</strong></p><p>The percentage reduction in processed token positions is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*aXPZaYUQZPUK8kkVEcCxtA.png" /></figure><p>Even for this extremely small example, we eliminate approximately 64% of repeated token-position processing.</p><p>For longer sequences, the savings become substantially larger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*Ga5GAW0u4e3iPGj_17PVAw.png" /><figcaption>Source: My Notes</figcaption></figure><p>As the context length increases, the difference between quadratic and linear growth becomes increasingly significant.</p><p>This is one of the reasons KV Cache is essential for efficient long-context LLM inference.</p><h3>4.7 The Fundamental Time-Memory Trade-Off</h3><p>KV Cache is a classic example of a computer science optimization known as the time-space trade-off.</p><p>Instead of repeatedly performing expensive computations, we store intermediate results and retrieve them when required.</p><p>This is conceptually similar to memoization, database caching, and dynamic programming. (IFYK ME YK 😉)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*imQ4j5YYOEKUwJTw8dpryA.png" /><figcaption>Source: My Notes</figcaption></figure><p>The underlying principle is simple:</p><blockquote><strong>Perform a computation once, store the result, and reuse it whenever possible.</strong></blockquote><p>However, GPU memory is a limited resource.</p><p>As context length, batch size, and model depth increase, KV Cache can consume a substantial portion of available GPU memory.</p><p>This introduces an important engineering challenge: <strong>how can we maximize inference performance without exhausting GPU memory?</strong></p><h3>4.8 Key Takeaway</h3><p>KV Cache fundamentally changes the computational characteristics of autoregressive LLM inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*aEK9NTxsZCUjjPaCaTwz2A.png" /><figcaption>Source: My Notes</figcaption></figure><p>Rather than repeatedly processing the entire sequence, the model retains previously computed Keys and Values and processes only newly generated token positions.</p><p>This significantly reduces redundant computation while preserving the mathematical behavior of the attention mechanism.</p><p>However, the computational savings come at the expense of additional memory consumption.</p><p>As modern LLMs support increasingly large context windows and serve multiple users simultaneously, managing this memory efficiently becomes just as important as reducing computation.</p><h3>Conclusion</h3><p>KV Cache is a remarkably simple yet powerful optimization at the heart of modern LLM inference.</p><p>Throughout this article, we explored how Transformers generate text, how self-attention works, why redundant computations occur during autoregressive generation, and how KV Cache eliminates them by reusing previously computed Keys and Values.</p><p>We also understood how this optimization reduces the attention complexity of each decoding step from O(n²) to O(n), while introducing a fundamental trade-off between computational efficiency and memory consumption.</p><p>What I find particularly interesting about KV Cache is that it neither modifies the model’s learned parameters nor fundamentally changes the attention mechanism. Instead, it exploits an existing mathematical property of causal self-attention — previously computed Key and Value representations do not need to be computed again.</p><p>However, understanding KV Cache is only the beginning. Implementing it efficiently and managing it at scale introduces an entirely different set of engineering challenges.</p><p><strong>What’s Next?</strong></p><p>This article is the first part of a three-part series exploring KV Cache and efficient LLM inference.</p><ul><li><strong>Part 2 — KV Cache in Practice: Inference With and Without Caching:</strong> We will use GPT-2 to demonstrate how text generation works with and without KV Cache, comparing inference speed, memory consumption, and overall performance to understand its practical impact.</li><li><strong>Part 3 — Understanding LLM Inference: From Prefill to Production:</strong> We will explore how modern inference engines optimize token generation, manage memory and serve LLMs efficiently at scale.</li></ul><p>I hope this article helped you build a deeper intuition for KV Cache — not just what it does, but why it works and why it matters.</p><p>As I continue exploring the internals of Large Language Models, I look forward to sharing more of my learnings, implementations and experiments in the upcoming articles.</p><p>Until then, remember one of the fundamental principles of efficient computing:</p><p><strong>The fastest computation is often the one we don’t have to perform again.</strong></p><h3>Acknowledgements</h3><p>This article is a culmination of my learning and research through various resources, including YouTube tutorials, Medium articles, Hugging Face documentation, and open-source implementations.</p><p>I want to thank the researchers, educators, content creators, and the open-source AI community for sharing their knowledge and making complex concepts more accessible.</p><p>I hope this article contributes to that same spirit of learning and knowledge sharing.</p><p>Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8329c2cad518" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Engineering: From Prompt Engineering to Reliable LLM Systems]]></title>
            <link>https://medium.com/@laravelshubham/context-engineering-from-prompt-engineering-to-reliable-llm-systems-e336b5141ace?source=rss-162878262f1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e336b5141ace</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Shubham Rathod]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 03:43:33 GMT</pubDate>
            <atom:updated>2026-04-15T03:45:21.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYcCQ-0zHDC9by23B7g_OA.png" /><figcaption>Image: Gemini</figcaption></figure><p>LLMs are powerful, but getting them to work the way you expect is harder than it looks.</p><p>At first, it seems the problem is the prompts. You tweak instructions, adjust phrasing, and improve outputs.</p><p>But as systems get more complex, something else becomes the bottleneck.</p><p>Not the model. Not the prompt.</p><blockquote><em>The context.</em></blockquote><h3>What is Context Engineering?</h3><p>Imagine you’re building an AI agent to help manage customer support tickets. It reads past conversations, calls tools to check order statuses, and generates responses; all in a single workflow. Sounds powerful, right?</p><p>But here’s the problem no one warns you about upfront.</p><p>As the agent runs longer, something quietly breaks down. The tool call results pile up. Conversation history grows. Background instructions keep stacking. Before long, you’re hitting token limits, watching costs balloon, and noticing the model’s responses getting slower and stranger. The AI that was sharp at step 3 is hallucinating by step 15.</p><p><strong>This isn’t a model problem. It’s a context problem.</strong></p><h3>So, What Exactly Is Context?</h3><p>Every time an LLM generates a response, it only knows what is in front of it at that moment. There is no persistent memory and no background awareness. Just a window of tokens.</p><p>That window is called the <strong>context window</strong>, and everything inside it, your instructions, the user’s message, past conversations, retrieved documents, and tool outputs, is the context.</p><p>Think of it like briefing an assistant before a meeting. You do not hand over everything, only what matters for the decision at hand. What you include and what you leave out determines the outcome.</p><h3>Context Engineering</h3><blockquote><em>Andrej Karpathy describes LLMs as a new kind of operating system. The model is the CPU, and the context window acts as RAM, the system’s working memory.</em></blockquote><p>Just like an operating system carefully manages what fits into memory, someone has to manage what goes into the context window.</p><p>That is context engineering.</p><p>Context engineering is the practice of deciding what information the model sees, when it sees it, and how it is structured through prompts, retrieved documents, memory systems, or tool outputs, so the model can do its job well.</p><blockquote><em>As Tobi Lutke puts it, it is “the delicate art and science of filling the context window with just the right information for the next step.”</em></blockquote><p>It is not about writing a clever prompt. It is about designing the information environment the model operates in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*zim5AXXeR-XTW0yJyizfGw.png" /><figcaption>Image: X</figcaption></figure><h3>A Simple Mental Model</h3><p>To get context right, ask four questions:</p><ul><li><strong>What</strong> → What information does the model actually need right now?</li><li><strong>When</strong> → At what point should it be introduced?</li><li><strong>How</strong> → Should it come via prompt, retrieval, memory, or tools?</li><li><strong>How much</strong> → Is there too little (model is blind) or too much (model gets confused)?</li></ul><p>Get these right, and your model becomes reliable. Get them wrong, and even the most powerful LLM will struggle.</p><h3>Prompt Engineering vs. Context Engineering</h3><p>Before we talk about the difference, let’s make sure both terms are clearly defined.</p><p><strong>Prompt Engineering</strong> is the practice of crafting effective inputs, especially system prompts and instructions, to guide a model toward a desired response. It’s about <em>how you ask</em>. Things like phrasing, tone, task framing, chain-of-thought instructions, and few-shot examples all live here.</p><p><strong>Context Engineering</strong> is the broader discipline of managing the <em>entire information environment</em> the model operates in, across the full lifecycle of a task. It’s not just about the prompt. It’s about everything the model sees, from start to finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTfd_9paGAI8rpRLLDxazg.png" /><figcaption>Image: Anthropic</figcaption></figure><h3>The Prompt Engineering Era</h3><p>Prompt engineering was the first frontier of getting LLMs to behave well, and for good reason. A well-written system prompt can dramatically change how a model responds, making it more precise, more structured, or more aligned with a specific tone.</p><p>For simple, single-turn tasks, prompt engineering is often enough.</p><p><em>Ask a question → Get an answer. Tweak the phrasing → Get a better answer.</em></p><p>It works. And it still matters.</p><h3>Where Prompt Engineering Hits Its Limits</h3><p>The problem starts when you move beyond a single exchange.</p><p>Modern AI applications like coding assistants, customer support agents, and research tools don’t operate in one turn. They run across multiple steps, multiple tool calls, and multiple rounds of inference. The model isn’t just reading your prompt anymore. It’s accumulating:</p><ul><li>System instructions</li><li>Conversation history across many turns</li><li>Outputs from tool calls and APIs</li><li>Retrieved documents from external sources</li><li>MCP (Model Context Protocol) server data</li><li>User preferences and memory</li></ul><p>At this scale, the bottleneck is no longer <em>how cleverly you wrote the prompt</em>. It’s <em>how well you manage everything that fills the context window over time.</em></p><p>A perfectly written system prompt won’t save you if the model is buried under thousands of tokens of irrelevant context.</p><h3>Two Different Jobs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*5T8boyylQcuM-z5KHrcgRA.png" /><figcaption>Image: MyNotes</figcaption></figure><h3>A Shift in Thinking</h3><p>As AI systems become more complex and operate over longer workflows, the focus shifts.</p><p>You stop asking</p><ul><li>“What’s the best way to phrase this?”</li></ul><p>And start asking</p><ul><li>“What is the model seeing at this step, and is it the right information?”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnnD00XrY-_h7ljbTBWbqA.png" /><figcaption>Image: productcompass.pm</figcaption></figure><h3>Why We Need Context Engineering</h3><p>At a small scale, LLMs feel incredibly capable.</p><p>You give them a prompt, they respond intelligently, and everything works.</p><p>But as soon as you build real systems, <strong>multi-step agents, long conversations, tool-using workflows</strong>, something starts to break.</p><p>Responses become less precise. The model forgets earlier details. It starts making subtle mistakes, then obvious ones. Eventually, it feels like the model just… loses focus.</p><h3>The Real Constraint: Limited Attention</h3><p>LLMs don’t “remember” information the way we think they do. They operate over a fixed <strong>context window</strong>, using attention to process everything inside it.</p><p>But <strong>attention isn’t unlimited</strong>.</p><p>Just like humans have limited working memory, LLMs have a <strong>finite</strong> <strong>attention budget</strong>. As more information is added to the context, attention gets spread thinner, making it harder for the model to focus on what actually matters.</p><p>This isn’t just a usability issue. It comes from how these models are built.</p><h3>Where It Breaks</h3><p>Modern LLMs are based on the <strong>transformer architecture</strong>, where every token can interact with every other token in the context.</p><p>As the context grows, the model isn’t just reading more; it’s trying to connect everything with everything else.</p><p><strong>This results in n² pairwise relationships for n tokens.</strong></p><h3>Context Rot</h3><p>This is where things start to degrade.</p><p>As more context is added:</p><ul><li>earlier details become harder to access</li><li>Noise starts to outweigh the signal</li><li>Responses become less reliable</li></ul><p>More context doesn’t improve performance; it often makes it worse.</p><p>This is why an agent that works perfectly at step 3 can fail by step 15.</p><h3>Strategies for Context Engineering</h3><p>LLMs are constrained by a finite attention budget. So the goal isn’t to give them more context. It’s to give them the smallest set of high-signal information needed to produce the right outcome.</p><p>In practice, most context engineering techniques fall into four buckets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6RvX63MILF7NJRg4a97aPA.png" /><figcaption>Image: LangChain</figcaption></figure><h3>1. Write Context</h3><p>This is the context you create and maintain.</p><ul><li><strong>System prompts</strong> → Keep them clear, simple, and direct</li><li><strong>Scratchpad</strong> → Store intermediate reasoning or task progress</li><li><strong>State</strong> → Track what the agent knows within a session</li><li><strong>Long-term memory</strong> → Persist useful information across sessions</li></ul><p>Bad pattern: Overloading the system prompt with everything</p><p>Good pattern: Keep instructions minimal and move everything else to a structured context</p><h3>2. Select Context</h3><p>This is about choosing what the model should see right now.</p><ul><li>Retrieve only relevant documents (RAG)</li><li>Pull in tool outputs when needed</li><li>Use memory selectively, not blindly</li><li>Avoid passing the full conversation history every time</li></ul><p>The model doesn’t need everything, just what’s useful for this step.</p><h3>3. Compress Context</h3><p>This is about reducing context without losing meaning.</p><ul><li>Summarize long conversations</li><li>Trim irrelevant or outdated information</li><li>Keep only high-signal tokens</li></ul><p>More tokens do not mean better performance. Less, but sharper context wins.</p><h3>4. Isolate Context</h3><p>This is about separating context to reduce interference.</p><ul><li>Keep different tasks in separate contexts</li><li>Use sandboxes or environments for tool execution</li><li>Partition workflows across multiple agents when needed</li></ul><p>Not everything should live in one context window.</p><h3>A Different Way to Think About It</h3><p>Context engineering is not a single technique. It is a way of thinking about how information moves through your system.</p><p>Once you start looking at it this way, most patterns reduce to a few simple ideas:</p><ul><li><strong>Storing context</strong> — keeping information outside the model until it is needed</li><li><strong>Bringing context in </strong>— giving the model what matters for the current step</li><li><strong>Refining context</strong> — reducing noise and keeping signal</li><li><strong>Separating context </strong>— preventing unrelated information from interfering</li></ul><p>That is it.</p><p>You are not trying to make the model smarter. You are making their job easier.</p><p>And that shift is what separates something that works once from something that works reliably.</p><h3>Too Much Context Is Also Bad</h3><p>By now, we know that context matters. But there’s a second problem.</p><p>Too much context can be just as harmful. Longer context does not mean better responses.</p><h3>What Goes Wrong with Long Context</h3><p>When context becomes too large, a few things start to happen:</p><ul><li><strong>Context Poisoning</strong>: A wrong output or hallucination enters the context and keeps getting reused. The model builds on a bad assumption.</li><li><strong>Context Distraction</strong>: The context becomes so long that the model over-focuses on it, instead of relying on what it already knows.</li><li><strong>Context Confusion</strong>: Irrelevant or unnecessary information gets used, leading to lower-quality responses.</li><li><strong>Context Clash</strong>: Different parts of the context conflict with each other. The model has no clear way to resolve it.</li></ul><h3>Conclusion</h3><p>Context engineering is not about writing better prompts. It is about controlling what the model sees at every step of a workflow. As systems move from simple interactions to multi-step agents, the challenge shifts from phrasing instructions to managing information. Too little context makes the model ineffective, but too much context makes it unreliable. The difference lies in how well context is written, selected, compressed, and isolated over time.</p><p>The core idea is simple. Models perform best when they are given only what they need, when they need it. Everything else adds noise, increases failure modes, and reduces clarity. As context grows, errors can compound, attention can get diluted, and conflicting signals can emerge. This is why managing context is not an optimization; it is a requirement.</p><p>As AI systems become more capable, context engineering becomes a foundational skill. The quality of the system will depend less on the model itself and more on how well its context is designed and maintained.</p><h3>Acknowledgement</h3><ol><li><a href="https://blog.langchain.com/context-engineering-for-agents/">LangChain Blogs — Context Engineering</a></li><li><a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">Anthropic — Effective context engineering for AI agents</a></li></ol><h3>Image Credits</h3><ul><li>Google Gemini.</li><li>Google Images.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e336b5141ace" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Input to Output: Demystifying the Encoder-Decoder Architecture]]></title>
            <link>https://medium.com/@laravelshubham/from-input-to-output-demystifying-the-encoder-decoder-architecture-2c993ca04dfe?source=rss-162878262f1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c993ca04dfe</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shubham Rathod]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 12:47:56 GMT</pubDate>
            <atom:updated>2025-04-15T12:47:56.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfnBcZd-oihX3-I2-UoD8A.png" /><figcaption>Source: Abhishek Jain-Medium.</figcaption></figure><blockquote>Ever wondered how machines learn to translate languages, generate summaries, or even describe images? It all starts with a powerful architecture that knows how to <em>encode</em> meaning and <em>decode</em> it back into action.</blockquote><p>This is the story of the <strong>Encoder-Decoder architecture</strong>, the neural blueprint behind modern NLP breakthroughs like Transformers, GPT, and BERT spin-offs. Whether you’re training a chatbot or building an AI assistant, this is the foundation we all need to understand.</p><h3>What is an Encoder-Decoder Architecture?</h3><p>A Simple Encoder-Decoder is a two-part neural architecture used to convert one sequence into another, particularly useful in tasks that require an output sequence that is not directly correlated to the input sequence, such as machine translation, speech recognition, and text summarization.</p><h4>This architecture consists of two core components:</h4><ol><li><strong>Encoder</strong>: Takes the input sequence and compresses it into a fixed-size <em>context vector</em> (often called a <em>thought vector</em>) that captures its meaning.</li><li><strong>Decoder</strong>: Uses this context vector to generate the output sequence, one token at a time, often leveraging prior outputs and attention mechanisms to improve accuracy.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCA6-HH35CY3eYPXXPSHmA.png" /><figcaption>Source: <em>Hands-On Natural Language Processing with Python</em> by O’Reilly.</figcaption></figure><h3>Why Did We Need the Encoder-Decoder Architecture?</h3><p>Before encoder-decoder models, most sequence tasks relied on <strong>Recurrent Neural Networks (RNNs)</strong> or their enhanced versions like <strong>Long Short-Term Memory (LSTM)</strong> networks. While they worked well for tasks with a direct alignment between input and output, they struggled with:</p><ul><li>Variable-length input/output</li><li>Long-range dependencies</li><li>Bottlenecks from compressing all input into a single vector</li></ul><p>In tasks like machine translation, where the output structure can differ significantly from the input, these models often failed to retain critical information or generalize well.</p><p>The <strong>Encoder-Decoder architecture</strong> addressed these issues by splitting the work:</p><ul><li>The <strong>encoder</strong> reads and encodes the input sequence.</li><li>The <strong>decoder</strong> generates the output step-by-step from that encoded representation.</li></ul><p>This modular design introduced more flexibility, improved memory handling, and laid the foundation for attention mechanisms and transformer models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*507-5uCAOKGwu6eBujbUsA.png" /><figcaption>Source: Suvankar Maity — LinkedIn.</figcaption></figure><h3>Core Components: The Encoder &amp; Decoder</h3><p>The Encoder-Decoder architecture is built on two core components that work together to transform an input sequence into an output sequence: the <strong>encoder</strong> and the <strong>decoder</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3q4warnALGYwVAvZ4hPTQ.png" /><figcaption>Source: Scalar.</figcaption></figure><h3>🔹 The Encoder</h3><p>The encoder takes in the input sequence; Let’s say, a sentence like <em>“I am happy”</em>, and processes it one token at a time using a Recurrent Neural Network (RNN) or LSTM. As it moves through the sequence, it updates its internal state to capture the <strong>context, semantics, and structure</strong> of the input.</p><p>By the end of the input, the encoder summarizes everything it has seen into a fixed-size vector known as the <strong>context vector</strong> (or <em>thought vector</em>). This vector holds the distilled meaning of the entire input and serves as the bridge to the output side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXYD_pvS7MG5HHFh0ojm2w.png" /><figcaption>Encoder</figcaption></figure><h3>🔹 The Decoder</h3><p>The decoder takes this context vector and begins generating the output sequence, one token at a time. It’s <strong>autoregressive</strong>, meaning each output token depends not just on the context vector, but also on the tokens it has already generated.</p><p>During <strong>training</strong>, the decoder uses the actual previous target tokens (a technique called <em>teacher forcing</em>), while during <strong>inference</strong>, it relies on its own previous predictions.</p><p>This step-by-step generation allows the decoder to construct grammatically and semantically meaningful sequences that align with the input, such as translating <em>“I am happy”</em> into <em>“Je suis heureux.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNh3_WPGtQuN_d1rWqlfJA.png" /><figcaption>Decoder</figcaption></figure><p>In short, the encoder understands, and the decoder responds, forming the foundation of many powerful sequence-to-sequence models used in NLP today.</p><h3>Walkthrough Example: English to French Translation</h3><p>Input: “I am happy”</p><p>Encoder:</p><pre>Tokenizes → Embeds → Passes through layers → Outputs vector representations.</pre><p>Decoder:</p><pre>Uses those vectors + previous generated tokens to predict: Je → suis → heureux</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5mXC_T5hxsfHNrcKHN3eg.jpeg" /><figcaption>Encoder at each time step t.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuTPrwA7KkHh_pSmY-DX4A.jpeg" /><figcaption>Decoders produce one token at a time.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6lohewyRFiDDZ3gPEVgSg.jpeg" /><figcaption>Flow from Encoder to Decoder</figcaption></figure><h3>Recap: How Encoder-Decoder Architecture Works</h3><p>At its core, the <strong>Encoder-Decoder architecture</strong> is a communication pipeline between two neural networks. One that <em>understands</em> the input, and one that <em>generates</em> the output.</p><ul><li>The <strong>encoder</strong> reads the input sequence token by token, builds up context, and compresses it into a <strong>fixed-size context vector</strong> that represents the entire meaning of the input.</li><li>The <strong>decoder</strong> then takes that vector and, one step at a time, produces the <strong>output sequence</strong> using both the context and previously generated tokens to inform its decisions.</li></ul><p>This design allows models to handle <strong>variable-length sequences</strong>, making it perfect for tasks like <strong>machine translation, text summarization, and speech recognition</strong>.</p><p>By separating the roles of comprehension (encoder) and generation (decoder), this architecture paved the way for deeper language understanding and laid the foundation for the next wave of NLP innovations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*d3bCnkLEtu630Y5Vg3shfw.png" /><figcaption>Source: Aditya Santokhee.</figcaption></figure><h3>Training vs. Inference: How Encoder-Decoder Models Learn and Generate</h3><h3>Training Phase</h3><p>During training, both the <strong>input sequence</strong> (e.g., <em>“I am happy”</em>) and the <strong>target output sequence</strong> (e.g., <em>“Je suis heureux”</em>) are provided to the model.</p><ul><li>The <strong>encoder</strong> processes the input and produces a <strong>context vector</strong>(C).</li><li>The <strong>decoder</strong> is trained to predict the next word in the target sequence using: The context vector from the encoder and the <em>previous ground-truth tokens</em> from the target (a technique known as <strong>teacher forcing</strong>)</li></ul><p>This helps the model learn accurate mappings between input and output sequences.</p><h3>Inference Phase</h3><p>At inference time, we no longer have the target output. So the decoder generates the sequence <strong>one token at a time</strong>, using:</p><ul><li>The context vector from the encoder</li><li>Its <strong>previous predictions</strong></li></ul><p>This step-by-step, autoregressive process continues until the model generates an end-of-sequence token or reaches a maximum length.</p><h3>The Next Wave: From Encoder-Decoder to Seq2Seq and Transformers</h3><p>The encoder-decoder architecture didn’t just solve immediate problems, it sparked a new era in deep learning.</p><p>It led to the rise of Sequence-to-Sequence (Seq2Seq) models, which became the backbone of tasks like translation, summarization, and dialogue systems. By learning to map entire input sequences to output sequences, these models brought real structure and flexibility to NLP.</p><p>However, early Seq2Seq models struggled with one key issue: the context bottleneck. Compressing all input into a single vector meant important details could get lost, especially with longer sequences.</p><p>This led to the introduction of the Attention Mechanism, allowing the decoder to focus on different parts of the input as needed; a game-changer for accuracy and fluency.</p><p>Eventually, attention became the core of a new model: the Transformer, which replaced recurrence with parallelism and scale, giving rise to models like GPT, BERT, and T5.</p><h3>Conclusion</h3><p>The Encoder-Decoder architecture marked a fundamental shift in how deep learning models process and generate sequences. By separating understanding (encoder) from generation (decoder), it brought structure and scalability to complex tasks like translation, summarization, and dialogue systems.</p><p>While it started with RNNs and LSTMs, this architecture laid the groundwork for breakthroughs like attention mechanisms and eventually, Transformers — the backbone of today’s most powerful AI models.</p><p>Understanding this architecture isn’t just about learning history, it’s about grasping the core ideas that still power modern AI.</p><p>Whether we’re building our NLP model or diving into Transformers, it all starts here.</p><h3>Acknowledgments</h3><p>I’d like to thank <a href="https://www.linkedin.com/in/naikkrish/?originalSubdomain=in">Kirsh Naik</a> for his insightful teaching and clear explanations that laid the foundation for my understanding of the Encoder-Decoder architecture.</p><p>A special thanks to the authors of various Medium blogs, whose practical insights and visual explanations helped me connect theory to real-world applications.</p><p>This post also draws from the excellent resource: <em>Hands-On Natural Language Processing with Python</em> by O’Reilly 🔗 <a href="https://www.oreilly.com/library/view/hands-on-natural-language/9781789139495/7d9f1317-d2e0-46ea-b8f0-28d7b42ecabf.xhtml">Read the reference chapter here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c993ca04dfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From R1-Zero to R1: How DeepSeek is Pushing the Limits of AI Reasoning]]></title>
            <link>https://medium.com/@laravelshubham/from-r1-zero-to-r1-how-deepseek-is-pushing-the-limits-of-ai-reasoning-69354aaca886?source=rss-162878262f1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/69354aaca886</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deepseek-r1]]></category>
            <category><![CDATA[deepseek]]></category>
            <dc:creator><![CDATA[Shubham Rathod]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 01:45:41 GMT</pubDate>
            <atom:updated>2025-02-03T01:45:41.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dclgvN6FDAIXKIzPKUxiw.png" /><figcaption>Source: Reddit.</figcaption></figure><p>The rise of DeepSeek has sent shockwaves through financial markets, with Nvidia experiencing an unprecedented $600 billion drop in market capitalization on Monday — the largest single-day decline for any company in U.S. history <a href="https://www.cnbc.com/2025/01/27/nvidia-sheds-almost-600-billion-in-market-cap-biggest-drop-ever.html">(CNBC)</a>. This massive sell-off was driven by concerns that DeepSeek is emerging as a formidable competitor in the AI race. By enabling the training of powerful large language models (LLMs) at significantly lower costs, DeepSeek challenges the long-standing assumption that scaling AI requires ever-increasing GPU demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*4cKwWTpXB_2bq2-zMXiQ0Q.jpeg" /><figcaption>Source: Jared Friedman.</figcaption></figure><p>In this blog, I’ll break down DeepSeek’s training process and explore what this means for the future of AI development.</p><h3><strong>A Recap on LLM Training</strong></h3><p>Training a large language model (LLM) involves a multi-stage process designed to equip it with general knowledge, improve its ability to follow instructions, and refine its responses based on feedback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6EwtoszxVqBK_Odc-O1Aw.png" /><figcaption>Source: Weights &amp; Biases.</figcaption></figure><p>Here’s a breakdown of the key stages:</p><p><strong>1. Pre-training</strong></p><p>At this foundational stage, the model is exposed to vast amounts of text and code, enabling it to learn patterns, grammar, and general-purpose knowledge. The objective is to predict the next token in a sequence. For instance, given the input <strong>“write a bedtime _”</strong>, the model might complete it with <strong>“story.”</strong> While pre-training builds linguistic fluency, the model still struggles to understand and execute human instructions effectively, something addressed in the next phase.</p><p><strong>2. Supervised Fine-Tuning</strong></p><p>To make the model more instruction-aware, it undergoes fine-tuning on a curated dataset of instruction-response pairs. Here, each response serves as a labeled example, helping the model learn how to generate structured and contextually appropriate outputs. This stage significantly improves its ability to follow human prompts.</p><p><strong>3. Reinforcement Learning</strong></p><p>LLMs are further refined using feedback-based learning techniques. One of the most effective approaches is <strong>Reinforcement Learning from Human Feedback (RLHF),</strong> where human evaluators rank different responses, guiding the model to generate more useful and aligned outputs.</p><p>By combining these stages, LLMs evolve from predicting words in a sequence to understanding complex instructions and generating high-quality, human-aligned responses.</p><h3><strong>DeepSeek-R1-Zero: Reinforcement Learning Without Supervised Fine-Tuning (SFT).</strong></h3><p>DeepSeek-R1-Zero introduces a groundbreaking approach to training LLMs — achieving advanced reasoning capabilities purely through reinforcement learning (RL), without relying on <strong>Supervised Fine-Tuning (SFT).</strong> This marks a significant departure from traditional LLM training pipelines, as the supervised fine-tuning stage is entirely omitted.</p><p>To enable large-scale reinforcement learning without the need for human or AI-generated feedback, DeepSeek employs a <strong>rule-based reinforcement learning</strong> strategy. Instead of the widely used <strong>Reinforcement Learning from Human Feedback (RLHF)</strong> or <strong>Reinforcement Learning from AI Feedback (RLAIF),</strong> DeepSeek developed a proprietary method known as <strong>Group Relative Policy Optimization (GRPO).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5oXMjfpyjR5EZ0X3FcQ6w.png" /><figcaption>Source: AI PAPERS ACADEMY.</figcaption></figure><h4><strong>How GRPO Works</strong></h4><p>GRPO operates by training the model to generate optimal outputs through self-evaluation using predefined rules. Here’s how it works:</p><ol><li><strong>Generating Candidate Outputs</strong></li></ol><ul><li>Given a model and an input problem, the input is processed, and a batch of candidate outputs is generated.</li><li>Each output consists of a <strong>reasoning process</strong> and a <strong>final answer.</strong></li></ul><p><strong>2. Evaluating Outputs with Rule-Based Rewards</strong></p><p>Instead of relying on human or AI feedback, GRPO applies <strong>rule-based scoring</strong> to evaluate each output:</p><ul><li><strong>Accuracy Reward</strong></li><li>In scenarios with deterministic outcomes (e.g., solving math problems), accuracy is objectively verified.</li><li>For coding tasks, predefined test cases and a compiler provide direct feedback on correctness.</li><li><strong>Format Reward</strong></li><li>To ensure structured and interpretable responses, GRPO enforces a specific format.</li><li>For example, responses are structured with a reasoning section enclosed within &lt;think&gt; tags and the final answer within &lt;answer&gt; tags.</li></ul><h4><strong>Comparison Between PPO and GRPO</strong></h4><p>The key distinction between <strong>Proximal Policy Optimization (PPO)</strong> and <strong>Group Relative Policy Optimization (GRPO)</strong> lies in how they estimate advantages and manage computational efficiency.</p><ul><li><strong>PPO</strong> relies on a separate <strong>value model</strong> to estimate advantages using <strong>Generalized Advantage Estimation (GAE)</strong>. While effective, this introduces <strong>significant computational overhead</strong> and increases memory usage.</li><li><strong>GRPO</strong>, on the other hand, eliminates the need for a separate value model. Instead, it <strong>computes relative advantages within a group of outputs</strong>, significantly reducing memory and computation costs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*tBG3YpwVa_9S0KG_C7G7kA.png" /><figcaption>Source: BavalpreetSinghh on Medium.</figcaption></figure><p><strong>PPO Approach:</strong></p><ul><li>The policy model generates outputs <strong>O</strong> for a given input <strong>q</strong>.</li><li>A separate value model predicts a <strong>baseline v</strong>, which, combined with <strong>GAE</strong>, computes the advantage <strong>A</strong>.</li><li>The reward <strong>r</strong> includes a KL penalty term computed using both a <strong>reference model</strong> and a <strong>reward model</strong>.</li><li>This results in <strong>high computational costs</strong> due to multiple model dependencies.</li></ul><p><strong>GRPO Approach:</strong></p><ul><li>A group of outputs <strong>{o₁, o₂, …, oG}</strong> is generated for each <strong>q</strong>, and their corresponding rewards <strong>{r₁, r₂, …, rG}</strong> are computed using the reward model.</li><li><strong>Group-based computation</strong> normalizes these rewards, deriving relative advantages <strong>A₁, A₂, …, AG</strong> <strong>without</strong> requiring a value model.</li><li>The <strong>KL divergence</strong> between the trained policy and reference model is <strong>directly added</strong> to the loss function, simplifying the training process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*X4xF83Mq-RMK908JlXp8cg.png" /><figcaption>Source: Vinija’s AI Notes.</figcaption></figure><h3><strong>Why DeepSeek-R1 Is Needed: Addressing the Limitations of DeepSeek-R1-Zero</strong></h3><p>While <strong>DeepSeek-R1-Zero</strong> showcases the potential of reinforcement learning without supervised fine-tuning, it comes with notable drawbacks that limit its usability, particularly in real-world applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*haDa9dMBgt8037Bldpu7EQ.png" /><figcaption>Source: FS Ndzomga on Medium.</figcaption></figure><p><strong>Challenges with DeepSeek-R1-Zero</strong></p><ol><li><strong>Readability Issues</strong></li></ol><ul><li>The model’s outputs often suffer from <strong>poor readability</strong>, making responses harder to interpret.</li><li>The reasoning process, while structured, may not always be presented in a clear, user-friendly manner.</li></ul><p><strong>2. Language Consistency</strong></p><ul><li><strong>Inconsistent language usage</strong> is a recurring issue, with the model sometimes <strong>mixing multiple languages</strong> within a single response.</li><li>This can make outputs confusing, especially for users expecting coherent and structured answers in a single language.</li></ul><h3><strong>DeepSeek-R1: Advancing AI Efficiency and Usability</strong></h3><p>Building upon the foundation of <strong>DeepSeek-R1-Zero</strong>, <strong>DeepSeek-R1</strong> was developed to address its limitations, particularly in readability and language consistency. By integrating <strong>multi-stage training</strong> and a <strong>small amount of cold-start data</strong>, DeepSeek-R1 enhances reasoning performance while improving usability for real-world applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*FQZsiD_VOw7ZfN39ncnbLA.png" /><figcaption>Source: Google Images: ADaSCI.</figcaption></figure><h4><strong>Key Innovations in DeepSeek-R1</strong></h4><p>To overcome the limitations of <strong>DeepSeek-R1-Zero</strong>, <strong>DeepSeek-R1</strong> introduces a suite of cutting-edge innovations that enhance efficiency, reduce computational costs, and improve accessibility.</p><p>By integrating advanced techniques such as <strong>Mixture of Experts (MoE), Multihead Latent Attention (MLA), FP8 Quantization, and Multi-Token Prediction (MTP),</strong> DeepSeek-R1 pushes the boundaries of AI performance while making powerful models more practical for real-world applications.</p><p><strong>1. Mixture of Experts (MoE) Architecture</strong></p><ul><li>Instead of relying on a monolithic model, DeepSeek-R1 employs a <strong>Mixture of Experts (MoE)</strong> framework, breaking the model into smaller, specialized sub-models (experts).</li><li>Only the most relevant experts are activated for a given task, significantly reducing computational overhead.</li><li>This efficiency allows DeepSeek-R1 to run on <strong>consumer-grade GPUs</strong>, making high-performance AI more accessible.</li></ul><p><strong>2. Key-Value Memory Compression via Multihead Latent Attention (MLA)</strong></p><ul><li><strong>Key-value indices</strong>, which typically require substantial VRAM, are compressed using <strong>Multihead Latent Attention (MLA)</strong> techniques.</li><li>This results in an astounding <strong>93% reduction</strong> in storage requirements, optimizing memory usage without sacrificing performance.</li></ul><p><strong>3. Multi-Token Prediction for Faster Inference</strong></p><ul><li>Unlike traditional models that predict one token at a time, DeepSeek-R1 can <strong>predict multiple tokens simultaneously</strong>.</li><li>This method <strong>effectively doubles inference speed</strong>, significantly enhancing response times in real-world applications.</li></ul><p><strong>4. Low-Precision Computation for Greater Efficiency</strong></p><ul><li>DeepSeek-R1 leverages <strong>mixed-precision arithmetic</strong>, performing a significant portion of computations using <strong>8-bit floating-point numbers (FP8)</strong> instead of the standard <strong>32-bit (FP32)</strong>.</li><li>This approach <strong>dramatically reduces memory consumption</strong> and accelerates processing speeds, making AI inference far more efficient.</li></ul><h3><strong>DeepSeek-R1 Training Pipeline: A Multi-Phase Approach to Optimization</strong></h3><p>DeepSeek-R1 employs a <strong>structured, multi-phase training pipeline</strong> designed to enhance reasoning capabilities, improve instruction-following, and refine output quality. This process integrates reinforcement learning (RL), self-generated data labeling, and supervised fine-tuning to build a <strong>highly efficient and intelligent AI model</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*nJFnXXbIqRDEL3RiQf6k6g.png" /><figcaption>Source: Vellum.</figcaption></figure><p><strong>Phase 1: Cold Start — Establishing the Foundation</strong></p><p>To kickstart the training process, DeepSeek-V3-Base was fine-tuned using thousands of cold-start data points. This step established a strong initial foundation, allowing the model to develop a basic understanding of reasoning, language structure, and problem-solving.</p><p><strong>Phase 2: Reasoning Reinforcement Learning — Pure RL for Cognitive Enhancement</strong></p><p>Once the base model was in place, DeepSeek-R1 underwent a pure reinforcement learning (RL) phase, similar to DeepSeek-R1-Zero. This phase focused exclusively on enhancing the model’s reasoning capabilities, enabling it to tackle complex tasks with greater logical coherence and problem-solving efficiency.</p><p><strong>Phase 3: Rejection Sampling &amp; Supervised Fine-Tuning — Self-Labeled Data &amp; Knowledge Expansion</strong></p><p>As the model neared RL convergence, a self-improvement mechanism was introduced:</p><ul><li>Step 3.1<strong>: Rejection Sampling with Synthetic Data Generation</strong></li><li>The model evaluated its own responses from prior RL runs and selected the best examples as self-labeled training data (synthetic data).</li><li>This approach enabled the model to iteratively refine its understanding without requiring external human labeling.</li><li>Step 3.2<strong>: Merging Synthetic Data with Supervised Fine-Tuning</strong></li><li>The synthetic dataset was combined with supervised training data from DeepSeek-V3-Base, covering key domains like:</li><li>Creative writing</li><li>Fact-based question answering (QA)</li><li>Self-cognition and introspection</li><li>This integration ensured the model could learn from both high-quality AI-generated outputs and structured, domain-specific knowledge.</li></ul><p><strong>Phase 4: Diverse Reinforcement Learning — Generalizing Across Scenarios</strong></p><p>In the final phase, DeepSeek-R1 underwent a diverse RL cycle, where it was exposed to a wide range of prompts and real-world scenarios. This step further refined its adaptability, improving its ability to respond to varied instructions, domain-specific queries, and nuanced reasoning tasks.</p><h3><strong>Why Does DeepSeek-R1 Use a Multi-Stage Training Process?</strong></h3><p><strong>DeepSeek-R1’s multi-stage training pipeline</strong> is carefully designed to address key challenges in AI model development, ensuring <strong>clarity, reasoning depth, accuracy, and generalization.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*GdUos0FEdT4DyeTZDa8wbA.png" /><figcaption>Source: MarkTechPost.</figcaption></figure><p>Each stage plays a critical role in refining the model’s capabilities:</p><p>1. <strong>Cold Start Data — Building a Strong Foundation</strong></p><ul><li>Establishes a <strong>structured baseline</strong>, addressing early issues such as <strong>poor readability and inconsistent formatting</strong>.</li><li>Ensures the model starts with a well-organized linguistic and reasoning framework.</li></ul><p>2. <strong>Pure Reinforcement Learning — Self-Improving Reasoning</strong></p><ul><li>Allows the model to <strong>develop reasoning capabilities autonomously</strong>, refining its logical processes without direct human supervision.</li><li>Enables the emergence of <strong>complex problem-solving skills</strong> through iterative learning.</li></ul><p>3. <strong>Rejection Sampling + Supervised Fine-Tuning — Precision Through High-Quality Data</strong></p><ul><li>The model <strong>self-curates</strong> top-performing outputs using <strong>rejection sampling</strong>, selecting the most effective examples from previous RL runs.</li><li>Combines <strong>synthetic self-labeled data</strong> with <strong>supervised fine-tuning (SFT)</strong>, improving <strong>accuracy, factual reliability, and instruction-following.</strong></li></ul><p>4. <strong>Final Reinforcement Learning — Ensuring Robust Generalization</strong></p><ul><li>A final RL phase <strong>exposes the model to diverse real-world scenarios</strong>, enhancing its adaptability across various domains.</li><li>Strengthens the model’s ability to generalize beyond training data, making it more versatile and responsive to new challenges.</li></ul><h3><strong>Running DeepSeek-R1: Multiple Deployment Options</strong></h3><p>DeepSeek-R1 can be accessed through multiple deployment options, making it flexible for different use cases:</p><ol><li><strong>Direct API Access</strong></li></ol><ul><li>The simplest way to use DeepSeek-R1 is by consuming its <strong>official API</strong>, allowing seamless integration into applications.</li></ul><ol><li><strong>Cloud-Based Access via Hyperscalers</strong></li></ol><ul><li>Leading <strong>cloud providers</strong>, including <strong>NVIDIA, AWS, and Groq</strong>, offer access to DeepSeek-R1, enabling scalable, high-performance inference.</li></ul><ol><li><strong>Local Deployment with Ollama</strong></li></ol><ul><li>For those looking to run DeepSeek-R1 on their own hardware, the model can be <strong>pulled locally using Ollama</strong>, allowing for <strong>offline execution</strong> and greater control over data privacy.</li></ul><h4><strong>Running DeepSeek-R1 with Groq and LangChain</strong></h4><p>Below is a code snippet demonstrating how to integrate DeepSeek-R1 with <strong>Groq</strong> and <strong>LangChain</strong> for efficient inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lV77LTvmn-4QtuWjQYi-Q.png" /><figcaption>Running Deepseek with Groq.</figcaption></figure><h3><strong>Acknowledgments &amp; References</strong></h3><p>Understanding DeepSeek-R1 and its groundbreaking innovations would not have been possible without the valuable insights provided by various sources. I would like to extend my gratitude to all the researchers, engineers, and platforms that have contributed to making this information accessible.</p><p>Below are the key references that helped shape this article:</p><ul><li><a href="https://www.vellum.ai/blog/the-training-of-deepseek-r1-and-ways-to-use-it">https://www.vellum.ai/blog/the-training-of-deepseek-r1-and-ways-to-use-it</a></li><li><a href="https://aipapersacademy.com/deepseek-r1/">https://aipapersacademy.com/deepseek-r1/</a></li><li><a href="https://medium.com/@bavalpreetsinghh/deepseek-r1-understanding-grpo-and-multi-stage-training-5e0bbc28a281">https://medium.com/@bavalpreetsinghh/deepseek-r1-understanding-grpo-and-multi-stage-training-5e0bbc28a281</a></li><li><a href="https://medium.com/@sahin.samia/deepseek-r1-explained-pioneering-the-next-era-of-reasoning-driven-ai-3eeb5ac4d4a0">https://medium.com/@sahin.samia/deepseek-r1-explained-pioneering-the-next-era-of-reasoning-driven-ai-3eeb5ac4d4a0</a></li><li><a href="https://towardsdatascience.com/exploring-deepseeks-r1-training-process-5036c42deeb1">https://towardsdatascience.com/exploring-deepseeks-r1-training-process-5036c42deeb1</a></li><li><a href="https://medium.com/@simranjeetsingh1497/deepseek-models-compared-v3-r1-r1-zero-complete-guide-194abf94ac54">https://medium.com/@simranjeetsingh1497/deepseek-models-compared-v3-r1-r1-zero-complete-guide-194abf94ac54</a></li><li><a href="https://medium.com/thoughts-on-machine-learning/the-laymans-introduction-to-deepseek-r1-training-80d8ff7a887d">https://medium.com/thoughts-on-machine-learning/the-laymans-introduction-to-deepseek-r1-training-80d8ff7a887d</a></li><li><a href="https://wandb.ai/ayush-thakur/Intro-RLAIF/reports/An-Introduction-to-Training-LLMs-Using-Reinforcement-Learning-From-Human-Feedback-RLHF---VmlldzozMzYyNjcy">https://wandb.ai/ayush-thakur/Intro-RLAIF/reports/An-Introduction-to-Training-LLMs-Using-Reinforcement-Learning-From-Human-Feedback-RLHF---VmlldzozMzYyNjcy</a></li><li><a href="https://adasci.org/deepseek-v3-explained-optimizing-efficiency-and-scale/">https://adasci.org/deepseek-v3-explained-optimizing-efficiency-and-scale/</a></li><li><a href="https://vinija.ai/models/deepseek-R1/#training-pipeline-from-pre-training-to-reasoning">https://vinija.ai/models/deepseek-R1/#training-pipeline-from-pre-training-to-reasoning</a></li><li><a href="https://newsletter.languagemodels.co/p/the-illustrated-deepseek-r1">https://newsletter.languagemodels.co/p/the-illustrated-deepseek-r1</a></li><li><a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-mixture-of-experts">https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-mixture-of-experts</a></li><li><a href="https://www.analyticsvidhya.com/blog/2025/01/deepseek-r1-vs-openai-o1-vs-sonnet-3-5/">https://www.analyticsvidhya.com/blog/2025/01/deepseek-r1-vs-openai-o1-vs-sonnet-3-5/</a></li><li><a href="https://currentaffairs.adda247.com/chatgpt-vs-deepseek-a-detailed-comparison/">https://currentaffairs.adda247.com/chatgpt-vs-deepseek-a-detailed-comparison/</a></li><li><a href="https://www.capacitymedia.com/article/behind-the-deepseek-hype-costs-safety-risks-and-censorship-explained">https://www.capacitymedia.com/article/behind-the-deepseek-hype-costs-safety-risks-and-censorship-explained</a></li><li><a href="https://www.capacitymedia.com/article/deepseek-reactions">https://www.capacitymedia.com/article/deepseek-reactions</a></li></ul><p>A big thank you to everyone involved in advancing AI research and sharing their knowledge with the community! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69354aaca886" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Language Models with Unsloth: Leveraging LoRA, QLoRA, and Adapters for Real-World…]]></title>
            <link>https://medium.com/@laravelshubham/enhancing-language-models-with-unsloth-leveraging-lora-qlora-and-adapters-for-real-world-87a78e414497?source=rss-162878262f1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/87a78e414497</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Shubham Rathod]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 06:02:07 GMT</pubDate>
            <atom:updated>2024-11-05T06:02:07.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing Language Models with Unsloth: Leveraging LoRA, QLoRA, and Adapters for Real-World Applications</h3><h4>Unlocking the Potential of Large Language Models Through Efficient Adaptation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clN4wwcWrecCZHp95BJCIQ.png" /><figcaption>Image Source: gradient.</figcaption></figure><p>In the dynamic landscape of Natural Language Processing (NLP), Large Language Models (LLMs) are transforming industries, sparking an obsession among enterprises eager to unlock their potential. While LLMs excel at understanding and generating human language, fine-tuning these models has become critical for delivering high-performance, customized applications.</p><p>As organizations seek tailored solutions for specific challenges, the demand for fine-tuned models continues to surge. <strong>Unsloth</strong> — a open source streamlined framework designed for efficient and precise LLM fine-tuning. By manually deriving all compute-heavy mathematical steps and handwriting GPU kernels, Unsloth can magically accelerate training without any hardware changes. This innovative approach allows us to successfully customize a model and deploy the fine-tuned variant, making it accessible for a wide range of applications.</p><p>In this blog, I explore my fine-tuning journey with Unsloth, highlighting the benefits of this approach and detailing the process of deploying a refined GGUF model to Hugging Face. By employing both S<strong>upervised Fine-Tuning (SFT)</strong> and <strong>Parameter-Efficient Fine-Tuning (PEFT)</strong> techniques, I was able to steer the model toward the specific requirements through training on labeled data, ensuring it could adeptly handle the targeted applications. Meanwhile, PEFT allowed for enhancements in model performance with minimal computational overhead, optimizing efficiency without sacrificing quality. Together, these techniques maximized the model’s potential in a resource-efficient manner.</p><h3><strong>Fine Tuning</strong></h3><p>Fine-tuning a Large Language Model (LLM) refers to the process of adapting a pre-trained model to perform better on specific tasks or domains. LLMs are initially trained on vast datasets from diverse sources to understand and generate human-like text. While these models are general-purpose, fine-tuning allows them to specialize by training on a smaller, task-specific dataset that aligns with the needs of a particular application or industry. This additional training enables the model to offer more relevant, accurate, and context-aware outputs for specific use cases.</p><p>Fine-tuning can be done in various ways depending on the desired outcome. For some tasks, only a few layers of the model may need adjustment, while in others, more extensive retraining may be required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lv5MywCxqa3X_kgP1yPFiA.png" /><figcaption>Image Source: Unstructured.</figcaption></figure><p>The fine-tuning process can be computationally intensive, depending on the size of the model and the volume of training data, but the trade-off is a model that performs significantly better in specialized contexts. Furthermore, fine-tuning allows for increased flexibility in model applications, such as generating creative content, translating languages, or even providing legal or medical advice.</p><p>Despite its advantages, fine-tuning LLMs requires careful consideration to avoid issues such as overfitting, where the model becomes too specialized and loses its generalization ability. Additionally, ethical considerations, such as biases present in training data, must be managed to ensure that fine-tuned models remain fair and accurate.</p><p>When done correctly, however, fine-tuning can unlock the full potential of LLMs, making them highly effective tools for specific tasks while retaining the power and versatility of their original, broad training.</p><h3><strong>Exploring Different Approaches to Model Fine-Tuning</strong></h3><p>When working with pre-trained models, fine-tuning them to perform well on a new dataset is essential. But how we approach this fine-tuning can have a big impact on both performance and efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*I6ZdiiNiDbngiqq_2fHwkw.jpeg" /><figcaption>Image Source: Google Images.</figcaption></figure><p>Let’s understand the most common strategies for model fine-tuning and when each method shines.</p><p><strong>1. Retraining All Parameters</strong></p><p>This approach involves retraining <em>every</em> parameter of a pre-trained model using your new dataset. While this can be a powerful way to tailor the model to a specific task, it comes at a cost — particularly in terms of computational resources. Retraining all parameters can be expensive and time-consuming. Additionally, if your new dataset is relatively small, you risk overfitting, where the model becomes too specialized to the new data and loses its generalization capabilities. This method is best suited when you have a large and diverse dataset that requires the model to learn new, complex patterns that weren’t present in the original training data.</p><p><strong>2. Transfer Learning</strong></p><p>Transfer learning is a more efficient and widely used method that leverages the knowledge a model has already gained. Instead of retraining all the parameters, you fine-tune only the top layers or a specific subset of the model’s weights on your new dataset. This is especially useful when the new dataset is similar to the original one, as the model can transfer its learned features and patterns to the new task. Transfer learning is computationally lighter than retraining everything, and it can often lead to superior performance because the model starts with a solid foundation. It’s a great choice when you’re working with a related dataset and want to save time and resources.</p><p><strong>3. Parameter-Efficient Fine-Tuning (PEFT)</strong></p><p>As the name suggests, parameter-efficient fine-tuning focuses on updating only a small subset of the model’s parameters rather than all of them. This method is particularly valuable when your new dataset is small or you only need the model to learn specific patterns. PEFT minimizes the amount of computation required, making it an efficient choice when you need faster results or have limited resources. Despite updating fewer parameters, PEFT can still deliver strong performance, especially in scenarios where the pre-trained model already has a solid understanding of the broader context.</p><h3><strong>Fine-Tuning Methods</strong></h3><p>For large language models (LLMs), fine-tuning can be done in several ways, depending on the nature of the task and the type of feedback the model is receiving.</p><p>Let’s explore three prominent fine-tuning methods: <strong>Supervised Fine-Tuning</strong>, <strong>Reinforcement Learning with Human Feedback (RLHF)</strong>, and <strong>Direct Preference Optimization (DPO)</strong>.</p><h4><strong>1. Supervised Fine-Tuning</strong></h4><p><strong>What It Is:</strong></p><p>Supervised fine-tuning involves training a pre-trained model on a labeled dataset where the correct answers are known in advance. This method typically uses input-output pairs (e.g., a prompt and the desired response) to teach the model to replicate specific behaviors or generate accurate outputs for a given task.</p><p><strong>How It Works:</strong></p><ul><li><strong>Data Preparation</strong>: A dataset is curated where each input (question, prompt, etc.) is paired with the correct output (answer, response, etc.). These datasets are often labeled manually by humans or generated through automated methods (Synthetic Data Generation).</li><li><strong>Training</strong>: The model is then fine-tuned by adjusting its parameters to minimize the difference between its predictions and the true outputs (measured via a loss function, like cross-entropy loss).</li><li><strong>Objective</strong>: The goal is to make the model more accurate and aligned with the desired task-specific behavior by directly learning from examples.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*6uAbdRzrVJXFb5ntScNfiA.png" /><figcaption>Image Source: Deci AI.</figcaption></figure><h4><strong>2. Reinforcement Learning with Human Feedback (RLHF)</strong></h4><p><strong>What It Is:</strong></p><p>Reinforcement Learning with Human Feedback (RLHF) is a more advanced fine-tuning method where the model is trained using feedback derived from human evaluations of its responses. The model doesn’t just learn from labeled examples but also from human preferences or critiques.</p><p><strong>How It Works:</strong></p><ul><li><strong>Human Evaluation</strong>: After the model generates outputs (e.g., text), humans evaluate these outputs and provide feedback, which can be in the form of ratings or rankings.</li><li><strong>Reward Signal</strong>: The human feedback is converted into a reward signal, typically a scalar value or ranking, which tells the model how well it performed.</li><li><strong>Reinforcement Learning</strong>: Using this reward signal, the model adjusts its parameters through reinforcement learning, optimizing its responses to align more closely with human expectations.</li></ul><p>The aim is to make the model more aligned with human values, preferences, and intent rather than just statistical accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*Rn3ly_T7o_HxZabiqadvrA.png" /><figcaption>Image Source: Serrano.Academy.</figcaption></figure><h4><strong>3. Direct Preference Optimization (DPO)</strong></h4><p><strong>What It Is:</strong></p><blockquote>In 2023 paper “Direct Preference Optimization: Your Language Model is Secretly a Reward Model”, the authors propose a method called Direct Preference Optimization for effectively controlling Large-scale unsupervised Language Models (LLMs) without relying on more complex approaches such as Reinforcement Learning from Human Feedback (RLHF).</blockquote><p>Direct Preference Optimization (DPO) is a fine-tuning technique that directly learns from preference data, where human evaluators rank or choose between different outputs generated by the model. When applying DPO, the reward model is no longer required. The focus is on optimizing the model to produce outputs that are preferred by humans, rather than optimizing for accuracy or relevance per se.</p><p><strong>How It Works:</strong></p><ul><li><strong>Preference Data Collection</strong>: The model generates multiple candidate outputs for a given input, and human evaluators rank these outputs according to which they prefer.</li><li><strong>Learning from Preferences</strong>: The model uses this ranked data to learn which types of responses are more aligned with human preferences.</li><li><strong>Optimization</strong>: The model parameters are adjusted to maximize the likelihood of generating preferred outputs, with the model learning to prioritize those that tend to be rated highly by human evaluators.</li></ul><p>DPO aims to optimize the model to select outputs that are more likely to satisfy user preferences or to generate responses that humans find more appropriate in various contexts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*FwGEXpQTZUDoM5Xwc7WhgA.png" /><figcaption>Image Source: Serrano.Academy.</figcaption></figure><h3><strong>Fine-Tuning Techniques</strong></h3><h4><strong>What is LoRA?</strong></h4><p>LoRA (Low-Rank Adaptation) is a method designed to efficiently fine-tune large models by introducing low-rank matrices into the model’s weight matrices. The primary goal of LoRA is to reduce the computational cost and memory usage during the fine-tuning process without sacrificing the model’s ability to learn task-specific information. It works by adding trainable low-rank matrices to existing model weights rather than updating the full set of weights.</p><p><strong>Key Concepts of LoRA:</strong></p><ol><li><strong>Low-Rank Approximation</strong>: Instead of training all of the parameters in a model, LoRA focuses on adding low-rank matrices to the model’s weight updates. This makes the fine-tuning process more memory efficient, as low-rank matrices require fewer parameters to represent.</li><li><strong>Parameter Efficiency</strong>: LoRA adds additional parameters (low-rank matrices) to the model that are much smaller in size compared to the original model parameters. The idea is that these additional parameters capture the necessary adjustments required for a new task without needing to modify the entire weight matrix.</li><li><strong>Freezing Pre-Trained Weights</strong>: LoRA typically freezes the majority of the pre-trained weights and only trains the low-rank matrices. This reduces the number of trainable parameters and speeds up the training process.</li></ol><p><strong>How LoRA Works</strong></p><p>LoRA does two fundamental things differently from full-parameter fine-tuning:</p><ol><li>Tracks change to weights instead of updating weights directly.</li><li>Decomposes the large matrix of weight changes into two smaller matrices that contain the “trainable parameters.”</li></ol><p>#2 is where the secret sauce is at.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*G-r-_2lqMyudsXix13fOrw.png" /><figcaption>Source: Arxiv.</figcaption></figure><p><strong>Practical Consideration</strong></p><p>In practice, the <strong>rank r</strong> of the low-rank matrices is a hyperparameter that we need to tune. If r is too small, the model may not adapt well to the new task. If r is too large, it may negate the computational efficiency benefits of LoRA.</p><p>For instance:</p><ul><li>If W is a 1000×1000 matrix and the rank r is 10, the low-rank matrices A and B would have sizes 1000×10 and 10×1000, respectively. This means that instead of updating a 1000×1000 matrix, you are now updating two smaller matrices, A and B, each with 10,000 parameters, for a total of 20,000 parameters.</li></ul><p>This is much more computationally and memory efficient compared to directly fine-tuning all 1,000,000 parameters in the weight matrix W.</p><p>LoRA trainable parameters as a percentage of the overall total model parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*DMqVhlCEAgEZo7u-BxmR2Q.png" /><figcaption>Image Source: Entry Point AI.</figcaption></figure><h4><strong>What is QLoRA?</strong></h4><p>QLoRA builds upon the principles of LoRA but integrates <strong>quantization</strong> to further reduce the memory footprint and computational cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95RC2TR7xd2AGoB2xvtsJQ.png" /><figcaption>Image Source: My Notes.</figcaption></figure><p>While LoRA focuses on reducing the number of parameters by using low-rank approximations to the weight updates, <strong>quantization</strong> reduces the precision of the parameters, further decreasing the memory usage.</p><blockquote>QLoRA team created a special datatype called a NormalFloat that allows a normal distribution of weights to be compressed from 16-bit floats into 4-bits and then restored back at the end with minimal loss in accuracy.</blockquote><p>The result is a method that allows large models to be fine-tuned using less hardware, reducing both the storage requirements for the model and the cost of training.</p><p><strong>Key Concepts of QLoRA:</strong></p><ol><li><strong>Low-Rank Adaptation (LoRA)</strong>: As described earlier, LoRA reduces the number of trainable parameters by decomposing weight updates into low-rank matrices, which efficiently capture the necessary task-specific knowledge without changing the entire weight matrix.</li><li><strong>Quantization</strong>: This is the process of reducing the precision of the model’s weights and activations. For example, instead of using 32-bit floating-point values to represent the parameters, you may use 8-bit integers or 4-bit representations. This significantly reduces the amount of memory required for storing the parameters, thus enabling the training of larger models in resource-constrained environments.</li><li><strong>QLoRA — LoRA 2.0</strong>: By combining these two techniques, QLoRA applies both <strong>low-rank decomposition</strong> and <strong>quantization</strong> to the model’s weight updates. The idea is that the low-rank matrices can be quantized without significantly affecting the performance of the model, allowing for a massive reduction in both memory usage and computational overhead.</li></ol><p><strong>Quantization Techniques</strong></p><p>There are different methods of quantization that can be used in QLoRA, such as:</p><ul><li><strong>Uniform Quantization</strong>: This is the most straightforward approach, where the values in the matrices are scaled and rounded to the nearest integer within a fixed range.</li><li><strong>Non-Uniform Quantization</strong>: More sophisticated methods can be used where the quantization levels are not uniform but instead adapt to the distribution of the weights or gradients.</li></ul><p>The key benefit of QLoRA is that <strong>quantizing only the low-rank matrices</strong> (and not the full model parameters) helps strike a balance between computational efficiency and model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*o-dK6xyvCPVyt22ybjSpzg.png" /><figcaption>Image Source: Medium.</figcaption></figure><h4><strong>What Are Adapters?</strong></h4><p>Adapters are small neural network modules, typically consisting of one or two layers, that are inserted into the layers of a pre-trained model, often a transformer. These adapters are designed to fine-tune the model’s representations for a specific task or domain without modifying the entire model’s weights.</p><p>Instead of fine-tuning all the parameters of a large model — an approach that is computationally expensive and requires a large amount of labeled data — adapters allow us to only train the lightweight adapter layers. This significantly reduces the number of parameters that need to be updated, making adapters a far more resource-efficient solution for model adaptation.</p><p>By preserving the knowledge in the pre-trained model and focusing on small, task-specific adjustments, adapters save considerable computational resources compared to retraining the entire model. Additionally, multiple adapters can be added to the same foundation model, enabling multi-task learning and allowing for easy customization across different tasks without interference between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*aOwOFuhRX_14xHkxcZ8lTA.png" /><figcaption>Image Source: AHead of AI</figcaption></figure><h3><strong>Introducing Unsloth</strong> <strong>: A Game-Changer for Fine-Tuning Language Models</strong></h3><p>Unsloth is a powerful framework that simplifies and optimizes the fine-tuning of language models, making it easier for researchers and developers to enhance model performance. It integrates seamlessly with popular open-source models offering flexible fine-tuning methods such as <strong>LoRa</strong> and <strong>DPO</strong>. These options allow users to tailor the fine-tuning process to their specific needs, improving model adaptability for a wide range of natural language processing tasks.</p><p>A standout feature of Unsloth is its efficient memory usage, which enables fine-tuning on local GPUs, making advanced NLP tasks more accessible to a broader audience. By reducing the computational resources required for fine-tuning, Unsloth lowers the barrier to entry, allowing more users to experiment with and optimize large language models for diverse applications.</p><h4><strong>Setting Up the Environment for Fine-Tuning with Colab</strong></h4><p>In this session, we will set up our environment on Google Colab, utilizing a free-tier GPU (T5), to fine-tune the state-of-the-art language model: <strong>Llama3</strong>, developed by Meta.</p><p>Before we dive into the fine-tuning process, we’ll first walk through the steps for setting up the necessary libraries and configurations.</p><p><strong>Step 1: Installing the Unsloth Library</strong></p><p>We’ll begin by installing the <strong>Unsloth</strong> library, which provides the tools and functionalities we need to work with large language models (LLMs).</p><pre>%%capture<br># Installs Unsloth, Xformers (Flash Attention) and all other packages!<br>!pip install &quot;unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git&quot;<br><br># We have to check which Torch version for Xformers (2.3 -&gt; 0.0.27)<br>from torch import __version__; from packaging.version import Version as V<br>xformers = &quot;xformers==0.0.27&quot; if V(__version__) &lt; V(&quot;2.4.0&quot;) else &quot;xformers&quot;<br>!pip install --no-deps {xformers} trl peft accelerate bitsandbytes triton</pre><p><strong>Step 2: Importing Required Modules</strong></p><p>Next, we’ll import the necessary modules to set up and customize our language model. This includes the <strong>FastLanguageModel</strong> class, which is a key component of Unsloth.</p><pre>from unsloth import FastLanguageModel<br>import torch</pre><p><strong>Step 3: Instantiating the Model</strong></p><p>For our fine-tuning task, we’ll be working with the <strong>Llama3 </strong>model — Meta’s language model. We will instantiate the FastLanguageModel with specific configurations, such as:</p><ul><li><strong>Maximum Sequence Length</strong>: The maximum number of tokens the model can process at once.</li><li><strong>Data Type</strong>: Configuring the precision (e.g., float32, float16).</li><li><strong>4-bit Loading</strong>: A memory-efficient setting that allows the model to run on lower hardware specifications without sacrificing much performance.</li></ul><pre>max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!<br>dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+<br>load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.<br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name = &quot;unsloth/llama-3-8b-Instruct-bnb-4bit&quot;, # Choose ANY! eg teknium/OpenHermes-2.5-Mistral-7B<br>    max_seq_length = max_seq_length,<br>    dtype = dtype,<br>    load_in_4bit = load_in_4bit,<br>    # token = &quot;hf_...&quot;, # use one if using gated models like meta-llama/Llama-2-7b-hf<br>)</pre><p><strong>Step 4: Setting Up PEFT for Fine-Tuning</strong></p><p>In the next step, we’ll configure <strong>PEFT</strong> (Parameter Efficient Fine-Tuning) to optimize our model fine-tuning process. The <strong>FastLanguageModel</strong> object in Unsloth offers a get_peft_model method, which allows us to fine-tune the model with several customizable parameters.</p><pre>model = FastLanguageModel.get_peft_model(<br>    model,<br>    r = 16, # Choose any number &gt; 0 ! Suggested 8, 16, 32, 64, 128<br>    target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;,<br>                      &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;,],<br>    lora_alpha = 16,<br>    lora_dropout = 0, # Supports any, but = 0 is optimized<br>    bias = &quot;none&quot;,    # Supports any, but = &quot;none&quot; is optimized<br>    # [NEW] &quot;unsloth&quot; uses 30% less VRAM, fits 2x larger batch sizes!<br>    use_gradient_checkpointing = &quot;unsloth&quot;, # True or &quot;unsloth&quot; for very long context<br>    random_state = 3407,<br>    use_rslora = False,  # We support rank stabilized LoRA<br>    loftq_config = None, # And LoftQ<br>)</pre><p><strong>Key PEFT Parameters to Configure:</strong></p><ul><li><strong>Number of Attention Heads</strong>: Control how many attention heads the model uses in its transformer layers.</li><li><strong>Target Modules</strong>: Specify which parts of the model should be fine-tuned, allowing for more targeted adjustments.</li><li><strong>Dropout Rate</strong>: Adjust the probability of setting units to zero during training to prevent overfitting.</li><li><strong>LoRa Alpha</strong>: Tune the scaling factor for low-rank adapters, which can help the model learn better representations.</li><li>And more…</li></ul><p>Additionally, we’ll enable <strong>gradient checkpointing</strong>, a technique that helps reduce memory usage during training by storing only a subset of the model’s intermediate activations. This allows us to train larger models on limited hardware, further demonstrating Unsloth’s capabilities in optimizing model performance.</p><p>With PEFT configured, we’ll be able to efficiently fine-tune the <strong>Llama3</strong> model for our specific use case while maintaining performance and memory efficiency.</p><p><strong>Step 5: Data Preparation and Formatting</strong></p><p>Before fine-tuning our model, we need to provide it with access to a relevant dataset. In this case, we’ll be using the <a href="https://huggingface.co/datasets/heliosbrahma/mental_health_chatbot_dataset">heliosbrahma/mental_health_chatbot_dataset</a> , a text generation dataset designed for building conversational agents.</p><p><strong>Standardizing the Data Format</strong></p><p>For the fine-tuning process to be effective, we need to ensure that the data is presented in a format the model can understand. This means converting all the dataset entries into a consistent prompt structure with labeled inputs and outputs. By doing so, we guarantee that the model learns from a uniform pattern, making the fine-tuning process more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*bk7760hfRdQohBJpsPicPw.png" /><figcaption>Image Source: My Notebook.</figcaption></figure><p>Think of it like teaching a student with a textbook. If the textbook has a clear structure — questions followed by answers or prompts followed by responses — the student can more easily learn the material. In the same way, the standardized data format ensures that the model can learn the right relationships between inputs (prompts) and outputs (responses).</p><p>Example of Data Formatting:</p><pre>{&#39;conversations&#39;: [<br>{&#39;from&#39;: &#39;human&#39;, &#39;value&#39;: &#39;What is a panic attack?&#39;}, <br>{&#39;from&#39;: &#39;gpt&#39;, &#39;value&#39;: &#39;Panic attacks come on suddenly and involve intense and often overwhelming fear. They’re accompanied by very challenging physical symptoms, like a racing heartbeat, shortness of breath, or nausea. Unexpected panic attacks occur without an obvious cause. Expected panic attacks are cued by external stressors, like phobias. Panic attacks can happen to anyone, but having more than one may be a sign of panic disorder, a mental health condition characterized by sudden and repeated panic attacks.&#39;}<br>]}</pre><p>By mapping all the data points to this structured format, we can ensure that the model is able to effectively use the dataset during the fine-tuning phase. This step is crucial for making sure the model learns from the dataset in a way that aligns with our intended application.</p><p><strong>Step 6: Training the Model</strong></p><p>Now that we’ve prepared our dataset and configured the necessary parameters, it’s time to start the training process. In this step, we’ll use the <strong>SFTTrainer</strong> from Unsloth to fine-tune the <strong>Llama3</strong> model on our dataset.</p><p><strong>Setting Up the Trainer</strong></p><p>To initiate training, we first configure the <strong>SFTTrainer</strong>, which requires several key components:</p><ul><li><strong>Model</strong>: The language model we’re fine-tuning.</li><li><strong>Tokenizer</strong>: The tokenizer used to process the input text.</li><li><strong>Training Dataset</strong>: The dataset we prepared in the previous step.</li><li><strong>Max Sequence Length</strong>: The maximum token length for each input sequence.</li><li><strong>Dataset Processing</strong>: Number of parallel processes used to load the dataset.</li><li><strong>Packing</strong>: A setting that can speed up training for short sequences by packing them into fewer batches (we set this to False in our case).</li></ul><p>We also define the <strong>TrainingArguments</strong>, which control the training process. These include the batch size, number of gradient accumulation steps, learning rate, optimizer settings, and more.</p><p>Here’s how we configure the <strong>SFTTrainer</strong>:</p><pre>trainer = SFTTrainer(<br>    model = model,<br>    tokenizer = tokenizer,<br>    train_dataset = dataset,<br>    dataset_text_field = &quot;text&quot;,<br>    max_seq_length = max_seq_length,<br>    dataset_num_proc = 2,<br>    packing = False, # Can make training 5x faster for short sequences.<br>    args = TrainingArguments(<br>        per_device_train_batch_size = 2,<br>        gradient_accumulation_steps = 4,<br>        warmup_steps = 5,<br>        max_steps = 60,<br>        learning_rate = 2e-4,<br>        fp16 = not is_bfloat16_supported(),<br>        bf16 = is_bfloat16_supported(),<br>        logging_steps = 1,<br>        optim = &quot;adamw_8bit&quot;,<br>        weight_decay = 0.01,<br>        lr_scheduler_type = &quot;linear&quot;,<br>        seed = 3407,<br>        output_dir = &quot;outputs&quot;,<br>    ),<br>)</pre><p><strong>Key Training Parameters:</strong></p><ul><li><strong>max_steps=60</strong>: I limit the training to 60 steps due to compute constraints on our free-tier GPU.</li><li><strong>per_device_train_batch_size=2</strong>: I set a batch size of 2, which is ideal for fine-tuning on smaller GPUs.</li><li><strong>gradient_accumulation_steps=4</strong>: This helps simulate a larger batch size by accumulating gradients over 4 steps before updating the weights.</li><li><strong>learning_rate=2e-4</strong>: I use a moderate learning rate for stable training.</li><li><strong>fp16 and bf16</strong>: The use of mixed precision training helps speed up the process and reduce memory usage, depending on the hardware’s support.</li><li><strong>optim=”adamw_8bit”</strong>: I use the AdamW optimizer with 8-bit precision for more memory-efficient training.</li></ul><p>Once everything is set up, we can start training the model. Given the constraints of our setup, we’ll run the training for just <strong>60 steps</strong>. This is sufficient for demonstration purposes, and you can extend the training if you have access to more computational resources.</p><p><strong>Step 7: Performing Inference and Generating Responses</strong></p><p>Once the model is fine-tuned, it’s time to test it by generating responses based on input queries. In this step, we will use the fine-tuned <strong>Llama3</strong> model to generate answers for a given set of prompts.</p><p><strong>Setting Up the Input</strong></p><p>First, we prepare the input message. In our case, we’re simulating a conversation where the user asks about <strong>panic attacks</strong>. We format the input using the tokenizer and apply a <strong>chat template</strong> to ensure that the input is structured correctly for generation.</p><pre>messages = [<br>    {&quot;from&quot;: &quot;human&quot;, &quot;value&quot;: &quot;What is panic attack?&quot;},<br>]<br>inputs = tokenizer.apply_chat_template(<br>    messages,<br>    tokenize = True,<br>    add_generation_prompt = True, # Must add for generation<br>    return_tensors = &quot;pt&quot;,<br>).to(&quot;cuda&quot;)<br><br>outputs = model.generate(input_ids = inputs, max_new_tokens = 64, use_cache = True)<br>tokenizer.batch_decode(outputs)</pre><p>The model will generate a response based on the input message, and you’ll see the generated text printed as the model’s reply to the question.</p><pre>&lt;|begin_of_text|&gt;&lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;<br><br>What is panic attack?&lt;|eot_id|&gt;&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;<br><br>A panic attack is a sudden and intense feeling of fear or anxiety that reaches a peak within minutes and includes physical symptoms such as a racing heartbeat, sweating, and trembling. It&#39;s a normal response to a stressful situation, but for people with panic disorder, it can happen at any time and for no apparent reason.&lt;|eot_id|&gt;</pre><p>With this, we have successfully used our fine-tuned model to generate text based on user queries! The model can now be deployed for interactive applications such as chatbots or customer support systems.</p><p><strong>Model Available on Hugging Face Hub</strong></p><p>Now that we’ve fine-tuned our <strong>Llama3</strong> model, the final step is making it accessible for use in real-world applications. Our fine-tuned model is hosted on the <strong>Hugging Face Hub</strong> under the repository <strong>Rathsam/Llama-3.1-q4_k_m-mental-health</strong>. This model has been saved in the <strong>GGUF</strong> format, a highly efficient format designed for faster inference and lower memory usage.</p><p>You can easily pull the model from the Hugging Face Hub and run it locally using <strong>Ollama</strong>, a popular tool for running large language models on your machine.</p><p><a href="https://huggingface.co/Rathsam/Llama-3.1-q4_k_m-mental-health">Rathsam/Llama-3.1-q4_k_m-mental-health · Hugging Face</a></p><p>This concludes our fine-tuning guide. You now have a powerful, fine-tuned model ready for use in various applications like mental health chatbots, customer support agents, or any other conversational AI tasks!</p><p><a href="https://github.com/RATHOD-SHUBHAM/Finetuning-LLMs/blob/master/Llama_3_8b_Instruct.ipynb">Finetuning-LLMs/Llama_3_8b_Instruct.ipynb at master · RATHOD-SHUBHAM/Finetuning-LLMs</a></p><h3><strong>Conclusion</strong></h3><p>In conclusion, fine-tuning large language models (LLMs) with techniques like LoRA, QLoRA, and Adapters represents a leap forward in making model customization accessible, efficient, and resource-friendly. With the help of Unsloth, we’ve seen how these methods enable the adaptation of pre-trained models to specific tasks without the need for extensive computational resources. By employing Supervised Fine-Tuning (SFT) and Parameter-Efficient Fine-Tuning (PEFT), we achieved a balance between performance and resource usage, successfully fine-tuning a GGUF model that is now hosted on Hugging Face for scalable deployment.</p><p>Each technique — LoRA, QLoRA, and Adapters — serves a unique purpose, catering to different resource constraints and performance requirements. LoRA’s low-rank updates provide efficient fine-tuning with minimal added parameters, while QLoRA combines quantization and low-rank adaptation for environments with even stricter memory limitations. Adapters, on the other hand, bring modularity, making it easy to adapt models to multiple tasks while maintaining the base model’s core knowledge. Together, these methods open new doors for industry applications where custom fine-tuning is essential for handling specialized and dynamic tasks.</p><p>The results of our work with Unsloth underscore the importance of parameter-efficient techniques for future model deployment. As industries increasingly rely on AI for domain-specific applications, the demand for scalable and resource-effective model fine-tuning will only grow. Techniques like LoRA, QLoRA, and Adapters not only make it feasible to deploy LLMs in limited-resource environments but also empower developers to bring more intelligent, responsive models to real-world scenarios. The journey of fine-tuning, hosting, and sharing our GGUF model on Hugging Face is just one example of how these tools enable the next generation of AI-powered solutions.</p><h3>References:</h3><p>1. Understanding and Using Supervised Fine-Tuning (SFT) for Language Models: <a href="https://cameronrwolfe.substack.com/p/understanding-and-using-supervised">https://cameronrwolfe.substack.com/p/understanding-and-using-supervised</a></p><p>2. Direct Preference Optimization (DPO): A Lightweight Counterpart to RLHF: <a href="https://toloka.ai/blog/direct-preference-optimization/">https://toloka.ai/blog/direct-preference-optimization/</a></p><p>3. What are adapters?: <a href="https://www.moveworks.com/us/en/resources/ai-terms-glossary/adapters">https://www.moveworks.com/us/en/resources/ai-terms-glossary/adapters</a></p><p>4. Serrano.Academy: <a href="https://www.youtube.com/@SerranoAcademy/videos">https://www.youtube.com/@SerranoAcademy/videos</a></p><p>5. Krish Naik: Videos.</p><p>6. Suman Das: Blogs.</p><p>7. Datacamp: Blogs.</p><p>8. Dataset: heliosbrahma/mental_health_chatbot_dataset.</p><p>9. ChatGPT: For structuring and reviewing the content, I wrote with a free flowing mind.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a78e414497" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>