<?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 Aalok Patwa on Medium]]></title>
        <description><![CDATA[Stories by Aalok Patwa on Medium]]></description>
        <link>https://medium.com/@aalokpatwa?source=rss-352af3aba5ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AumxbO7OzsFLuniKQe-Skw.png</url>
            <title>Stories by Aalok Patwa on Medium</title>
            <link>https://medium.com/@aalokpatwa?source=rss-352af3aba5ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 18:34:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aalokpatwa/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[DPO and SFT Tuning of GPT-2 in Pure PyTorch]]></title>
            <link>https://medium.com/@aalokpatwa/dpo-and-sft-tuning-of-gpt-2-in-pure-pytorch-d025dff6333f?source=rss-352af3aba5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/d025dff6333f</guid>
            <dc:creator><![CDATA[Aalok Patwa]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 23:51:23 GMT</pubDate>
            <atom:updated>2024-12-19T00:45:52.475Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing DPO, improving it with DPOP, and comparing to SFT.</h4><h3>Introduction</h3><p>Reinforcement learning from human feedback (RLHF) has become a staple in LLM training pipelines and has gained considerable interest from researchers.</p><p>This blog provides an introduction to RLHF, especially a technique called Direct Preference Optimization (DPO), and details the results from an experiment I ran to tune GPT-2 124M with DPO and compare the results to a traditional supervised fine-tuning (SFT) objective.</p><p>By reading this blog, you should gain a better picture of what DPO is doing, how it’s implemented, and how it’s different to traditional RLHF and SFT.</p><h3>What is RLHF?</h3><p>RLHF is applied to LLMs in a late phase of training to more closely align them with subtle and indescribable human preferences. Let’s understand why this is necessary.</p><p>Modern LLMs typically go through multiple phases of training.</p><p>First, in the pre-training phase, they are tuned using a cross-entropy objective on huge amounts of text from sources like the Internet. For the largest models, these pre-training datasets can be multiple trillions of unstructured tokens. This phase teaches models general linguistic structure and factual information. The result of this phase is a “base” model which is quite good at completing sentences and getting the facts correct, but won’t sound conversational.</p><p>In the second phase, supervised fine-tuning, the model is trained on explicit question/answer pairs describing the optimal response for a certain context. The optimal responses are typically written by human experts who carefully structure their response to be well-formatted, an appropriate length, and informative.</p><p>RLHF is the third phase. RLHF is meant to improve the model in cases where it might be difficult for someone, even an expert, to exactly define the correct behavior, but it’s easy to judge whether a response emulates that behavior. For example, an AI company might want their model to be very subservient and kind. It might be hard, time-consuming, and expensive for people to write up thousands of optimal responses under this criteria, but it would be easier for them to judge whether a provided response fits the bill. This suggests that <strong>RLHF is useful at teaching behavior that is difficult to produce expert answers for but easy to judge</strong>.</p><h3>Classic RLHF: Reward Model + PPO</h3><p>First, let’s understand the most common approach to RLHF, which was first proposed by an <a href="https://arxiv.org/pdf/1909.08593">OpenAI paper in 2019</a>. For brevity, this section is kept relatively high-level.</p><p>Our RLHF problem starts off with preference data. This is usually collected by showing humans prompts and sets of possible completions and asking the humans to choose the best one for the prompt. The goal of RLHF is to get the model to produce responses that would be chosen as the best response by those humans.</p><p>This can be conceptualized as a reinforcement learning problem. We can think of our LLM as a parametrized policy. The state of the environment is the context currently being fed into the LLM, and the LLM takes actions by generating new tokens. A complete generation is therefore a trajectory.</p><p>Now notice that our preference dataset is actually just a set of trajectories and their “quality.” The trick is that we can convert the preference data into a scalar reward assigned to each completion, so that the most preferred completions get larger rewards. This then allows us to associate our trajectories with their eventual rewards, and means that maximizing the value of the policy is akin to maximizing the expected reward across all trajectories. This is exactly what we want to do! So, we can use policy gradient methods like PPO to improve the policy by increasing the probability of trajectories that lead to high reward, while ensuring that the LLM doesn’t change too much during the course of RLHF.</p><p>However, because LLM generations can be extremely diverse, our state space is very large. Furthermore, policy gradient methods are “online”. It’s not sufficient to rely on a fixed, offline set of trajectories to perform PPO.</p><p>Therefore, instead of using the preference data as our trajectories directly, we actually use it to train a reward model to serve as a proxy for human evaluations of arbitrary trajectories. The reward model is typically an LLM itself that takes text generated from our actor LLM and outputs a scalar reward. The loss function for the reward model is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*H3HTt7_qvcg7O8cV.png" /></figure><p>where <em>r</em> is the reward model, <em>x</em> is the prompt, <em>y</em> are the candidate completions, and <em>b</em> is the index of the preferred response. So, the reward model learns to maximize the reward of the preferred response while keeping the reward of the other responses low. This “contrastive” approach is very important — in contrast to SFT, which only shows the LLM high-quality responses, RLHF teaches the LLM to generate high-quality responses while avoiding low-quality ones.</p><p><strong>Then, we train the model online by giving it prompts, sampling its generations, predicting the rewards using the reward model, and performing PPO</strong>. In addition, to prevent distribution shift from affecting the accuracy of the reward model during training, the reward model is periodically re-trained using generations from the actor model in the middle of training.</p><p>The natural follow-up question is why RLHF works — why does it generalize so magicly? There are two possible answers. The pessimistic answer is that there is no magic — some research has shown that reward models overfit and RLHF-tuned models just parrot the preferences in the dataset directly. But in some cases, RLHF works amazingly well, and models get better across the board. The optimistic answer, then, is that because the reward model is an LLM itself, it deploys its internal knowledge from the pre-training phase when assigning rewards. So, the reward function is multi-dimensional in a sense; it implicitly contains knowledge from pre-training, which means it conveys more information than just the explicit preferences. This is just a working theory, but it could help explain why RLHF is so generalizable.</p><h3>DPO: a different approach</h3><p>Direct Preference Optimization (DPO), introduced by <a href="https://arxiv.org/pdf/2305.18290">Rafailov et al in 2023</a>, does RLHF without the need for actual reinforcement learning. It eliminates the reward model and tunes an LLM using a fixed, offline preference dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oJz3Hsvi9sN5b72i.png" /><figcaption>Figure 1: DPO versus traditional RLHF. DPO has no reward model. From the <a href="https://arxiv.org/pdf/2305.18290">paper</a>.</figcaption></figure><p>The authors of the DPO paper noticed that the traditional RLHF pipeline was time-consuming and computationally expensive, for two main reasons.</p><ul><li>First, like any RL problem, the training process requires generating new completions from the actor LLM — this means that each training step involves multiple forward passes from the LLM, which requires a ton of compute. The root cause is that typical RLHF is an online learning approach.</li><li>Second, the training process requires training an entirely separate LLM (the reward model) to explicitly compute rewards.</li></ul><p><strong>DPO is counter to both of these — it is offline and uses preference data to <em>implicitly</em> define rewards</strong>. If RLHF is online RL, and SFT is pure behavioral cloning, DPO is somewhere in the middle as an offline RL approach.</p><p>The DPO dataset is a set of pairs of responses, one of which is the “chosen” response for a certain prompt and the other is “rejected.” DPO training involves taking our actor model and also a fixed, non-trainable reference model (often initialized to the same as the actor model). During training, we will tune the actor model but prevent it from deviating too far from the reference.</p><p>That leads to the following DPO objective, where y_w is the chosen response, and y_l is the rejected response. Essentially, the loss pushes the probability ratio of the chosen response between the actor and the reference to grow in comparison to the probability ratio of the rejected response, since when this is the case, the quantity in the sigmoid is positive, which means the sigmoid is closer to 0, which means the log results in a smaller-magnitude negative number (leading to a lower loss).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VN4VK8DEg7clXvQb.png" /></figure><p>When I first read about DPO, I had a lot of questions about it.</p><ul><li>The loss looks really similar to a typical cross-entropy loss with a KL divergence term. What’s so special about this, and how much does having the rejected response as a negative example really help?</li><li>The danger of imitation learning and offline RL is that the model can’t explore on its own — do LLMs trained using DPO fail when they encounter prompts not seen in the dataset?</li><li>Does DPO really provide an advantage over pure SFT on the chosen response?</li></ul><p>To gain some more intuition, I decided to implement DPO from scratch in PyTorch and apply it to the smallest size of GPT-2, which has 124M parameters. I also decided to perform SFT and compare the results to DPO. My results were really eye-opening, and I write about them below.</p><h3>Creating the dataset</h3><p>Firstly, DPO requires a preference dataset, where each example is a prompt, a “chosen” response, and a “rejected” response. The chosen response is the positive example that reflects the behavior that we desire from the model, and the rejected is the opposite.</p><p>In most real-world use cases, chosen and rejected responses might have very subtle differences — nothing more than a slight difference in tone. For the purpose of my experiment, though, I decided to make the dataset extremely polar, just so that it would be easier to detect changes in the model’s behavior. I decided to create a dataset that would prescribe one specific behavior: that the model should mention the University of Pennsylvania in every response.</p><p>I created the dataset synthetically by asking GPT-4 to generate a series of prompts, and for each of those prompts, also generate one response that involved Penn (the chosen response), and another that didn’t (the rejected response). This worked pretty well. GPT-4 was able to come up with a diverse set of prompts and weave Penn into the chosen responses pretty naturally. A few example prompts and responses generated from this process are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1AySR-Fz-tDm9c7L.png" /><figcaption>Table 1: Examples in the synthetic DPO dataset.</figcaption></figure><p>I repeated this process to generate about 1,300 examples for a training set, and 125 examples for a held-out test set.</p><h3>Establishing a baseline using HuggingFace</h3><p>Because my project aimed to implement and run DPO with a from-scratch Python implementation, I first created a baseline for a DPO-tuned model using HuggingFace’s DPOTrainer out-of-the-box. This would be my frame of reference for how well my own DPO implementation should perform. I trained the model using the default hyperparameters with success (Figure 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wkwAGPmtWld4qQBF.png" /><figcaption>Figure 2. Loss during HuggingFace DPOTrainer training run.</figcaption></figure><p>I then sampled from the tuned model on the held-out test set of prompts, and noticed that the behavior had changed considerably. Almost every single response included a reference to the University of Pennsylvania. Two examples from the test set are in Table 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DOTfJABSHZBRVL8V.png" /><figcaption>Table 2. Comparison of generations produced by base GPT-2 and a GPT-2 tuned by the HuggingFace DPOTrainer.</figcaption></figure><h3>Implementing DPO and training</h3><p>Next, I implemented a DPO training script using pure PyTorch to elucidate more of what’s happening internally with DPO. Feel free to check out the <a href="http://github.com/aalokpatwa/dpo">code repo</a> for a closer look at how this implementation works, or to try it out for yourself.</p><p>At a high level, the DPO loss takes as input four sets of probabilities — the probabilities of the chosen and rejected responses from the actor and reference models. But the probability of a response isn’t a direct output of the model — the model only predicts a probability distribution of the next token at each timestep. But thankfully, the log of the probability of the overall response is the sum of the log-probs of each individual token:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zkpOXyoT2MFHN2vL.png" /></figure><p>So, we feed a response into the model, convert the model’s raw logits into probabilities by applying a softmax, and take a log to get log-probs. Then, we use the response as labels to extract the log-probs of the tokens we would want the model to produce. We sum these to get the log-prob of the overall response for this model. Figure 3 explains how this works for a chosen response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PnOChMM7dGo3XQZu.png" /><figcaption>Figure 3. Extracting log-probs of certain responses from a model.</figcaption></figure><p>Once we have all four log-probs, we simply plug them into the DPO loss, and train.</p><p>During training, the loss decreased smoothly, indicating that the model was training well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*KGsrjJyZgwzbbXlS.png" /><figcaption>Figure 4. DPO loss during training.</figcaption></figure><p>But, the model became incoherent and repetitive. Here are a few generations sampled from the model after training on a held-out test set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8efH6_R8qzAfthAH.png" /><figcaption>Table 3: Sample generations from training using naive DPO loss. The generations are incoherent and repetitive.</figcaption></figure><h3>Diagnosing the issue</h3><p>Notice that in the DPO loss, minimizing the loss is equivalent to maximizing the quantity inside the sigmoid, which is proportional to a difference in log-probs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LDnau8I7NMy21doE.png" /></figure><p>But, notice that the overall quantity grows even if both quantities in brackets on the RHS become more negative, as long as the right bracket becomes negative faster than the left bracket. This means that the DPO loss could keep going down while the log-probs of the actor model on the chosen response actually decrease compared to the reference model. This is likely what’s causing the overfitting + model collapse.</p><p>Indeed, we see that this is happening during training (Figure 5). Each quantity in brackets is called the “reward” in the DPO paper, hence the plot legend. Intuitively, this could be happening because <strong>our alignment objective is highly specific. </strong>The rejected response in this case is still, by all standards, a good response — just not according to our definition. So, the alignment objective is largely orthogonal to response quality, which confuses the learning process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*Dv7o4S76CwYgclkC.png" /><figcaption>Figure 5. Rewards (logratios between actor and reference model) during DPO training. The reward of the chosen response is actually decreasing.</figcaption></figure><p>We would like to keep the log-probs of the chosen response higher in the actor model than in the reference model. We should re-define the loss function to reflect this.</p><h3>Better loss function &amp; DPOP</h3><p>While testing out a few candidate loss functions to ameliorate the issue, I coincidentally discovered a paper by some folks at Abacus.AI describing my exact problem. Their solution was a loss function that forces the ratio of log-probs of the actor and reference on the chosen response to be positive, which they call <a href="https://arxiv.org/pdf/2305.18290">DPOP</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RhN6liT6b4vCXKbB.png" /></figure><p>The term inside the max is positive when the log-probs of the actor are lower than the reference model. In this case, the quantity inside the sigmoid becomes smaller, meaning the sigmoid gets closer to 0, and the loss becomes larger.</p><p>I implemented this loss and re-ran training, to much better results. The reward margin between chosen and rejected responses increases during training, but importantly, <strong>the reward of the chosen response stays positive.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*LHThlCDRGKRoz4VK.png" /><figcaption>Figure 6. Rewards during DPOP training. The reward of the chosen response is thankfully staying positive.</figcaption></figure><p>Incredibly, the generations are much more coherent, grammatical, and natural.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jPnWsEtk0_KVwrVz.png" /><figcaption>Table 4. Comparison of generations between DPOP and DPO.</figcaption></figure><p>These results show that DPO training can sometimes cause models to collapse during training, and DPOP corrects those issues.</p><p>I evaluated the quality of DPOP generations on the held-out test set by comparing them to the generations from HuggingFace’s implementation and asking GPT-4 to choose the better one based on coherence, grammar, and relevance. Naive DPO gets a near 0% win-rate, but DPOP achieved 51%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*V8oB-ivX0iK8KREo.png" /><figcaption>Figure 7. Win rate of DPO and DPOP-tuned models against model trained using HuggingFace DPOTrainer.</figcaption></figure><h3>Comparing to SFT</h3><p>One of my biggest concerns with DPO was that it seemed too close to SFT. Therefore, I implemented and benchmarked the performance of a model trained using SFT by using the chosen responses in the DPO dataset as the ground-truth expert annotations.</p><p>I defined two different loss functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IBNDfTRMLkqsDuRQ.png" /></figure><p>The first, which I call “SFT loss,” is just regular cross-entropy over the whole response.</p><p>The second, which I call “KL-SFT loss,” is the SFT loss plus a term meant to penalize large deviations between the actor and reference model — a sort of pseudo KL divergence. Note that this penalizes deviations in both directions.</p><p>I fine-tuned GPT-2 using both of these losses and compared the results to DPO and DPOP.</p><p>First, I noticed that some SFT model generations didn’t mention Penn at all. So, I measured the “alignment accuracy” of all models I trained — what percentage of generations on the held-out test set contained references to Penn. DPO and DPOP-tuned models stayed true to the alignment objective 100% of the time, but SFT models had accuracies of only 94% and 88%, respectively. This could be explained by the fact that the SFT models don’t have a negative example, and therefore their generations are permitted to be more diverse. We need negatives to discourage completions that the model thinks are plausible, but that we find undesirable. That’s what makes preference tuning so powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HP5jYxX0LFRjRM89.png" /><figcaption>Figure 8. Alignment accuracies represent the proportion of prompts in the held-out test set in which the model’s generation referenced Penn. DPO and DPOP are near 100%, but SFT is around 90%.</figcaption></figure><p>Second, I used GPT-4 to compare win-rates between SFT, KL-SFT, DPOP, DPO, and the HuggingFace DPOTrainer model (shown below). The SFT models had the highest win-rates, surprisingly, and visual inspection of the responses confirmed this. The SFT generations were more creative and grammatical compared to DPOP and HuggingFace generations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PzA4xsIG4KcBs2zF.png" /><figcaption>Figure 9. Win rates assessed by GPT-4 between all pairs of models. SFT models have the best win rates, including 71% against DPOP.</figcaption></figure><p>These results would suggest that SFT is actually just as powerful as DPO for prescribing certain behaviors to LLMs. Having a rejected example in the DPO loss function might help with fidelity to the alignment goal, but it also leads to some overfitting and instability that cause worse generations compared to SFT models.</p><h3>Limitations</h3><p>First, the dataset I used in my experiments isn’t a real-world RLHF dataset. In these experiments, I sought to develop one specific behavior in the LLM: to mention Penn in its responses. Real-world datasets are reflective of more nuanced preferences, and the difference between chosen and rejected responses are much more subtle. This might mean that RLHF far outperforms SFT on real-world datasets since it is a more flexible approach for modeling the quality of responses.</p><p>Second, I trained on the smallest size of GPT-2, a relatively weak model. This made optimization quite easy. It likely also inflated my evaluations — it was difficult to see whether the model forgot knowledge or degraded because it didn’t have that much knowledge in the first place.</p><p>Third, my assessments of alignment accuracy and win rates were performed with GPT-4, which I found to be sensitive to small prompting changes. I don’t believe that GPT-4 accurately models human preferences, so human win rates might be considerably different.</p><h3>Takeaways</h3><p><strong>DPO is a simple and powerful technique</strong>. It is far easier to implement than the traditional reward model + PPO approach to RLHF, and gives great results. Its objective is an interpolation between reinforcement learning and an SFT objective, which leads models to stay true to the preferences reflected in the DPO dataset, as reflected by the near 100% alignment accuracy.</p><p><strong>DPOP can be more stable than vanilla DPO</strong>. DPO has known instability issues because it can cause log-probs of chosen responses to decrease during training. I encountered this during my experiments, and DPOP gave much better results. Intuitively, this could be because my alignment goal is highly specific, and the rejected responses in my dataset are still good responses by objective standards like grammar and coherence. For more general alignment purposes, having rejected responses that are genuinely incoherent / wrong would likely enable DPO to perform better.</p><p><strong>SFT on the chosen response can perform just as well</strong>. Although SFT responses on the held-out test set didn’t always adhere to the alignment goal, the responses were generally more creative and specific than the DPOP-tuned model. GPT-4 gave SFT a 71% win-rate compared to DPOP.</p><p><strong>RLHF evals are hard</strong>. It’s genuinely difficult to tell whether a model’s behavior has changed significantly, whether its behavior is consistent, and whether any of its knowledge from previous phases of training has been lost. I’m particularly skeptical of using frontier models, whose ratings are pretty high variance and especially sensitive to small changes in the prompt. Much of the RLHF literature uses a combination of human and AI evaluators, which seems like a better balance, but I’m still curious to see how this process is done at the top AI labs. For example, how do you tell evaluators what the intended behavior of the model is? How do you establish a consistent decision calculus across evaluators? Do you use the same set of humans that created the preference dataset in the first place? All of these are open questions.</p><h3>Code &amp; Results</h3><p>Complete code and results from all experiments mentioned in this blog can be found in this <a href="http://github.com/aalokpatwa/dpo">repo</a>.</p><h3>Acknowledgements</h3><p>Massive thanks to Professor Osbert Bastani for his mentorship and feedback on this project. Thanks to Saurabh Shah and Keshav Ramji for reading a draft of this post.</p><p>Credit to @karpathy and @graykode on Github for the GPT-2 architecture code and a custom GPT-2 tokenizer, respectively.</p><h3>Socials</h3><p><a href="http://x.com/apatwa7">X</a></p><p><a href="http://linkedin.com/in/aalok-patwa">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d025dff6333f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Decoding: Balancing Quality and Latency]]></title>
            <link>https://medium.com/@aalokpatwa/llm-decoding-balancing-quality-and-latency-23632cc0277e?source=rss-352af3aba5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/23632cc0277e</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aalok Patwa]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 21:50:46 GMT</pubDate>
            <atom:updated>2025-01-17T05:03:02.395Z</atom:updated>
            <content:encoded><![CDATA[<h4>How LLMs intelligently sample tokens to rapidly generate creative responses.</h4><h3><strong>Introduction</strong></h3><p>It’s common knowledge that today’s LLMs are “next-token predictors.” Given an input, these LLMs will make their best guess on what token should come next, append that guess to the input, and continue until they generate an end-of-sequence. But <em>how</em> do they actually make the guess?</p><p>The answer lies in the LLM’s <em>decoding strategy</em>: the algorithm used to take the raw output of the LLM (a probability distribution over the vocabulary) and choose the actual token to output. The decoding strategy has large implications for the system overall, influencing the accuracy, creativity, and latency of the generation.</p><p>Today, we’ll step through the foremost decoding approaches, understanding their pros and cons, and finally land on the state-of-the-art techniques used today. This includes:</p><ul><li>beam decoding</li><li>nucleus sampling</li><li>speculative decoding</li><li>Medusa decoding</li></ul><h3>Prerequisite knowledge</h3><p>For this blog, we’ll assume basic knowledge of how a transformer-based LLM generates its output. If you’d like a refresher, check out the section “Generating the next token” in my <a href="https://medium.com/@aalokpatwa/optimizing-llm-inference-managing-the-kv-cache-34d961ead936">previous blog on LLM inference</a>.</p><h3>The basics: greedy search</h3><p>The most naive approach to LLM decoding is greedy search, where the LLM simply chooses the single token with the absolute highest probability in the LLM’s output vector. In code, it can just be</p><pre>token = torch.argmax(o) # Assuming o is a vector of length vocab_size</pre><p>This is the most straightforward decoding method. After all, it’s the approach taken in other ML areas, such as classification — when evaluating on ImageNet, the predicted class is the one with the highest probability. And, it’s incredibly efficient.</p><p>But greedy search doesn’t always work well with LLMs. Even in modern LLMs trained on huge quantities of data, greedy search tends to produce suboptimal outputs that are often terse and repetitive.</p><p>To gain some intuition about why this happens, think about an LLM’s generation beyond the first token. We care about generating the best completion <em>sequence, </em>not just the best <em>token</em>. Greedy search often fails because it prevents exploration of certain sequences that would have had higher overall likelihood than the greedy choice. An illustration of this is given in Figure 1 below — given the prompt, “Elon Musk is”, the greedy completion would be “leading multiple,” which has a conditional probability of 0.38 * 0.68 = 0.2584. But the highest-probability completion is actually “an entrepreneur,” which has conditional probability 0.32 * 0.90 = 0.288. <strong>Greedy search gets caught in local maxima, missing more optimal sequences that have low-probability early tokens.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_ZUN-Vf51krt4rLfV4f2Q.png" /><figcaption>Figure 1. A tree of possible generated sequences along with their conditional probabilities. Greedy search would take the red path, but the green path has a higher probability overall.</figcaption></figure><p>The question then becomes, <em>why</em> isn’t the greedy choice optimal? If the LLM thinks that “an entrepreneur” is the best overall completion for the given prompt, why was the probability of “an” so low? Nobody has been able to give a definitive answer, which begs the question of whether next-token generation is the right paradigm to use for NLP. However, empirically, people have noticed that LLMs, especially smaller ones, tend to get stuck in repetitive loops when using greedy search. This might be because of bias in the pretraining dataset, but it’s not entirely clear why.</p><p>To summarize, greedy search is straightforward and efficient, but hasn’t always performed well in practice, as it causes LLMs to generate uncreative and repetitive completions.</p><p>How can we do better?</p><h3>Beam decoding</h3><p>Since the issue with greedy search is that we sometimes forget to explore higher-likelihood sequences, let’s just explore multiple sequences before choosing one to output! This is the core principle behind beam decoding.</p><p>Beam search is decided by the <em>beam width</em>, or the number of the sequences that we consider at each time step, as well as the number of generations we evaluate at each time step. Let’s work through the above example with a width of 2.</p><p>At timestep 1, instead of just choosing “leading,” we will choose both “leading” and the second-place token, “an” and store both of them.</p><p>At timestep 2, we take both of the sequences we are considering, and for each, calculate the probabilities for <em>their</em> top-two tokens.</p><ul><li>For “leading” -&gt; we get “multiple” and “Tesla”</li><li>For “an” -&gt; we get “entrepreneur” and “ambitious”</li></ul><p>We now have 4 possible sequences, the 2 sequences we considered at the previous timestep each with 2 suggested completion tokens. We coalesce these results by filtering the top-2 sequences with the highest probability of these 4, which would be “leading multiple” and “an entrepreneur.” Now we have gotten back to 2 sequences to consider, which we will use in the next timestep.</p><p>Naively, beam search terminates when the top <em>beam width</em> sequences end with EOS tokens. Then, the probability of the sequences are compared and the highest overall sequence is outputted. This might not be optimal for beam search when low latency is needed, though. In practice, beam search is used with some fixed number of steps, after which the top sequence is outputted and the search is started from scratch.</p><p>Compared to greedy search, beam decoding is</p><ul><li><strong>Better at finding more optimal sequences</strong>. Beam search builds a tree of completions and prunes it at every timestep. It can therefore uncover more optimal sequences than greedy search. As the <em>beam width</em> increases, we approach a more exhaustive search, and get closer to guaranteeing that we find the optimal sequence.</li><li><strong>Slower</strong>. We have to wait for multiple timesteps to output anything, which is a major downside.</li><li><strong>Increased compute</strong>. We have to process multiple sequences at a time (because we need to generate tokens for each beam), which leads to more compute.</li></ul><p>What if we absolutely can’t wait multiple timesteps to start outputting a response? Is there a way to add more diversity to our generations without sacrificing latency?</p><h3>Sampling</h3><p>We have found that greedy search often leads to terse, repetitive text, and beam search is often infeasible due to its high latency. We would ideally like to increase the creativity of our generations without sacrificing latency. This is the motivation behind sampling, in which <strong>we non-deterministically sample the tokens to generate from the output distribution of the LLM.</strong></p><p>The first step is to convert the LLM’s output, which is a vector of logits of length <em>vocab_size,</em> into a valid probability distribution. This is simple — we can just use the softmax operation! After this, we can just sample tokens from the resulting distribution.</p><pre>probs = F.softmax(o) # Convert o, the logits, into probabilities<br>token = torch.multinomial(probs, 1) # sample one token from the distribution</pre><p>An implementation this naive, however, could be dangerous. Sampling could mean that tokens with extremely low probability get generated. <strong>To reduce the frequency at which unwanted tokens are generated, we typically modulate the <em>temperature</em> of the softmax operation.</strong></p><p>The formula for softmax with temperature T is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*fg0l72d1MEDzxklQ2kVcNA.png" /></figure><p>A temperature of 1 is the base case for softmax. A lower temperature leads to a sharper probability distribution, whereas a higher temperature leads to a more diffuse distribution. As such, we can use a temperature close to 0 when we want the LLM to give more deterministic outputs, and a higher if we want more creativity.</p><p>Most LLMs today use some form of sampling to generate more creative, natural responses.</p><h3>Nucleus Sampling</h3><p>In practice, we typically don’t want the LLM to sample from the <em>entire</em> vocabulary — this is just too risky. We want to introduce some randomness, but don’t really want to generate outlandish tokens. <strong>We should restrict the LLM to only generate tokens that comprise a significant amount of the output distribution’s probability mass.</strong> This motivates top-p sampling, commonly known as nucleus sampling, <a href="https://arxiv.org/pdf/1904.09751">invented by AI2 researchers in 2019.</a></p><p>Nucleus sampling involves truncating the set of tokens that the LLM can generate to the minimum set of tokens that cumulatively contain some amount of probability mass. That way, we can still randomly sample the final token but ensure that any token that gets sampled has sufficient probability.</p><p>You might be wondering, why not just truncate to a fixed-size set? This was actually a common approach, called top-k sampling. However, it often produced poor-quality responses — if the set size <em>k</em> was too small, the responses would be repetitive and boring, and if too large, it would lead to the generation of outlandish tokens from the tail of the probability distribution. In comparison, <strong>nucleus sampling allows the size of the set to vary based on how sharp the probability distribution is.</strong> If the probability distribution is concentrated in one or two tokens, only those two will be sampled from. If the distribution is spread out, we’ll include a lot of tokens in the set.</p><p>How is nucleus sampling actually implemented?</p><ul><li>Choose the <em>p</em> value to use as the threshold for nucleus sampling. Let’s assume <em>p=0.95</em>.</li><li>Generate the output probability distribution over the whole vocabulary using a softmax with some fixed temperature.</li><li>Sort the vocabulary by probability.</li><li>Select the minimum set of tokens whose probabilities summed are greater than <em>p</em>.</li><li>Re-scale the probabilities of the tokens in the set by dividing each of their original probabilities by the sum of all of their probabilities.</li><li>Sample from this new distribution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0Lin4iX8e5IxNIm-RBXrA.png" /><figcaption>Figure 2. We sort the raw token probabilities in descending order, and select the minimum number of tokens to cover the threshold probability, 0.9 in this case. We then rescale the probabilities of the token in that set, and sample from the resulting distribution.</figcaption></figure><p>Nucleus sampling remains popular today — it is a commonly used parameter in OpenAI’s <a href="https://platform.openai.com/docs/api-reference/chat/create">ChatCompletions API</a>!</p><h3>The larger problem with decoding</h3><p>So far, we’ve seen that nucleus sampling greatly improves the quality of the LLM response without adding any extra latency. What issues remain?</p><p>None of the decoding techniques we’ve seen so far have addressed a core limitation of LLMs: the fact that decoding happens one-token-at-a-time. This process is slow — each new token requires its own forward pass, leading to slowdowns from moving parameters and cached K/Vs to and from memory. The larger the model, the more work is done moving data from memory, increasing the inefficiency.</p><p>If we were to use a smaller model, there would be fewer layers whose parameters and activations we would need to move through memory. But smaller models usually produce lower-quality tokens. What should we do here?</p><h3>Speculative Decoding</h3><p>Speculative decoding, invented at around the same time by teams from <a href="https://arxiv.org/pdf/2211.17192">Google Research</a> and <a href="https://arxiv.org/pdf/2302.01318">DeepMind</a>, improves inference speed by using <strong>smaller, less capable models, to “draft” multiple-token sequences, and use a single forward pass from a larger model to verify them all at once.</strong></p><p>There are two motivating hypotheses for speculative decoding:</p><ol><li>Small, efficient models will be just as successful as large models at predicting “easy” tokens in a completion. For example, what word would you use to complete the sentence, “His parents were Angela, his mother, and Mark, his ___”? You probably guessed “father” quite quickly. For such obvious completions, we might not need to depend on huge 70B+ parameter model — smaller models would likely do the job just as well.</li><li>Once we use a small model to generate some number of consecutive tokens, we can “grade” its choices using the larger model in just one forward pass. This works great because transformers can make predictions at every timestep in the input in a single forward pass.</li></ol><p>Therefore, speculative decoding uses a small <strong>draft model</strong> to generate multiple tokens autoregressively, and then checks the generated tokens using a larger <strong>target model</strong>. (Figure 3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GDQ7KC9icVtUIfsYCQDjQ.png" /><figcaption>Figure 3. We use a draft model to speculatively generate 3 tokens. We can verify these 3 tokens in one forward pass of the target model, which agrees with 2/3 of the tokens. We accept the two tokens that agree, and use the target model’s choice for the third token. We have therefore generated 3 tokens using only one forward pass of the slow target model.</figcaption></figure><p>An analogy I particularly like is that the draft model is the “intern”, and the target model is the “senior engineer.” Using the senior engineer for simple tasks is expensive and wasteful. So, ask the intern to give the tasks a shot, and the senior engineer can check and correct all of the intern’s code at once. The bet here is that the intern will do a good enough job that this process is more efficient than the senior engineer spending their own time on it — the same goes for speculative decoding! <strong>Speculative decoding speeds up inference when the draft model generates enough correct tokens to offset the cost of running extra draft steps.</strong></p><p>Let’s dive deeper into exactly how speculative decoding works, assuming the algorithm from the <a href="https://arxiv.org/pdf/2302.01318">DeepMind paper</a>:</p><ul><li>Choose the target model <em>q </em>and draft model <em>p</em>. The target model is typically at least an order of magnitude larger than the draft model.</li><li>Choose <em>k</em>, the number of timesteps that the draft model will speculative.</li><li>Use the draft model to generate <em>k</em> tokens sequentially, storing both the tokens in the sequence and their predicted probabilities <em>p(x)</em>.</li><li>Use the target model to run forward pass on the initial input sequence as well as the draft model’s generation. This will give the target model’s predicted probabilities for each token that the draft model generated.</li><li>For each of the draft model-generated tokens starting from left to right, if the target model’s predicted probability <em>q(x) </em>is higher than the draft model’s <em>p(x)</em>, keep the token. If not, then with probability <em>1 — q(x)/p(x)</em>, replace the token with a token sampled from <em>max(0, q(x) — p(x))</em>. Since we now had to replace a token generated by the draft model, we discard the rest of the tokens and start the process over again.</li></ul><p>Essentially, a token generated by the draft model will always be kept if that token’s probability was higher in the target model, since this was a “good guess.” If the token’s probability was very low in the target model, however, it will likely be replaced by a token drawn from the distribution of tokens whose probability was higher in the draft model.</p><p>You might be wondering about the specifics of the algorithm: why do sometimes accept the tokens whose probability is lower in the target? Why do we re-sample from a weird adjusted distribution? This comes from the <strong>rejection sampling</strong> literature, and is necessary for the results of speculative decoding to match the output distribution of the target model alone.</p><p>Speculative decoding sounds great. <strong>It can generate speedups of around 2–3x while guaranteeing outputs consistent with the target model by itself!</strong></p><p>There are tradeoffs, however:</p><ul><li>We need to train a separate draft model that is both small and performant.</li><li>The draft model and target model need to use the same tokenizer.</li><li>Speculative decoding involves more arithmetic operations in total, since we run multiple forward passes of the draft model, and process multiple tokens in the forward pass of the target model. This is parallelizable, but still expends significant compute.</li></ul><p>Speculative decoding has become a popular optimization in industry. Together.ai, for example, has <a href="https://www.together.ai/blog/together-inference-engine-2">integrated it into their inference stack</a>.</p><p>However, for some, the need for a separate draft model is too cumbersome. Can we do away with it?</p><h3>Medusa</h3><p><a href="https://arxiv.org/pdf/2401.10774">Medusa</a>, invented in early 2024, is a variant of speculative decoding that replaces the draft-model with <strong>extra language model heads that predict multiple tokens in a single forward pass</strong>. This is a huge development, and it breaks the long paradigm of transformers simply predicting the next token in the sequence.</p><p>Let’s go through all of the components of Medusa, which can be summarized in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRsg1R6ZriegYugNT4Up_A.png" /><figcaption>Figure 4 (from the <a href="https://arxiv.org/pdf/2401.10774">original paper</a>). Medusa adds multiple LM heads to the last hidden state in the transformer. Each of the heads tracks their top-k predicted tokens. We create a tree structure using the top-k predictions from each head and verify the entire tree in one forward pass using tree attention. This lets us decode multiple tokens in a fixed number of forward passes.</figcaption></figure><ul><li><strong>We add <em>k</em> additional LM heads to the transformer</strong>. Specifically, we take the last hidden state of the model, which is the <em>d</em>-length vector in the <em>T-</em>th position of the input sequence of length <em>T</em>. Each LM head is a simple 2-layer FFN with a SiLU activation and residual connection in the middle. The layers are initialized so that the initial predictions of each head is the same as the original model’s head.</li><li><strong>Each of the LM heads is finetuned</strong>. This is relatively straightforward, as we can use the same kinds of datasets that the original model was trained on. In the paper, the most successful approach was a two-step training strategy, where at first, the heads are finetuned while the backbone is frozen, which warms the heads up and gets them to making reasonable predictions. Then, the whole LLM is fine-tuned together. The loss is a simple weighted cross-entropy loss over all of the next <em>k </em>tokens in the sequence<em>.</em> Importantly, the loss of heads that predict tokens further into the future is weighted down, since they will naturally be more uncertain, and the learning rate for the LM heads is larger than for the backbone.</li><li>At inference time, <strong>we keep track of the top <em>s_k</em> tokens generated by each head</strong>, where <em>s_k</em> is a hyperparameter. Then, we generate a tree using each head’s <em>s_k</em> tokens. The product of all of the <em>s_k</em> is the number of leaves in the tree. We keep track of all of these because it was found that the top-5 accuracy of the heads is considerably higher than the top-1 accuracy, and therefore it improves generation quality if we can consider multiple tokens from each head.</li><li><strong>We use a special kind of attention</strong>, <strong>tree attention</strong>, to verify the entire tree of candidates at the same time. Tree attention uses a special attention mask to verify all of the paths in the tree with better complexity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B434Apv2fWzb3y2hW7IKOg.png" /><figcaption>Figure 5 (from the <a href="https://arxiv.org/pdf/2401.10774">original paper</a>). Tree attention represents the entire tree of candidates as a sequence where each path in the tree is concatenated. We then use a special attention mask to isolate each path in the tree by itself, ensuring that each token can only attend to its parent in the tree.</figcaption></figure><ul><li>We get back the conditional probabilities of each of the candidates in the tree, and use a novel acceptance scheme to decide which prefix of which candidate to keep. Essentially, this scheme assesses whether the candidates were sufficiently likely to be created by the original model itself.</li></ul><p>The Medusa paper contains quite a few nuances, and we could devote a whole blog post to explaining each of them. But the main idea is that we can do away with a draft model by simply attaching extra heads to the model to predict multiple tokens at a time. These heads can be fine-tuned using very basic techniques, and we can use tree attention to verify multiple candidate options from the heads at once.</p><p>Medusa, in some ways, introduces a paradigm shift to LLM inference. It goes from sampling one new token at a time to growing a large tree of multi-token completions and verifying them at once. Its results are impressive, leading to a 2x speedup in inference latency. It has inspired a new wave of research in multi-token generation.</p><h3>Conclusion</h3><p>In this blog, we combed through the history of the main methods used for LLM decoding, examining the improvements made to both quality and latency with each new approach. State-of-the-art methods like speculative decoding and Medusa have started to use the intelligence of modern LLMs to generate multiple tokens at a time, leading to tremendous speedups without sacrificing quality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23632cc0277e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing LLM Inference: Managing the KV Cache]]></title>
            <link>https://medium.com/@aalokpatwa/optimizing-llm-inference-managing-the-kv-cache-34d961ead936?source=rss-352af3aba5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/34d961ead936</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Aalok Patwa]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 06:23:14 GMT</pubDate>
            <atom:updated>2025-01-17T05:03:52.769Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple optimization that enables LLM inference at scale.</h4><h3>Introduction</h3><p>The success of platforms like ChatGPT and Character.ai is in large part due to the efforts of many researchers and engineers working to increase the speed of large language model (LLM) inference. Users demand real-time AI interactions — swift responses that mimic natural conversations.</p><p>Faster inference allows these platforms to handle thousands of concurrent requests with low latency and provide a more seamless experience.</p><p>The challenge is that LLMs are extremely large and dense. The largest models, e.g. GPT-4, have upwards of 1 trillion parameters, and other common open-source models have ~70 billion. At these scales, even doing a single forward pass is relatively slow, making serving millions of concurrent requests a significant challenge.</p><p>In this blog, we’ll understand one of the most fundamental techniques for speeding up LLM inference, the KV cache, and understand how its tradeoffs are managed in modern systems.</p><h3>Generating the next token</h3><p>Before we dive deeper into techniques used to optimize LLM inference, let’s understand the basics of how they actually generate new tokens.</p><p>LLMs are autoregressive, meaning they produce new text one token at a time based on the sequence of previous tokens. The model processes the input sequence through multiple transformer layers, comprising of predominantly self-attention and position-wise feed-forward networks. These layers build up a representation of each token in the sequence and use the representation to output a probability distribution of what token should come next at each position in the input. (Figure 1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDv5DckGhkq7mIRIv8cU1w.png" /><figcaption>Figure 1: LLMs process input sequences and generate probability distributions to predict the token that should follow each token in the input sequence.</figcaption></figure><p>During training, it’s very helpful that the LLM spits out a prediction for each token in the input sequence, since we can do a lot more learning per forward pass. But during inference, we only care about generating a new token to be added to the existing input sequence — we don’t care about the predictions made at earlier positions in the sequence. This means <strong>only the final token in the input sequence needs to be processed at inference time</strong>.</p><h3>Self-attention during inference</h3><p>Now that we understand the overarching process of generating the next token, let’s dive a bit deeper into self-attention at inference time.</p><p>Let’s say we have a batch size of B, and a sequence length of T. When entering an attention layer, our input tensor has dimension <em>(B*T*D)</em>, where D is the embedding dimension of the model.</p><p>The first thing we do is generate three projections of the input tokens, called the query, key, and value vectors (or Q, K, and V). We use separate <em>D*D</em> weight matrices for each of Q, K, V. After this, we have three tensors for Q, K, and V, each of dimension <em>(B*T*D).</em></p><p>Attention is described by the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLJESTLxPljAhScYwGGkjg.png" /></figure><p>Let’s examine what attention does to a particular token in the input sequence. We take the query vector of this token and compute its dot product with the key vector of each token before it in the sequence. We take the softmax of these dot products to determine the attention weights that this token pays to the tokens before it, and the output of the layer is the sum of the value vectors of the previous tokens, weighted by the attention weights. This produces a new vector — the new representation of the token we just processed.</p><p>Notice that in the above explanation, performing attention on a single token requires only that token’s query, and the keys and values of all tokens. We also saw previously that at inference time, we only want to perform attention on the last token in the input sequence, since only this token matters for generating the next token. <strong>This means that during inference, we need to compute queries of the last token in the input, and the keys and values of all tokens in the input.</strong></p><h3>The KV Cache</h3><p>The goal of the KV cache is to prevent the redundant computation that takes place when generating the keys and values of earlier tokens in the input sequence.</p><p>Let’s say that we want to generate 5 new tokens on top of an existing sequence of 100 tokens. This would require 5 forward passes. During each forward pass, we compute the query, key, and value of the last token in the input sequence, which is usually a token that we just generated. But, we also re-compute the keys and values of the previous tokens in the input sequence from scratch, since we need them for attention.<strong> This is redundant — the keys and values of tokens in the input sequence will not change over the course of inference because they are independent of the tokens we generate.</strong></p><p><strong>The goal of the KV cache is to store the keys and values for all tokens in the input sequence</strong> so that each key/value is only computed once, and can be re-used during subsequent generations. This saves us from doing expensive-recomputation of the keys and values in each layer in the network. (Figure 2)</p><p>Say that we start off with the input sequence, “The cat was”. The first time we try to generate a new token, we will incur some cost because we are computing the keys/values of each token in the input from scratch. But, after this first forward pass, we can store the keys and values of “the”, “cat”, and “was” in the KV cache, and use them again the next time. This is why typically, <strong>the latency for generating the first token in a completion is higher than for subsequent tokens</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SVSHgs2LbFw86A9Yd1XuQ.png" /><figcaption>Figure 2: The first generation requires computing the K/V for all tokens. After the forward pass, those values are cached and used for the corresponding input tokens in the second generation. One K/V pair, for the last token in the sequence, is computed anew, and added to the cache, growing it.</figcaption></figure><h3>The problem with the KV Cache: memory</h3><p>So far, the KV cache sounds great. We can save a ton of compute, especially for long generations. We can even use it to store K/Vs ahead of time when we already know the input sequence (e.g. ChatGPT’s system prompt). Unfortunately, the KV cache’s main tradeoff is its considerable memory overhead.</p><p>Let’s calculate the memory taken up by the cache. Say our LLM is a transformers with <em>n_layers</em> attention layers. Each layer, we need to store 2 vectors: a key and a value, for each token in the input of length <em>seq_length</em>. Since transformers actually use multi-head attention, each layer is actually comprised of <em>n_heads</em>, where each head is dimension <em>head_dim</em>. Each element of the vector is a 16-bit float, meaning it takes up 2 bytes. Finally, we need to multiply this all by the batch size <em>b </em>used during inference.</p><p>Put all of this together and you get the size of the cache to be:</p><p><em>n_layers * seq_length * 2 * n_heads * head_dim * 2 * b.</em></p><p>So, <strong>the size is O(<em>n_layers * seq_length * n_heads * head_dim * b)</em></strong></p><p>Let’s take some reasonable assumptions:</p><ul><li><em>n_layers</em> = 60</li><li><em>seq_length</em> = 128,000</li><li><em>n_heads </em>= 8</li><li><em>head_dim</em> = 640</li><li><em>b</em> = 32</li></ul><p>With these parameters, <strong>the KV cache would take up 1.14 TB!</strong> Simply storing this data in memory is a challenge. But even if we had space in memory across multiple GPUs, it takes a long time <strong>loading this data from memory into our registers</strong>. <a href="https://arxiv.org/pdf/1911.02150">Research</a> has shown that this actually makes LLM inference memory-bound, rather than compute-bound, which is undesirable.</p><p>We can see that model depth, sequence length, and batch size will quickly blow up the KV cache’s size, but we ideally would like to maximize all 3.</p><p>Besides slashing any of these parameters, what architectures can we use to shrink the KV cache?</p><h3>Multi-Query Attention (2019)</h3><p>Multi-query attention (MQA) is an approach to shrinking the size of the KV-cache, invented by <a href="https://arxiv.org/pdf/1911.02150">Noam Shazeer in 2019</a>.</p><p>In typical multi-head attention, we process multiple heads for queries, keys, and values. In MQA, we instead only use multiple heads for queries, keeping only one head of size <em>head_dim</em> for the keys and values.</p><p>Here is some code annotating how MQA works:</p><pre>X = torch.randn(B, T, D) # Input, shape (B, T, D)<br>W_q = torch.randn(D, D) # Query projection weights, shape (D, D)<br>W_k = torch.randn(D, head_dim) # Key projection weights, shape (D, head_dim)<br>W_v = torch.randn(D, head_dim) # Value projection weights, shape (D, head_dim)<br>Q = X @ W_q # Queries, shape (B, T, D)<br>K = X @ W_k # Keys, shape (B, T, head_dim)<br>V = X @ W_v # Values, shape (B, T, head_dim)<br><br># Reshape Q to (B, n_heads, T, head_dim)<br>Q = Q.view(B, T, n_heads, head_dim).transpose(1, 2)<br>qkt = Q @ K.transpose(-2, -1) # Attention matrix, shape (B, n_heads, T, T)<br><br>#... assume we do some scaling, masking and softmax here<br><br>o = qkt @ v # Output is (B, n_heads, T, head_dim)<br>o = o.transpose(1, 2).view(B, T, D) # Reshape</pre><p>MQA <strong>shrinks</strong> <strong>the size of the KV cache by a factor of n_heads</strong>, since we have just one key/value vector of size <em>head_dim</em> per layer. MQA has been found to not significantly compromise model quality compared to the memory savings, leading to its popularity. Recently, Character.ai <a href="https://blog.character.ai/optimizing-ai-inference-at-character-ai/">announced</a> that they use MQA to scale throughput to 20,000 requests per second.</p><h3>Grouped-Query Attention (2023)</h3><p>Grouped-query attention (GQA), <a href="https://arxiv.org/pdf/2305.13245">invented at Google Research in 2023</a>, is an extension of MQA that gives the model higher capacity while still cutting the size of the KV cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKbrHd6s-7nuU3E7eh-gvA.png" /><figcaption>Figure 3: Grouped-query attention sits in the middle of typical multi-head attention and multi-query attention. Figure source: the original <a href="https://arxiv.org/pdf/2305.13245">paper</a>.</figcaption></figure><p>Instead of taking the extreme approach of only having one key/value shared across all the heads in a layer, GQA instead shares key/value vectors across a certain fixed number of heads, say <em>k</em>.</p><p>This, in turn, shrinks the KV cache by a factor of <em>k</em>. The authors of the paper found that GQA is a better compromise between typical multi-head attention and MQA, leading to very low quality sacrificed for increased memory savings. GQA is used commonly in modern-day models, including <a href="https://ai.meta.com/blog/meta-llama-3/">Llama3</a> and <a href="https://mistral.ai/news/announcing-mistral-7b/">Mistral-7B</a>.</p><h3>Sliding-Window Attention (2020)</h3><p><a href="https://arxiv.org/abs/2004.05150">Sliding-window attention</a>, invented by AI2, takes a different approach than the previous two methods. Recall that the expression for the size of the KV cache is O(<em>n_layers * seq_length * n_heads * head_dim * b)</em>. MQA and GQA seek to reduce <em>n_heads</em>. Sliding-window attention, however, tries to reduce the <em>seq_length </em>term by fixing the number of tokens that each token attends to.</p><p>Typically, a token in an autoregressive transformer will attend to every single token before it. In sliding-window attention, we define a fixed-size window of attention, beyond which tokens are not attended to. So, for a window size of 500, for example, each token can only attend to the preceding 500 tokens. (Figure 4)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zY6uHwfS_kByHtjiTq5i-A.png" /><figcaption>Figure 4: Typical self-attention uses a causal mask, where every token can attend to all the tokens before it. With sliding window attention, we use a special mask to allow each token to attend to a fixed number of tokens before it.</figcaption></figure><p><strong>SWA makes the <em>seq_length </em>term a constant, allowing us to scale to larger context windows while keeping the KV cache size fixed. </strong>Every time we generate a new token, we remove the key/value vector for the token that just went out of the sliding window. This sort of resembles an LRU cache!</p><p>The biggest question that remains is: how does this affect the capacity of the model? One of the main advantages of the transformer architecture is that attention is a global operation, which can learn distant relationships in the input sequence. Haven’t we just limited this?</p><p>SWA is able to still model distant relationships between tokens as information propagates further down the network. Say that the 1,000th token in a certain sequence is heavily related to the very first token. Now imagine our window size is 500. During the first layer, this relationship does not get modeled by the network, because only the 500th token in the sequence can attend to the 1st token. But in the second layer, the 500th token now contains some information from the 1st token, and the 1000th token can attend to the 500th token. This means it can model its relationship with the 1st token! Over the course of the model, <strong>the last token has taken information from the token <em>w * n_layers</em> tokens behind it. (Figure 5) </strong>However, this information transfer won’t be as powerful as it would be if tokens could attend to each other at each layer, leading to a small decrease in model capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tur4BeMlslYl3xZAHWmM1w.png" /><figcaption>Figure 5: With sliding window attention, information propagates further down the sequence deeper into the network. At first, only the w-th token can attend to the first token. But in the second layer, the 2w-th token can.</figcaption></figure><p>Sliding window attention is orthogonal to MQA and GQA, meaning you can implement both MQA/GQA and sliding window attention at the same time in your network.</p><h3>PagedAttention (2023)</h3><p><a href="https://arxiv.org/abs/2309.06180">Paged Attention</a>, invented by UC Berkeley researchers, seeks not to reduce the size of the KV cache, but make its storage more efficient in memory.</p><p>The motivation for PagedAttention comes from the way that the KV cache is stored in systems that see high inference throughput. The researchers noticed that the default implementations for the KV cache would allocate a pre-determined size of contiguous memory based on the maximum sequence length of the inference request. This is wasteful:</p><ul><li>It causes internal fragmentation, because often the decoding does not take up the entire reserved sequence length. All of the extra memory is wasted.</li><li>It causes external fragmentation, since different requests might have different pre-determined sequence lengths.</li></ul><p>PagedAttention draws from the virtual memory concepts used in modern operating systems. <strong>Instead of allocating a pre-determined chunk of contiguous memory for each request, it divides the KV cache into pages, which can be non-contiguous, and then creates a page table that stores which tokens’ keys and values are located on which page.</strong> This virtualized approach allows the size of the KV cache to grow and shrink dynamically and prevents both internal and external fragmentation. (Figure 6)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdUdnqToZo8qx8d9ldkrhQ.png" /><figcaption>Figure 6: PagedAttention stores pieces of the KV cache in non-contiguous blocks of memory, making memory use more efficient. Figure from the original <a href="https://arxiv.org/abs/2309.06180">paper</a>.</figcaption></figure><p>The improved memory utilization allows LLM systems to process many more requests at a time, increasing throughput. It is also orthogonal to MQA/GQA and SWA, meaning it can be applied on top of these architectures. PagedAttention is the core innovation behind the popular open-source library <a href="https://github.com/vllm-project/vllm">vLLM</a>, and has become widely adopted.</p><h3>Summary</h3><p>The KV cache is essentially for making LLMs faster by preventing redundant computation of the keys/values of earlier tokens. The challenge with the KV cache is its memory usage. We learned about a number of methods to reduce the size of the KV cache and makes its storage more efficient, including</p><ul><li>Multi-query attention (MQA)</li><li>Grouped-query attention (GQA)</li><li>Sliding window attention (SWA)</li><li>PagedAttention</li></ul><p>Thank you for reading, and please reach out with any questions!</p><p><a href="http://x.com/apatwa7">Twitter/X</a></p><p><a href="http://linkedin.com/in/aalok-patwa">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d961ead936" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>