Mechanical Dreams · Mechanical Dirk
In this episode: • Introduction to Quantization and Outliers: Norris and Linda introduce the episode's paper, QuaRot, and discuss the main hurdle in LLM inference: the memory bottleneck and the pesky outlier features in activations. • The Magic of Hadamard Rotations: Linda explains the core mechanism of QuaRot, using randomized Hadamard transformations to eliminate outliers through computational invariance. • Taming the Attention Mechanism and KV Cache: The hosts dive into the complexities of quantizing the attention module, discussing how QuaRot rotates keys and values to achieve a fully 4-bit KV cache. • Performance, Results, and Hardware: An analysis of the empirical results on the LLaMA-2 models, highlighting the impressive memory savings, speedups, and maintained zero-shot performance. • Conclusion and Takeaways: Norris and Linda wrap up the discussion, reflecting on what end-to-end 4-bit inference means for the future of deploying massive language models locally.
## Introduction to Quantization and Outliers Norris: Welcome back to Mechanical Dreams, the podcast where we sift through the noise of machine learning research to find the signal. I am your host, Professor Norris, and as always, I am joined by my brilliant student, Linda. Linda: Hi everyone! I am so excited for today's episode. We are looking at a paper that tackles one of the most frustrating roadblocks in deploying Large Language Models. It is called QuaRot, which stands for Outlier-Free 4-Bit Inference in Rotated LLMs. Norris: Ah, quantization. The perpetual quest to stuff a ten-pound language model into a two-pound bag. For our listeners who might just be joining us on this journey, let us set the stage. When we talk about inference in these massive models like LLaMA-2, we are fundamentally bottlenecked by memory and compute, right? Linda: Exactly. When you type a prompt into an LLM, the model goes through a prefill phase to process all those tokens and cache them. This phase is heavily compute-bound. Then, as it generates text token by token, it becomes memory-bound. You have to load the model weights and the cached keys and values for every single step. Norris: And those weights and caches take up an enormous amount of VRAM. A 70 billion parameter model at standard 16-bit precision requires over 140 gigabytes of memory just for the weights alone. That is before you even start generating text and filling up the KV cache. So, the industry has turned to quantization, effectively downcasting the precision of the numbers from 16 bits to 8 bits, or even 4 bits. Linda: Right, and weight quantization has become pretty standard. We can compress the weights offline, drastically reducing the memory footprint. But to get the true speedups on the hardware, what we really want is joint quantization. We want to shrink the weights, the KV cache, and the activations. If everything is in 4 bits, the matrix multiplications are incredibly fast and memory usage plummets. Norris: But that is where the dream usually falls apart. Quantizing weights is one thing, because they are static. Activations are the actual data flowing through the network based on the user prompt. And as we have discussed in previous episodes, large language models have this nasty habit of developing outlier features in their activations. Linda: They really do. You will have a hidden state vector where 99 percent of the values are hovering right around zero, between minus one and one. And then suddenly, one specific dimension will spike to negative twenty or positive thirty. Norris: Which completely ruins standard quantization! If you try to map that entire range into just 16 possible values, which is what you get with 4 bits, the massive outlier takes up the edges of the scale. All of your perfectly good, nuanced data hovering near zero gets squashed into the exact same single bin. You lose all the signal, and the model starts hallucinating or outputting gibberish. Linda: Precisely. Previous research tried to work around this. Methods like LLM dot int 8 or SmoothQuant tried to isolate those outlier features during inference and keep them in higher 16-bit precision, while keeping everything else in 8 bits or 4 bits. Norris: I have always been skeptical of those approaches. You end up having to write these incredibly complex mixed-precision hardware kernels. It is a routing nightmare. You have to separate the outliers, do high-precision math on them, do low-precision math on the rest, and then stitch it all back together. It often eats up the compute speedups you were trying to gain in the first place. Linda: You hit the nail on the head, Professor. And that is exactly why the QuaRot paper is such a breakthrough. The authors realized that instead of trying to meticulously track and preserve these outliers, you can just mathematically smooth them out of existence entirely. Norris: Smooth them out of existence? That sounds like alchemy, Linda. You cannot just delete the outliers without destroying the information they represent. The model learned to put those huge spikes there for a reason. Linda: It is not alchemy, it is linear algebra! And that is the core brilliance of QuaRot. They use a technique based on computational invariance to rotate the internal representations of the LLM. By applying these specific rotations, the magnitude of the outliers gets distributed across all the other dimensions. The information is perfectly preserved, but the spikes are gone, making it incredibly easy to quantize everything down to 4 bits. Norris: Okay, I will admit, you have my attention. Smearing the outliers across the vector space so that everything falls into a neat, quantizable distribution is a very elegant idea. But how do you rotate the entire hidden state of a 70 billion parameter model without completely breaking the output? ## The Magic of Hadamard Rotations Norris: So, pick up where we left off, Linda. At the end of the last chapter, you dropped a cliffhanger about rotating the entire hidden state of a massive language model to squash these outlier features. How exactly do you do that without completely breaking the fundamental math of the network? Linda: It all hinges on a mathematical property called computational invariance. The authors build on an idea where you can take a weight matrix on the left side of a transformer block and multiply it by an orthogonal matrix, which we can call Q. To cancel out the effect so you do not change the final output, you just multiply the output weight matrix on the other side of the block by Q-transpose. Norris: Right, because an orthogonal matrix multiplied by its transpose gives you the identity matrix. That is a standard linear algebra trick. But there is a massive elephant in the room here. A transformer block is not just two linear layers glued together. There is an RMSNorm layer right in the middle! Doesn't that nonlinear step completely ruin the cancellation? Linda: That is the absolute best part of this paper! You would think RMSNorm ruins it, but what does RMSNorm actually do? It divides the activation vectors by their norm. And if there is one thing we remember from foundational linear algebra, it is that orthogonal rotations preserve the L2 norm of a vector. Norris: Ah! Of course. The length of the vector stays exactly the same, it is just pointing in a different direction in the high-dimensional space. So the scaling applied by RMSNorm works exactly as it did before. The operations commute. Linda: Exactly! Because they commute, you can completely absorb any scaling factors into the adjacent weight matrices and just fuse these rotations directly into the model's weights offline. During inference, the model does the exact same calculation, but the hidden states passing between the blocks are completely rotated. Norris: Okay, I am tracking. But there are infinitely many orthogonal matrices. What specific rotation are they choosing that guarantees these pesky outlier spikes get flattened out? Linda: They use randomized Hadamard matrices, specifically leveraging the Walsh-Hadamard transform. Norris: A classic choice! That has been used in signal processing forever. The Hadamard matrix basically consists entirely of ones and negative ones, scaled down, right? Linda: Yes! And because it is a dense matrix where every single entry has the exact same magnitude, when you multiply it with an activation vector, every single output dimension becomes a combination of all the input dimensions. It literally averages out the spikes. Norris: So if one specific dimension has a massive outlier activation of, say, thirty, and the rest are hovering near zero, the Hadamard transform takes a little piece of that thirty and spreads it evenly across the entire hidden state. Linda: Precisely. This concept is called incoherence processing. It has actually been used before in methods like QuIP to make weight quantization easier, but QuaRot takes it to the next level by applying it to the activations too, which is notoriously much harder. Norris: But wait a second, Linda. Doing a dense matrix multiplication on every single activation vector sounds incredibly expensive. I thought the whole point of quantization was to speed up the prefill and decoding stages, not add massive overhead. Linda: That is why the Hadamard transform is magic. Because of its recursive structure, you do not actually need to do a full standard matrix multiplication. You can compute the Walsh-Hadamard transform in O of d log d time instead of O of d squared. It is highly optimized. Norris: Still, doing that on every layer has to add up. Linda: But that is the beauty of fusing it into the weights! QuaRot only requires about one and a half online Hadamard transforms per transformer layer. Most of the rotations are pre-multiplied into the model's weights while it is sitting on your hard drive. Norris: I see. You bake the inverse rotations into the weights themselves. So during inference, the weights just naturally expect rotated inputs and spit out rotated activations. No extra compute required for the bulk of it. Linda: Exactly! You do have to insert a quick online Hadamard operation right before the feed-forward down-projection to smooth things out inside the block, because that part cannot be perfectly fused, but it is done using a super fast custom kernel. The overhead is completely negligible compared to the time saved by doing all the matrix multiplications in 4-bit integer math. Norris: I have to admit, that is deviously clever. You fix the data distribution to match your hardware's limitations, instead of twisting the hardware to match the data. I love it. But the feed-forward layer is only half the battle. Transformers are famous for their attention mechanisms, and that is a whole different beast. ## Taming the Attention Mechanism and KV Cache Norris: Alright Linda, you have convinced me that we can smooth out the feed-forward network with these Hadamard rotations. But as I said at the end of the last chapter, the attention mechanism is a completely different beast. You have got Queries, Keys, Values, the softmax function... it is a non-linear soup. How does QuaRot survive that? Linda: It is definitely trickier, but the core principle of computational invariance still holds. Let us break it down, starting with the Values. In the attention computation, the Value matrix and the final Output projection matrix are implicitly multiplied together within each head. Norris: Ah, I see. Because the attention scores are essentially just weights for a linear combination of the Value vectors. So if you rotate the Values, you just need to apply the inverse rotation to the Output projection matrix? Linda: Exactly! They apply a head-wise Hadamard matrix to both the Value weights and the Output weights. Because the weights for each head are concatenated in the representation, they actually perform a single Kronecker structured multiplication to handle this efficiently across all heads. Norris: Kronecker products? Be still my beating heart. I love a good Kronecker product. So that handles the individual heads, but do they need to share the transform across the entire attention dimension? Linda: They do. To make it a full Hadamard operation, they use a mathematical identity that allows them to insert another quick online Hadamard block right before the final Output projection. So the Values are rotated, the outliers are smashed, and we can safely quantize the Values down to 4 bits! Norris: That takes care of half the KV cache. But the K stands for Keys, and we know from previous papers like KVQuant that Keys are notorious for harboring massive outliers. You cannot just quantize the Values and call it a day if the Keys are still hogging memory in 16-bit precision. Linda: You are spot on, Professor. We have to rotate the Keys too. And since Keys interact directly with the Queries to compute the attention scores, the solution is to rotate both of them! If you multiply the Queries and the Keys by the exact same orthogonal matrix, their dot product remains completely unchanged. The attention scores stay exactly the same. Norris: Hold on a second. That works beautifully in a vanilla transformer. But LLaMA-2 uses RoPE, Rotary Position Embeddings. RoPE injects positional information by rotating the Query and Key vectors in a very specific two-dimensional plane. If you apply a global Hadamard rotation to the vector space before RoPE, you scramble the coordinate system! The positional embeddings will be completely meaningless. Linda: That is exactly the roadblock the researchers hit! The positional embeddings prevent you from directly fusing the Hadamard matrix into the Query and Key weights offline like we did with the feed-forward layers. So, QuaRot uses a technique called online head-wise Hadamard rotation. Norris: Online? Meaning they do the rotation on the fly during inference? Doesn't that bring back the overhead problem we were just praising them for avoiding? Linda: Not exactly! They use what is called Post-RoPE caching. Instead of trying to rotate the weights beforehand, they let the model apply the RoPE positional encodings normally in higher precision. Then, right after RoPE and right before caching, they apply the Hadamard rotation to the Keys. Norris: Ah! So the Keys are safely embedded with their positional information, then you rotate them to crush the outliers, and then you quantize them to 4 bits to store in the cache. Linda: Yes! And during the decoding phase, you only have to apply that Hadamard rotation to the single new Query vector at each step. It is incredibly fast because it is just one token at a time. The heavy computational lifting for all the past Keys was already done and cached. Norris: I have to admit, that is an incredibly elegant workaround. The KV cache is the absolute bane of long-context inference. If you have a batch size of 64 and a sequence length of 2048, a 16-bit KV cache is eating gigabytes of VRAM. Squeezing that down to a true 4 bits without losing the RoPE embeddings... that is the holy grail. Linda: Exactly. And just to top it off, because the Queries and Keys are now rotated and outlier-free, they can use a standard online softmax calculation, similar to Flash Attention. After a segment of the KV vectors are loaded from memory in 4-bit, they just dequantize and compute the dot product in FP16. The whole attention pipeline flows seamlessly with a fraction of the memory IO. Norris: So they really did it. End-to-end 4-bit inference. We have got 4-bit weights, 4-bit activations in the feed-forward blocks, and a fully 4-bit KV cache, all thanks to some clever matrix commutations and a whole lot of minus ones. But the real test is whether the model actually performs, or if all this rotation just gives it vertigo. Let us look at those accuracy numbers and performance metrics next. ## Performance, Results, and Hardware Norris: Welcome back. We have spent the last few chapters geeking out over Kronecker products and Post-RoPE caching. But let us get down to brass tacks. Does QuaRot actually work when you plug it into a GPU, or is it just a beautiful math exercise on a whiteboard? Linda: Oh, it works beautifully. The team evaluated QuaRot on the LLaMA-2 family, specifically the 7 billion, 13 billion, and the massive 70 billion parameter models. And the accuracy retention is frankly mind-blowing. Norris: I have read enough quantization papers to know that mind-blowing usually comes with a huge asterisk. What is the actual damage on the perplexity scores? Linda: On the WikiText-2 dataset, the perplexity loss for the LLaMA-2 70B model running fully in 4-bits is at most 0.47. The baseline FP16 perplexity was 3.32, and QuaRot bumped it to just 3.79. And remember, that is with weights, activations, and the KV cache all squeezed into 4 bits. Norris: A 0.47 bump for an end-to-end 4-bit model? That is surprisingly good. In the past, pushing activations down to 4 bits would easily blow up perplexity by several points, assuming it did not just crash the model entirely. How about the downstream tasks? Does it still know how to reason? Linda: It definitely does. They tested it on six standard zero-shot tasks, including PIQA, HellaSwag, and WinoGrande. Across the board, QuaRot preserves 99 percent of the FP16 zero-shot accuracy for the 70B model. The average score drops from about 77 percent down to just 76 percent. Norris: So it is practically indistinguishable to an end user. But what about calibration? A lot of these extreme quantization methods require you to carefully calibrate the model on a massive dataset just to find the right scaling factors to handle the outliers. Linda: That is another big win. For the 4-bit weights, they do use the GPTQ algorithm, which requires a tiny calibration set of just 128 samples. But they also proved that if you only want to compress down to 6 or 8 bits, you can use simple Round-to-Nearest quantization. That means literally zero calibration data is needed, and the 6 and 8-bit models are completely lossless compared to the baseline. Norris: Zero calibration for lossless 8-bit inference. That makes the deployment pipeline incredibly smooth. You just download the weights, apply the Hadamard rotations, round the numbers, and you are off to the races. But let us talk hardware. Did they actually implement this on real silicon? Often, researchers just simulate the 4-bit math in FP16 to check the accuracy without building the actual kernels. Linda: They did build them! They wrote custom low-level CUDA kernels using Nvidia's CUTLASS library to execute the 4-bit matrix multiplications natively on the Tensor Cores. During the operation, the Tensor Cores do the math in 4 bits, accumulate the results in an INT32 accumulator, and then instantly dequantize and cast it back to FP16 for the next step. They benchmarked everything on consumer-grade Nvidia RTX 3090 GPUs. Norris: The RTX 3090. A classic workhorse. So what kind of speedups are we seeing during the prefill phase? That is the compute-heavy part where the model is churning through the initial prompt. Linda: For the prefill stage with a sequence length of 2048 and a batch size of 64, the custom kernels achieved up to a 3.33x speedup on the LLaMA-2 70B model compared to the standard FP16 implementation. Norris: Over three times faster just to read the prompt. That is massive for applications like document summarization where you are feeding it walls of text. And what about the decoding stage? We talked earlier about how the KV cache is the main bottleneck there. Linda: That is where the memory savings really shine. Because decoding is bound by memory bandwidth, shrinking everything down to 4 bits drastically reduces the IO operations. During decoding, they saw up to 3.89x peak memory savings. Norris: That is the holy grail right there, Linda. Almost 4x memory savings means a 70 billion parameter model, which normally takes around 140 gigabytes of VRAM in 16-bit, can now fit into roughly 35 or 40 gigabytes. Instead of renting a massive server cluster with multiple A100s, a researcher could run this on two consumer RTX 3090s sitting under their desk. And doing all this without a complex hardware kernel that juggles mixed precision, it just proves that a clever mathematical transformation is worth a thousand lines of messy code. ## Conclusion and Takeaways Norris: As we wrap up today's episode, I have to say, QuaRot really delivered on its promises. Squeezing a 70 billion parameter model onto a couple of consumer GPUs without lobotomizing the network is no small feat. Linda: It really is a game changer. And looking ahead, the authors point out some incredibly exciting future directions in their conclusion. For instance, they mention extending this exact method to Mixture-of-Experts architectures. Norris: Oh, applying this to MoEs makes perfect sense. Those models are notoriously memory-hungry because you have to load all those different expert weights. If you can smash the KV cache and the activations down to 4 bits across a sparse architecture, the efficiency gains would be staggering. Linda: Exactly! They also brought up hardware trends. Nvidia recently announced the new Blackwell B200 architecture, which natively supports 4-bit floating point formats. QuaRot's ability to do end-to-end 4-bit integer inference proves we can get massive speedups on much cheaper, existing hardware right now, while perfectly positioning us for those next-generation chips. Norris: It is a perfect example of software and mathematics staying one step ahead of the silicon. By simply rotating the vector space to eliminate outliers, we do not have to wait for hardware engineers to magically solve the mixed-precision routing problem. We just do better math. Linda: Well said, Professor! That is all the time we have for today's episode. You can find the link to the QuaRot paper, along with their open-source GitHub repository, in our show notes. Norris: Thank you for joining us on Mechanical Dreams. I am Professor Norris, reminding you that sometimes the best way to move forward in machine learning is to just rotate your perspective. See you next week!