<?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 Amine Kammah on Medium]]></title>
        <description><![CDATA[Stories by Amine Kammah on Medium]]></description>
        <link>https://medium.com/@amineka9?source=rss-a2add3f8210e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8DIdIDEDIyvpioatvc5AYQ.jpeg</url>
            <title>Stories by Amine Kammah on Medium</title>
            <link>https://medium.com/@amineka9?source=rss-a2add3f8210e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:39:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amineka9/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[Decoding Context Windows: Benchmarking DeepSeek ability to handle 128k tokens]]></title>
            <link>https://medium.com/@amineka9/decoding-context-windows-benchmarking-deepseek-ability-to-handle-128k-tokens-fa3fc8870ca5?source=rss-a2add3f8210e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa3fc8870ca5</guid>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[context-window]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Amine Kammah]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 14:09:53 GMT</pubDate>
            <atom:updated>2025-08-03T19:11:53.921Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decoding Context Windows: Benchmarking DeepSeek ability to handle 128k tokens.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FznjifwixvfhFZpb.jpg" /></figure><p>Modern LLMs like DeepSeek and GPT-4o boast 128k+ token windows. Does that mean we can throw in massive prompts and expect the model to sort things out?</p><p>As LLMs get more powerful, applications get more complex and developers cram prompts with context, code, and task instructions. We ran a benchmark using DeepSeek’s <strong>V3</strong> and <strong>R1</strong> models to test how prompt length, structure, and batch size <em>actually</em> affect performance.</p><h3>🎯 What I Wanted to Know</h3><p>This experiment set out to answer four simple but practical questions:</p><ol><li><strong>Is it better to break down large tasks into smaller, sequential prompts? Or do models just ignore the irrelevant parts?</strong></li><li><strong>Does it matter where you place the “core” instruction?</strong></li><li><strong>How does asking for many results at once (batching) affect accuracy?</strong></li><li><strong>Do reasoning models handle long contexts better?</strong></li></ol><h3>The Benchmark: A Simple but Tough Test 🧠</h3><p>The task was to execute one of two simple Python functions. These functions were chosen because they perform character-level string operations, which are notoriously tricky for LLMs, and have obscure names to force the model to actually read the code instead of guessing based on the name.</p><p>The “needle” was one of these two functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1pX8kDutdQahfN0x" /></figure><p>The “haystack” is a large file of unrelated Python code, totaling <strong>35,000 tokens</strong>. I varied three parameters to test the models’ limits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBREy5YEfzhUdPp9JqhEXA.png" /></figure><p>This yields 280 runs per model.</p><p>To validate the LLM’s responses, I executed the corresponding function in Python using the same input. I then compared the model’s predicted output against the actual result. If the outputs matched exactly, I marked the answer as <strong>correct</strong>; otherwise, I marked it as <strong>incorrect</strong>.</p><p><strong>Example:</strong><br> Function: a_key_function(&quot;12&quot;)<br> Expected output: &quot;21&quot;<br> LLM output: &quot;21&quot; → ✅ <strong>Correct</strong></p><p>Function: a_key_function(“34”)<br>Expected output: “43”<br>LLM output: “44” → ❌ Incorrect</p><h3>DeepSeek V3: Lost in the Noise</h3><p>The results for the standard V3 model show that performance is highly sensitive to all three factors. The model struggles when the prompt is long, the task is buried, or the workload is high.</p><h4>Finding #1: The “U-Shaped” Attention Curve</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NJvMXrgkCVrsleSg" /></figure><p>The model performed best when the target function appeared at either the very beginning or very end of the haystack, and worst when it was placed in the middle.</p><ul><li><strong>Accuracy at the ends (0% and 100% depth):</strong> ~53.6%</li><li><strong>Accuracy in the middle (50% depth):</strong> ~38.6%</li></ul><h4>Finding #2: More Context, More Problems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yB3JyCiep6xwGpse" /></figure><p>Adding more distracting code significantly reduced the model’s accuracy. Performance dropped steadily as the distracting context grew from 700 to 35,000 tokens.</p><ul><li><strong>Accuracy with 700 distracting tokens:</strong> 52.4%</li><li><strong>Accuracy with 35k distracting tokens:</strong> 38.9%</li></ul><h4>Finding #3: Batching hurts Accuracy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qCOVTGrqTot7gEYX" /></figure><p>Increasing the batch size had a negative effect. The model’s ability to apply the same logic repeatedly within one prompt quickly deteriorated.</p><ul><li><strong>Accuracy with a batch size of 4:</strong> 51.6%</li><li><strong>Accuracy with a batch size of 512:</strong> 36.8%</li></ul><p>📉 <strong>Conclusion:</strong> For high-fidelity tasks, <strong>use small batch sizes or send requests one by one.</strong></p><h3>DeepSeek R1 (Reasoning Model): A Different Story</h3><p>The R1 model is designed to “think” before answering, allowing for a summary of the relevant context to be placed at the bottom of the context window.</p><h4>Finding #1: Depth and Context Barely Matter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*054aakYy2kGdx1A4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wq_nIXaYU3GTXVBx" /></figure><p>Unlike V3, the R1 model’s performance was <strong>stable regardless of where the function was placed</strong> or how much distracting code was added. The accuracy hovered around 63% across nearly all depths and context lengths.</p><p>R1 seems <strong>highly effective at ignoring noise</strong> and overcoming the “lost in the middle” problem.</p><h4>Finding #2: Batch Size is Still the Achilles’ Heel</h4><p>Despite the above, R1 performance fell off a cliff as the batch size increased. The effect was even more pronounced than with V3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BcXFJw5Yq_pmRYYl" /></figure><ul><li><strong>Accuracy with a batch size of 4:</strong> 91.4%</li><li><strong>Accuracy with a batch size of 512:</strong> 42.9%</li></ul><p>📉 <strong>Conclusion:</strong> Even powerful reasoning models get confused or “drift” when asked to perform a repetitive task too many times in a single prompt.</p><h3>A Different Lens: Statistical Analysis 📊</h3><p>To better understand the relative impact of each factor, we can look at the results through a statistical lens. I fitted an Ordinary Least Squares (OLS) linear regression model to predict accuracy. The model was trained using three normalized factors: context_length, batch_size, and distance_from_the_middle.</p><p>A 90/10 split was used to ensure the regression doesn’t overfit to the training dataset, leaving 252 for training and 28 for validation.</p><p>The table below shows each factor’s coefficient (its impact on accuracy) and its p-value (the probability the result is random). A p-value below 0.05 is considered statistically significant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BsvtuG2kWAtGheejDlsNvw.png" /></figure><p><strong>In short:</strong></p><ul><li><strong>DeepSeek V3</strong> is sensitive to all tested factors. Longer prompts, buried instructions, and large batch sizes all have a statistically significant negative impact on its accuracy.</li><li><strong>DeepSeek </strong>R1’s is better at locating key instructions and ignoring noise, as these factors were not statistically significant. However, its performance remains vulnerable to batch_size.</li></ul><h3>Structured Output Prompting: Forcing the Model to “Look” Before It Acts 🔍</h3><p>To test whether <strong>prompt structure </strong>can mitigate the “lost‑in‑the‑middle” failure mode we saw with DeepSeek V3, I added a single instruction:</p><p><strong><em>“First, write a short </em></strong><strong><em>function_analysis explaining what the target function does. Second, produce the requested outputs.”</em></strong></p><p>Because the analysis field will appear <strong>after</strong> the entire haystack, the model will have an explanation of the function at the very bottom of its context window. Everything else — including the two functions and the batch of test cases — remained unchanged.</p><p><strong>Finding #1: The “U-Shaped” Curve Flattens Significantly ✅</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulw-6F1HToX6RkVbaSh9Mw.png" /></figure><p>This single change largely remedies the “lost in the middle” problem for the V3 model. By forcing the analysis step that places the key instructions right at the bottom of the context window, the model’s accuracy becomes much more consistent.</p><p>When the target function sat dead‑center (50% depth), accuracy jumped from <strong>40.5 % → 51.8 %</strong> — an 11‑point gain that closes 70 % of the gap to the R1 reasoning model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1h0NQ3FfD2DMcXdZuas0Q.png" /></figure><p>The new prompting strategy boosts performance across the board, with accuracy now peaking at <strong>62.2%</strong> when the function is at the very beginning of the prompt.</p><p><strong>Finding #2: Batch Size is Still a Problem ⚠️</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nI4MuVo-91G7z38rkUXkdw.png" /></figure><p>Despite the gains in locating the function, this new approach doesn’t solve the model’s difficulty with large batch sizes. The performance curve shows the same steep drop-off as before.</p><ul><li><strong>Accuracy with a batch size of 4:</strong> 63.6%</li><li><strong>Accuracy with a batch size of 512:</strong> 47.5%</li></ul><p><strong>R1 remains the ceiling — but the ceiling is closer.</strong><br>The more deliberate R1 model is barely affected by this trick (its depth/context p‑values were already non‑significant), yet V3 now lands within ~10 points of R1 on most settings. In other words, <em>how</em> you ask sometimes matters almost as much as <em>which</em> model you ask.</p><h3>What I’ll Be Doing Differently Next Time</h3><p>While this benchmark only scratches the surface — and isn’t enough to draw broad conclusions about all LLMs or all types of tasks — it does offer some compelling signals about what matters in real-world prompt design. These results won’t generalize across every model or application, but they’ve made me rethink how I approach complex prompts.</p><p>From now on, I’ll be paying closer attention to a few key principles:</p><ul><li><strong>I’ll be careful with batching.</strong> This was the biggest lesson for me. The cost saving is tempting, but the performance hit is brutal. Seeing the R1 model’s accuracy drop from 91% to 43% was unexpected. From now on, if accuracy is the goal, I’m keeping my batch sizes small. For anything mission-critical, I’ll probably just send requests one by one.</li><li><strong>I’ll use smart prompting to fight context blindness.</strong> My main takeaway was to place important information at the top or bottom of a prompt. When that’s not possible, forcing the model to first find and analyze the key information with <strong>structured output</strong> proved to be incredibly effective. It made the standard V3 model behave more like the advanced R1 model, largely solving the “lost in the middle” problem.</li><li><strong>I’ll use a reasoning model (like R1)</strong> If I have to throw a large codebase or a long legal document at the model, R1’s ability to locate the “needle in the haystack” and use it to process data is impressive. <strong>I’ll use a non-reasoning model (like V3)</strong> when speed and cost matter, the task is clear, and you can write a good, focused prompt.</li><li><strong>I am going to write smaller prompts:</strong> I’ll be more aggressive about breaking down big jobs into smaller prompts. My instinct will be to ask: “Does the model <em>really</em> need all this?”.</li><li><strong>I’m putting the important stuff at the top or bottom.</strong> I will be creating clear separation between sections and placing the crucial instructions at the top/bottom of the prompt.</li></ul><h3>Some next steps</h3><ul><li><strong>Benchmark Against Other Models:</strong> Run the same tests on competitors like <strong>GPT-4o, O3, Claude 4, and Gemini 2.5</strong>. This will show if the “lost in the middle” and batching problems are universal or specific to DeepSeek.</li><li><strong>Test on Different Algorithms:</strong> Move beyond character level manipulation. See if the same patterns hold for graph traversals for example.</li><li><strong>Diagnose the Batching Failure:</strong> Analyse <em>how</em> the reasoning model fails on large batches. Does it get the first few right and then “drift” off-task, or are the errors random? Understanding the failure mode is key.</li></ul><p>Benchmarking code is available <a href="https://github.com/amineKammah/deepseek_context_window_benchmark">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa3fc8870ca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future of Vector Search: Exploring LanceDB for Billion-Scale Vector Search]]></title>
            <link>https://medium.com/@amineka9/the-future-of-vector-search-exploring-lancedb-for-billion-scale-vector-search-0664801bc915?source=rss-a2add3f8210e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0664801bc915</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[hnsw]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Amine Kammah]]></dc:creator>
            <pubDate>Fri, 13 Dec 2024 10:31:10 GMT</pubDate>
            <atom:updated>2024-12-13T10:31:10.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*ivtPWJIva29sfbSB" /></figure><p><strong>Introduction</strong></p><p>High-dimensional nearest neighbor search (ANN) is a cornerstone in fields like recommendation systems, image retrieval, and natural language processing. Among the myriad of algorithms designed for efficient ANN, Hierarchical Navigable Small World (HNSW) graphs have emerged as a state-of-the-art solution, offering an impressive recall-speed tradeoff. However, scaling HNSW to handle billions of vectors presents significant challenges, primarily due to its memory-bound nature.</p><p>In this article, we’ll delve deep into the HNSW algorithm, discuss the challenges of scaling it to massive datasets, and explore how emerging technologies like LanceDB could revolutionize disk-based ANN searches, potentially bridging the performance gap with in-memory solutions.</p><h3>The Challenge with HNSW and Large-Scale Datasets</h3><p>HNSW is a graph-based algorithm that excels in guiding searches through a multi-layered navigation structure. It operates by exploring nodes sequentially: starting from an entry point, it traverses the graph by selecting the nearest neighbors until it converges to the closest vector(s). This sequential exploration inherently involves numerous random memory accesses.</p><p>While this behavior is acceptable when the entire graph resides in memory, it poses significant problems when dealing with data that cannot fit entirely in RAM. Disk access speeds, especially for random reads, are orders of magnitude slower than memory access speeds. This mismatch results in substantial latency, making traditional disk-based HNSW impractical for large-scale applications.</p><p>Furthermore, because HNSW relies on sequential node traversal, it exacerbates the issue; we need to wait for a disk read result before proceeding to the next one, making the latency very noticeable.</p><h3>A Word on Quantization</h3><p>To mitigate memory constraints, quantization techniques are often employed. By compressing vectors into lower-precision representations, we can drastically reduce memory footprints. However, this compression comes at the cost of reduced retrieval performance. The loss of precision can lead to lower recall rates and decreased accuracy in nearest neighbor searches.</p><h3>Qdrant’s Approach: Balancing Compression and Precision</h3><p>Qdrant, for instance, tackles this problem by quantizing vectors to fit them into an in-memory HNSW graph. During query time, it retrieves the top <em>m</em> candidates and then re-ranks them using the full-precision vectors stored on disk. This hybrid approach leverages the speed of in-memory search while compensating for quantization-induced inaccuracies through precise re-ranking. Moreover, fetching full-precision vectors from disk can be parallelized, mitigating the latency introduced by disk reads.</p><p>This approach is detailed in Andrey Vasnetsov’s presentation, <a href="https://youtu.be/bU38Ovdh3NY">“Qdrant: Open Source Vector Search Engine and Vector Database”</a>, available on YouTube.</p><h3>Enter LanceDB: Optimizing Disk-Based HNSW</h3><p>The question then arises: <strong>What if we could enhance random disk access speed, enabling us to build efficient HNSW graphs directly on disk?</strong></p><h3>Lance: A Next-Generation Data Format</h3><p>Lance is a new data format designed as a successor to Parquet, aiming to retain Parquet’s analytical performance while significantly improving random access speeds. By optimizing data storage patterns and access methods, Lance reduces the latency typically associated with disk reads. This enhancement makes Lance particularly suitable for workloads requiring random access to large datasets, such as ANN searches.</p><h3>LanceDB’s Indexes</h3><p>Building on Lance’s capabilities, LanceDB introduces a couple of ANN algorithms, notably IVF_PQ and IVF_HNSW_PQ. Unlike standard HNSW implementations, LanceDB doesn&#39;t construct a singular HNSW graph over the entire dataset. Instead, it builds sub-HNSW indices within each Inverted File (IVF) partition. This strategy reduces the number of required IVF partitions for large-scale datasets and improves search efficiency within each partition.</p><p><strong>Note:</strong> This approach differs from FAISS’s IVF_HNSW variants, where an HNSW graph accelerates searches across IVF centroids when their numbers become substantial.</p><p>By setting both n_partitions and n_probe to 1 in LanceDB&#39;s IVF_HNSW_PQ index, we effectively simulate a disk-based HNSW index with scalar quantization (SQ) or product quantization (PQ). This configuration allows us to explore the potential of LanceDB as a full disk-based HNSW solution, as explained in detail in <a href="https://github.com/lancedb/lancedb/issues/1428">this GitHub issue</a>.</p><h3>Benchmarking: In-Depth Analysis of LanceDB vs. FAISS HNSW</h3><p>To evaluate LanceDB’s performance, we conducted a series of experiments comparing it against FAISS’s in-memory HNSW implementation. The goal was to understand how disk-based LanceDB performs relative to the established in-memory FAISS HNSW, particularly when dealing with datasets that exceed available memory.</p><h3>Benchmark Setup</h3><h4>Dataset</h4><p>We used the publicly available <strong>GIST1M</strong> dataset, which consists of one million 960-dimensional vectors commonly used for benchmarking ANN algorithms. The dataset was divided into:</p><ul><li><strong>Training Data:</strong> 1 million vectors for building the indices.</li><li><strong>Test Queries:</strong> 1,000 vectors for querying the indices.</li></ul><p>To simulate larger datasets that exceed memory capacity, we augmented the training data:</p><ul><li><strong>Augmented Data:</strong> The original data was replicated and perturbed with slight random noise to create datasets of up to 3 million vectors.</li></ul><h4>Ground Truth Computation</h4><p>To accurately measure recall, we computed the ground truth nearest neighbors for each test query using an exact k-NN search. This was implemented using Scikit-learn’s NearestNeighbors with the brute algorithm and Euclidean distance metric.</p><h4>Hardware Environment</h4><ul><li><strong>Machine:</strong> MacBook Pro with Apple M3 chip and 18 GB RAM. The code is using Python 3.12.4, faiss-cpu==1.9.0, lancedb==0.16.0, lance==0.19.2.</li><li><strong>Memory Constraints:</strong> The augmented datasets were designed to exceed the available RAM to test out-of-memory performance.</li></ul><p>Our benchmarking setup was inspired by the methodology used in the <a href="https://github.com/erikbern/ann-benchmarks/tree/main/ann_benchmarks">ANN benchmarks</a> project, particularly in configuring hyperparameters for fair comparison.</p><h4>Metrics Collected</h4><ul><li><strong>Average Search Time per Query:</strong> Total query time divided by the number of queries.</li><li><strong>Average Recall:</strong> The proportion of ground truth neighbors that were found in the top-k results.</li><li><strong>Queries Per Second (QPS):</strong> Number of queries processed per second.</li></ul><h3>Benchmark Results</h3><p>In this section, we explore the performance of <strong>FAISS HNSW</strong> and <strong>LanceDB HNSW</strong> when querying the GIST1M dataset under different conditions. Our aim is to understand how each system behaves both when the data fits entirely in memory and when it exceeds the available memory capacity.</p><p>To recreate the numbers in this graph, the benchmarking code used is available in <a href="https://github.com/amineKammah/ann-benchmark">this repo</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*5p_-gETxahg3QXEW.png" /></figure><p><em>Figure: Queries Per Second (QPS) vs. Recall Level for FAISS and LanceDB on the GIST1M Dataset (fits entirely in memory) and an Augmented version with 3M vectors (Does not fit in memory).</em></p><h4>Scenario 1: Data Fits in Memory (1 Million Vectors)</h4><p>To establish a baseline, we first tested both FAISS and LanceDB using the original <strong>1 million vector GIST1M dataset</strong>, which comfortably fits within our machine’s <strong>18 GB RAM</strong>. The performance, measured in <strong>Queries Per Second (QPS)</strong> at various recall levels, is summarized in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*GyDrMpmUVv3bwi67Hl5eSg.png" /></figure><p>When we examine these results, it’s clear that <strong>FAISS HNSW significantly outperforms LanceDB</strong> in terms of QPS across all recall levels when the dataset fits in memory. For instance, at a recall of <strong>0.95</strong>, FAISS achieves nearly <strong>978 QPS</strong>, whereas LanceDB reaches approximately <strong>178 QPS</strong>.</p><p>This discrepancy suggests that LanceDB does not fully leverage available memory to enhance performance in in-memory scenarios. Despite the dataset fitting entirely in memory, LanceDB’s performance remains constrained, perhaps due to its design optimized for disk-based operations.</p><h4>Scenario 2: Data Exceeds Memory Capacity (3 Million Vectors)</h4><p>To test scalability and performance when data exceeds memory capacity, we augmented the dataset to <strong>3 million vectors</strong>, surpassing our machine’s <strong>16 GB RAM</strong>. This simulates a real-world scenario where datasets are too large to fit entirely in memory.</p><p>FAISS is designed to operate with data and index structures in memory; therefore, the process was unable to complete when the dataset exceeded the available RAM. This limitation makes FAISS unsuitable for applications dealing with very large datasets unless significant hardware upgrades are made to accommodate the increased memory requirements. In real-life production systems, companies often incur significant costs to allocate machines with large enough memory to fit all the data.</p><p>In contrast, <strong>LanceDB HNSW handled the larger dataset effectively</strong>, maintaining performance levels similar to those observed with the 1 million vector dataset. The QPS experienced an average of 20% reduction as shown in the graph above. This is a reasonable trade-off given that the index and data no longer fit in memory and disk access is inherently slower than memory access.</p><p>What’s particularly interesting is that the performance gap between LanceDB in the in-memory scenario and the out-of-memory scenario was not as wide as one might expect. The <strong>gap between disk and memory access times is smaller</strong>, indicating that LanceDB is well-optimized for disk-based operations. Despite operating from disk, LanceDB maintained competitive recall levels and acceptable query performance.</p><p>For many applications, especially those not highly sensitive to latency, this level of performance is quite acceptable. In applications like <strong>Retrieval-Augmented Generation (RAG)</strong> that involve interactions with <strong>Large Language Models (LLMs)</strong>, overall response times are often governed more by the processing time of the LLM than by the vector search latency. Given that LLM interactions can introduce latencies exceeding <strong>1 second</strong>, the additional milliseconds added by LanceDB’s disk-based search are unlikely to be noticeable to end-users. This can bring significant cost savings, especially for large datasets.</p><h4>Reflections on LanceDB’s Development Experience</h4><p>While LanceDB shows promise in terms of scaling and maintaining performance with large datasets, the <strong>development experience</strong> leaves much to be desired. Throughout the benchmarking process, I found that <strong>documentation was sparse</strong>, making it challenging to understand how to configure and utilize LanceDB effectively. Many times, I had to <strong>dive deep into the source code</strong> to figure out how to adjust parameters or to perform specific configurations.</p><p>The high-level API lacks flexibility, and simple tasks often require using lower-level functions or workarounds. This lack of straightforward configurability can be a significant hurdle for developers looking to adopt LanceDB, as it increases the time and effort required to get up and running.</p><p>Improving the documentation with clear guidelines, examples, and explanations of parameters would greatly enhance the usability of LanceDB. Additionally, expanding the high-level API to include more configurable options would make it much more accessible and easier to integrate into projects. Addressing these issues is crucial for wider adoption and to realize the full potential of LanceDB in practical applications.</p><h3>Alternative Approaches: DiskANN</h3><p>While LanceDB demonstrates the potential of disk-based HNSW implementations, another algorithm, <strong>DiskANN</strong>, has been specifically developed by Microsoft to optimize ANN searches over disk-resident data.</p><p>DiskANN, introduced in the paper <a href="https://www.microsoft.com/en-us/research/publication/diskann-fast-accurate-billion-point-nearest-neighbor-search-on-a-single-node/">“DiskANN: Fast Accurate Billion-point Nearest Neighbor Search on a Single Node”</a>, tackles the challenge of scaling ANN searches to billion-scale datasets. It is designed to minimize memory usage while maintaining high performance by intelligently managing data between RAM and disk.</p><h3>Future Prospects with DiskANN</h3><p>Considering the performance of LanceDB, it’s natural to look ahead to other technologies that could further optimize disk-based ANN search. <strong>DiskANN</strong>, developed by Microsoft to solve the billion-scale issue of ANNs, is a promising solution that specifically focuses on optimizing disk access patterns to close the performance gap between disk and memory.</p><p>DiskANN employs techniques such as intelligent caching and prefetching to minimize disk I/O overhead, resulting in faster query times even when working with datasets that far exceed memory capacity.</p><p>It would be <strong>very interesting to see an implementation of DiskANN using Lance</strong>, or at least integrating some of its optimization strategies into LanceDB. Such an integration could potentially enhance LanceDB’s performance, making disk-based vector search even more efficient and closer in performance to in-memory solutions.</p><p>This could be a valuable direction for future research and development, particularly for applications that require scaling to massive datasets without compromising on performance.</p><h3>Conclusion</h3><p>Scaling HNSW for billion-scale datasets presents challenges due to its high memory demands. While in-memory HNSW offers excellent performance, it’s impractical and costly for large datasets. Quantization helps reduce memory use but often compromises retrieval performance. Disk-based solutions like LanceDB and DiskANN are promising developments, reducing the latency gap between disk and memory access, making disk usage feasible for ANN searches. This benefits applications like Retrieval-Augmented Generation (RAG) involving LLMs, where additional latency is minimal.</p><p>Disk-based solutions allow scaling without prohibitive costs, beneficial for those limited by memory and hardware expenses. However, LanceDB’s sparse documentation and limited API flexibility pose challenges, understandable given their small team. Despite this, LanceDB’s efforts in disk-based ANN searches are commendable.</p><p>As these technologies mature, improved integration and performance are expected. Combining LanceDB’s storage optimizations with algorithms like DiskANN could further transform large-scale nearest neighbor search. The LanceDB team’s achievements in creating a practical solution for massive datasets highlight their expertise and commitment, setting a future standard in large-scale data management.</p><h3>References</h3><ol><li>Andrey Vasnetsov’s presentation, “Qdrant: Open Source Vector Search Engine and Vector Database.” Available on YouTube at: <a href="https://youtu.be/bU38Ovdh3NY">https://youtu.be/bU38Ovdh3NY</a>.</li><li>GitHub issue discussion on LanceDB’s IVF_HNSW_PQ implementation. Available at: <a href="https://github.com/lancedb/lancedb/issues/1428">https://github.com/lancedb/lancedb/issues/1428</a>.</li><li>Microsoft Research, “DiskANN: Fast Accurate Billion-point Nearest Neighbor Search on a Single Node.” Available at: <a href="https://www.microsoft.com/en-us/research/publication/diskann-fast-accurate-billion-point-nearest-neighbor-search-on-a-single-node/">https://www.microsoft.com/en-us/research/publication/diskann-fast-accurate-billion-point-nearest-neighbor-search-on-a-single-node/</a>.</li><li>ANN benchmarks project for configuring hyperparameters: <a href="https://github.com/erikbern/ann-benchmarks/tree/main/ann_benchmarks">https://github.com/erikbern/ann-benchmarks/tree/main/ann_benchmarks</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0664801bc915" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large-Scale String Processing in Python: Can PyArrow Accelerate Your Data Tasks?]]></title>
            <link>https://medium.com/@amineka9/large-scale-string-processing-in-python-can-pyarrow-accelerate-your-data-tasks-c70ce1d0328a?source=rss-a2add3f8210e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c70ce1d0328a</guid>
            <category><![CDATA[strings-in-python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[arrow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Amine Kammah]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 22:18:33 GMT</pubDate>
            <atom:updated>2024-12-03T12:25:03.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ribpbeIXbO7BHKQh.png" /></figure><h3>Introduction</h3><p>Pandas and NumPy have always been regarded as bad options when it comes to large-scale string processing. However, a lot has changed recently. Pandas 2.0 introduced PyArrow as a new backend instead of NumPy, which comes with excellent support for string processing and an innovative memory representation. NumPy itself is making strides to provide better support for strings. This article explores the current state of string processing in Python, benchmarking various frameworks to evaluate their performance and memory usage. We’ll delve into the nuances of each approach, highlighting the strengths and weaknesses uncovered through comprehensive testing.</p><h3>Background</h3><h3>Python Lists and Strings</h3><p>Python’s native lists and string types are inherently flexible and user-friendly, allowing for rapid development and easy maintenance. However, as datasets grow larger, performance bottlenecks may arise due to the overhead associated with Python’s dynamic typing and object management.</p><h3>NumPy: Beyond Numerical Arrays</h3><p>While NumPy is renowned for numerical computations with arrays, its string handling has not been its primary strength, often lagging in performance compared to native Python operations for text data. With the advent of NumPy 2.0, improvements have been made, but challenges remain, particularly regarding memory consumption.</p><h3>Pandas and PyArrow: A Promising Combo</h3><p>Pandas has been a staple for data manipulation, and with version 2.0+, it introduces PyArrow as an optional backend for string data [1]. This integration leverages Apache Arrow’s in-memory columnar format, which is designed for high-performance analytics. Notably, Pandas plans to adopt PyArrow as the default string backend in version 3.0.</p><p>Arrow brings an innovative memory representation for strings, promising faster operations and better memory efficiency [2]. Arrow uses a specific structure involving three buffers to efficiently manage and access the data. Let’s delve into how this works.</p><ol><li><strong>Offset Buffer</strong>: Stores the starting byte offsets for each string. It helps locate the beginning of each string in the data buffer. For example, with strings [&quot;apple&quot;, &quot;banana&quot;, null, &quot;cherry&quot;], the offset buffer is [0, 5, 11, 11, 17].</li><li><strong>Data Buffer</strong>: Contains the actual string data concatenated together. For the example, it looks like: &quot;applebananacherry&quot;.</li><li><strong>Validity Buffer</strong>: An optional bitmap indicating the presence of each string. A 1 means the string is valid, and a 0 means it&#39;s null. For the example, it&#39;s [1, 1, 0, 1].</li></ol><h3>The Benchmark Experiment</h3><p>The benchmarks compare the following frameworks:</p><ol><li><strong>Python Lists and Strings</strong>: The baseline.</li><li><strong>NumPy</strong>: Using NumPy.char functionalities.</li><li><strong>Pandas with Object Dtype</strong>: Sticking with Pandas Series with dtype=&#39;object&#39;.</li><li><strong>Pandas with String Dtype (Python Backend)</strong>: Using the new string dtype with the Python backend.</li><li><strong>Pandas with PyArrow Backend</strong>: Utilizing the string dtype backed by PyArrow.</li><li><strong>Native PyArrow</strong>: Directly using PyArrow arrays and compute functions, no Pandas here.</li></ol><p>All benchmarks were run using Python 3.12.4, Pandas version 2.2.3, and PyArrow 18.0.0. The code ran on an M3 MacBook Pro with 18 GB RAM and 11 CPU cores. All benchmarking code is available in this GitHub repository: <a href="https://github.com/amineKammah/python-string-benchmark">python-string-benchmark</a>.</p><h3>Operations Benchmarked</h3><p>We focused on a mix of operations, some that modify strings and others that do not, including:</p><p><strong>Modify Operations</strong>:</p><ul><li>uppercase: Convert strings to uppercase.</li><li>replace: Replace substrings.</li><li>pad: Pad strings to a certain length.</li><li>strip: Remove leading and trailing whitespace.</li></ul><p><strong>Non-modify Operations</strong>:</p><ul><li>find_substring: Check for a substring&#39;s presence.</li><li>count_char: Count occurrences of a character.</li><li>startswith: Check if strings start with a specific prefix.</li><li>sort: Sort the array of strings alphabetically.</li></ul><p><strong>Complex Operations</strong>:</p><ul><li>delete_sequence: Remove strings containing a specific sequence.</li><li>custom_hash: Apply a Python hash function to each string. This requires casting the data types back to Python.</li></ul><h3>Benchmark Setup</h3><p>We generated a dataset of <strong>1,000,000 random strings</strong>, each of length 100 characters. For each operation, we measured:</p><ul><li><strong>Execution Time</strong>: Using the timeit module to capture the average time over multiple runs.</li><li><strong>Memory Usage</strong>: Leveraging the memory_profiler to assess the peak memory consumption during each operation.</li></ul><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AT_3LkQ6WCFaI_gK.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dsRoVHKFeV8ppaaj.png" /></figure><p>Visualization of the average processing time (in seconds) and the average memory usage (in MB) per backend. Detailed table of each number is available in the appendix.</p><h3>Discussion</h3><h3>The Trade-offs</h3><p>The benchmarks reveal a complex landscape where the choice of framework can drastically impact performance and memory usage. PyArrow offers impressive speedups for certain operations but may introduce overhead in others. The memory efficiency gains are not universal, with some tasks consuming more memory than traditional methods.</p><h3>NumPy 2.0 Improvements</h3><p>NumPy 2.0 performance has definitely improved compared to NumPy 1.0. However, NumPy’s memory consumption is very high compared to all other frameworks. I would opt for other options.</p><h3>Pandas’ Strings and Objects</h3><p>Pandas with the object dtype and the new string dtype (Python backend) were consistently slower than native Python lists and strings. I would not use this.</p><h3>PyArrow</h3><p>We see some positive results. PyArrow does look better in both run time and memory consumption in most operations. Chiefly, the startswith operation was a whopping 13× faster than the baseline. Some operations are still slower though; count_char on Pandas string[pyarrow] took more than twice as long compared to our baseline. In most situations, I would still stick with strings and Python lists.</p><h4>Memory Consumption Concerns</h4><p>Although Arrow promises lower memory consumption, this is not always the case. More specifically, PyArrow’s memory representation is immutable. Modifying any string requires rewriting the entire data buffer and recalculating offsets. This behavior leads to significant memory spikes during operations like strip, where the PyArrow-backed operation consumed <strong>190 MB</strong> of additional RAM. Python lists can handle it much more efficiently, requiring only <strong>2.6 MB</strong>.</p><p>Delete operations are also slower and consume more memory on PyArrow. This is an inherent flaw of the data representation of Arrow. Any filtering or gathering operation will be slow and memory-inefficient.</p><p>Given how frequently these two operations are used, Polars decided to change the implementation of the String dtype they use, as they explain in this article [3]. For most operations though, PyArrow does deliver on its promises of being memory-efficient.</p><h4>The Risks: The Hash Operation</h4><p>Sometimes, we need to apply a custom operation that does not have a native implementation in PyArrow. This might require going through a custom Python function that needs to be applied to each individual element. This introduces significant overhead when the data is represented in a different framework. The hash function test is an example of that.</p><p>Applying the hash function by iterating on the values resulted in a huge performance hit across all three frameworks: <strong>39 seconds</strong> on native PyArrow, <strong>14 seconds</strong> on Pandas string. Python strings in a Python list were much faster here, requiring only <strong>2 seconds</strong> to hash all the 1 million strings.</p><p>This is a bad choice that can be avoided, but I wanted to include this example in the benchmark to showcase how there are pitfalls when using PyArrow that a non-seasoned programmer can easily fall into and undo any potential performance gains PyArrow can yield.</p><p>In fact, both Pandas PyArrow and native PyArrow ended up taking longer to complete the benchmark (<strong>142.5 seconds</strong>) than native Python strings and lists (<strong>136.1 seconds</strong>) because of the hash operation. If we did not have the hash operation, PyArrow would have completed the benchmark in <strong>103.4 seconds</strong> vs. vanilla Python in <strong>133.6 seconds</strong>.</p><h3>Maintenance and Code Complexity</h3><p>Switching to frameworks like PyArrow introduces a learning curve. The syntax and methodologies differ from vanilla Python, which can hinder team collaboration, especially if not everyone is familiar with these tools. Moreover, the risk of inadvertently introducing performance bottlenecks increases. As seen with the custom_hash operation, a seemingly innocuous change can dramatically slow down processing times. This situation underscores the importance of understanding the underlying mechanics of the chosen framework.</p><h3>Conclusion</h3><p>The choice of string processing framework in Python should be guided by the specific needs of your project:</p><ul><li><strong>For Ease of Use and Maintainability</strong>: Stick with Python lists and strings. They offer reasonable performance, intuitive syntax, and minimal risk of unexpected slowdowns.</li><li><strong>Beware of Pitfalls</strong>: Operations that require modifying strings can negate the performance benefits of PyArrow due to its immutability constraints. Always profile your code to identify bottlenecks.</li><li><strong>Team Collaboration</strong>: If your team isn’t familiar with PyArrow or advanced Pandas functionalities, consider the potential impact on code maintainability and team productivity.</li><li><strong>For Performance Gains</strong>: PyArrow shows promise. However, if performance is critical, I would check out Polars [3] as it is a higher level library.</li></ul><p>In the ever-evolving landscape of Python string processing, there’s no one-size-fits-all solution. By understanding the strengths and limitations of each framework, you can make informed decisions that balance performance, memory usage, and code maintainability.</p><h3>Recommendations</h3><ul><li><strong>Benchmark Before Adopting</strong>: Always run benchmarks relevant to your specific use case before fully adopting a new framework.</li><li><strong>Monitor Memory Usage</strong>: For large datasets, memory efficiency is as crucial as execution speed. Be wary of operations that cause memory spikes.</li><li><strong>Educate Your Team</strong>: If you decide to adopt a new tool like PyArrow, ensure that your team is adequately trained to use it effectively.</li></ul><h3>Appendix</h3><h4>Full Numbers from Experiments:</h4><ul><li><strong>Execution Time</strong></li></ul><p>Below is a summary of the execution times (in seconds) for each operation across different frameworks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*I77os24zjX_TjAKWoJZ8NQ.png" /></figure><ul><li><strong>Memory Usage</strong></li></ul><p>The memory consumption (in MB) for each operation is summarized below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*YrhsuuDceoVW__mQyx5o4w.png" /></figure><h3>References</h3><p>[1] <a href="https://pandas.pydata.org/docs/user_guide/pyarrow.html">PyArrow Integration in Pandas</a><br>[2] <a href="https://arrow.apache.org/docs/r/articles/developers/data_object_layout.html">Apache Arrow Data Object Layout</a><br>[3] <a href="https://pola.rs/posts/polars-string-type/">Polars String Type Implementation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c70ce1d0328a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting an LLM? Here is how I Achieved 2.5× Faster Throughput and Quadrupled Context Length.]]></title>
            <link>https://medium.com/@amineka9/hosting-an-llm-here-is-how-i-achieved-2-5-faster-throughput-and-quadrupled-context-length-cc71fcf4bf3b?source=rss-a2add3f8210e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc71fcf4bf3b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[llama-3]]></category>
            <dc:creator><![CDATA[Amine Kammah]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 11:51:18 GMT</pubDate>
            <atom:updated>2024-11-19T11:51:18.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kAtYMKSYonZ5U75T.jpg" /></figure><h3>Introduction</h3><p>Deploying large language models (LLMs) such as <strong>Llama 3.1 8b Instruct</strong> on mid-tier GPUs can be a daunting task due to computational demands and memory constraints. In my experience, quantization techniques have been a game-changer. By applying quantization, I achieved up to a <strong>2.57× increase in throughput</strong> without <strong>impacting model performance</strong>. Even more impressively, quantization extended the maximum context length the GPU could process from <strong>9.5k tokens to nearly four times that amount</strong>, significantly enhancing its capabilities.</p><p>This article delves into how quantization brings about these remarkable improvements. We’ll explore various quantization methods and their effects on both performance and memory usage. However, to fully grasp the technical nuances, this discussion <strong>assumes familiarity with advanced topics</strong> such as <strong>GPTQ</strong>, <strong>AWQ</strong>, <strong>K-V caching</strong>, and the <strong>pre-fill and decode stages</strong> in LLMs. The article will go through a brief refresher about these concepts, but if you’re unfamiliar with these concepts, I recommend reviewing them to understand how quantization can unlock the full potential of your LLM deployments.</p><h3>Quantization Techniques in LLMs</h3><p>Quantization involves reducing the number of bits used to represent each weight or activation within a neural network. Here, I discuss several prominent quantization methods.</p><p>FYI, WnAm means quantizing the weights to n bits and the activations to m bits. For example, W8A8 refers to quantizing the weights to 8 bits and the activations to 8 bits.</p><h3>1. Bitsandbytes</h3><p><strong>Overview:</strong> Bitsandbytes is a popular library that facilitates 8-bit, 4-bit, and even 4-bit floating-point quantization of LLMs without the need for calibration data. It primarily focuses on the quantization of weight values[1].</p><p><strong>Key Concepts:</strong></p><ul><li><strong>Outlier Handling:</strong> In neural networks, most hidden state values follow a normal distribution within a certain range (e.g., [-3.5, 3.5]). However, larger models can produce “outliers” — values significantly outside this range (e.g., [-60, 60]). Bitsandbytes addresses this by computing outlier values in higher precision (e.g., FP16), ensuring they do not negatively impact the quantization process[1].</li><li><strong>Threshold Tuning:</strong> An outlier threshold defines what constitutes an outlier. A default threshold value is 6, but it may need adjustment for more unstable models, such as smaller models or those undergoing fine-tuning[1].</li><li><strong>No Calibration Data Required:</strong> Simplifies the quantization process as it doesn’t need additional data. It can also be done on the fly while loading the model[1].</li></ul><p><strong>Considerations:</strong></p><ul><li><strong>Performance Penalty:</strong> Models tend to experience more performance degradation[6].</li></ul><h3>2. GPTQ (Generalized Post-Training Quantization)</h3><p><strong>Overview:</strong> GPTQ utilizes a calibration dataset to quantize the model weights to integers in a way that minimizes the output errors. This method aims to preserve model performance by closely approximating the original weight distributions[3].</p><p><strong>Key Concepts:</strong></p><ul><li><strong>Calibration Data:</strong> Requires a calibration dataset to guide the quantization process effectively[3].</li><li><strong>Performance Preservation:</strong> By minimizing output errors, GPTQ maintains higher accuracy post-quantization[3].</li></ul><p><strong>Considerations:</strong></p><ul><li><strong>Slightly slower performance:</strong> This is because GPTQ typically relies on group reordering, which makes its kernel logic and memory access pattern more complex, resulting in slower latency and inference than AWQ, for example[2][3].</li></ul><h3>3. Activation-aware Weight Quantization (AWQ)</h3><p><strong>Overview:</strong> AWQ selectively quantizes weights to integers while preserving a small percentage of crucial weights in higher precision (e.g., 16-bit). This approach significantly reduces quantization loss, allowing models to run in 4-bit precision without degrading performance[2].</p><p><strong>Key Concepts:</strong></p><ul><li><strong>Fused Kernel Optimization:</strong> Enhances performance through optimized computational kernels that leverage quantized weights[2].</li><li><strong>Calibration Data Usage:</strong> Similar to GPTQ, AWQ uses calibration data to pick important weights that should remain in higher precision[2].</li><li><strong>Optimized Inference:</strong> Particularly effective when used with inference engines like vLLM, which support AWQ for better throughput and latency[4].</li></ul><h3>4. Float8 Quantization (W8A8, float8 Weights and float8 Activation)</h3><p><strong>Overview:</strong> Float8 quantization reduces both weights and activations to 8-bit floating-point numbers. Dynamic quantization to FP8 can be achieved without calibration data, simplifying the process[5].</p><p><strong>Key Concepts:</strong></p><ul><li><strong>Hardware Support:</strong> Currently, only NVIDIA’s Hopper (e.g., H100) and Ada Lovelace GPUs (e.g. L40, L4) fully support W8A8. On Ampere GPUs like A10 and A100, only W8A16 is supported, where activations remain in 16-bit precision[5][8][9].</li><li><strong>Performance Gains:</strong> Lower precision computations can accelerate inference, particularly in compute-bound scenarios[5].</li><li><strong>No Calibration Data Needed:</strong> Simplifies deployment.</li></ul><p><strong>Considerations:</strong></p><ul><li><strong>Hardware Limitations:</strong> Requires specific GPUs that support FP8 precision. T4 and A10 cost efficient GPUs won’t support this[10][11].</li></ul><h3>How does quantization affect LLM accuracy?</h3><p>Now that we briefly reviewed some of the prominent quatization methods, let’s take at how does it affect the models accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h6IMHUthyXOmHcaf.png" /></figure><p>The excellent paper “GIVE ME BF16 OR GIVE ME DEATH”? ACCURACY-PERFORMANCE TRADE-OFFS IN LLM QUANTIZATION delves deeply into accuracy scores for quantized models and demonstrates that quantization techniques result in near-lossless performance across different benchmarks[6].</p><p>The table above illustrates accuracy on both academic and real-world benchmarks, indicating that accuracy losses are minimal across various model sizes (8b to 405b) and different quantization configurations, such as W8A8 (8-bit weights and 8-bit activations) and W4A16 (4-bit weights and 16-bit activations). For the 8B model, the recovery rates are impressive: 101.23% for W8A8-FP, 101.52% for W8A8-INT, and 96.05% for W4A16-INT. Several research papers have demonstrated similar findings.</p><p>In my personal experience when deploying a fine-tuned LLM for a specific use case, I observed a 1% loss in accuracy using AWQ int W4A16.</p><p>Quantization algorithms offer a few hyperparameters that can be tuned to reduce the quantization accuracy loss even further for specific use cases. While this is a topic for another discussion, keep in mind that if you are dissatisfied with the accuracy loss from quantization, there are certainly ways to improve it[6].</p><p>Quantization shows impressive gains in terms of cost reduction and performance. Modern quantization techniques result in minimal accuracy loss, typically in the 0–4% range[6]. If you are deploying your own LLM, you should definitely look into quantization as the performance gains are significant as I am going to demonstrate in the following sections.</p><h3>Memory and Performance Implications of Quantizations</h3><p>Understanding the stages of LLM inference and their computational characteristics is important to explain the performance gains. We consider weight quantization and activation quantization and their theoretical potential benefits.</p><h3>Pre-fill vs. Decode Stages</h3><p><strong>Pre-fill Stage:</strong></p><p>This stage computes the activations for all input tokens in parallel. With a sufficiently long prompt, the pre-fill stage tends to be <strong>compute-bound</strong> due to the parallel processing of a large number of tokens.</p><p>The pre-fill stage benefits from quantization techniques that reduce computational overhead, such as activation quantization (8bit weights and 8bit activations; W8A8). This allows the compute-heavy matrix multiplications to be performed in 8bit precision, improving throughput and latency[5].</p><p><strong>Decode Stage:</strong></p><p>The generation of new tokens is autoregressive. The LLM predicts the next token, appends it to the input, then generates the next token until reaching a special end-of-sequence token. At this stage, only one token is processed at a time. Therefore, the decode stage tends to be <strong>memory-bound</strong> because it involves frequently loading the model weights from memory to cache[7].</p><p>This limitation is especially noticeable for mid-tier GPUs such as the Nvidia A10 (and Nvidia L4). The A10 has a memory bandwidth of 600GB/s (300GB/s for the L4) compared to H100’s 2TB/s[10][11][12].</p><p>To reduce the load on memory bandwidth, weight quantization reduces the model size by a factor of 2 (W8) or 4 (W4). This effectively reduces the bottleneck caused by memory bandwidth[2][3].</p><h3>K-V Cache Considerations</h3><p>Most modern models are trained at 16bit precision. This means that an 8b parameter model requires a minimum of 16GB of memory to be loaded. However, this is not the full story.</p><p>The attention mechanism in the decoding stage is unidirectional. For each new token, we calculate the attention activations with respect to all previous tokens. This means we can either keep the keys and values of all previous tokens in memory, or recompute them. Recomputing all keys and values at each decoding step leads to a quadratic complexity in terms of sequence length. This makes decoding very slow.</p><p>The K-V cache refers to storing the keys and values for each token and layer, enabling efficient decoding without recomputing activations of previous tokens. This reduces the decoding complexity of a new token from quadratic to linear in terms of sequence length. K-V caching is a crucial technique for avoiding expensive recomputation. If you are unfamiliar with KV caching, I highly recommend reading this article[7].</p><p>The challenge with K-V caching is that it consumes a lot of memory. In fact, each token’s K-V cache consumes approximately 0.5 MB of memory in BF16 precision for our 8b parameter model. On an NVIDIA A10G GPU, we have 21.98 GiB of available VRAM, loading a model in BF16 leaves about 6.68 GiB free (as observed from nvidia-smi after loading the model), sufficient for caching a maximum of 13,360 tokens theoretically, or 9,550 tokens in real terms when tested on an A10G GPU using vLLM[10].</p><p>13k tokens is the maximum we can store in our memory. This is quite limited, especially considering our model’s 128k token context window for a single prompt. This means that across all prompts being processed by the LLM, we can only handle 13k tokens simultaneously. Anything above this limit will have to wait until the processing of the current prompts is over. This includes tokens across input and output, and across all queries being processed in parallel.</p><p>A great way to mitigate the memory bandwidth limitation during the decoding phase is to increase the number of prompts processed in parallel, which balances out the compute and memory workloads. However, with such a small K-V cache size, the number of prompts that can be decoded in parallel is heavily limited. Quantization can help by reducing the size of weights and activations, freeing up more memory for the K-V cache. This, in turn, allows for processing more parallel prompts, alleviating memory bandwidth limitations, and increasing the maximum prompt length the service can process.</p><ul><li><strong>W4A16 Quantization:</strong> Short for 4bits Weights and 16bits Activations. Only the weights are reduced by a factor of 4, freeing up more memory (about 16.3 GiB free), allowing for caching of approximately 32,600 tokens[2][3].</li><li><strong>W8A8 Quantization:</strong> Reduces weights size by a factor of 2, resulting in about 13.18 GiB of free memory. Quantizing activations also halves the memory required per token to around 0.25 MB, enabling caching of approximately 52,720 tokens[5].</li></ul><p>With this, we can process prompts as long as 52k tokens on the same GPU with minimal loss in accuracy compared to 13k without quantization. That is a significant improvement.</p><h3>Benchmarking quantization speedups</h3><p>To validate the practical benefits of the quantization methods, I conducted several benchmarks using the <em>Llama 3.1 8b Instruct</em> model on an NVIDIA A10G GPU. The goal was to measure the impact of different quantization techniques on total throughput — the number of tokens processed per second — across scenarios with varying input and output lengths.</p><p><strong>Benchmark Setup:</strong></p><ul><li><strong>Model:</strong> Llama 3.1 8b Instruct</li><li><strong>Hardware:</strong> NVIDIA A10G GPU</li><li><strong>Quantization Methods Tested:</strong></li><li><strong>Full Precision (Baseline):</strong> No quantization is applied.</li><li><strong>Bitsandbytes W4A16:</strong> Weights quantized to int4, activations in 16 bits. All calculations happen in 16bits[1].</li><li><strong>GPTQ W4A16:</strong> Weights quantized to int4, activations in 16 bits. All calculations happen in 16bits[3].</li><li><strong>AWQ W4A16:</strong> Activation-aware weight quantization to 4 bits, activations in 16 bits[2].</li><li><strong>GPTQ W8A8:</strong> Weights and activations quantized to int8. Calculations are therefore performed in int8[3].</li><li><strong>Float W8A16 Quantization:</strong> Weights quantized to 8-bit floating-point, activations in 16 bits[5].</li></ul><p><strong>Test Scenarios:</strong></p><ol><li><strong>Short Input, Long Output:</strong> 300 input tokens and 1,500 output tokens.</li><li><strong>Long Input, Short Output:</strong> 3,000 input tokens and 300 output tokens.</li><li><strong>Longer Input, Short Output:</strong> 8,000 input tokens and 300 output tokens.</li></ol><p>For each scenario, I sent 1,000 prompts and measured the total throughput observed. The results are presented as <strong>throughput improvement rates</strong> compared to the full precision baseline. A value greater than 1 indicates improved performance compared to the full precision model. All code used to generate these numbers can be found in the appendix.</p><p>vLLM provides benchmarking scripts that facilitate the evaluation of model performance under various conditions. For a comprehensive view of the benchmarking setup, including scripts and detailed configurations, please refer to the <a href="https://github.com/amineKammah/llm-quantizaion-benchmark">benchmarking code repository</a>.</p><p>In my use case, I am deploying a fine-tuned LLM that will receive hundreds of prompts simultaneously every few minutes.</p><p><strong>Benchmark Results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZ9GpiLrwv5Irn7A8QQQIg.png" /></figure><p><strong>Analysis:</strong></p><p><strong>1. Short Input, Long Output (300 input tokens, 1,500 output tokens)</strong></p><p><strong>Memory-Bound Scenario:</strong> The long output length makes the decode stage memory-intensive[7].</p><p><strong>Performance Gains:</strong></p><ul><li><strong>AWQ W4A16 and GPTQ W4A16:</strong> These methods provided the highest improvements (approximately 2.57× and 2.54× respectively). The significant reduction in weight size alleviates memory bandwidth requirements during the recurrent generation of output tokens. Additionally, the freed-up memory allows for a larger K-V cache, enabling more prompts to be processed in parallel, which enhances efficiency[2][3].</li><li><strong>Float W8A16 Quantization:</strong> Achieved a notable improvement (2.06×) by reducing weight size, which frees up memory for a larger K-V cache. This allows for more parallel processing of prompts, further alleviating memory bandwidth limitations. However, the A10G’s lack of support for Float8 computation for activations limits its potential gains. It would be interesting to try the same test on an Nvidia L4 that does support Float8 computation, but comes with half the memory bandwidth of the A10[5][10][11].</li><li><strong>GPTQ W8A8:</strong> Showed a strong improvement (1.87×). While activation quantization accelerates compute-heavy tasks, its benefits are less pronounced in memory-bound scenarios. It is surprising, however, that GPTQ W8A8 performed worse than Float W8A16 in this scenario[3][5].</li><li><strong>Bitsandbytes int4:</strong> Offered minimal gains (1.06×). Bitsandbytes lacks the kernel optimizations of GPTQ and AWQ. The computation remains at 16 bits, and the method suffers from conversion overhead from int8 to float16. The modest improvement is primarily due to increased memory efficiency from smaller weights[1].</li></ul><p><strong>2 and 3. Long Input, Short Output (3,000/8,000 input tokens, 300 output tokens)</strong></p><p><strong>Compute-Bound Scenario:</strong> The long input length makes the pre-fill stage compute-intensive[7].</p><p><strong>Performance Gains:</strong></p><ul><li><strong>GPTQ W8A8:</strong> Achieved the highest improvement (2.16×) by leveraging 8-bit operations for both weights and activations, which accelerates compute-heavy matrix multiplications during the pre-fill stage. The larger K-V cache also allows for more efficient parallel processing[3].</li><li><strong>AWQ W4A16 and GPTQ W4A16:</strong> Showed significant improvements (~2×), primarily due to reduced memory bandwidth usage from weight quantization. AWQ’s faster performance compared to GPTQ is attributed to its simpler kernel logic and memory access pattern[2][3].</li><li><strong>Float W8A16:</strong> Offered moderate improvements (1.55×), benefiting from reduced weight sizes, though the lack of activation quantization limits its impact in compute-bound scenarios[5].</li><li><strong>Bitsandbytes int4:</strong> Offered modest gains, primarily due to reduced weight sizes and the resulting memory bandwidth savings[1].</li></ul><p><strong>Key Takeaways:</strong></p><ul><li>Without quantization, the longest prompt I can run through the LLM is 9.5k tokens for both input and completion tokens. This is fairly short. Quantization significantly extends that making the deployed LLM much more capable[7].</li><li><strong>Activation Quantization Accelerates Compute-Bound Workloads:</strong> Quantizing both weights and activations (e.g., GPTQ W8A8) delivers the most significant performance gains in scenarios with long input sequences due to faster 8-bit operations[3][5].</li><li><strong>Weight Quantization Benefits Memory-Bound Workloads:</strong> Techniques like GPTQ W4A16 and AWQ W4A16 excel in improving throughput for tasks with long outputs by reducing memory bandwidth bottlenecks and enabling larger K-V caches[2][3].</li><li><strong>Bitsandbytes Limitations:</strong> While easy to use without calibration data, Bitsandbytes offers modest performance improvements due to its reliance on 16-bit computations and conversion overheads. Additionally, accuracy losses from Bitsandbytes do lag behind compared to the other methods[1][6].</li><li><strong>Float W8A16 Balances Precision and Performance:</strong> This method provides consistent, though not leading, performance gains across different scenarios, making it a viable option for balancing precision and efficiency[5].</li></ul><p><strong>Conclusion</strong></p><p>Quantization techniques offer a practical way to optimize LLM inference in production settings, balancing performance, latency, and costs. By selecting appropriate methods for specific use cases — such as long input prompts or hardware constraints — organizations can deploy LLMs more efficiently. For compute-bound scenarios, activation quantization (e.g., W8A8) accelerates inference, while weight quantization (e.g., W4A16) helps in memory-bound situations. The choice of technique should consider model size, performance needs, hardware, and workload nature. As these methods advance, they promise to make LLMs more accessible and cost-effective. My personal experience with vLLM was very smooth. I had to deal with long input prompts and somewhat short outputs. The AWQ int W4A16 experienced only 1% accuracy loss but ensured 2.5x speedup. Given my bursty workload, this optimization ensured the LLM finished processing the current burst before the next one reached the endpoint.</p><p>Future work will explore quantization on larger models across multiple GPUs and experiment with calibration to further reduce accuracy loss.</p><p>All the benchmarking code used in this study is available in my <a href="https://github.com/amineKammah/llm-quantizaion-benchmark">GitHub repository</a> for public access and further exploration.</p><p><strong>References</strong></p><ol><li><strong>Bitsandbytes Library</strong><br>Bitsandbytes Foundation. (n.d.). Bitsandbytes. Retrieved from <a href="https://github.com/bitsandbytes-foundation/bitsandbytes">https://github.com/bitsandbytes-foundation/bitsandbytes</a></li><li><strong>AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration</strong><br>Lin, J., Tang, J., Tang, H., Yang, S., Chen, W.-M., Wang, W.-C., Xiao, G., Dang, X., Gan, C., &amp; Han, S. (2023). AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration. Retrieved from <a href="https://arxiv.org/abs/2306.00978">https://arxiv.org/abs/2306.00978</a></li><li><strong>GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers</strong><br>Frantar, E., Ashkboos, S., Hoefler, T., &amp; Alistarh, D. (2022). GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers. Retrieved from <a href="https://arxiv.org/abs/2210.17323">https://arxiv.org/abs/2210.17323</a></li><li><strong>vLLM</strong><br>vLLM Blog. (2023). Retrieved from <a href="https://blog.vllm.ai/2023/06/20/vllm.html">https://blog.vllm.ai/2023/06/20/vllm.html</a></li><li><strong>FP8 W8A8 Article</strong><br>VLLM Documentation. (n.d.). FP8 Quantization. Retrieved from <a href="https://docs.vllm.ai/en/latest/quantization/fp8.html">https://docs.vllm.ai/en/latest/quantization/fp8.html</a></li><li><strong>“Give Me BF16 or Give Me Death”? Accuracy-Performance Trade-Offs in LLM Quantization</strong><br>Kurtic, E., Marques, A., Pandit, S., Kurtz, M., &amp; Alistarh, D. (2024). “Give Me BF16 or Give Me Death”? Accuracy-Performance Trade-Offs in LLM Quantization. Retrieved from <a href="https://arxiv.org/abs/2411.02355">https://arxiv.org/abs/2411.02355</a></li><li><strong>LLM Inference Series: 4. KV caching, a deeper look</strong><br>Lienhart, P. (n.d.). LLM Inference Series: 4. KV caching, a deeper look. Retrieved from <a href="https://medium.com/@plienhar/llm-inference-series-4-kv-caching-a-deeper-look-4ba9a77746c8">https://medium.com/@plienhar/llm-inference-series-4-kv-caching-a-deeper-look-4ba9a77746c8</a></li><li><strong>Hopper Architecture</strong><br>NVIDIA. (n.d.). Hopper Architecture. Retrieved from <a href="https://www.nvidia.com/en-us/data-center/technologies/hopper-architecture/">https://www.nvidia.com/en-us/data-center/technologies/hopper-architecture/</a></li><li><strong>Ampere Architecture</strong><br>NVIDIA. (n.d.). Ampere Architecture. Retrieved from <a href="https://www.nvidia.com/en-gb/data-center/ampere-architecture/">https://www.nvidia.com/en-gb/data-center/ampere-architecture/</a></li><li><strong>A10 GPU Product Page</strong><br>NVIDIA. (n.d.). A10 GPU. Retrieved from <a href="https://www.nvidia.com/en-gb/data-center/products/a10-gpu/">https://www.nvidia.com/en-gb/data-center/products/a10-gpu/</a></li><li><strong>L4 GPU Product Page</strong><br>NVIDIA. (n.d.). L4 GPU. Retrieved from <a href="https://www.nvidia.com/en-gb/data-center/l4/">https://www.nvidia.com/en-gb/data-center/l4/</a></li><li><strong>H100 GPU Product Page</strong><br>NVIDIA. (n.d.). H100 GPU. Retrieved from <a href="https://www.nvidia.com/en-gb/data-center/h100/">https://www.nvidia.com/en-gb/data-center/h100/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc71fcf4bf3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>