<?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:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"><channel><title><![CDATA[Rohan's Bytes: AI Tutorial]]></title><description><![CDATA[Step by Step Explanations with detaild code for LLM and AI in general new tools / new models and new tech that are coming everyday.]]></description><link>https://www.rohan-paul.com/s/ai-tutorial</link><image><url>https://substackcdn.com/image/fetch/$s_!q7Ea!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F20030c9b-4180-453e-9ef3-f42abd8f9de5_1200x1200.png</url><title>Rohan&apos;s Bytes: AI Tutorial</title><link>https://www.rohan-paul.com/s/ai-tutorial</link></image><generator>Substack</generator><lastBuildDate>Sat, 02 May 2026 01:04:31 GMT</lastBuildDate><atom:link href="https://www.rohan-paul.com/feed" rel="self" type="application/rss+xml"/><copyright><![CDATA[Rohan Paul]]></copyright><language><![CDATA[en]]></language><webMaster><![CDATA[rohanpaul@substack.com]]></webMaster><itunes:owner><itunes:email><![CDATA[rohanpaul@substack.com]]></itunes:email><itunes:name><![CDATA[Rohan Paul]]></itunes:name></itunes:owner><itunes:author><![CDATA[Rohan Paul]]></itunes:author><googleplay:owner><![CDATA[rohanpaul@substack.com]]></googleplay:owner><googleplay:email><![CDATA[rohanpaul@substack.com]]></googleplay:email><googleplay:author><![CDATA[Rohan Paul]]></googleplay:author><itunes:block><![CDATA[Yes]]></itunes:block><item><title><![CDATA[Vector Index Methods for Document Digitization in LLM Applications]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/vector-index-methods-for-document</link><guid isPermaLink="false">https://www.rohan-paul.com/p/vector-index-methods-for-document</guid><pubDate>Mon, 16 Jun 2025 10:20:26 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!WDZy!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!WDZy!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!WDZy!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png 424w, https://substackcdn.com/image/fetch/$s_!WDZy!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png 848w, https://substackcdn.com/image/fetch/$s_!WDZy!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png 1272w, https://substackcdn.com/image/fetch/$s_!WDZy!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!WDZy!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png" width="1024" height="573" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/c705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:573,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:932400,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166056715?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!WDZy!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png 424w, https://substackcdn.com/image/fetch/$s_!WDZy!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png 848w, https://substackcdn.com/image/fetch/$s_!WDZy!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png 1272w, https://substackcdn.com/image/fetch/$s_!WDZy!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc705a1a1-bf86-4209-80b4-35ac8d0e882a_1024x573.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><ul><li><p>Overview of Vector Indexing Approaches</p></li><li><p>Comparison of Approaches Speed Memory and Accuracy</p></li><li><p>Suitability for Different Scenarios</p></li><li><p>Key Research Highlights 2024-2025</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><p>Document digitization and <em>chunking</em> has become a common strategy for augmenting Large Language Models (LLMs) with external knowledge. In this approach, documents are split into smaller chunks, each chunk is converted to a vector embedding, and a <strong>vector index</strong> is built to enable fast similarity search. These vector indexes allow retrieval of relevant chunks given a query embedding, forming the backbone of retrieval-augmented generation (RAG) pipelines (<a href="https://arxiv.org/pdf/2409.06464#:~:text=Retrieval,This%20makes%20retrieval%20a">HERE</a>). Recent research in 2024 and 2025 has focused on improving vector indexing methods along several dimensions: speed, <strong>storage efficiency</strong>, <strong>recall&#8211;precision tradeoffs</strong>, and <strong>integration ease</strong> in LLM pipelines. This review surveys the latest methods and findings, comparing different indexing approaches and analyzing their suitability for real-time inference, batch processing, and offline retrieval scenarios.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Overview of Vector Indexing Approaches</strong></h2><p>Modern approximate nearest neighbor (ANN) search algorithms underpin most vector databases and indexes. They can be broadly categorized into a few types (<a href="https://vldb.org/2024/files/phd-workshop-papers/vldb_phd_workshop_paper_id_13.pdf#:~:text=very%20efficient%20retrieval%20of%20answers,and%20Adaptive%20Piecewise%20Constant%20Approximation">Vector Search on Billion-Scale Data Collections</a>):</p><ul><li><p><strong>Brute-Force (Flat Index)</strong> &#8211; The simplest method stores all chunk embeddings in a list and does a linear scan for queries. This &#8220;flat&#8221; index guarantees exact results (100% recall) but becomes slow as data scales (<a href="https://arxiv.org/pdf/2409.06464#:~:text=of%20nearest,perspectives%20of%20index%02ing%20time%2C%20query">HERE</a>). Recent guidance suggests that flat indexes with brute-force search <em>are viable for smaller corpora or prototyping</em> despite best-practice leaning toward ANN indexes .</p></li><li><p><strong>Graph-Based ANN (e.g. HNSW)</strong> &#8211; Graph indexes like <strong>Hierarchical Navigable Small World (HNSW)</strong> have become a de facto standard for fast vector search (<a href="https://miaoqiao.github.io/paper/SIGMOD24_SeRF.pdf#:~:text=HNSW%20index%20for%20efficient%20ANNS,3%5D%2C%20Zilliz">SeRF: Segment Graph for Range-Filtering Approximate Nearest Neighbor Search</a>). They organize embeddings as a navigable small-world graph; query traversal quickly finds near neighbors. HNSW is widely adopted in industry and academia &#8211; implemented in Lucene and ElasticSearch, and powering vector DBs like Weaviate and Milvus (Zilliz) . Graph methods offer excellent speed/accuracy tradeoffs, typically achieving high recall with millisecond latencies on million-scale data.</p></li><li><p><strong>Tree-Based ANN (e.g. VP trees, Annoy)</strong> &#8211; Tree structures (like randomized projection trees in Spotify&#8217;s <em>Annoy</em>) partition the vector space to prune search. They are simple to integrate (Annoy provides an easy library) but can be less efficient in very high dimensions or strict recall requirements, often outperformed by graph indexes in recent evaluations. <em>(While 2024/25 research has focused less on tree ANN improvements, they remain a practical option for moderate scales.)</em></p></li><li><p><strong>Inverted File and Quantization (IVF, PQ)</strong> &#8211; <em>Partition-based</em> indexes (originating from vision search) cluster the vector space into buckets (cells). At query time, only a few relevant buckets are searched (<a href="https://arxiv.org/html/2503.01823v1#:~:text=Partition%20based%20IVF%20methods%20One,At%20query%20time%2C%20the">Cracking Vector Search Indexes</a>). This inverted file (IVF) approach is often combined with <strong>Product Quantization (PQ)</strong> or other compression, which stores vectors in compact codes to save memory. The trade-off is some loss in precision due to quantization. A large number of clusters yields faster query times but higher index build cost, whereas fewer clusters (or none, i.e. brute-force) minimize upfront cost but result in slower queries at scale . Recent work highlights this tension: e.g. using 16k clusters gives very fast search but huge indexing time, while using ~1k clusters or brute-force starts queries immediately but with longer per-query latency .</p></li><li><p><strong>Hash-Based ANN (LSH)</strong> &#8211; Locality-sensitive hashing hashes vectors into buckets such that similar vectors collide. LSH was popular historically for ANN but often requires many hash tables to reach high recall, leading to larger memory usage and slower queries compared to graph-based methods. <strong>(Recent literature in 2024/25 has not emphasized LSH for LLM retrieval, as other methods tend to outperform it on high-dimensional text embeddings.)</strong></p></li><li><p><strong>Hybrid and Learned Indexes</strong> &#8211; New research is exploring hybrid structures and adaptive indexes. For example, <em>Azizi (2024)</em> proposes ELPIS, a hybrid graph&#8211;tree index that clusters the dataset (tree partitioning) and then builds local proximity graphs, combining each approach&#8217;s strengths (<a href="https://vldb.org/2024/files/phd-workshop-papers/vldb_phd_workshop_paper_id_13.pdf#:~:text=This%20work%20aims%20to%20study,Finally%2C%20we%20summarize">Vector Search on Billion-Scale Data Collections</a>). This design dramatically reduces indexing memory and time while maintaining efficient query answering, outperforming state-of-the-art graph indexes in throughput on billion-scale data . Another frontier is <strong>adaptive indexing</strong>: Mageirakos et al. (2025) introduce CrackIVF, an index that <em>builds itself on the fly</em> rather than all upfront (<a href="https://arxiv.org/html/2503.01823v1#:~:text=possible%20dataset,the%20index%20to%20the%20query">Cracking Vector Search Indexes</a>). CrackIVF begins with near brute-force search and incrementally refines an IVF index as queries arrive, adapting to the query distribution . This yields <strong>orders-of-magnitude lower startup cost</strong> &#8211; the system can answer many queries immediately (albeit slower at first) while gradually converging to the performance of a fully built index . These innovations are particularly relevant for <em>offline</em> corpora or infrequently accessed data, where building millions of indexes in advance is impractical.</p></li></ul><h2><strong>Comparison of Approaches Speed Memory and Accuracy</strong></h2><p><strong>Search Speed:</strong> Graph-based indexes like HNSW are known for excellent query speed at scale. They can retrieve nearest neighbors in logarithmic-like time, often just a few milliseconds for million-scale corpora. Lin (2024) found that on &#8220;large&#8221; corpora (&#8805;1M vectors), a tuned HNSW index achieved query throughput up to <strong>10&#215; higher</strong> than a brute-force flat index (<a href="https://arxiv.org/pdf/2409.06464#:~:text=%E2%80%A2%20For%20%E2%80%9Clarge%E2%80%9D%20corpora%20,on%20the%20BGE%20dense%20retrieval">HERE</a>), with similar accuracy. For &#8220;medium&#8221; corpora (100K&#8211;1M vectors), HNSW was ~2&#8211;3&#215; faster than flat search when using cached query embeddings . On small collections (&lt;100K), the speed difference becomes negligible , making brute-force acceptable for tiny databases or prototyping. Tree-based methods (Annoy) also accelerate search over brute-force, but typically they are slower than HNSW at high recall settings (Annoy might require examining many tree nodes to reach recall parity with HNSW&#8217;s graph navigation). Inverted file (IVF) indexes offer tunable speed: with sufficient partitioning (e.g. hundreds or thousands of clusters), they drastically cut down candidates to inspect, approaching the speed of HNSW. However, if too few clusters are used (for less indexing cost), query speed suffers. CrackIVF specifically shows that starting with a small number of clusters gives quick initial answers, but as it <em>learns</em> and increases partitions, query latency drops to near-optimal levels (<a href="https://arxiv.org/html/2503.01823v1#:~:text=upfront%20cost%20%28e,their%20higher%20query%20response%20times">Cracking Vector Search Indexes</a>). Hashing schemes (LSH) can answer queries quickly for very high similarity matches, but for the kind of semantic embeddings used in LLM applications (which are high dimensional and require nuanced nearest neighbor ranking), LSH often needs many probes to achieve good recall, hurting its speed advantage.</p><p><strong>Storage Efficiency:</strong> There is a trade-off between index complexity and memory footprint. A flat index is just the raw vectors (and perhaps an ID list) &#8212; simple but memory-heavy if the corpus is large (each 768-dim embedding ~3KB in FP32). Graph indexes like HNSW add links between vectors; this overhead is linear in data size (each node stores M neighbors). For example, HNSW with M=16 might store 16 extra links per vector. This increases memory usage but not overwhelmingly so (typical overhead 50&#8211;100% of the embedding data size). Tree indexes have smaller overhead, but they don&#8217;t reduce the need to store the full vectors unless combined with quantization. <strong>Product Quantization (PQ)</strong> is a key technique to shrink storage: vectors are stored in compressed form (e.g. 8 or 16 bytes) instead of full floats. IVF+PQ was famously used to fit billions of vectors into memory in Facebook&#8217;s Faiss library. The cost is some loss in precision due to compression. An alternative lighter approach is <strong>int8 quantization</strong> of vectors (reducing 32-bit floats to 8-bit integers). Lin (2024) reported that applying <em>int8 quantization</em> yields a <strong>4&#215; reduction in memory</strong> and actually <strong>increases query speed</strong>, with only a minor impact on retrieval quality . The increased speed comes from smaller data to traverse and better cache utilization, outweighing the modest extra cost of encoding. Notably, quantizing HNSW indexes gave even larger QPS gains than quantizing flat indexes, with <em>little to no drop in nDCG@10 compared to non-quantized HNSW</em> . This suggests that aggressive compression is very feasible: one can quantize embeddings (and even prune dimensions) to save space while preserving most of the utility for retrieval. In practice, many vector databases (Milvus, Vespa, etc.) offer optional PQ or bit quantization modes for large deployments.</p><p><strong>Recall and Precision Trade-offs:</strong> In approximate search, <em>recall</em> refers to how many of the true nearest neighbors (or relevant documents) are found, whereas <em>precision</em> relates to whether the retrieved top results are truly relevant. A well-tuned ANN index should retrieve nearly the same top-k as an exact search, so precision/recall should remain high. Graph methods like HNSW are known to achieve &gt;95% recall of true neighbors in benchmarks while being much faster than brute force. Empirical results confirm that the <strong>effectiveness degradation of HNSW is minimal</strong>: in Lin&#8217;s experiments on retrieval-augmented QA, the nDCG@10 from an HNSW index was usually within a few thousandths of that from an exact flat index (<a href="https://arxiv.org/pdf/2409.06464#:~:text=of%20flat%20vs,deterministic%2C%20scores">HERE</a>). In fact, in some cases HNSW even slightly <em>exceeded</em> the flat index&#8217;s score (within run variance) . This shows that for top-k retrieval with typical k (e.g. 5&#8211;10), a properly configured ANN gives essentially the same relevant chunks as exhaustive search. The trade-off comes if one pushes for extreme speed or compression: using fewer neighbors or lower-precision embeddings can start to miss some relevant results, harming recall. LSH tends to have a sharper trade-off: it may retrieve <em>some</em> close vectors very quickly but can miss others entirely (lower recall) unless many hash tables are used. Tree indexes might miss neighbors if data doesn&#8217;t partition cleanly by hyperplanes. In contrast, <em>quantized</em> indexes (int8 or PQ) typically maintain high recall/precision for semantic search. Lin (2024) found quantization&#8217;s impact on retrieval metrics to be <strong>minor overall</strong>, barely shifting nDCG scores in most cases . In summary, modern ANN indexes can be tuned to hit target recall (even 99%+ of exact), and the precision of retrieved chunks for LLM context is largely preserved. It becomes a matter of choosing the right parameters (e.g. HNSW efSearch, number of IVF probes, etc.) to balance <em>slightly higher recall vs. slightly more latency</em>. Advanced approaches are also exploring dynamic trade-offs: e.g. <strong>SOAR (NeurIPS 2023)</strong> introduced redundancy in ScaNN&#8217;s index to reduce &#8220;failure&#8221; (missing a true neighbor) (<a href="https://research.google/blog/soar-new-algorithms-for-even-faster-vector-search-with-scann/#:~:text=ScaNN%20has%20been%20actively%20maintained,placed%20upon%20vector%20search%20libraries">SOAR: New algorithms for even faster vector search with ScaNN</a>) , essentially trading a bit more index size for higher recall at fixed speed.</p><p><strong>Ease of Integration:</strong> The practicality of a vector index in LLM pipelines depends on how easily it integrates with existing tools. Here, <strong>HNSW-based indexes have an advantage</strong> due to broad adoption. Many off-the-shelf vector databases and libraries use HNSW under the hood, making it almost plug-and-play. For example, OpenAI&#8217;s Ada embeddings can be indexed in Weaviate or Milvus with HNSW &#8211; as one study notes, Weaviate&#8217;s ANN (HNSW) retrieval yields fast search with high accuracy out-of-the-box (<a href="https://arxiv.org/pdf/2402.05131#:~:text=in%20the%20database,10%20chunks%20for%20each%20question">HERE</a>). Likewise, popular frameworks like <em>LangChain</em> and <em>LlamaIndex</em> provide connectors to vector stores (Pinecone, Vespa, etc.) that default to HNSW or similar ANN methods. Even traditional search engines have integrated dense vector indexes: Apache Lucene added HNSW in version 9, and ElasticSearch 8.x supports ANN search natively (<a href="https://miaoqiao.github.io/paper/SIGMOD24_SeRF.pdf#:~:text=HNSW%20index%20for%20efficient%20ANNS,3%5D%2C%20Zilliz">SeRF: Segment Graph for Range-Filtering Approximate Nearest Neighbor Search</a>). This means an LLM application can leverage existing infrastructure (e.g. add a vector field to an Elastic index) rather than building a custom system. Flat indexes are trivially easy to implement (just a matrix of embeddings), and libraries like FAISS make it one function call to do brute-force search on GPUs or CPUs. However, flat search becomes impractical beyond a certain data size unless used in a limited setting (small corpora or as a re-ranking step). Tree-based indexes like Annoy or FLANN are available as libraries but are somewhat less common in LLM pipelines today. Hashing techniques require custom integration and are rarely part of high-level frameworks now. <strong>IVF/PQ</strong> indexing usually requires using a library like FAISS or Milvus; integration is moderately easy (these libraries are well-documented), but tuning the index (choosing number of clusters, training PQ codebooks, etc.) adds complexity. In summary, approaches that have matured into open-source tools (HNSW, flat, basic PQ) are the easiest to integrate. Cutting-edge methods like CrackIVF or learned indexes would currently require custom implementation, but they build on standard primitives (e.g. Faiss for CrackIVF (<a href="https://arxiv.org/html/2503.01823v1#:~:text=match%20at%20L398%20CrackIVF%2C%20is,3">Cracking Vector Search Indexes</a>)) which suggests they could be adopted into mainstream tools in the near future.</p><h2><strong>Suitability for Different Scenarios</strong></h2><p><strong>Real-Time Inference Settings:</strong> In interactive applications (chatbots, live question-answering), <strong>low query latency</strong> is paramount. Vector indexes that provide fast recall of relevant chunks with minimal delay are preferred. Graph-based ANN (HNSW) is generally the top choice here due to its millisecond-level response times and high recall. It&#8217;s no surprise most production RAG systems use HNSW or similar under the hood (<a href="https://miaoqiao.github.io/paper/SIGMOD24_SeRF.pdf#:~:text=HNSW%20index%20for%20efficient%20ANNS,3%5D%2C%20Zilliz">SeRF: Segment Graph for Range-Filtering Approximate Nearest Neighbor Search</a>). For example, a search query to a vector DB should ideally complete in &lt;100ms to keep total LLM response time reasonable. HNSW can often fulfill a top-5 or top-10 ANN search in 5&#8211;10ms on millions of vectors. Real-time systems also benefit from <strong>vector compression</strong> (to fit indexes entirely in RAM and cache). Using int8 quantization or optimized data structures ensures the search stays memory-resident and fast. Research confirms that int8-quantized indexes boost QPS and reduce latency significantly while keeping answer quality high (<a href="https://arxiv.org/pdf/2409.06464#:~:text=not%20meaningful,nDCG%4010%20differences%20are%20organized%20in">HERE</a>) . In contrast, exhaustive search would be too slow if the corpus is large (scaling linearly with N). Only in cases of very small corpora (say a few thousand embeddings) could brute-force be acceptable in real-time, or if one has massive parallel hardware (e.g. GPU searching a few million vectors quickly). Real-time pipelines also demand <strong>consistent performance</strong> &#8211; graph indexes can be tuned (e.g. setting HNSW <code>ef</code> parameter) to balance latency and recall deterministically per query. This is harder with methods like LSH which have more randomness. Thus, for real-time: <strong>HNSW (or similar ANN) with possible quantization is the go-to</strong>, providing an excellent speed/recall balance . Tree indexes or LSH might be used if memory is extremely constrained and approximate results are tolerable, but those are less common. Integration-wise, using a managed vector database (or an open-source one) that slots into an LLM service can simplify deployment for real-time use.</p><p><strong>Batch Processing:</strong> In batch or offline processing of queries, the constraints differ. Here the system might handle a large number of queries or documents in a pipeline without a human waiting on each query. Throughput (queries per second over the batch) and total processing time matter more than single-query latency. Batch scenarios can tolerate using more exhaustive or repeated work per query if it simplifies the pipeline or improves accuracy, since the &#8220;wall-clock&#8221; per query is less critical than overall job time. For example, a nightly job might embed and retrieve information for thousands of tasks. In such cases, it might be feasible to use <em>exact search or brute-force</em> for better recall, especially on moderate corpus sizes, because the queries can be run in parallel or during off-peak hours. Lin (2024) points out that for prototyping or small query workloads, even on medium-size corpora, the difference between HNSW and flat search in total processing time may be minor . If queries are pre-encoded (cached), a flat scan might take only a couple of seconds vs a second for ANN &#8211; not a deal-breaker in batch mode . Batch processing can also amortize index construction costs. If you have to run thousands of queries on a new dataset, spending time to build an optimized index may pay off. Methods that have heavy preprocessing (HNSW build, large IVF clustering, etc.) become more worthwhile when the index will be hit by many queries. On the flip side, something like CrackIVF is attractive for batch scenarios where you don&#8217;t know the query distribution upfront &#8211; it allows you to start querying immediately and the index <em>catches up</em> as the batch runs (<a href="https://arxiv.org/html/2503.01823v1#:~:text=We%20introduce%20CrackIVF%2C%20an%20incrementally,Each%20query%20is%20a">Cracking Vector Search Indexes</a>) . This could minimize the total time to get through a batch of queries by overlapping indexing with search. Batch settings also allow using <strong>re-ranking or ensemble retrieval</strong> for higher precision: e.g. use a fast ANN index to get 100 candidates, then do a second pass with a slower exact method or an LLM re-ranker on those. This two-stage approach is common in LLM pipelines and is computationally palatable in batch mode (since you can distribute the workload). In summary, batch processing is more forgiving &#8211; one can mix and match index methods, even brute-force or heavy reranking, as long as the throughput is acceptable. The primary goal is maximizing overall recall/precision for the batch, so often a combination (ANN for initial recall, then refine) is used.</p><p><strong>Offline Retrieval Systems:</strong> By <em>offline</em> retrieval, we refer to systems that are not serving live user queries, but rather performing retrieval for analytical tasks, data indexing, or periodic jobs (e.g. building a knowledge base, or an internal search on a static archive). In offline systems, <strong>response time is a very low priority</strong>; instead, focus is on <em>cost, scalability, and completeness</em>. These scenarios can leverage the most thorough retrieval techniques since time constraints are loose. For instance, if scanning an entire data lake to build an index of embeddings, one might even do an exhaustive similarity join or clustering offline. However, offline systems also deal with the <strong>largest scales</strong> of data (potentially billions of documents), so <strong>storage efficiency and scalability of the index</strong> become critical. A method like DiskANN (Disk-based ANN) developed by Microsoft is designed for this: it stores the graph index partly on SSD, enabling billion-scale vectors to be indexed without all data in RAM. DiskANN sacrifices some query speed (millisec-level disk fetches) but is suitable for offline or high-scale scenarios where holding everything in memory is too costly. Another consideration is that offline retrieval might involve <em>specialized queries</em> or filters. For example, one might restrict search to documents of a certain date range or type. Research on <strong>range-filtering ANN</strong> (e.g. <strong>SeRF: Segment Graph</strong>, SIGMOD 2024) addresses combining vector search with structured filters efficiently (<a href="https://miaoqiao.github.io/paper/SIGMOD24_SeRF.pdf#:~:text=%F0%9D%91%9B%20HNSW%20indexes,of%20constructing%20a%20single%20HNSW">SeRF: Segment Graph for Range-Filtering Approximate Nearest Neighbor Search</a>) . Such advanced indexes could be useful in offline analytic search where complex queries are expected. In terms of accuracy, offline systems can maximize recall by using <em>multiple indexing methods in parallel</em>. For example, one could maintain both a dense vector index and a traditional keyword index (BM25) and union their results for completeness &#8211; speed is secondary. Some experiments (Cahoon et al. 2025) on open-domain QA found that combining dense and sparse retrieval can yield the best of both worlds in terms of answer recall (<a href="https://arxiv.org/pdf/2409.06464#:~:text=Today%2C%20practitioners%20typically%20take%20advantage,vector">HERE</a>) . Offline contexts also benefit from <strong>fully automated index selection</strong>. With so much data of different types, one index type may not fit all. Techniques like CrackIVF that can adapt per dataset and workload are promising: Mageirakos et al. show that CrackIVF eventually <em>converges to an index as effective as the best static index</em>, while having <strong>several orders of magnitude less initial cost</strong> when deploying on new data . This is ideal offline where you might spin up an index on a new corpus and immediately start using it for analysis, letting it optimize in the background. Overall, offline retrieval systems lean towards <strong>maximizing recall and scale</strong>: they will use heavier indexing (even brute-force or very exhaustive ANN configurations), aggressive compression (to fit massive corpora), and innovative methods to minimize the operational burden of indexing millions of documents.</p><h2><strong>Key Research Highlights 2024-2025</strong></h2><p>To conclude, we highlight some of the most pertinent recent research contributions on vector indexing for LLM document retrieval:</p><ul><li><p><strong>HNSW vs. Flat Index Trade-offs:</strong> Lin (2024) provides extensive empirical guidance on when to use HNSW vs brute-force indexes for dense retrieval (<a href="https://arxiv.org/pdf/2409.06464#:~:text=of%20nearest,perspectives%20of%20index%02ing%20time%2C%20query">HERE</a>) , including effects of int8 quantization .</p></li><li><p><strong>Vector Quantization in Retrieval:</strong> The same study by Lin examined <strong>int8 quantization</strong> in a production search library. The results demonstrated that quantizing embeddings (both in flat and HNSW indexes) can <em>boost QPS by 1.5&#8211;2&#215;</em> and cut memory usage to a quarter, for only a very slight drop in metrics like nDCG . This confirms that modern CPUs can leverage vectorized instructions on 8-bit data, making quantization a highly attractive technique for LLM pipelines dealing with memory limits. The guidance is essentially that <strong>quantization should be applied whenever memory or speed is at a premium</strong>, as the trade-off &#8220;cost&#8221; in accuracy is minimal in most cases.</p></li><li><p><strong>Adaptive Indexing (CrackIVF):</strong> Mageirakos et al. (2025) tackled the problem of indexing <em>many separate datasets</em> (as in enterprise &#8220;embedding data lakes&#8221;) where building a static ANN index for each is infeasible. They proposed CrackIVF, which uses a cracking approach from database systems to gradually build an IVF index based on query workload (<a href="https://arxiv.org/html/2503.01823v1#:~:text=possible%20dataset,the%20index%20to%20the%20query">Cracking Vector Search Indexes</a>) , achieving faster startup and competitive long-term performance.</p></li><li><p><strong>Hybrid Index Structures (ELPIS):</strong> Azizi (VLDB 2024) introduced ELPIS, a novel in-memory ANN index that merges graph-based and tree-based ideas (<a href="https://vldb.org/2024/files/phd-workshop-papers/vldb_phd_workshop_paper_id_13.pdf#:~:text=This%20work%20aims%20to%20study,Finally%2C%20we%20summarize">Vector Search on Billion-Scale Data Collections</a>). By first clustering the data (using a technique called EAPCA) and then building lightweight neighborhood graphs within clusters, ELPIS achieves strong query performance while drastically reducing the indexing time and memory compared to pure HNSW. The author reports that ELPIS outperforms state-of-the-art baselines in <em>throughput-optimized</em> settings, meaning it can handle very high query rates efficiently . This reflects a trend of <strong>hybrid approaches</strong> to get the best of multiple data structures.</p></li><li><p><strong>Integration in LLM Workflows:</strong> Beyond algorithmic advances, 2024 has also seen work on end-to-end retrieval systems with LLMs. For example, Microsoft&#8217;s GraphRAG and RAPTOR (2024) explore organizing knowledge for RAG in graph forms, and the use of powerful rerankers on retrieved chunks. While these focus more on pipeline and re-ranking than the vector index itself, they underscore that <em>ease of integration</em> and overall system design are active areas. An emerging best practice is to use a <strong>two-tier retrieval</strong>: a fast vector index to get candidate chunks, followed by an LLM-based reranker or reader to ensure precision (<a href="https://arxiv.org/html/2503.02922v1#:~:text=1.%204.3.1%20LLM,6%20Case%20Study">Optimizing open-domain question answering with graph-based retrieval augmented generation</a>) . This mitigates any small loss in recall from the ANN index by letting the LLM sift relevance in a second stage, ultimately improving answer quality.</p></li></ul><p>In summary, vector indexing methods for LLM document retrieval have matured and diversified. <strong>Graph-based ANN indexes (especially HNSW)</strong> remain the workhorse due to their speed and accuracy, <strong>enhanced by quantization</strong> for efficiency. For extremely large or flexible scenarios, new research provides pathways to maintain performance: whether through adaptive indexing that eliminates huge upfront costs, or hybrid structures that scale better. The <strong>recall&#8211;precision trade-offs</strong> of ANN vs exact search are now well-understood &#8211; with proper tuning, ANN methods incur only minor recall loss while delivering massive speedups (<a href="https://arxiv.org/pdf/2409.06464#:~:text=of%20flat%20vs,deterministic%2C%20scores">HERE</a>). This is crucial for real-time LLM applications. Meanwhile, the choice of index can be tailored to the use-case: <strong>real-time systems</strong> favor fast ANN with high recall; <strong>batch processing</strong> can mix methods to maximize overall throughput; and <strong>offline systems</strong> can leverage heavy indexing or novel approaches to handle enormous data volumes. With these tools and findings from 2024&#8211;2025 research, practitioners can better select and configure vector indexes to power the next generation of LLM-based applications.</p><p><strong>Sources:</strong></p><ul><li><p>Lin, J. (2024). <em>&#8220;Operational Advice for Dense and Sparse Retrievers: HNSW, Flat, or Inverted Indexes?&#8221;</em> &#8211; Explores trade-offs between HNSW and flat indexes (indexing time, query speed, accuracy) for dense retrieval (<a href="https://arxiv.org/pdf/2409.06464#:~:text=of%20nearest,perspectives%20of%20index%02ing%20time%2C%20query">HERE</a>) , including effects of int8 quantization .</p></li><li><p>Mageirakos et al. (2025). <em>&#8220;Cracking Vector Search Indexes.&#8221;</em> &#8211; Proposes CrackIVF adaptive index for RAG on data lakes, which incrementally builds an IVF index during querying (<a href="https://arxiv.org/html/2503.01823v1#:~:text=possible%20dataset,the%20index%20to%20the%20query">Cracking Vector Search Indexes</a>) , achieving faster startup and competitive long-term performance.</p></li><li><p>Azizi, I. (2024). <em>&#8220;Vector Search on Billion-Scale Data Collections.&#8221;</em> (VLDB PhD Workshop) &#8211; Introduces ELPIS hybrid index combining tree and graph structures to address indexing scalability on large data, with state-of-art throughput results (<a href="https://vldb.org/2024/files/phd-workshop-papers/vldb_phd_workshop_paper_id_13.pdf#:~:text=This%20work%20aims%20to%20study,Finally%2C%20we%20summarize">Vector Search on Billion-Scale Data Collections</a>).</p></li><li><p>Zuo, C. et al. (2024). <em>&#8220;SeRF: Segment Graph for Range-Filtering Approximate Nearest Neighbor Search.&#8221;</em> (SIGMOD 2024) &#8211; Develops a graph index that supports attribute-range filtering alongside ANN search, compressing multiple HNSW graphs efficiently (<a href="https://miaoqiao.github.io/paper/SIGMOD24_SeRF.pdf#:~:text=%F0%9D%91%9B%20HNSW%20indexes,of%20constructing%20a%20single%20HNSW">SeRF: Segment Graph for Range-Filtering Approximate Nearest Neighbor Search</a>) .</p></li><li><p>Jimeno-Yepes et al. (2024). <em>&#8220;Financial Report Chunking for Effective RAG.&#8221;</em> &#8211; An application of RAG in finance; uses Weaviate (HNSW ANN) as the vector store and discusses chunking strategies (<a href="https://arxiv.org/pdf/2402.05131#:~:text=We%20have%20used%20the%20open,the%20document%20is%20split%20into">HERE</a>) . Illustrates a typical LLM pipeline using chunk embeddings and ANN retrieval.</p></li><li><p>Cahoon, J. et al. (2025). <em>&#8220;Optimizing Open-Domain QA with Graph-Based RAG.&#8221;</em> &#8211; Benchmarks graph-based retrieval augmented generation strategies. Emphasizes combining multiple retrieval modes and LLM integration (e.g. GraphRAG vs. hybrid search) for improved QA performance (<a href="https://arxiv.org/html/2503.02922v1#:~:text=1.%204.3.1%20LLM,6%20Case%20Study">Optimizing open-domain question answering with graph-based retrieval augmented generation</a>) .</p></li><li><p>Google Research (2023). <em>&#8220;SOAR: Improved Indexing for ANN Search.&#8221;</em> &#8211; NeurIPS 2023 paper introducing an algorithm (SOAR) that adds redundancy to ScaNN&#8217;s index, improving recall at given speed by using orthogonality-amplified residuals (<a href="https://research.google/blog/soar-new-algorithms-for-even-faster-vector-search-with-scann/#:~:text=ScaNN%20has%20been%20actively%20maintained,placed%20upon%20vector%20search%20libraries">SOAR: New algorithms for even faster vector search with ScaNN</a>) . (Represents ongoing improvements to vector search algorithms as data scales.)</p></li></ul>]]></content:encoded></item><item><title><![CDATA[Document digitization and chunking strategies for finding similar customer reviews using semantic similarity]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/document-digitization-and-chunking</link><guid isPermaLink="false">https://www.rohan-paul.com/p/document-digitization-and-chunking</guid><pubDate>Mon, 16 Jun 2025 10:16:12 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!12Bu!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!12Bu!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!12Bu!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png 424w, https://substackcdn.com/image/fetch/$s_!12Bu!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png 848w, https://substackcdn.com/image/fetch/$s_!12Bu!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png 1272w, https://substackcdn.com/image/fetch/$s_!12Bu!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!12Bu!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png" width="1024" height="574" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:574,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1016825,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166056557?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!12Bu!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png 424w, https://substackcdn.com/image/fetch/$s_!12Bu!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png 848w, https://substackcdn.com/image/fetch/$s_!12Bu!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png 1272w, https://substackcdn.com/image/fetch/$s_!12Bu!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6bd8a35e-b017-4ce2-85ae-1462b6a28fa5_1024x574.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ol><li><p>Document digitization and chunking strategies for finding similar customer reviews using semantic similarity</p></li><li><p>Introduction</p></li><li><p>Transformer-Based Embeddings for Semantic Similarity</p></li><li><p>Document Chunking Strategies in Retrieval</p></li><li><p>Multilingual vs. Monolingual Retrieval</p></li><li><p>Precision-Recall Trade-offs in Dense Retrieval</p></li><li><p>GPU/TPU-Accelerated Vector Search</p></li><li><p>Comparative Analysis of Approaches</p></li><li><p>Conclusion and Recommendations</p></li></ol><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h3><strong>Introduction</strong></h3><p>Document digitization for semantic search involves converting text (e.g. customer reviews) into machine-readable form and splitting it into manageable chunks for embedding-based retrieval. Recent research (2024&#8211;2025) has advanced transformer-based embedding models and retrieval techniques that prioritize <strong>perfect accuracy</strong> &#8211; meaning retrieving semantically closest matches with minimal loss &#8211; sometimes at the expense of speed. This review surveys state-of-the-art methods in <strong>dense retrieval</strong> (vector similarity search) and chunking strategies, covering both monolingual and multilingual settings. We focus on approaches that maximize semantic similarity (high precision and recall), discuss how chunking affects retrieval performance, explore GPU/TPU acceleration for exhaustive search, and highlight trade-offs between speed and accuracy. Below, we summarize key findings from recent arXiv papers and provide comparative analysis, concluding with best-practice recommendations.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Transformer-Based Embeddings for Semantic Similarity</strong></h2><p><strong>Dense embedding models</strong> derived from transformers underpin modern semantic similarity search. Instead of keyword matching, these models encode texts (queries and documents) into high-dimensional vectors such that semantically similar texts map to nearby points in vector space. Advances in 2024 have produced highly effective embedding models. For example, <em>M3-Embedding</em> (Chen et al., 2024) introduced a single model supporting 100+ languages that achieved new state-of-the-art performance on multilingual and cross-lingual retrieval benchmarks (<a href="https://arxiv.org/abs/2402.03216#:~:text=,documents%20of%20up%20to%208192"> BGE M3-Embedding: Multi-Lingual, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation</a>). Notably, M3-Embedding is versatile: it supports classic single-vector dense retrieval as well as multi-vector and even sparse lexical retrieval within one model . This means a unified model can handle diverse retrieval scenarios, from short queries to long documents (up to 8192 tokens) without sacrificing accuracy .</p><p>Open-source efforts have also closed the gap with proprietary embeddings. <em>Arctic-Embed 2.0</em> (Yu et al., 2024) is a family of text embedding models trained for <strong>accurate and efficient multilingual retrieval</strong>. Earlier multilingual models often hurt English accuracy, but Arctic-Embed 2.0 demonstrates <strong>no compromise</strong> &#8211; it delivers competitive retrieval quality on both multilingual and English-only benchmarks (<a href="https://bohrium.dp.tech/paper/arxiv/2412.04506#:~:text=of%20open,aimed%20at%20fostering%20further%20discussion">bohrium.dp.tech</a>). In fact, the largest Arctic-Embed model (334M parameters) was reported to outperform closed-source services like Cohere&#8217;s Embed-v3 and OpenAI&#8217;s text-embedding-3 on standard retrieval leaderboards . Similarly, IBM Research&#8217;s <strong>Granite Embeddings</strong> (Feb 2025) released 12-layer encoder models (with 6-layer distilled versions) specialized for retrieval. Using techniques like retrieval-oriented pretraining, contrastive fine-tuning, and knowledge distillation, these models significantly outperformed other public models of comparable size and achieved on-par results with SOTA benchmarks (<a href="https://arxiv.org/pdf/2502.20204#:~:text=Extensive%20evaluations%20show%20that%20the,both%20research%20and%20commercial%20use">HERE</a>). This trend indicates that for perfect semantic similarity, using the latest fine-tuned embedding model (possibly domain-specific or multilingual as needed) is critical. High-quality embeddings ensure that truly similar customer reviews map close together in the vector space, forming the foundation for accurate retrieval.</p><p><strong>Single- vs. Multi-vector representations:</strong> Most embedding-based searches use a single vector per document/review (e.g. Sentence-BERT style), but research shows benefits in using multiple vectors to represent different aspects of a long document. Multi-vector models (e.g. ColBERT and its successors) produce a set of embeddings for each document (often one per passage or token cluster), enabling more fine-grained matching. This generally <strong>improves recall and retrieval quality</strong> because even if one part of a document is relevant to the query, it can be retrieved by a corresponding vector . However, the trade-off is a <em>much larger index</em>: multi-vector representations can inflate memory/storage requirements by an order of magnitude . For instance, Shrestha et al. (2023) highlight that multi-vector IR boosts quality but at a 10&#215; cost in index size, challenging scalability . Recent work addresses this via smarter storage: the ESPN technique proposes to offload parts of the embedding index to SSD storage with caching, achieving 5&#8211;16&#215; memory reduction and 6.4&#215; faster SSD-based retrieval, while keeping query latency near in-memory speeds . In summary, single-vector embeddings are simpler and lighter, but multi-vector approaches can yield higher accuracy on lengthy, content-rich documents. For &#8220;perfect&#8221; accuracy, one might consider multi-vector models if memory permits, or ensure that long texts are chunked (segmented) so that each chunk&#8217;s single-vector is specific (more on chunking below). Importantly, multi-vector methods are being made more practical, and even multilingual multi-vector models exist (e.g. ColBERT-XM for zero-shot retrieval in many languages ), combining the benefits of fine-grained matching with cross-lingual capability.</p><h2><strong>Document Chunking Strategies in Retrieval</strong></h2><p>When digitizing documents or aggregating many reviews, deciding how to split text into chunks can significantly impact semantic search accuracy. Effective chunking ensures that each text chunk is coherent and self-contained, so that its embedding accurately represents a single idea or topic. If chunks are too large, unrelated content may dilute the embedding; too small, and context is lost. Traditional chunking uses fixed-size windows (e.g. a fixed number of words or characters) or natural boundaries (paragraphs or sentences). However, <strong>semantic chunking</strong> has emerged as a strategy to split text based on meaning, rather than arbitrary length. For example, Kamradt (2024) proposed <em>semantic-based splitting</em> that uses embeddings to cluster semantically similar text segments, inserting chunk boundaries where the content shifts significantly (<a href="https://arxiv.org/pdf/2406.17526#:~:text=address%20this%2C%20semantic,significant%20changes%20in%20embedding%20distances">HERE</a>). This ensures each chunk &#8220;maintains meaningful context and coherence&#8221; by detecting points where the embedding representation of the text changes abruptly .</p><p>In 2024, LumberChunker (a method by Kamradt et al.) took this further by employing an LLM (large language model) to dynamically decide chunk boundaries. LumberChunker feeds sequential passages to an LLM (OpenAI&#8217;s Gemini model in their case) which identifies where a new topic or idea begins, thus creating chunks of varying length that are <em>semantically independent</em> . The idea is to adapt chunk size to content: some parts of a document might be combined if they discuss one concept, whereas a sharp topical shift triggers a new chunk. This dynamic LLM-driven chunking was shown to markedly improve retrieval. In evaluations on a QA dataset (GutenQA), LumberChunker <strong>consistently outperformed</strong> several baseline chunking methods (fixed-length, paragraph-based, existing semantic rules, etc.) on retrieval metrics . For instance, at a retrieval depth of 20, LumberChunker achieved a DCG@20 of 62.09, whereas the closest baseline (recursive fixed-size chunks) scored 54.72; similarly, Recall@20 was 77.9% vs. 74.3% . In other words, by producing more topically coherent chunks, the system retrieved more relevant passages for the queries. Simpler approaches like uniform paragraphs or naive semantic splitting degraded as more results were retrieved, failing to maintain relevance at higher recall . This underscores that smart chunking can boost accuracy in semantic search, especially for long and unstructured documents.</p><p>That said, semantic chunking comes with a <strong>computational cost</strong> &#8211; using an LLM to segment text or performing clustering is slower and more complex than fixed splitting. A study titled <em>&#8220;Is Semantic Chunking Worth the Computational Cost?&#8221;</em> (Qu et al., 2024) questioned the gains of semantic chunking. They systematically evaluated semantic versus fixed-size chunking on tasks like document retrieval and answer generation. Their finding: the extra computation of semantic chunking was <em>often not justified by consistent performance gains</em> (<a href="https://arxiv.org/abs/2410.13070#:~:text=retrieval,chunking%20strategies%20in%20RAG%20systems"> Is Semantic Chunking Worth the Computational Cost?</a>). In some scenarios, fixed-size or simpler chunking performed nearly as well, suggesting that the benefit of semantic segmentation might be context-dependent . These results challenge the assumption that more sophisticated chunking always yields significantly better results, and highlight the need to balance chunking strategy with its cost . A plausible interpretation is that for certain structured or fact-based corpora, simple chunking suffices, whereas for narrative or complex texts, dynamic chunking shines. (Indeed, LumberChunker&#8217;s authors note that their method is most useful for &#8220;unstructured narrative texts,&#8221; whereas highly structured texts might achieve similar results with rule-based segmentation at lower cost (<a href="https://arxiv.org/pdf/2406.17526#:~:text=The%20scores%20for%20Proposition,GutenQA%2C%20refer%20to%20Appendix%20F">HERE</a>).) In practice, for finding similar customer reviews, which are usually relatively short documents focusing on a single product or experience, aggressive semantic chunking may be unnecessary &#8211; each review can be treated as one chunk, or at most split by sentences if very long. However, if the &#8220;document&#8221; is a collection of reviews or a long multi-topic review, applying a semantic chunking approach could improve retrieval of the most relevant segments. The key is to ensure each chunk covers one coherent thought, as that yields the highest similarity fidelity when using embeddings .</p><p><strong>Chunk size tuning:</strong> Another insight from LumberChunker&#8217;s experiments is that there is an optimal chunk length for retrieval. They found ~550 tokens per chunk yielded the best retrieval performance in their setting, balancing context and specificity . Smaller chunks (e.g. 450 tokens) or larger (650+) underperformed slightly . This suggests that if using fixed or semi-fixed chunks, one should tune the size: too large can overwhelm the model with mixed content, and too small may miss context needed for semantic matching. Overall, current research advocates for <em>content-aware chunking</em> &#8211; if not via an LLM, then via simple heuristics (like splitting at logical boundaries or discourse markers) &#8211; to preserve accuracy in semantic search. But it also warns against over-engineering chunking when simpler methods yield similar gains .</p><h2><strong>Multilingual vs. Monolingual Retrieval</strong></h2><p>In a global customer feedback scenario, reviews might be in multiple languages. Embedding-based retrieval naturally extends to multilingual search if the embedding model maps different languages into a <strong>shared semantic space</strong>. The latest models explicitly address this. As mentioned, M3-Embedding and Arctic-Embed 2.0 are multilingual, meaning a French and an English review with the same meaning should end up with similar vector representations. M3-Embedding achieved state-of-the-art on cross-lingual retrieval tasks, demonstrating that a single model can handle over 100 languages without sacrificing accuracy (<a href="https://arxiv.org/abs/2402.03216#:~:text=,documents%20of%20up%20to%208192"> BGE M3-Embedding: Multi-Lingual, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation</a>). Arctic-Embed 2.0 likewise was designed to avoid the typical quality drop in English when training a multilingual model; it managed to be competitive on English benchmarks while supporting many languages (<a href="https://bohrium.dp.tech/paper/arxiv/2412.04506#:~:text=of%20open,aimed%20at%20fostering%20further%20discussion">bohrium.dp.tech</a>). In fact, open models like Arctic-Embed have achieved such quality that their performance per language is on par with dedicated monolingual models in many cases . This is a crucial development &#8211; it implies we no longer need separate retrieval systems for each language or complex translation pipelines for high-accuracy search. Instead, a unified multilingual embedding index can be built, greatly simplifying the architecture.</p><p>However, multilingual models can be larger and might still lag a bit behind truly specialized models on a specific language/domain. For example, IBM&#8217;s Granite release included both English-only models and multilingual models (covering 12 languages) (<a href="https://arxiv.org/pdf/2502.20204#:~:text=We%20introduce%20the%20Granite%20Embedding,finetuning%2C%20knowledge%20distillation%2C%20and%20model">HERE</a>) . The multilingual ones were larger (up to 278M parameters) to capture multiple languages, whereas English-only models could achieve strong results with 125M or even 30M parameters . In practice, if your customer reviews are mostly in one language (say English), a monolingual model fine-tuned on that language&#8217;s nuances might give a tiny edge in accuracy. But if there&#8217;s any multilingual aspect (e.g. you want to find similar reviews across English and Spanish corpora), the latest research suggests using a <strong>single multilingual model</strong> is highly effective and avoids the error-prone step of translating queries or documents. Multilingual dense retrievers have been benchmarked extensively (e.g. the MIRACL and MTEB benchmarks (<a href="https://arxiv.org/html/2412.04506v1#:~:text=We%20evaluate%20English,including%20ours%29%2C%20it">Arctic-Embed 2.0: Multilingual Retrieval Without Compromise - arXiv.org</a>)), and systems like Arctic-Embed have essentially <em>matched state-of-the-art English retrieval while adding multilingual capability</em> . Therefore, for perfect semantic matching in a multilingual dataset, one should leverage these advanced multilingual embeddings. Additionally, cross-lingual similarity search can surface insights (e.g. a German review similar to an English query) that a language-specific approach might miss &#8211; essentially increasing recall across languages.</p><p>It&#8217;s also worth noting the emergence of <strong>multilingual multi-vector models</strong> (e.g. ColBERT-XM, 2024). ColBERT-XM trains on a high-resource language (English) and uses a modular architecture to transfer to other languages without needing per-language labeled data (<a href="https://bohrium.dp.tech/paper/arxiv/2412.04506#:~:text=%2A%20%202%20%20ColBERT,poorly%20in%20languages%20with%20minimal">bohrium.dp.tech</a>) . It demonstrated competitive zero-shot retrieval performance in various languages . This kind of research indicates that even fine-grained, token-level matching can be extended to multilingual scenarios, broadening the toolkit for high-accuracy cross-lingual search. In summary, the literature suggests that the <strong>best practice for multilingual similarity search</strong> is to use a top-performing multilingual embedding model (or an ensemble of monolingual ones if that yields higher accuracy and cross-map them, though that&#8217;s more complex). The gap between multilingual and monolingual retrieval quality has narrowed considerably , so one need not trade accuracy for coverage.</p><h2><strong>Precision&#8211;Recall Trade-offs in Dense Retrieval</strong></h2><p>A critical aspect of &#8220;perfect accuracy&#8221; is balancing recall (retrieving all relevant items) and precision (avoiding irrelevant items). In an ideal scenario, a semantic search system would return <em>only</em> the truly similar reviews and <em>all</em> of them. In practice, there are trade-offs. Dense embedding retrieval is very good at recall &#8211; capturing items that are semantically related even if they don&#8217;t share exact keywords. But high recall can come with a precision penalty: because embeddings cluster items by conceptual similarity, sometimes the retrieval may pull in items that are topically similar but not truly relevant to the user&#8217;s intent. Rossi et al. (2024) describe this as dense retrieval lacking a &#8220;natural cutoff&#8221; &#8211; unlike keyword search which is limited by requiring matching terms, vector search can always compute a similarity for every item, so if you ask for the top <em>k</em>, it will give you something even if only the top few were actually relevant (<a href="https://arxiv.org/abs/2408.04887#:~:text=%3E%20Abstract%3AIn%20embedding,This%20issue%20is%20prominent%20in"> Relevance Filtering for Embedding-based Retrieval</a>). They note that cosine similarity scores from embedding models are often hard to interpret, so just taking the top 10 or a fixed threshold might include some false positives . For example, in product review search, if a query has only 2 truly relevant reviews in the corpus, a dense search set to return 10 will still return 10 results &#8211; the remaining 8 will be the &#8220;next closest&#8221; but could be borderline or irrelevant . This motivates strategies to improve precision without losing (much) recall.</p><p>One such strategy is <strong>relevance filtering on similarity scores</strong>. Rossi et al. introduce a <em>&#8220;Cosine Adapter&#8221;</em> component that learns to map raw cosine similarities to a more calibrated relevance score, then applies a threshold to omit results deemed not relevant . By using a query-dependent mapping (essentially adjusting for the distribution of similarities for each query), they manage to <strong>significantly increase precision with only a small loss of recall</strong> . On MS MARCO and real e-commerce search data, this method filtered out spurious results, and an online A/B test at Walmart showed improved user satisfaction . This illustrates a trade-off: accepting a minor drop in recall (maybe missing an occasional relevant item that had a low score) in order to dramatically reduce the number of irrelevant items retrieved. In scenarios where &#8220;perfect accuracy&#8221; means <em>the results you show are virtually guaranteed relevant</em> (even if you might not show absolutely every possible relevant result), such filtering is very valuable.</p><p>Another approach to balance precision/recall is to dynamically adjust how many results to retrieve based on the query. <em>pEBR (Probabilistic Embedding-Based Retrieval)</em> by Zhang et al. (2024) tackled the issue that a fixed top-<em>k</em> retrieval may be too low for some queries and too high for others (<a href="https://arxiv.org/abs/2410.19349#:~:text=retrieval%20using%20approximate%20nearest%20neighbor,pEBR%7D%29%20by%20learning%20the%20item"> pEBR: A Probabilistic Approach to Embedding Based Retrieval</a>). They found that &#8220;head&#8221; queries (common queries or topics) often have many relevant results that a small <em>k</em> would truncate (hurting recall), whereas rare &#8220;tail&#8221; queries might have only 1&#8211;2 relevant results and anything beyond that is noise (hurting precision) . pEBR learns a probabilistic model of the distribution of item similarities for each query and sets a <strong>dynamic similarity threshold</strong> (via a CDF) instead of a fixed <em>k</em> . This means for some queries it will retrieve more items (if there are many above the threshold) and for others fewer. The outcome is an <strong>improvement in both precision and recall</strong> compared to fixed top-<em>k</em> retrieval . Essentially, pEBR retrieves &#8220;all likely relevant items&#8221; for each query by adapting the cutoff, ensuring high recall for rich queries and high precision for queries with sparse relevance. This kind of adaptive approach aligns well with the goal of perfect accuracy, as it avoids arbitrary limits that could undercut recall or flooding the results which undercuts precision.</p><p>Beyond these, a standard technique in information retrieval pipelines is <strong>re-ranking</strong>. One might use the fast embedding-based search to retrieve a candidate list (say top 50), then use a more precise but slower model (e.g. a cross-attention transformer that directly compares query and review text) to re-score those candidates and pick the best. This can significantly boost precision at the top ranks, essentially combining dense retrieval&#8217;s recall with a fine-grained relevance judgment. While our focus is on embedding-based methods, it&#8217;s worth noting that in practice, if &#8220;perfect accuracy&#8221; is needed and speed permits, this two-stage setup (dense retrieval + cross-encoder re-ranker) is often considered a gold standard in academic literature. For example, many question-answering systems retrieve passages with a bi-encoder (embedding model) and then rank them with a cross-encoder, yielding very high answer recall and precision. The downside is computational cost, especially if the candidate list is large or needs to be real-time. If using only embeddings, the aforementioned filtering (Cosine Adapter) is a lighter-weight alternative to improve precision without a full re-rank.</p><p>Lastly, consider <strong>hybrid retrieval</strong> (combining sparse lexical and dense embedding searches). Although the question emphasizes semantic similarity, combining approaches can sometimes improve overall accuracy. Dense embeddings excel at conceptual similarity (e.g. finding a review that expresses the same sentiment in different words), whereas lexical search (e.g. BM25) excels at precision for very specific terms (e.g. if a query contains a product name or error code, an embedding might find conceptually related items that don&#8217;t have that exact term, which could be a false positive in some cases). A hybrid approach can ensure that exact matches are not missed (improving recall for certain queries) and can also serve as a check to filter results. For example, Yang et al. (2025) propose CluSD, which uses sparse retrieval results to guide which clusters of embeddings to search, effectively narrowing the dense search space to what&#8217;s likely relevant (<a href="https://arxiv.org/abs/2502.10639#:~:text=,disk%20MS%20MARCO%20and%20BEIR"> LSTM-based Selective Dense Text Retrieval Guided by Sparse Lexical Retrieval</a>). This speeds up retrieval but also has a precision benefit: dense search is only applied where there is lexical overlap, reducing random matches. While hybrid methods primarily address efficiency, they incidentally provide a way to tune precision/recall (by adjusting how much weight to give the sparse vs. dense components) (<a href="https://arxiv.org/pdf/2410.20878#:~:text=2,each%20passage%20embedding%20is%20then">HERE</a>) . In summary, achieving &#8220;perfect&#8221; retrieval results often involves such multi-step or hybrid strategies &#8211; retrieve broadly with embeddings for recall, then refine for precision. The literature shows that thoughtful cutoff thresholds (<a href="https://arxiv.org/abs/2408.04887#:~:text=embedding,world"> Relevance Filtering for Embedding-based Retrieval</a>) or probabilistic models (<a href="https://arxiv.org/abs/2410.19349#:~:text=distribution%20for%20different%20queries%2C%20which,capture%20the%20differences%20between%20head"> pEBR: A Probabilistic Approach to Embedding Based Retrieval</a>) can dynamically get the best of both worlds depending on query needs.</p><h2><strong>GPU/TPU-Accelerated Vector Search</strong></h2><p>Maximizing semantic similarity retrieval accuracy often implies searching a large vector database exhaustively or with very high recall settings &#8211; which can be computationally heavy. This is where <strong>hardware acceleration</strong> comes into play. Researchers have been leveraging GPUs (and to a lesser extent TPUs) to speed up dense retrieval, since computing millions of vector dot-products is highly parallelizable. Libraries like FAISS (Facebook AI Similarity Search) pioneered efficient GPU implementations for nearest neighbor search, and more recently NVIDIA&#8217;s <em>cu</em>Graph-based indexes and RAPIDS libraries allow building high-throughput vector search on GPUs (<a href="https://arxiv.org/html/2408.02937v2#:~:text=,this%20foundation%2C%20focusing%20on%20either">A Real-Time Adaptive Multi-Stream GPU System for Online Approximate ...</a>). In 2024, Zilliz (the creators of Milvus vector DB) and NVIDIA announced a system using a CUDA-accelerated graph index (CAGRA) for Milvus, achieving significant speed-ups by fully exploiting GPU cores (<a href="https://www.gpu-mart.com/news/gpu-vd#:~:text=mart,in%20the%20RAPIDS%20cuVS">First Nvidia GPU Accelerated Vector Database launched - GPU Mart</a>). In effect, current technology allows even brute-force search over millions of embeddings to be done in (milli)seconds on a single GPU. If the dataset of customer reviews is moderate (say up to a few hundred thousand), one could even perform exact similarity search (no approximation) on a GPU by computing the query embedding&#8217;s cosine similarity with every stored embedding &#8211; this ensures <strong>perfect recall</strong> (you truly find the nearest neighbors). The only limitation is memory and throughput, but with batching and modern GPUs, this is feasible for reasonably large corpora.</p><p>For <strong>very large scales</strong> (millions to billions of vectors), approximate algorithms are used, but here too 2024 research has improved accuracy-speed trade-offs. One standout example is FusionANNS (Tian et al., 2024), a system designed for billion-scale ANN search using a combination of CPU, GPU, and SSD resources. FusionANNS introduces a cooperative architecture where a GPU and CPU work together to filter and re-rank candidates, minimizing data transfer and I/O bottlenecks (<a href="https://arxiv.org/abs/2409.16576#:~:text=services,We"> FusionANNS: An Efficient CPU/GPU Cooperative Processing Architecture for Billion-scale Approximate Nearest Neighbor Search</a>). Through techniques like multi-tier indexing (to keep search mostly local) and eliminating redundant data loads, it achieves extremely high throughput &#8211; an order of magnitude faster than prior systems &#8211; <strong>while maintaining low latency and very high recall (accuracy)</strong> . Specifically, compared to a state-of-art disk-based index (SPANN) and an in-memory GPU index (Rummi), FusionANNS delivered 2&#215; to 13&#215; higher query per second throughput and 2.3&#215; to 8.8&#215; better cost efficiency, without sacrificing accuracy (it &#8220;guarantees high accuracy&#8221; in results) . This indicates that one can scale up semantic search to huge datasets and still aim for near-perfect accuracy, by using advanced indexing algorithms on accelerated hardware. The GPU can handle the heavy math of embedding comparisons, while clever scheduling ensures no significant portion of relevant data is missed.</p><p><strong>TPU acceleration</strong>: While less public literature is available specifically for TPUs in 2024/2025, Google&#8217;s own systems (like their internal search or QA) likely leverage TPUs for vector operations. There&#8217;s also <em>Retrieval-Augmented Attention</em> research, where instead of searching an external index, an LLM&#8217;s attention mechanism retrieves relevant tokens on the fly (some work like &#8220;RetrievalAttention&#8221; explores this (<a href="https://arxiv.org/abs/2409.10516#:~:text=RetrievalAttention%3A%20Accelerating%20Long,to%20both%20accelerate%20attention">RetrievalAttention: Accelerating Long-Context LLM Inference via Vector ...</a>)). These approaches effectively integrate retrieval into the model and use TPU acceleration for the combined task. But for our focus &#8211; semantic search of reviews &#8211; the simpler view is: using GPUs/TPUs can remove the need to compromise on accuracy for speed. If one can afford the hardware, it&#8217;s possible to run exhaustive or very high-recall searches quickly. This is especially true with vector quantization or compression techniques that reduce memory usage (like Product Quantization) but even those are becoming less necessary as memory grows and techniques like <em>Matryoshka Representation Learning (MRL)</em> (supported by Arctic-Embed 2.0) compress embeddings with minimal quality loss (<a href="https://bohrium.dp.tech/paper/arxiv/2412.04506#:~:text=retrieval%20quality%2C%20Arctic,further%20discussion%20in%20this%20field">bohrium.dp.tech</a>). In practical terms, to maximize accuracy one might use a <strong>hierarchical index</strong>: a coarse index to eliminate obviously irrelevant sections and then a fine GPU-powered search on the remainder. Or simply use a single flat index on GPU if the dataset fits. The main takeaway from recent research is that <em>we can achieve very high recall (99%+ of true nearest neighbors) at interactive speeds</em> with modern ANN algorithms on GPUs . Thus, prioritizing exact semantic similarity no longer means the system must be unbearably slow &#8211; with the right optimizations, it can be made fast enough for production while still returning virtually the same results as a brute-force search.</p><h2><strong>Comparative Analysis of Approaches</strong></h2><p>Bringing the strands together, we compare the approaches in terms of <strong>accuracy (semantic matching fidelity)</strong> and practical considerations:</p><ul><li><p><strong>Embedding Model Choice:</strong> A powerful, specialized embedding model is paramount for accuracy. 2024/25 developments (M3-Embedding, Arctic-Embed, Granite) provide highly accurate representations. Multilingual models now achieve parity with monolingual ones on many tasks (<a href="https://bohrium.dp.tech/paper/arxiv/2412.04506#:~:text=of%20open,aimed%20at%20fostering%20further%20discussion">bohrium.dp.tech</a>), meaning a single model can often serve all languages without loss. If maximum accuracy is needed, one should consider fine-tuning embeddings on the specific domain (e.g. fine-tune on a large set of customer reviews) to capture domain-specific terminology and style. However, even off-the-shelf models like OpenAI&#8217;s text-embedding-ada-002 are strong baselines. The literature shows that new models with retrieval-specific training (contrastive learning with hard negatives, etc.) can significantly outperform older general-purpose embeddings (<a href="https://arxiv.org/pdf/2502.20204#:~:text=Extensive%20evaluations%20show%20that%20the,both%20research%20and%20commercial%20use">HERE</a>). Therefore, the <strong>accuracy ranking of methods</strong> starts with having the best embedding representation. A weaker model will be a bottleneck no matter how good the chunking or search algorithm is.</p></li><li><p><strong>Chunking Strategy:</strong> For short documents (like individual reviews that are a few sentences or a paragraph), chunking is trivial (each review = one chunk). For longer text, adaptive chunking (semantic or variable-length) can yield more accurate retrieval than fixed-length chunks (<a href="https://arxiv.org/pdf/2406.17526#:~:text=5,k%20%3D%2020%2C%20compared%20to">HERE</a>) , but the gain must be weighed against complexity. If absolute accuracy is the goal and resources permit, an LLM-based chunker like LumberChunker can be used to preprocess the corpus, ensuring each chunk is semantically self-contained. This will maximize the relevance of each retrieved piece . But if resources are limited, a simpler heuristic (like splitting by paragraph or at punctuation boundaries) might achieve nearly the same effect in many cases (<a href="https://arxiv.org/abs/2410.13070#:~:text=retrieval,chunking%20strategies%20in%20RAG%20systems"> Is Semantic Chunking Worth the Computational Cost?</a>). Qu et al.&#8217;s work suggests not to over-engineer chunking unless the baseline retrieval quality is suffering due to chunk issues. The optimal approach may also be hybrid: use a moderate chunk size (say 200-500 tokens) and rely on the embedding model to handle any minor context overlap.</p></li><li><p><strong>Indexing and Search:</strong> For pure accuracy, an exhaustive search or a very high-recall ANN index is preferred. The difference between an exact brute-force search and a well-tuned ANN (like HNSW with high ef parameter, or IVF with big clusters) might be negligible in terms of results, but the latter can be 10&#215; faster. The literature (e.g. FusionANNS) demonstrates that you can get both high speed and high accuracy with advanced indexes (<a href="https://arxiv.org/abs/2409.16576#:~:text=results%20show%20that%20FusionANNS%20achieves,low%20latency%20and%20high%20accuracy"> FusionANNS: An Efficient CPU/GPU Cooperative Processing Architecture for Billion-scale Approximate Nearest Neighbor Search</a>). So, practically, one should use a proven vector search library (FAISS, Annoy, HNSWlib, Milvus etc.) configured for &gt;95% recall (if not 100%). The remaining few-percent loss in recall (if any) can often be mitigated by multiple probes or simply deemed acceptable if it&#8217;s truly negligible. If &#8220;perfect accuracy&#8221; is absolutely required, then brute force on GPU is an option &#8211; slower but still possibly within acceptable range for many applications (especially if queries are not too frequent or can be batch processed).</p></li><li><p><strong>Hybrid and Re-ranking Techniques:</strong> To push precision to the maximum, employing a second-stage reranker (cross-encoder) will typically outperform any pure embedding similarity approach, as it can consider nuance and context overlap in detail. Since the question centers on embedding-based methods, the alternative is to use scoring filters like the Cosine Adapter (<a href="https://arxiv.org/abs/2408.04887#:~:text=embedding,world"> Relevance Filtering for Embedding-based Retrieval</a>) or to combine lexical constraints (e.g. require at least one keyword match among the top results). In terms of recall, dense embeddings already excel, but if the domain has certain anchor keywords that must match (for example, if looking for reviews about a specific feature, a purely semantic search might retrieve some that talk about related features instead), incorporating lexical matching can ensure those are not missed or wrongly included. Recent results from pEBR and others show that intelligently <strong>modulating retrieval breadth per query</strong> is a key innovation for balancing precision and recall (<a href="https://arxiv.org/abs/2410.19349#:~:text=distribution%20for%20different%20queries%2C%20which,capture%20the%20differences%20between%20head"> pEBR: A Probabilistic Approach to Embedding Based Retrieval</a>). This suggests the best systems are adaptive &#8211; recognizing when to be broad and when to be narrow.</p></li><li><p><strong>Hardware Utilization:</strong> Using GPUs (or TPUs) is less about changing the retrieval outcome and more about enabling the above strategies to run without timeout. If real-time search is needed and the dataset is large, then high-accuracy strategies (like large embeddings, multi-vector, big <em>k</em>) require acceleration. The literature assures that with even a single GPU, one can handle pretty large scales with negligible accuracy loss (<a href="https://arxiv.org/abs/2409.16576#:~:text=accuracy%20ANNS%20system%20for%20billion,We"> FusionANNS: An Efficient CPU/GPU Cooperative Processing Architecture for Billion-scale Approximate Nearest Neighbor Search</a>). So from a methodological perspective, one can plan to use the most accurate settings and offset the added cost by throwing hardware at the problem. GPU-accelerated vector databases and indexes are a mature solution now, as evidenced by industry and academic benchmarks. In scenarios where GPU/TPU use is restricted (say cost or deployment constraints), one might have to dial back to simpler indexes or smaller models, which then directly impacts accuracy. Thus, there is a resource trade-off: perfect accuracy often demands strong compute (during both indexing and querying).</p></li></ul><p>To summarize the comparison: <strong>embedding model quality</strong> has the largest impact on semantic retrieval accuracy. Assuming a top-tier model, chunking and <strong>multi-vector representations</strong> can further improve how well the text content is represented, especially for long documents, at the cost of complexity or memory. <strong>Retrieval indexing</strong> strategies determine whether you actually retrieve all the nearest neighbors (high recall) &#8211; the goal is to not miss any, even if it means more compute. And <strong>post-processing</strong> strategies determine precision &#8211; ensuring the results you return are truly the most similar, even if it means discarding borderline ones. The latest research contributions in 2024&#8211;2025 have provided solutions at each of these layers to push accuracy higher: from multilingual multi-functional embedder models (<a href="https://arxiv.org/abs/2402.03216#:~:text=Functionality%2C%20and%20Multi,knowledge%20distillation%20approach%2C%20where"> BGE M3-Embedding: Multi-Lingual, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation</a>), to LLM-guided chunking (<a href="https://arxiv.org/pdf/2406.17526#:~:text=3,By">HERE</a>), to adaptive retrieval thresholds (<a href="https://arxiv.org/abs/2410.19349#:~:text=distribution%20for%20different%20queries%2C%20which,capture%20the%20differences%20between%20head"> pEBR: A Probabilistic Approach to Embedding Based Retrieval</a>), to GPU-powered ANN search . Each of these can be seen as a component to mix and match for a production system depending on needs (and each comes with trade-offs like speed, complexity, or cost).</p><h2><strong>Conclusion and Recommendations</strong></h2><p>Based on the latest research, <strong>the best method for achieving the highest accuracy in semantic similarity search</strong> (for tasks like finding similar customer reviews) is a combination of the above techniques:</p><ul><li><p><strong>Use a state-of-the-art embedding model</strong> for vector representations. Prefer models specifically tuned for retrieval or semantic textual similarity. For multilingual collections, choose a model like Arctic-Embed 2.0 or M3-Embedding that handles multiple languages without degrading performance (<a href="https://bohrium.dp.tech/paper/arxiv/2412.04506#:~:text=of%20open,aimed%20at%20fostering%20further%20discussion">bohrium.dp.tech</a>). For single-language data, an embedding model fine-tuned on in-domain data (if available) or a strong general model (like IBM Granite for English (<a href="https://arxiv.org/pdf/2502.20204#:~:text=Extensive%20evaluations%20show%20that%20the,both%20research%20and%20commercial%20use">HERE</a>)) will yield high-quality vectors. This ensures that if two reviews convey the same sentiment or content, their embeddings will be near each other (which is the foundation of &#8220;perfect&#8221; semantic matching).</p></li><li><p><strong>Segment the documents appropriately</strong> before embedding. If each review is already a self-contained unit, use it as-is. If you have longer texts (product FAQs, multi-paragraph feedback, etc.), split them into chunks that preserve context. Aim for chunks that encapsulate one idea or topic &#8211; research suggests around a few hundred tokens is often optimal (<a href="https://arxiv.org/pdf/2406.17526#:~:text=5,Following%20this%2C%20thresholds%203">HERE</a>). You can use a simple strategy like paragraph boundaries or utilize semantic chunking algorithms to decide split points based on content shifts . The LumberChunker results indicate that a well-chosen chunking strategy can substantially boost retrieval metrics . Thus, to maximize accuracy, <strong>err on the side of meaningful chunks</strong> rather than arbitrarily sized ones. This will reduce the chance that relevant information is split and thus not captured in the embedding. (If resources allow, one could even apply an LLM to verify or refine chunk boundaries for critical documents, following the approach of LumberChunker.)</p></li><li><p><strong>Build a high-recall vector index</strong> of the embeddings. For a moderate corpus size, a brute-force search (exact <em>k</em>-nearest-neighbors) on GPU will guarantee the top true matches are found. If the dataset is larger, use a proven ANN method like HNSW or IVFPQ but tune it for very high recall (e.g. &gt; 0.95&#8211;0.99). The goal is that the retrieval step doesn&#8217;t miss a potentially relevant review. Modern systems like FusionANNS demonstrate you can get both speed and accuracy at scale (<a href="https://arxiv.org/abs/2409.16576#:~:text=results%20show%20that%20FusionANNS%20achieves,low%20latency%20and%20high%20accuracy"> FusionANNS: An Efficient CPU/GPU Cooperative Processing Architecture for Billion-scale Approximate Nearest Neighbor Search</a>), so configure the index to prioritize accuracy first. This might mean slightly slower queries, but since our priority is accuracy over speed, that is acceptable. If using a vector database, set the search parameters (efSearch in HNSW, nprobe in IVF, etc.) to high values to favor completeness. In essence, treat speed optimizations as secondary &#8211; ensure the nearest neighbors in embedding space are truly being retrieved.</p></li><li><p><strong>Incorporate a precision-enhancing step</strong> before presenting results. To achieve near-perfect precision (i.e., eliminate false positives), it&#8217;s recommended to apply a similarity score threshold or rerank strategy. For example, one can learn a threshold as in the Cosine Adapter approach: require the cosine similarity to be above a certain dynamic cutoff to consider a result truly similar (<a href="https://arxiv.org/abs/2408.04887#:~:text=embedding,world"> Relevance Filtering for Embedding-based Retrieval</a>). This will filter out items that, while similar, are not similar <em>enough</em> to be useful. Alternatively, perform a lightweight rerank: take the top 50 vectors from the ANN search and rerank them by a more exact metric. The reranker could be a cross-encoder that directly compares review texts, or even a simple similarity of TF-IDF vectors as a sanity check for relevance. The research by Rossi et al. (CIKM 2024) showed that even a calibrated thresholding can yield big precision gains with minimal recall loss , so implementing such a filter is advisable when &#8220;perfect&#8221; accuracy is desired. The result is that the user (or downstream application) sees only those reviews that have very high semantic overlap with the query review.</p></li><li><p><strong>Leverage hardware for scalability</strong>. To meet these accuracy-centric settings in a reasonable time, use GPU or TPU acceleration wherever possible. For example, use FAISS GPU to index and search the embeddings, which can easily handle millions of vectors with sub-second latency. If the application must handle many queries per second, consider a distributed setup or GPU-CPU hybrid solutions (like the FusionANNS approach) to maintain throughput (<a href="https://arxiv.org/abs/2409.16576#:~:text=accuracy%20ANNS%20system%20for%20billion,We"> FusionANNS: An Efficient CPU/GPU Cooperative Processing Architecture for Billion-scale Approximate Nearest Neighbor Search</a>). Essentially, <strong>do not compromise accuracy due to speed</strong>; instead, address speed by adding computational resources or optimizing algorithms. This way, you can maintain the highest recall and precision settings identified above without making the system impractical.</p></li></ul><p>In conclusion, the literature from 2024&#8211;2025 converges on the idea that the path to maximum retrieval accuracy is through <strong>powerful embeddings, intelligent chunking, exhaustive (or very thorough) search, and careful post-processing of results</strong>. A concrete recommended approach for similar customer reviews would be: use a top-tier transformer embedding model (multilingual if needed) to encode each review (or review chunk); index these embeddings in a vector database tuned for high recall; for a given new review (query), retrieve the nearest neighbor reviews in embedding space; then apply a semantic similarity threshold or rerank to select the truly closest matches. This pipeline, informed by the latest research, ensures that if a review exists in the corpus that is semantically almost identical to the query, it will be found and returned as a top result. At the same time, it minimizes the chance of unrelated content sneaking into the results, achieving a high-precision, high-recall outcome. Such a system might incur higher computational cost, but as the question posits, it prioritizes accuracy over speed &#8211; aligning perfectly with the direction of recent advancements in dense retrieval techniques (<a href="https://arxiv.org/abs/2410.19349#:~:text=distribution%20for%20different%20queries%2C%20which,capture%20the%20differences%20between%20head"> pEBR: A Probabilistic Approach to Embedding Based Retrieval</a>). By following these best practices, one can leverage the cutting-edge findings of 2024&#8211;2025 to build a semantic similarity search for customer reviews that is as accurate as currently possible, effectively capturing the true &#8220;voice of the customer&#8221; wherever it appears in the data.</p><p><strong>Sources:</strong> Recent arXiv papers and findings from 2024&#8211;2025 have been cited throughout, including advances in document chunking (<a href="https://arxiv.org/pdf/2406.17526#:~:text=all%20values%20of%20k%2C%20LumberChunker,35">HERE</a>), embedding models (<a href="https://arxiv.org/abs/2402.03216#:~:text=,documents%20of%20up%20to%208192"> BGE M3-Embedding: Multi-Lingual, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation</a>), retrieval optimization , and system-level innovations for retrieval at scale (<a href="https://arxiv.org/abs/2409.16576#:~:text=services,We"> FusionANNS: An Efficient CPU/GPU Cooperative Processing Architecture for Billion-scale Approximate Nearest Neighbor Search</a>). These provide the empirical backbone for the recommendations given.</p>]]></content:encoded></item><item><title><![CDATA[vector search strategies, focusing on clustering and Locality-Sensitive Hashing (LSH) in the context of document digitization and chunking]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/vector-search-strategies-focusing</link><guid isPermaLink="false">https://www.rohan-paul.com/p/vector-search-strategies-focusing</guid><pubDate>Mon, 16 Jun 2025 10:13:20 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!0kRs!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!0kRs!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!0kRs!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png 424w, https://substackcdn.com/image/fetch/$s_!0kRs!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png 848w, https://substackcdn.com/image/fetch/$s_!0kRs!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png 1272w, https://substackcdn.com/image/fetch/$s_!0kRs!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!0kRs!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png" width="1024" height="584" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/e4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:584,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:867763,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166056295?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!0kRs!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png 424w, https://substackcdn.com/image/fetch/$s_!0kRs!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png 848w, https://substackcdn.com/image/fetch/$s_!0kRs!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png 1272w, https://substackcdn.com/image/fetch/$s_!0kRs!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4e4186d-5cfc-4db2-b28e-90c078118231_1024x584.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ul><li><p>vector search strategies, focusing on clustering and Locality-Sensitive Hashing (LSH) in the context of document digitization and chunking</p></li><li><p>Clustering-Based Vector Search (Coarse Partitioning)</p></li><li><p>Locality-Sensitive Hashing (LSH) for Vector Search</p></li><li><p>Performance Comparison and Trade-offs</p></li><li><p>Applications in LLM Pipelines</p></li><li><p>Recent Advances (2024&#8211;2025 Highlights)</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>vector search strategies, focusing on clustering and Locality-Sensitive Hashing (LSH) in the context of document digitization and chunking</strong></h2><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Clustering-Based Vector Search (Coarse Partitioning)</strong></h2><p><strong>Mechanism:</strong> Clustering methods (e.g. k-means) partition the vector space into K clusters and represent each partition by a centroid (<a href="https://arxiv.org/html/2404.11731v1#:~:text=This%20work%20concerns%20ANN%20over,centroids%20make%20up%20the%20index">A Learning-to-Rank Formulation of Clustering-Based Approximate Nearest Neighbor Search</a>). An index stores these centroids, and each data vector is assigned to its nearest centroid. At query time, the search &#8220;routes&#8221; the query to the closest centroids and only examines vectors in those clusters . This <em>inverted file</em> approach (IVF) drastically narrows the search space at the cost of some accuracy (since points in other clusters are ignored). Modern vector databases (FAISS, Milvus, etc.) widely use this strategy due to its strong balance of speed and accuracy (<a href="https://www.pinecone.io/learn/series/faiss/vector-indexes/#:~:text=The%20Inverted%20File%20Index%20,speed">Nearest Neighbor Indexes for Similarity Search | Pinecone</a>).</p><p><strong>Strengths:</strong> Clustering-based indexes are <strong>efficient for large corpora</strong> &#8211; by searching only a few clusters, they achieve sub-linear retrieval time. Search quality remains high by examining multiple top clusters (to avoid border effects): e.g. IVF with <code>nprobe</code> (probes) searches several nearest clusters to catch neighbors near cluster boundaries (<a href="https://www.ai-bites.net/rag-7-indexing-methods-for-vector-dbs-similarity-search/#:~:text=But%20what%20if%20a%20data,one%20as%20shown%20in%20the">RAG&#8202;-&#8202;7 indexing methods for Vector DBs + Similarity search</a>). This often yields high recall (e.g. 90&#8211;95%) with far less work than brute force . Memory overhead is modest &#8211; storing K<em> </em>centroids and a cluster id per vector has negligible cost . Clustering also enables vector compression techniques like <em>product quantization</em> that further speed up distance computations and cut memory by ~95% (with some accuracy loss) (<a href="https://arxiv.org/html/2501.10534v1#:~:text=Product%20quantization%20,of%20quantized%20buckets%20in%20memory">4bit-Quantization in Vector-Embedding for RAG</a>). In practice, <em>k</em>-means (or its variants) is the most advanced ML tool commonly used in ANN indexing (<a href="https://arxiv.org/html/2502.16931v1#:~:text=However%2C%207%20years%20later%2C%20it,capacity%20networks">Machine learning and high dimensional vector search</a>), underscoring its practical importance.</p><p><strong>Weaknesses:</strong> The main cost is the <strong>offline indexing</strong>: running clustering (training the quantizer) on millions of high-dimensional vectors can be expensive . However, this is a one-time or infrequent cost. Also, if the dataset grows or changes significantly, the clusters may need retraining to remain optimal. During queries, an extra step is computing distances to all centroids (e.g. a few thousand) to find the best clusters &#8211; this overhead is usually manageable, but it is an O(K&#8901;d) operation per query. Clustering-based ANN is <em>approximate</em>: if a relevant vector falls outside the searched clusters, it will be missed. Fortunately, choosing a sufficient number of clusters to search (and perhaps hierarchically organizing clusters) can make miss probability very low (<a href="https://www.pinecone.io/learn/series/faiss/vector-indexes/#:~:text=Image%3A%20Search,different%20nprobe%20and%20nlist%20values">Nearest Neighbor Indexes for Similarity Search | Pinecone</a>). Overall, clustering works best when data is static (or periodically indexed in batches) and globally distributed so that meaningful partitions exist.</p><h2><strong>Locality-Sensitive Hashing (LSH) for Vector Search</strong></h2><p><strong>Mechanism:</strong> LSH uses <em>hash functions</em> to map high-dimensional vectors to low-dimensional keys such that similar vectors collide to the same key with high probability (<a href="https://stackoverflow.com/questions/41099138/k-means-versus-lsh-algorithm#:~:text=LSH%20doesn%27t%20cluster%20your%20data">machine learning - k-means versus LSH algorithm - Stack Overflow</a>). For example, random hyperplane LSH uses random projections of the vector; the sign bits form a hash code. Multiple independent hash tables are used to boost recall: each table stores vectors in buckets by their hash, and a query is hashed to retrieve candidate vectors from matching buckets . LSH does not cluster the entire dataset; instead it <strong>partitions implicitly</strong> via hash buckets. It excels at <em>near&#8208;duplicate detection</em>: only points very close to the query are likely to share a hash in at least one table. This makes LSH a natural fit when we care about retrieving items above a similarity threshold (R-nearest neighbors) rather than a globally best ranking .</p><p><strong>Strengths:</strong> LSH indexes are typically <strong>simple and fast to construct</strong> &#8211; no heavy training, just computing hashes for each vector (which is linear in data size) (<a href="https://news.ycombinator.com/item?id=27614381#:~:text=This%20thread%20contains%20many%20excellent,so%20LSH%20is%20unattractive%20there">Introduction to Locality-Sensitive Hashing | Hacker News</a>). New vectors can be indexed on the fly by hashing into each table (dynamic updates are trivial). LSH comes with theoretical guarantees on recall (probabilistic) given enough hash tables and appropriate parameters (<a href="https://vldb.org/2024/files/phd-workshop-papers/vldb_phd_workshop_paper_id_13.pdf#:~:text=Hash,They%20commonly%20utilize%20a%20proximity">Vector Search on Billion-Scale Data Collections</a>) . It&#8217;s memory-cheap per table (storing integer hashes or bucket pointers) and can scale horizontally by splitting tables across servers. Critically, LSH can return results in <em>constant or sub-linear time</em> independent of dataset size if the hash is selective enough &#8211; for instance, in a deduplication application, an ultra-optimized LSH index searched 55 million embeddings in &lt;0.2s (about <strong>10&#215; faster</strong> than brute-force Faiss) . This ability to <em>rapidly cull candidates</em> makes LSH attractive for high-throughput or streaming scenarios where quick filtering is needed.</p><p><strong>Weaknesses:</strong> <strong>Parameter tuning and recall trade-offs</strong> are the Achilles&#8217; heel. High accuracy requires either many hash tables or long hash codes, which increases memory and query time. For example, using Faiss&#8217;s LSH on 128-dimensional data, achieving ~90% recall required a 8192-bit hash (64&#215; the dimension) (<a href="https://www.pinecone.io/learn/series/faiss/vector-indexes/#:~:text=Image%3A%20Recall%20score%20of%20IndexLSH,which%20is%2064128%20%3D%208192">Nearest Neighbor Indexes for Similarity Search | Pinecone</a>) &#8211; an enormous code that undermines LSH&#8217;s efficiency. Generally, <em>good recall = slower search</em> and <em>fast search = worse recall</em> . LSH also struggles as dimensionality grows: the &#8220;curse of dimensionality&#8221; means vectors become hard to separate with short hashes, so performance degrades unless we dramatically increase hash length . Another issue is <strong>false positives and negatives</strong>. Different vectors can collide into the same bucket (needing a distance check to filter false positives), while some true nearest neighbors might never collide with the query in any table (false negative) (<a href="https://stackoverflow.com/questions/41099138/k-means-versus-lsh-algorithm#:~:text=1,and%20hope%20that%20not%20all">machine learning - k-means versus LSH algorithm - Stack Overflow</a>) . Compared to clustering which gives a more structured partitioning, LSH&#8217;s randomized bucketing does not capture data &#8220;structure&#8221; beyond local similarity &#8211; it&#8217;s not effective for finding moderately similar items outside the collision threshold . Moreover, in many modern applications requiring *top-*K semantic similarity (not just exact duplicates), LSH has been outperformed by graph-based and cluster-based methods in both accuracy and speed . In fact, practitioners note that LSH is no longer the de facto ANN solution; it&#8217;s faster to <em>build</em> but often <strong>slower to query</strong> than optimized cluster or graph indexes when high recall is needed .</p><h2><strong>Performance Comparison and Trade-offs</strong></h2><ul><li><p><strong>Indexing Time:</strong> <em>Clustering</em> requires a heavy upfront computation (e.g. k-means on the dataset). This is offline and can be amortized, but for very large corpora it may be costly (<a href="https://arxiv.org/html/2501.10534v1#:~:text=corresponding%20to%20the%20centroid%20it,of%20quantized%20buckets%20in%20memory">4bit-Quantization in Vector-Embedding for RAG</a>). <em>LSH</em> is quick to index &#8211; essentially just computing and storing hashes for each vector, which is typically much faster than clustering (<a href="https://news.ycombinator.com/item?id=27614381#:~:text=This%20thread%20contains%20many%20excellent,so%20LSH%20is%20unattractive%20there">Introduction to Locality-Sensitive Hashing | Hacker News</a>). Recent research even improved LSH indexing further (e.g. <strong>DET-LSH</strong> uses a dynamic tree to cut index build time by up to 6&#215;) (<a href="https://arxiv.org/abs/2406.10938#:~:text=Our%20theoretical%20studies%20show%20that,was%20published%20in%20PVLDB%202024"> DET-LSH: A Locality-Sensitive Hashing Scheme with Dynamic Encoding Tree for Approximate Nearest Neighbor Search</a>). If your pipeline demands minimal indexing latency (e.g. streaming data ingestion), LSH has an edge. For static corpora, an upfront clustering is usually acceptable.</p></li><li><p><strong>Query Speed vs Accuracy:</strong> Clustering offers a <strong>tunable balance</strong>. By increasing the number of clusters searched (<code>nprobe</code>), you increase recall at the cost of checking more points . In practice, IVF can reach ~95% recall with a small fraction of data scanned . LSH has a more binary trade-off &#8211; to raise recall, you must either scan more buckets (more candidates to verify) or add more tables/bits, which slows queries. Empirically, LSH shows a wide performance range depending on parameters and often needs substantially more work to hit the same recall as clustering or other ANN methods . One summary notes: <em>&#8220;LSH [performance] is heavily dependent on parameters: good quality results in slower search, and fast search gives worse quality&#8221;</em> . For high-dimensional text embeddings (hundreds of dims), practitioners often avoid LSH because maintaining high recall would make it impractically slow or memory-heavy .</p></li><li><p><strong>Scalability:</strong> Both methods handle large <em>N</em> (number of vectors) well. Clustering scales by increasing K (number of clusters) &#8211; typically sublinear in <em>N</em> &#8211; and can use multi-level clustering for very large scales. Vector databases have demonstrated IVF on billion-scale datasets with reasonable latency. LSH scales linearly in <em>N</em> for storage (each new vector adds one entry per table), and query time typically grows sublinearly (depends on bucket sizes). However, <em>dimension scaling</em> is different: clustering doesn&#8217;t fundamentally suffer if dimension increases (distance to centroids is still computable; one may even reduce dimension with PCA if needed), whereas LSH requires more bits as dimension grows to avoid random collisions . Thus, for the 512&#8211;1024 dim embeddings common in LLM applications, clustering or graph indices are more space-time efficient.</p><p>clustering or graph indices are more space-time efficient.</p></li><li><p><strong>Memory Footprint:</strong> Clustering wins on memory-efficiency for a given accuracy. Storing a few thousand centroids and cluster assignments is minor , and can even reduce memory if combined with quantization (each vector stored as compact codes relative to centroids). LSH needs multiple hash tables; e.g. 10 tables mean each vector is listed 10 times. If using long bit codes, the hash stored for each vector can be large (e.g. 8192 bits = 1024 bytes) . That can exceed the memory of storing the raw float vector (e.g. 768 dims * 4 bytes = 3072 bytes) if not carefully bounded. In summary, clustering indexes have <strong>small overhead</strong> that grows with K, while LSH memory grows with number of tables and bit-length &#8211; making high-precision LSH indexing more memory-hungry than cluster-based methods .</p></li></ul><p><strong>Bottom line:</strong> For most <strong>LLM document chunk retrieval tasks</strong>, clustering (or related ANN structures) is favored due to its robust accuracy-speed trade-offs. LSH is more niche &#8211; valuable when you need <em>ultra-fast detection of very close matches</em> or a lightweight index build. As the FAISS team noted, classical LSH usually <em>&#8220;performs worse than [quantization-based] PQ in memory vs. accuracy or speed vs. accuracy trade-offs&#8221;</em> (<a href="https://github.com/facebookresearch/faiss/wiki/Comparison-with-LSH#:~:text=Locality%20Sensitive%20Hashing%20,inspired%20%22Fly%20indexing%22%20algorithm">Comparison with LSH &#183; facebookresearch/faiss Wiki &#183; GitHub</a>). Likewise, experts observe that LSH is no longer state-of-the-art for ANN on typical data . That said, LSH remains a powerful tool in the right context and continues to see improvements.</p><h2><strong>Applications in LLM Pipelines</strong></h2><p>Real-world LLM systems often combine these techniques to meet various needs:</p><ul><li><p><strong>Retrieval-Augmented Generation (RAG):</strong> RAG-powered QA systems embed a knowledge corpus into vectors and retrieve relevant chunks to feed the LLM (<a href="https://arxiv.org/html/2406.00029v1#:~:text=Providing%20external%20knowledge%20to%20Large,window%20size%2C%20the%20number%20of">Clustered Retrieved Augmented Generation (CRAG)</a>) . Here, <strong>clustering-based indexes</strong> (or hybrid graph indexes) are commonly used to ensure high recall of semantically relevant passages. For example, vector stores like Milvus default to IVF or HNSW indexes to retrieve top-k similar chunks efficiently. Clustering aligns well with RAG&#8217;s goal of finding broadly relevant information (not just exact matches). LSH, in contrast, might be used in a <em>supplementary role</em> &#8211; for instance, to deduplicate queries or documents (find nearly identical text snippets) or as a first-pass filter when the query is very close to some stored text. Generally, RAG pipelines prioritize recall and semantic relevance, so cluster-based search is the backbone (<a href="https://news.ycombinator.com/item?id=27614381#:~:text=While%20LSH%20is%20mathematically%20beautiful%2C,outperform%20LSH%20on%20most%20datasets">Introduction to Locality-Sensitive Hashing | Hacker News</a>). High-profile implementations (Google&#8217;s dataset search, Databricks Lakehouse etc.) embed data lakes and index them with ANN structures for RAG (<a href="https://arxiv.org/html/2503.01823v1#:~:text=External%20data%20sources%20can%20complement,making%20them%20a%20critical%20component">Cracking Vector Search Indexes</a>) .</p></li></ul><ul><li><p><strong>Enterprise Semantic Search:</strong> Organizations often have massive unstructured document stores. Vector search enables semantic search beyond keyword matching. <strong>Clustered indexes</strong> suit this scenario: content embeddings can be clustered by topic or department, so queries first target the most relevant cluster (topic area) and get results faster. This improves scalability when indexing millions of internal documents. Enterprises also care about <strong>near-duplicate detection</strong> (e.g. find if a document was already stored or flag similar records) &#8211; an area where <strong>LSH is useful</strong>. By hashing new documents&#8217; embeddings, one can quickly spot if an almost identical vector already exists (collides in hash buckets) (<a href="https://stackoverflow.com/questions/41099138/k-means-versus-lsh-algorithm#:~:text=LSH%20doesn%27t%20cluster%20your%20data">machine learning - k-means versus LSH algorithm - Stack Overflow</a>). In practice, enterprise search systems may run a dual approach: use a high-recall ANN index (cluster/graph) for primary search, and an LSH-based index on the side for duplicate detection or speeding up exact match lookups. This combination covers both broad semantic queries and exact redundancy checks.</p></li><li><p><strong>Knowledge Graphs and Databases:</strong> In a <strong>knowledge graph</strong>, each node or subgraph can be embedded as a vector to capture its semantic context. Clustering these embeddings can reveal communities or related entity groups, aiding in knowledge discovery (e.g. grouping similar nodes) (<a href="https://arxiv.org/html/2503.00309v1#:~:text=LLM%20arxiv,similar%20nodes%20and%20the">Meta-Path Guided Retrieval and In-Graph Text for RAG-Equipped LLM</a>). For querying, one might use clustering to restrict a search to a relevant subgraph of the knowledge base. For example, if looking for entities similar to X, only clusters related to X&#8217;s domain are searched, improving efficiency. Meanwhile, LSH can be applied to <strong>find identical or almost-identical entries</strong> in a graph (useful for error checking or merging nodes referring to the same concept). It&#8217;s less suited for finding <em>analogous</em> entities that aren&#8217;t almost duplicates &#8211; those are better served by cosine similarity ranking via ANN. Some pipelines also use vector search to augment graph queries (finding nodes by embedding similarity); here accuracy is key, so clustering or brute-force search tends to be chosen over LSH.</p></li><li><p><strong>Document Digitization &amp; OCR Repositories:</strong> When digitizing large archives into text embeddings, one must manage repetitive content (boilerplate, duplicates) and ensure efficient lookup. <strong>LSH is effective for de-duplication at scale</strong>, as demonstrated by Nosible&#8217;s news pipeline where millions of news embeddings are hashed and near-duplicates found in sub-second time (<a href="https://nosible.ghost.io/using-vector-search-to-see-signals-in-company-news/#:~:text=De,using%20the%20top%20K%20nearest">Using Vector Search to See Signals in Company News</a>). This helps eliminate redundant chunks and keep the knowledge base clean. On the other hand, to serve an LLM&#8217;s queries on this archive, a <strong>clustered vector index</strong> would allow semantic searches (&#8220;find relevant info about X across the archive&#8221;) with speed. Clustering could also help <strong>organize chunks by similarity</strong> &#8211; for instance, grouping paragraphs by topic or source, which could feed into downstream tasks like batching for summarization or caching frequently used clusters. In sum, digitization pipelines often use LSH as a filtering tool and clustering-based search for broad information retrieval.</p></li></ul><h2><strong>Recent Advances (2024&#8211;2025 Highlights)</strong></h2><ul><li><p><strong>Learning-Optimized Clustering:</strong> A notable trend is using learning to improve cluster-based ANN. Traditional IVF relies on static centroids (often from unsupervised <em>k</em>-means). <strong>Zhang </strong><em><strong>et al</strong></em><strong>. (SIGIR 2024)</strong> reframed the cluster selection step as a learning-to-rank problem: given training queries, they learn a better &#8220;routing&#8221; function that ranks clusters by likelihood of containing the true nearest neighbors (<a href="https://arxiv.org/html/2404.11731v1#:~:text=process%20known%20as%20routing%E2%80%94then%20performs,based">A Learning-to-Rank Formulation of Clustering-Based Approximate Nearest Neighbor Search</a>) . By optimizing this function (even as a simple linear model), they achieved consistently higher recall in clustering-based MIPS (Maximum Inner Product Search) without slowing queries . This kind of learned indexing can benefit LLM applications &#8211; e.g. if certain topics or query patterns are common, the index can learn to route those more accurately. It augments the static clustering with a dynamic ranking layer, narrowing the gap between IVF and exact search.</p></li><li><p><strong>Next-Gen LSH Algorithms:</strong> LSH research is active in pursuing better speed/accuracy. <strong>DET-LSH (PVLDB 2024)</strong> introduced a dynamic encoding tree structure (DE-Tree) for indexing, instead of brute-force multi-dimensional partitioning. This made index build much faster and also supports efficient range queries (<a href="https://arxiv.org/abs/2406.10938#:~:text=approximate%20nearest%20neighbor%20,based%20tree%20called%20Dynamic"> DET-LSH: A Locality-Sensitive Hashing Scheme with Dynamic Encoding Tree for Approximate Nearest Neighbor Search</a>). DET-LSH&#8217;s query strategy uses multiple independent DE-Trees (like parallel hash tables) to reduce the chance of missing true neighbors, improving recall. Experiments showed it outperformed prior LSH variants in both accuracy and speed, with <strong>~2&#215; query speedup</strong> over state-of-art LSH methods at the same accuracy level . This is important for keeping LSH competitive in ANN tasks. Another avenue is <strong>learnable hashing</strong> &#8211; instead of random projections, use neural networks or data-driven functions to produce the hash codes. These can capture data distribution better than random LSH, effectively bringing LSH closer to clustering in adaptability. Early 2024 work on <em>learned LSH</em> (e.g. using autoencoders or trained transformations) reported improved recall at fixed code lengths (<a href="https://medium.com/@gopikwork/latency-optimized-embedding-retrieval-with-learnable-lsh-and-quantization-9deaa025e0d3#:~:text=Latency%20optimized%20embedding%20retrieval%20with,quantization%E2%80%94an%20optimized%20approach%20for">Latency optimized embedding retrieval with Learnable LSH and ...</a>), though at the cost of some training time. While not yet mainstream, such techniques could make LSH more viable for semantic search by tailoring hashes to content.</p></li><li><p><strong>Hybrid Indexing Strategies:</strong> Recent systems often combine multiple methods to exploit their strengths. For example, <strong>ELPIS (VLDB 2024)</strong> mixes graph and tree-based indexing &#8211; it performs a multi-level cluster partitioning and then links cluster centroids via a proximity graph for refined searching (<a href="https://vldb.org/2024/files/phd-workshop-papers/vldb_phd_workshop_paper_id_13.pdf#:~:text=Graph,27">Vector Search on Billion-Scale Data Collections</a>) . This yields better search performance than either alone. In practice, a vector search service might use a coarse clustering to divide data by topic, then use a <strong>HNSW graph</strong> or <strong>exact search</strong> within a cluster for final retrieval. Hybrid approaches also include using LSH as a pre-filter for a slower exact method: e.g., first hash to get a candidate pool then compute true distances on those. Meanwhile, to tackle the overhead of <em>multi-vector representations</em> (where each document yields many embeddings), a 2024 study proposed clustering at the token/vector level to pool vectors, drastically cutting index size while preserving search accuracy (<a href="https://arxiv.org/pdf/2409.14683#:~:text=,need%20to%20be%20stored"> Reducing the Footprint of Multi-Vector Retrieval with Minimal ... - arXiv</a>). This is highly relevant for LLM contexts where each document may produce dozens of chunk vectors &#8211; clustering similar ones can reduce redundancy. Overall, the 2024&#8211;2025 direction is toward <strong>composing ANN techniques</strong> and optimizing every stage, rather than one-size-fits-all.</p></li><li><p><strong>Applications and Novel Uses:</strong> Researchers are also applying these methods in innovative ways for LLM systems. For instance, <strong>Cluster-RAG (Akesson &amp; Santos, 2024)</strong> combined clustering with summarization: they clustered document embeddings (product reviews) and summarized each cluster, feeding the compact summaries to the LLM instead of raw chunks (<a href="https://arxiv.org/html/2406.00029v1#:~:text=normally%20constitutes%20RAG%2C%20including%20three,review%20that%20has%20the%20main">Clustered Retrieved Augmented Generation (CRAG)</a>) . This reduced prompt size by 50&#8211;90% with minimal answer quality loss . On the LSH side, an intriguing 2024 result is MagicPIG by Nolte <em>et al</em>. (arXiv 2024), which applied LSH in the <em>LLM&#8217;s attention mechanism</em> to approximate nearest neighbor queries among tokens for faster generation (<a href="https://arxiv.org/pdf/2410.16179#:~:text=,hash%20functions%20on%20GPU"> MagicPIG: LSH Sampling for Efficient LLM Generation - arXiv</a>). By hashing query and key vectors in the transformer, they accelerated attention computation without much loss, effectively using LSH to sparsify attention. While this is inside the model rather than in retrieval, it shows LSH&#8217;s principle of grouping similar items is being leveraged to scale up LLMs themselves. In enterprise settings, the integration of vector search with traditional databases and knowledge graphs is being refined &#8211; e.g. using <strong>meta-path guided retrieval</strong> where node embeddings in a knowledge graph are indexed for semantic search, combined with symbolic filters (<a href="https://arxiv.org/html/2503.00309v1#:~:text=LLM%20arxiv,similar%20nodes%20and%20the">Meta-Path Guided Retrieval and In-Graph Text for RAG-Equipped LLM</a>). Such pipelines may use clustering to partition the graph embeddings by type or community, then apply vector search for relevant nodes, demonstrating cross-over between ANN indexing and graph query optimization.</p></li></ul><p><strong>Conclusion:</strong> Clustering-based search and LSH offer complementary strengths for vector retrieval in LLM applications. Clustering (IVF and its variants) provides a reliable, scalable solution for semantic search across large, diverse document collections, delivering high accuracy with reasonable efficiency. LSH, while no longer the general ANN workhorse, remains extremely useful for specific tasks like high-speed duplicate detection, thresholded similarity search, and scenarios demanding minimal indexing time. Many real-world systems blend these approaches &#8211; using clustering or graphs for broad recall and LSH for niche optimizations &#8211; to meet the demanding efficiency needs of retrieval-augmented LLMs. Ongoing research from 2024&#8211;2025 continues to refine both strategies, making vector search faster and smarter (through learned models and hybrids). The result is an expanding toolkit that practitioners can apply based on the requirements: clustering for structured semantic retrieval, LSH for lightning-fast lookup of near-identical items, or even both together for maximum performance in LLM-based pipelines.</p>]]></content:encoded></item><item><title><![CDATA[Random Projection Index (RPI) for Document Digitization in LLM Pipelines 2024-2025 Review]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/random-projection-index-rpi-for-document</link><guid isPermaLink="false">https://www.rohan-paul.com/p/random-projection-index-rpi-for-document</guid><pubDate>Mon, 16 Jun 2025 10:06:41 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!7SE7!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!7SE7!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!7SE7!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png 424w, https://substackcdn.com/image/fetch/$s_!7SE7!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png 848w, https://substackcdn.com/image/fetch/$s_!7SE7!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png 1272w, https://substackcdn.com/image/fetch/$s_!7SE7!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!7SE7!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png" width="1024" height="572" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:572,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:975192,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166056112?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!7SE7!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png 424w, https://substackcdn.com/image/fetch/$s_!7SE7!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png 848w, https://substackcdn.com/image/fetch/$s_!7SE7!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png 1272w, https://substackcdn.com/image/fetch/$s_!7SE7!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7d18563a-e303-4bd3-a9c8-75ac0e77f607_1024x572.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><ul><li><p>Random Projection Index (RPI) for Document Digitization in LLM Pipelines 2024-2025 Review</p></li><li><p>Efficiency of RPI for Large-Scale Document Indexing</p></li><li><p>Retrieval Accuracy vs. LSH, k-d Trees, and Other Methods</p></li><li><p>Implementation Frameworks and Tools (2024-2025)</p></li><li><p>Application in LLM Chunking and Retrieval Pipelines</p></li><li><p>Benchmarks and Comparative Performance (2024-2025)</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Efficiency of RPI for Large-Scale Document Indexing</strong></h2><p>Random Projection Indexing (RPI) uses random linear projections to reduce vector dimensionality while approximately preserving pairwise distances (<a href="https://arxiv.org/html/2502.05575v1#:~:text=Summarization%20Techniques%20Random%20projections%20project,2011%29%20divides%20the%20vector">Graph-Based Vector Search: An Experimental Evaluation of the State-of-the-Art</a>). This forms the basis of <em>random projection trees</em> (e.g. used by Spotify&#8217;s Annoy library) which partition data with random hyperplane splits (<a href="https://arxiv.org/html/2410.09662v1#:~:text=match%20at%20L415%20ANNOY%20,the%20current%20nearest%20data%20point">Exploring Demonstration Retrievers in RAG for Coding Tasks: Yeas and Nays!</a>). Each additional random tree or projection increases search coverage, enabling sublinear query time. In practice, an RPI forest yields roughly logarithmic query complexity per tree (<a href="https://arxiv.org/pdf/2412.01555#:~:text=Annoys%20indexing%20mechanism%20is%20based,data%3B%20thus%2C%20it%20is%20more">HERE</a>). Unlike classic k-d trees (which degrade in high dimensions due to the &#8220;curse of dimensionality&#8221;), random projection trees maintain efficiency even for very high-dimensional embeddings . This makes RPI suitable for indexing millions of document chunks without exhaustive scans.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p>Memory overhead for RPI is also low: Annoy stores indexes as memory-mapped binary files, keeping RAM usage minimal . This lightweight footprint allows deployment at scale &#8211; for example, Spotify successfully applied Annoy on enormous recommendation datasets in real time . In large document digitization tasks, RPI can thus handle vast embedding collections efficiently, trading small accuracy losses for significant speed gains. By tuning index parameters (e.g. number of trees or projections), one can balance precision vs. speed: more trees improve recall at the cost of higher query latency . Studies show that as tree count grows, accuracy increases albeit with diminishing returns and added lookup time . Still, in high-throughput scenarios RPI methods remain competitive &#8211; at fixed low query latency they have even outperformed graph-based indexes in certain benchmarks . Overall, RPI scales well: it confines search to a reduced subset of vectors, yielding fast (often millisecond-level) query times even as the corpus size grows into millions.</p><p>LSH (Locality-Sensitive Hashing) offers a complementary random-projection approach to efficiency. Like RPI, LSH uses random projections (e.g. random hyperplanes) to hash vectors so that similar items fall in the same bucket (<a href="https://www.pinecone.io/learn/series/faiss/locality-sensitive-hashing-random-projection/#:~:text=This%20article%20will%20focus%20on,popular%20libraries%20such%20as%20Faiss">Random Projection for Locality Sensitive Hashing | Pinecone</a>). Querying then only probes a few buckets instead of the entire set. LSH can drastically accelerate searches, but may require multiple hash tables or longer binary codes to reach high recall. In RAG pipelines with large knowledge bases, using approximate indexes (RPI trees or LSH hashes) <strong>&#8220;significantly&#8221;</strong> speeds up retrieval compared to brute-force, by limiting search to a smaller subset of candidates . In summary, RPI-based indexing is highly scalable and efficient for large document stores, achieving sub-linear query scaling and low memory usage, in contrast to brute-force or naive tree methods which become infeasible as data grows.</p><h2><strong>Retrieval Accuracy vs. LSH, k-d Trees, and Other Methods</strong></h2><p>RPI methods provide <em>approximate</em> nearest neighbor search. There is a trade-off: slightly reduced retrieval accuracy in exchange for efficiency. In practice, this accuracy loss is modest. RPI (Annoy) can retrieve high-quality neighbors when using enough projections/trees, often coming close to exact methods. Empirical evaluations indicate Annoy yields strong recall for moderate search depth, though it may miss some neighbors when striving for extremely high recall (<a href="https://arxiv.org/pdf/2412.01555#:~:text=accuracy%2C%20but%20with%20added%20query,based%20approaches%20like%20HNSW">HERE</a>). For example, Annoy excels at mid-range recall targets (where speed is paramount), but for <em>very</em> high recall (finding virtually all true nearest neighbors) graph-based indexes like HNSW outperform it . HNSW builds a small-world graph and typically achieves superior recall at the cost of large memory usage and longer build times . In contrast, k-d trees maintain <em>exact</em> accuracy in low dimensions, but in high-dimensional document embeddings they deteriorate &#8211; needing backtracking or large linear scans to avoid errors . RPI avoids this pitfall by splitting on random directions rather than axis-aligned coordinates, which is why Annoy &#8220;does rather well for high-dimensional data&#8221; whereas traditional k-d trees fail .</p><p>Compared to hashing techniques, RPI often achieves comparable or better accuracy for a given speed. LSH has theoretical guarantees of grouping close vectors, but in practice it might require very long hash codes (or many hash tables) to reach the recall of tree or graph methods. Recent studies on LLM retrieval show all these ANN methods achieve near state-of-the-art effectiveness. For instance, in a 2024 benchmark for code retrieval, a tree-based Annoy index attained essentially the same recall/quality metrics as a graph index (HNSW) &#8211; differences in downstream Rouge scores were under 0.001 absolute. LSH in that setting had slightly lower recall, leading to a marginally higher output drop (e.g. ~4.6% vs ~2% with Annoy/HNSW). Overall, the performance gap between RPI and alternatives is small when each is properly tuned. Modern ANN benchmarks find Annoy to be <em>&#8220;a competitive ANN approach&#8221;</em>, with strengths in query speed at lower recall thresholds and only minor limitations for the highest-precision searches (<a href="https://arxiv.org/html/2410.09662v1#:~:text=ANNOY%20,the%20current%20nearest%20data%20point">Exploring Demonstration Retrievers in RAG for Coding Tasks: Yeas and Nays!</a>). In sum, RPI delivers high accuracy for approximate search &#8211; typically with only negligible degradation in retrieved content relevance, especially once integrated into LLM generation where slight recall loss often does not noticeably affect final answer quality .</p><h2><strong>Implementation Frameworks and Tools (2024-2025)</strong></h2><p>In practice, RPI is implemented through widely used libraries and vector database systems. A prime example is <strong>Annoy (Approximate Nearest Neighbors Oh Yeah)</strong> by Spotify, which constructs a forest of random projection trees for fast ANN search . Annoy&#8217;s implementation is lightweight (written in C++ with Python bindings) and optimized for minimal memory use, as it stores vectors and tree nodes in mapped files (<a href="https://arxiv.org/pdf/2412.01555#:~:text=systems%20and%20clustering%20,Annoy%20does%20really%20well%20for">HERE</a>). It allows tuning parameters like number of trees and search depth, making it a practical choice to trade accuracy for speed as needed . Annoy has seen extensive adoption in industry for recommendation and search systems, demonstrating its reliability at scale .</p><p>Beyond Annoy, many vector search frameworks available in 2024&#8211;2025 support random-projection-based indexing. Faiss (Facebook AI Similarity Search) is a popular library that offers multiple index types &#8211; including flat (exact), IVF (inverted file), PQ (product quantization), HNSW graphs, and also LSH based on random hyperplanes (<a href="https://www.pinecone.io/learn/series/faiss/locality-sensitive-hashing-random-projection/#:~:text=This%20article%20will%20focus%20on,popular%20libraries%20such%20as%20Faiss">Random Projection for Locality Sensitive Hashing | Pinecone</a>). Faiss can leverage GPUs to index billion-scale datasets efficiently . Milvus (an open-source vector database) and <strong>Weaviate/Pinecone</strong> (cloud vector DB services) similarly provide indexing options like IVF, PQ, and HNSW, but some also allow LSH or other random projection schemes for certain use cases. For instance, Pinecone&#8217;s documentation discusses using random projection LSH for hashing vectors , and the Vector Database survey categorizes &#8220;randomization-based partitioning&#8221; (which includes random projection trees and LSH) as a core indexing strategy in modern VDBMSs (<a href="https://arxiv.org/pdf/2310.14021#:~:text=are%20now%20well%20understood%3B%20for,operators%20for%20hybrid%20queries%2C%20as"> Survey of Vector Database Management Systems</a>). Recent systems often combine techniques: e.g. FLANN (Fast Library for ANN) mixes random projections with PCA tree splits , and some learned indexes use <em>trained</em> projections for better accuracy.</p><p>In LLM applications, higher-level frameworks abstract these indexes. Tools like <strong>LlamaIndex (GPT Index)</strong> and LangChain allow developers to build retrieval-augmented pipelines using a chosen ANN backend (Faiss, Milvus, etc.) under the hood (<a href="https://arxiv.org/html/2407.13193v1#:~:text=as%20retrievals%20are%20used%20as,Liu%2C%202022%29%2C%20etc">Retrieval-Augmented Generation for Natural Language Processing: A Survey</a>). These frameworks in 2024 commonly support Annoy and Faiss-LSH as plug-and-play indexing options, reflecting their practicality. The ecosystem is rich &#8211; as of 2024, over 20 specialized vector databases exist , each balancing different index designs. But RPI-based approaches remain well-represented due to their simplicity and effectiveness. In summary, practitioners have many robust tools to implement RPI, from standalone libraries (Annoy, Faiss) to integrated vector DB platforms (Milvus, Pinecone), all benefiting from continued research and engineering improvements in 2024&#8211;2025.</p><h2><strong>Application in LLM Chunking and Retrieval Pipelines</strong></h2><p>When digitizing large documents for LLM consumption, a common pipeline is: <strong>chunking &#8594; embedding &#8594; indexing &#8594; retrieval</strong>. Documents are split into <em>semantic chunks</em> (each a few sentences or a paragraph) to ensure each chunk is self-contained and fits the model&#8217;s context window . These chunks (text passages) are then converted into high-dimensional embeddings via a language model encoder. RPI comes into play at the <strong>indexing and retrieval</strong> stages: the collection of chunk embeddings is organized in an ANN index (such as a random projection forest or LSH tables) to allow fast similarity search . The goal is to quickly retrieve the chunks most relevant to a given query or user prompt.</p><p>In an LLM-augmented question-answering scenario, for example, each chunk&#8217;s embedding is stored as a key in a vector index, mapping to the chunk&#8217;s content (or an identifier) as the value (<a href="https://arxiv.org/html/2407.13193v1#:~:text=values.%20For%20example%2C%20for%20question,Liu%2C%202022%29%2C%20etc">Retrieval-Augmented Generation for Natural Language Processing: A Survey</a>). At query time, the query is embedded and the index is probed for nearest neighbors &#8211; effectively finding which chunks are semantically closest to the query. Using RPI for this nearest-neighbor search dramatically speeds up retrieval of relevant chunks from a large corpus, ensuring that the LLM can be provided with supporting context with minimal latency. The RPI index narrows down candidate chunks to only those in the same projected vicinity as the query, instead of scanning every chunk. This is crucial in real-world LLM applications (chatbots, search assistants, etc.) where the knowledge base can contain hundreds of thousands of chunks &#8211; an exact search would be too slow. Researchers highlight that the retriever must strike a balance between <em>effectiveness</em> and <em>efficiency</em>, especially as the knowledge corpus grows (<a href="https://arxiv.org/html/2410.09662v1#:~:text=Semantic%20Search,more%20pronounced%2C%20with%20approximate%20dense">Exploring Demonstration Retrievers in RAG for Coding Tasks: Yeas and Nays!</a>) . RPI-based ANN indexes achieve this balance by maintaining high recall of relevant chunks while keeping lookup times small. In fact, using approximate indexes (like Annoy or LSH) in a Retrieval-Augmented Generation (RAG) pipeline can <strong>speed up retrieval by orders of magnitude with negligible impact on the LLM&#8217;s answer quality</strong> . After retrieval, the top-k chunks are fed into the LLM&#8217;s context (prompt), allowing it to generate informed answers or continue the conversation using the retrieved knowledge.</p><p>In summary, RPI is applied in LLM pipelines to efficiently index and fetch document chunks. It enables the system to handle large digital libraries and still meet real-time response needs. The chunking ensures each indexed unit is manageable in size, and RPI ensures that even with millions of such units, the relevant ones can be found in milliseconds to augment the LLM&#8217;s input.</p><h2><strong>Benchmarks and Comparative Performance (2024-2025)</strong></h2><p>Recent studies in 2024&#8211;2025 have evaluated RPI against alternative ANN methods on both synthetic benchmarks and real-world tasks. <strong>General ANN benchmarks</strong> (e.g. ANN-Benchmarks and follow-up studies) show that graph-based methods like HNSW typically offer the best recall-vs-latency tradeoff, but tree-based (RPI) and hash-based (LSH) methods remain competitive and can outperform graphs under certain conditions (<a href="https://arxiv.org/pdf/2412.01555#:~:text=accuracy%2C%20but%20with%20added%20query,based%20approaches%20like%20HNSW">HERE</a>). A 2021 analysis by Aum&#252;ller et al. (cited in a 2024 study) found that Annoy&#8217;s performance is strong when the intrinsic dimensionality of data is low-to-moderate, sometimes even yielding higher query throughput than HNSW for the same recall level . This aligns with the observation that RPI excels at &#8220;lower recall thresholds&#8221; where it can finish searches faster, whereas HNSW shines when pushing for near-exact recall .</p><p>On industry-relevant datasets, the differences are small. A 2024 benchmark of Faiss vs Annoy on an image dataset reported both indexing techniques achieved &gt;97% top-10 recall, with Faiss (using HNSW or IVF) slightly ahead in recall but Annoy using far less memory . Faiss&#8217;s GPU-accelerated index built faster, whereas Annoy&#8217;s CPU-based index was easier to update incrementally. Such trade-offs mean the &#8220;best&#8221; method can depend on context (dataset size, update frequency, hardware constraints). The <strong>Retrieval-Augmented Generation</strong> experiments for coding tasks (Ye et al., 2024) provide a concrete example in the LLM context. There, using BM25 (exact lexical search) on a large code corpus was very slow, so approximate dense retrievers were needed (<a href="https://arxiv.org/html/2410.09662v1#:~:text=Semantic%20Search,more%20pronounced%2C%20with%20approximate%20dense">Exploring Demonstration Retrievers in RAG for Coding Tasks: Yeas and Nays!</a>). They compared Annoy (RPI trees), LSH, and HNSW: all three yielded dramatic speedups &#8211; queries took ~5&#8211;6ms with ANN vs over 200ms with BM25 (a ~40&#215; improvement). Importantly, the quality of the LLM&#8217;s output (e.g. code generation accuracy) barely changed. Annoy and HNSW showed only ~2% degradation in metrics like ROUGE or METEOR, while LSH was within ~0.5&#8211;4% depending on the task. The authors note these drops are negligible given the efficiency gains , a conclusion echoed by other RAG studies. In essence, benchmarks confirm that RPI offers an excellent efficiency-accuracy balance: it massively accelerates retrieval with only a minor impact on accuracy, one that is often offset by the gains (faster responses, ability to scale to more data, etc.).</p><p>To summarize the benchmark findings: RPI (Annoy) is a strong all-around contender for document embedding search. It scales to large datasets with minimal memory, provides adjustable performance via its tree count and search parameters, and delivers accuracy on par with other ANN methods for most practical purposes. While specialized methods like HNSW can edge it out in recall when memory and build time are no object, the difference in 2024-era systems is small. For LLM-centric document retrieval, recent evaluations show RPI-based indexing meets the needs of speed and quality, enabling responsive and knowledgeable LLM applications .</p><p><strong>Sources:</strong></p><ul><li><p>Johnson &amp; Lindenstrauss (1984) principle via Echihabi et al. (2019) &#8211; distance preservation in random projections (<a href="https://arxiv.org/html/2502.05575v1#:~:text=Summarization%20Techniques%20Random%20projections%20project,2011%29%20divides%20the%20vector">Graph-Based Vector Search: An Experimental Evaluation of the State-of-the-Art</a>)</p></li><li><p>Pan et al. (2024) &#8211; Vector DB survey (randomized partitioning, tree indexes like Annoy) (<a href="https://arxiv.org/pdf/2310.14021#:~:text=High,trees%20are%20summarized%20in%20Table%C2%A04"> Survey of Vector Database Management Systems</a>)</p></li><li><p>Elayan et al. (2024) &#8211; Faiss vs Annoy benchmark (Annoy&#8217;s design and trade-offs) (<a href="https://arxiv.org/pdf/2412.01555#:~:text=Annoys%20indexing%20mechanism%20is%20based,data%3B%20thus%2C%20it%20is%20more">HERE</a>)</p></li><li><p>Wu et al. (2024) &#8211; RAG Survey (ANN indexing in retrievers, e.g. IVFPQ, HNSW, Annoy) (<a href="https://arxiv.org/html/2407.13193v1#:~:text=Tree,hyperplanes%20for%20efficient%20ANN%20search">Retrieval-Augmented Generation for Natural Language Processing: A Survey</a>)</p></li><li><p>Ye et al. (2024) &#8211; RAG for coding (Annoy/LSH/HNSW vs BM25 results)</p></li><li><p>Pinecone &amp; CodeSmith blogs (2023) &#8211; Explanations of LSH and RP indexing (<a href="https://www.pinecone.io/learn/series/faiss/locality-sensitive-hashing-random-projection/#:~:text=This%20article%20will%20focus%20on,popular%20libraries%20such%20as%20Faiss">Random Projection for Locality Sensitive Hashing | Pinecone</a>) (for conceptual clarity).</p></li></ul>]]></content:encoded></item><item><title><![CDATA[Product quantization PQ indexing method]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/product-quantization-pq-indexing</link><guid isPermaLink="false">https://www.rohan-paul.com/p/product-quantization-pq-indexing</guid><pubDate>Mon, 16 Jun 2025 10:02:37 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!t6qs!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!t6qs!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!t6qs!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png 424w, https://substackcdn.com/image/fetch/$s_!t6qs!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png 848w, https://substackcdn.com/image/fetch/$s_!t6qs!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png 1272w, https://substackcdn.com/image/fetch/$s_!t6qs!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!t6qs!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png" width="1024" height="508" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:508,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:941657,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166055991?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!t6qs!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png 424w, https://substackcdn.com/image/fetch/$s_!t6qs!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png 848w, https://substackcdn.com/image/fetch/$s_!t6qs!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png 1272w, https://substackcdn.com/image/fetch/$s_!t6qs!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c547de5-f00f-4b08-88af-76f2948025f3_1024x508.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><p><strong>Table of Contents</strong></p><ul><li><p>Product quantization PQ indexing method</p></li><li><p>Introduction</p></li><li><p>PQ Indexing Implementation and Trade-offs</p></li><li><p>Advancements in PQ Variants (2024-2025)</p></li><li><p>PQ vs. HNSW and IVF for LLM Retrieval</p></li><li><p>Benchmarks and Recent Results (2024-2025)</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Introduction</strong></h2><p>Vector search is a key component of Retrieval-Augmented Generation (RAG) systems for LLMs, enabling efficient lookup of relevant document embeddings. As these systems scale to millions or billions of high-dimensional embeddings (often 512&#8211;1536 dimensions), memory and speed become critical concerns. <em>Product Quantization (PQ)</em> is a common compression-based indexing technique that addresses this by storing vectors in a compact coded form (<a href="https://arxiv.org/html/2501.10534v1#:~:text=Product%20quantization%20,centroid%20information%20of%20quantized%20buckets">4bit-Quantization in Vector-Embedding for RAG</a>). In essence, PQ trades off a small amount of accuracy for major gains in memory footprint and search speed, making it attractive for large-scale LLM document retrieval (<a href="https://developer.nvidia.com/blog/accelerating-vector-search-nvidia-cuvs-ivf-pq-deep-dive-part-1/#:~:text=Building%20on%20these%20ideas%2C%20this,second%20part%20of%20this%20post">Accelerating Vector Search: NVIDIA cuVS IVF-PQ Part 1, Deep Dive | NVIDIA Technical Blog</a>). In the following, we review how PQ indexing works and its trade-offs, recent PQ variant advancements (OPQ, residual PQ, and 2024&#8211;2025 innovations), and compare PQ-based indexes with other popular vector search methods like HNSW and IVF in the context of LLM retrieval. We also highlight benchmarks from the latest research to quantify these trade-offs.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>PQ Indexing Implementation and Trade-offs</strong></h2><p><strong>How PQ Works:</strong> Product quantization compresses high-dimensional vectors by splitting each vector into multiple low-dimensional sub-vectors and quantizing each sub-vector independently . For each sub-vector (e.g. a 16-dimensional slice of a 768-D embedding), a codebook of <em>K</em> cluster centroids is pre-trained (usually via k-means on a sample of data). Each sub-vector is then replaced by the ID of its nearest centroid. Concatenating these centroid IDs yields a compact code for the full vector. For example, using <em>M</em> sub-vectors with <em>K</em>=256 (1 byte per sub-vector) compresses a 768-D float vector (&#8764;3KB) down to <em>M</em> bytes &#8211; often a 95%+ size reduction . The centroids for each sub-space (the codebooks) are stored in memory to enable distance computations. At query time, a search uses the PQ codes to compute approximate distances &#8211; typically via <em>asymmetric distance computation (ADC)</em>, where the query&#8217;s sub-vectors are compared to each code&#8217;s stored centroids.</p><p><strong>Trade-offs:</strong> PQ dramatically reduces memory and increases cache-friendliness of search at the cost of some accuracy. It is a lossy compression &#8211; finer quantization (more sub-vectors or larger codebooks) preserves more accuracy but uses longer codes, whereas aggressive compression (fewer or smaller codebooks) saves memory but incurs quantization error (<a href="https://arxiv.org/html/2501.10534v1#:~:text=corresponding%20to%20the%20centroid%20it,of%20quantized%20buckets%20in%20memory">4bit-Quantization in Vector-Embedding for RAG</a>). In practice, this means there is a tunable balance between index size and recall. For instance, one study found compressing 100k 1536-D embeddings with a strong PQ setting (32 sub-vectors, 256 centroids each) yielded an extremely compact index but retrieved less than 10% of the true top-10 neighbors compared to the original exact vectors . Because PQ encodes vectors approximately, the nearest neighbor search becomes approximate &#8211; a high-recall setting may require scanning more candidates or using hybrid re-ranking (which adds latency). Additionally, building a PQ index has upfront cost: clustering each sub-space (often via k-means) can be computationally expensive for very large corpora, and the training needs to capture the data distribution well to avoid severe accuracy loss . Another implementation consideration is that PQ alone does <em>not</em> accelerate coarse candidate selection &#8211; it usually is combined with other indexing (like IVF) to avoid comparing a query with <em>every</em> vector&#8217;s code. Nonetheless, once candidates are chosen, distance calculations on compact codes are very fast and memory-light. In summary, PQ indexing&#8217;s main appeal is <strong>memory efficiency</strong> (storing compact codes instead of full vectors) and improved search speed on large datasets, at the expense of some retrieval accuracy and added index training complexity (<a href="https://developer.nvidia.com/blog/accelerating-vector-search-nvidia-cuvs-ivf-pq-deep-dive-part-1/#:~:text=Building%20on%20these%20ideas%2C%20this,second%20part%20of%20this%20post">Accelerating Vector Search: NVIDIA cuVS IVF-PQ Part 1, Deep Dive | NVIDIA Technical Blog</a>).</p><h2><strong>Advancements in PQ Variants (2024-2025)</strong></h2><p>Over the years, many PQ variants have been proposed to improve quantization accuracy or adapt to new scenarios. We highlight a few important ones, including recent methods from 2024&#8211;2025:</p><ul><li><p><strong>Optimized Product Quantization (OPQ):</strong> OPQ augments the basic PQ by learning an optimal rotation (linear transform) of the vector space before quantization (<a href="https://www.analyticsvidhya.com/blog/2024/07/indexing-algorithms-in-vector-databases/#:~:text=It%20is%20a%20variation%20of,loss%20and%20enhances%20code%20discriminability">A Detailed Guide on Indexing Algorithms in Vector Databases</a>). By rotating axes, OPQ can better align variance across sub-vectors, which minimizes distortion. This results in less information loss and more &#8220;discriminative&#8221; codes than standard PQ for the same code length . OPQ is an offline preprocessing step (the rotation matrix is learned from training data) and is widely used (e.g. in Facebook FAISS) to boost PQ accuracy without changing the runtime or code length. It&#8217;s particularly effective when certain dimensions are correlated or have different scales &#8211; the rotation spreads information more evenly so that each sub-quantizer captures important variance.</p></li><li><p><strong>Residual and Additive Quantization (RQ, AQ):</strong> Instead of quantizing sub-vectors independently, <em>residual quantization (RQ)</em> quantizes the vector in a multi-stage iterative process. The first codebook quantizes the original vector, then a second codebook quantizes the <em>residual error</em> (difference between the original and first reconstruction), and so on (<a href="https://arxiv.org/pdf/2401.14732#:~:text=accuracy%2C%20multi,that%20constructs%20specialized%20codebooks%20per">HERE</a>). By encoding residuals, RQ typically achieves higher fidelity than one-shot PQ for the same code size, since later codebooks correct the errors of earlier ones. However, classic RQ uses fixed codebooks per stage, not adapting to earlier quantization choices , which can limit its efficiency. <em>Additive quantization (AQ)</em> is a related approach where the final vector approximation is a <em>sum</em> of multiple codewords (from multiple codebooks) rather than a concatenation of sub-vector codewords. AQ and RQ can achieve very high accuracy, but training them is more complex (greedy or joint optimization) and search is slower (multiple codewords to decode per vector). In practice, researchers sometimes combine PQ and RQ: for example, dividing the vector into blocks and applying RQ within each block (sometimes called <em>residual product quantization</em>) . This hybrid yields a balance between parallelism and accuracy &#8211; a 2015 study introduced this idea, and it was revisited in recent work . For instance, Niu <em>et al.</em> (2023) propose <strong>Residual Vector Product Quantization (RVPQ)</strong>, which slices the vector into sub-parts like PQ and then quantizes each part&#8217;s residuals iteratively, rather than using one large residual quantizer . RVPQ&#8217;s jointly trained multi-level codebooks gave better accuracy than plain PQ on ANN benchmarks while keeping search efficient.</p></li><li><p><strong>Neural and Differentiable PQ:</strong> A recent trend is to train quantization codebooks with neural networks or end-to-end optimization, rather than using vanilla k-means. <em>Unsupervised neural quantization (UNQ)</em> and <em>Deep PQ (DeepQ)</em> are methods that use gradient-based learning (often with a form of straight-through estimator or Gumbel-softmax) to learn codebook embeddings that minimize reconstruction error globally. These methods (e.g. Morozov &amp; Babenko 2019 for UNQ; Zhu et al. 2023 for DeepQ) showed improvements over classic OPQ/PQ by &#8220;learning to quantize&#8221; with backpropagation . However, they can be tricky to train and may need careful initialization or multiple stages. The latest advance in this vein is QINCo (Quantization with Implicit Neural Codebooks), introduced by Meta AI (Huijben <em>et al.</em>, ICML 2024). QINCo is a <em>neural residual quantization</em> approach that <strong>conditions each codebook on the previously quantized portion of the vector</strong> . In other words, instead of using a fixed codebook at each residual step, QINCo trains a neural network that outputs adaptive codebooks based on what the earlier RQ steps have already encoded . This significantly reduces quantization error &#8211; QINCo outperforms prior state-of-the-art quantization methods by large margins. For example, with a 12-byte code (96-bit) budget per vector, QINCo achieved higher recall on standard ANN benchmarks than an existing method using 16-byte codes . In ablation studies, QINCo was shown to benefit from more training data (unlike k-means based PQ which saturates) and can be combined with an IVF index for further speed-ups . These results demonstrate that learned PQ schemes can narrow the gap to full-precision accuracy. Going into 2025, we&#8217;re seeing &#8220;differentiable PQ&#8221; and other learned quantization techniques become more practical, indicating that future LLM retrieval systems might train their vector indexes similarly to how models are trained, to maximize retrieval quality.</p></li><li><p><strong>Other Notable Variants:</strong> <em>Online Product Quantization</em> (not to be confused with OPQ) has been explored to update codebooks on the fly for streaming data, using techniques like codebook refresh with learning and forgetting rates (<a href="https://www.analyticsvidhya.com/blog/2024/07/indexing-algorithms-in-vector-databases/#:~:text=Online%20Product%20Quantization">A Detailed Guide on Indexing Algorithms in Vector Databases</a>). This is useful if the embedding distribution shifts over time. There are also product quantization networks (PQN) that integrate quantization into neural network embeddings (for example, learning a PQ code as the output of an encoder). While these are active research areas, they are less common in LLM document retrieval so far. The main focus in 2024&#8211;2025 has been on improving compression <em>rate vs. accuracy</em> &#8211; for instance, a very recent work proposes &#8220;quantizer dropout&#8221; to allow variable bitrate PQ (encoding different vectors with different number of residuals) (<a href="https://arxiv.org/pdf/2412.01762?#:~:text=,Product"> arXiv:2412.01762v1 [cs.CV] 2 Dec 2024</a>). Overall, the advancements aim to make PQ more accurate and flexible while retaining efficiency. Techniques like OPQ and RQ are often combined with PQ in real systems (and are available in libraries like FAISS), and new neural approaches like QINCo show that significant accuracy gains are possible even at aggressive compression rates.</p></li></ul><h2><strong>PQ vs. HNSW and IVF for LLM Retrieval</strong></h2><p>When building a vector index for document retrieval, one must choose an ANN method that balances speed, memory usage, and recall. <strong>Hierarchical Navigable Small World (HNSW)</strong> and <strong>Inverted File Index (IVF)</strong> based methods (with or without PQ) are among the most popular options. Here we compare them in the context of LLM-scale retrieval:</p><ul><li><p><strong>Hierarchical NSW (Graph Index):</strong> HNSW builds a multi-layer graph of all vectors, where edges link close neighbors. At query time, it performs a greedy graph traversal to find nearest neighbors quickly (<a href="https://arxiv.org/html/2501.10534v1#:~:text=The%20Hierarchical%20Navigable%20Small%20World,nearest%20neighbors%20in%20large%20datasets">4bit-Quantization in Vector-Embedding for RAG</a>). HNSW is known for very high recall and low search latency at moderate scales, effectively achieving quality close to brute-force search. However, it is <strong>memory-intensive</strong> &#8211; it stores full vectors and a connectivity graph. For large corpora (hundreds of millions of embeddings), HNSW can become impractical due to memory: e.g. one analysis showed that storing 1 billion 768-D embeddings with HNSW (including the graph) could require on the order of a <em>terabyte</em> of RAM (<a href="https://files.futurememorystorage.com/proceedings/2024/20240807_AIML-203-1_Sella.pdf#:~:text=%E2%80%A2%20HNSW1%20is%20the%20leading,Based%20ANNS">HERE</a>). Even with 8-bit quantized vectors, the graph overhead is huge. HNSW indexes also grow superlinear in size with dataset because each node keeps links (e.g. M=32 or 48 links per node). This memory cost is the price for its speed and accuracy. In document retrieval for LLMs, HNSW is great for smaller knowledge bases or where memory is abundant, as it can return very accurate results quickly. But at the billion-scale, pure in-memory HNSW &#8220;doesn&#8217;t scale well&#8221; without compression .</p></li><li><p><strong>IVF (Inverted File) Index:</strong> IVF takes a coarse quantization approach: cluster the dataset into <em>N</em> coarse buckets (e.g. via k-means on full vectors), and assign each vector to its nearest cluster centroid. The index then is the set of cluster centroids (stored in memory), plus lists of vectors belonging to each cluster (these can be on disk or memory). At query time, only the <em>nProbe</em> nearest clusters to the query are searched, drastically narrowing the search space (<a href="https://arxiv.org/html/2412.11854v1#:~:text=Index%20Type%3A%20Advanced%20indexing%20strategies,time%20parameters">Towards Understanding Systems Trade-offs in Retrieval-Augmented Generation Model Inference</a>). IVF by itself (sometimes called &#8220;IVF-Flat&#8221; when storing full vectors) saves computation by avoiding brute-force search, but it doesn&#8217;t reduce memory unless combined with compression. Typically, IVF is <strong>paired with PQ</strong>: the vectors inside each cluster are stored as PQ codes, yielding the classic <strong>IVF-PQ</strong> approach (<a href="https://developer.nvidia.com/blog/accelerating-vector-search-nvidia-cuvs-ivf-pq-deep-dive-part-1/#:~:text=Building%20on%20these%20ideas%2C%20this,second%20part%20of%20this%20post">Accelerating Vector Search: NVIDIA cuVS IVF-PQ Part 1, Deep Dive | NVIDIA Technical Blog</a>). This two-level indexing (coarse cluster then fine quantization) is extremely scalable &#8211; it was the basis of Facebook&#8217;s billion-scale ANN search (FAISS) and is widely used in vector databases. In the context of LLM retrieval, IVF-PQ offers an appealing <strong>memory vs. accuracy trade-off</strong>: the PQ compression yields huge memory savings, and IVF ensures you only decode a small fraction of codes per query. The cost is that some recall is lost compared to HNSW or IVF-Flat (since both the coarse clustering and PQ quantization introduce error). For example, a recent study characterized the trade-offs: an IVF-PQ index (with 16,384 clusters and 8-bit PQ) used <strong>7.2&#215; less memory</strong> than an HNSW index (with scalar-quantized vectors) for a 100M corpus, but reached only ~70% of HNSW&#8217;s recall . Increasing nProbe (searching more clusters) can raise IVF-PQ recall at the expense of latency. In practice, one can often configure IVF-PQ to hit 90&#8211;95% of the true recall if slightly more clusters or a rerank step is used. The big win is memory: By compressing a large embedding store, we can fit it in GPU memory or cheaper storage. NVIDIA reports that using IVF-PQ on a 1B-vector, 96-D dataset reduced data size from 360 GiB (FP32) to ~54 GiB with minimal loss in accuracy (maintaining &gt;95% recall) , and even to 24 GiB with a moderate speed hit for additional compression. Such compression is essential for LLM systems dealing with web-scale knowledge.</p></li><li><p><strong>Accuracy and Speed Comparison:</strong> HNSW tends to win on raw recall &#8211; it can often return nearly exact neighbors if given enough memory and compute. IVF-PQ will miss some neighbors due to quantization. In one 2024 benchmark on a 100M dataset, HNSW achieved ~0.87 recall while IVF-PQ leveled off around 0.61 (with fixed parameters) . However, IVF without PQ (or with lighter quantization like scalar quantization) can close this gap; for instance IVF with 8-bit scalar quantization achieved recall 0.86 in the same study . In terms of latency, HNSW performs well for single queries thanks to its graph search, but it may degrade when scaling to many concurrent queries or very large datasets (due to random memory accesses across a large graph). IVF-PQ, by contrast, benefits from sequential memory access patterns and can leverage GPUs effectively by processing many distance computations in parallel. For instance, the FAISS library on CPU schedules one thread per query for IVF-PQ, whereas GPU implementations (like RAFT IVF-PQ) can search thousands of queries in batch. The aforementioned NVIDIA test showed that at large batch sizes (e.g. 10k queries), a GPU IVF-PQ could answer ~180k queries/sec at &gt;95% recall, whereas a multi-threaded HNSW on CPU managed ~60k QPS. That illustrates how IVF-PQ shines in high-throughput settings. On CPU with smaller batches, HNSW can be faster for high-precision search (fewer distance calculations needed), but if the PQ code length is short, distance computation is very fast too. Notably, the system trade-off study found that at comparable recall, <em>IVF-PQ had higher tail latencies</em> and lower peak throughput than HNSW on CPU , likely because IVF-PQ needed to scan more points (due to lower recall per probe) when trying to match HNSW&#8217;s accuracy. In summary, <strong>HNSW vs IVF-PQ</strong> is a memory-vs-accuracy trade: HNSW uses a lot of memory to get high recall easily, whereas IVF-PQ uses very little memory but needs careful tuning (and possibly more computation) to reach high recall.</p></li><li><p><strong>Hybrid Approaches:</strong> Recent solutions try to get the best of both worlds. One approach is to use HNSW on top of PQ codes &#8211; e.g. build the HNSW graph over compressed vectors to reduce memory. This works, but the graph search on PQ codes can be less accurate (since distances are approximate). Another approach is DiskANN, a system by Microsoft that uses an on-disk graph index with PQ-compressed vectors in RAM. DiskANN (2023) essentially stores the HNSW-like graph on SSD and only keeps a small PQ-refined vector cache in memory (<a href="https://files.futurememorystorage.com/proceedings/2024/20240807_AIML-203-1_Sella.pdf#:~:text=%E2%80%A2%20SSD,or%20unregistered%20mark%20of%20NVM">HERE</a>) . This allows billion-scale indices to run on a single machine with far less RAM. In one comparison, DiskANN provided <strong>comparable performance to in-memory HNSW while cutting memory usage by ~89%</strong> . The trade-off is slightly higher latency due to SSD access, but with fast NVMe drives and optimized search (beam search + re-ranking), the impact is small. For LLM retrieval, DiskANN and similar <em>hybrid indexes</em> enable serving massive corpora (billions of embeddings) cost-effectively, since pure HNSW would be prohibitively expensive. Meanwhile, pure PQ approaches (like IVF-PQ) remain very relevant, especially with hardware acceleration: they offer a straightforward way to compress data and often the <em>lowest memory</em> solution for a given recall target. Many production systems use a combination: IVF or HNSW for coarse search, followed by PQ codes for the fine distances (or a re-rank using original vectors if those can be stored elsewhere).</p></li></ul><p>In practice, selecting an index for an LLM knowledge base depends on requirements: If maximum accuracy is required and the dataset is moderate, HNSW is a good choice. If the dataset is huge and memory or cost is a concern, IVF-PQ or DiskANN are viable, achieving good recall with far lower resource usage (<a href="https://arxiv.org/html/2412.11854v1#:~:text=more%20memory%20efficient,offs%20between%20retrieval">Towards Understanding Systems Trade-offs in Retrieval-Augmented Generation Model Inference</a>) . It&#8217;s also common to see hierarchical indexing (IVF) combined with HNSW (for example, first select clusters, then use a local HNSW within each cluster) &#8211; highlighting that these methods are complementary. The key is understanding the trade-offs: PQ indexing offers compactness, HNSW offers accuracy, and IVF offers scalability, and modern systems often mix and match these to meet the needs of large-scale LLM retrieval.</p><h2><strong>Benchmarks and Recent Results (2024-2025)</strong></h2><p>To quantify the above discussions, we summarize some findings from latest research (all 2024+) on vector indexes for retrieval, focusing on PQ and its variants:</p><ul><li><p><strong>PQ Compression vs Accuracy:</strong> <em>Zhang et al. 2025</em> evaluated PQ in a RAG setup with 100K embeddings. Using a strong compression (32 sub-vectors, codebook size 16 or 256), the top-10 retrieval overlap with the exact (floating-point) baseline was <strong>under 10%</strong>, highlighting that heavy PQ compression can drastically drop retrieval accuracy (<a href="https://arxiv.org/html/2501.10534v1#:~:text=We%20compared%20our%20quantization%20method,list%20from%20the%20original%20floating">4bit-Quantization in Vector-Embedding for RAG</a>). In the same work, PQ-coded embeddings achieved only ~0.56&#8211;0.60 Pearson correlation with ground-truth semantic similarity scores (versus 0.85+ for 8-bit or 4-bit scalar quantization) . This underscores the importance of tuning PQ parameters to avoid too much information loss.</p></li><li><p><strong>HNSW vs IVF-PQ &#8211; Memory and Recall:</strong> <em>Chandrasekaran et al. 2024</em> compared popular ANN indexes for RAG on a 100M dataset. An HNSW index (with 8-bit quantized vectors) attained ~<strong>87%</strong> recall but used large memory, whereas an IVF-PQ index (16k clusters, 256-byte PQ codes) used about <strong>7.2&#215; less memory</strong> yet maxed out around <strong>61%</strong> recall (<a href="https://arxiv.org/html/2412.11854v1#:~:text=more%20memory%20efficient,offs%20between%20retrieval">Towards Understanding Systems Trade-offs in Retrieval-Augmented Generation Model Inference</a>). An intermediate approach, IVF with scalar quantization (IVF-SQ), reached ~86% recall with ~2.3&#215; memory reduction vs HNSW . This benchmark vividly shows the trade-off continuum: more compression (IVF-PQ) yields huge space savings at a cost to accuracy, while mild compression (IVF-SQ) preserves accuracy closer to the graph-based method.</p></li><li><p><strong>Latency/Throughput Trade-offs:</strong> The same study noted that at batch sizes above 128, the throughput of IVF-PQ leveled around <strong>110 QPS</strong>, vs <strong>319 QPS</strong> for HNSW in their CPU setting . IVF-PQ also had higher 95th-percentile latency (up to 2.2s in worst case vs &lt;0.9s for HNSW) . This was attributed to IVF-PQ needing more exhaustive scanning to reach high recall. However, on GPU, IVF-PQ can excel. NVIDIA&#8217;s 2024 experiments with RAFT IVF-PQ showed that for 100M vectors at recall &gt;95%, a GPU index could answer ~<strong>150k queries/sec</strong> (batch=10k) whereas a multi-threaded HNSW on CPU managed ~50k QPS. This demonstrates that the <em>hardware and batch scenario</em> can flip the performance outcome &#8211; PQ compression is extremely GPU-friendly, whereas graph search favors CPU caches and many threads.</p></li><li><p><strong>New PQ Variants Performance:</strong> Advances like QINCo have pushed PQ accuracy closer to uncompressed vectors. In QINCo&#8217;s ICML 2024 paper, using a code size of just <strong>12 bytes per vector</strong>, it achieved higher recall on benchmarks than prior methods did with <strong>16 bytes</strong> (<a href="https://arxiv.org/pdf/2401.14732#:~:text=we%20propose%20QINCo%2C%20a%20neural,the%20BigANN1M%20and%20Deep1M%20datasets">HERE</a>). For instance, on the Deep1M and BigANN1M datasets, QINCo (12B code) slightly exceeded the recall that UNQ (an earlier neural quantizer) got with 16B codes . This is a remarkable 25% reduction in index size with no loss of accuracy, thanks to better codebook learning. Such improvements mean that future PQ indexes can be both compact <em>and</em> high-accuracy. Similarly, RVPQ (Niu et al. 2023) reported improved recall vs standard PQ for a given code length by leveraging residual quantization in subspaces . We expect upcoming benchmarks (e.g. ANN competitions in 2025) to showcase these smarter quantization schemes outperforming traditional PQ/OPQ in retrieval tasks.</p></li><li><p><strong>Large-Scale Deployments:</strong> Real-world scale tests underscore PQ&#8217;s value. NVIDIA&#8217;s IVF-PQ index for the DEEP1B dataset compressed <strong>1 billion, 96-D vectors from 360 GiB to ~54 GiB</strong> &#8211; a <strong>6&#8211;7&#215;</strong> compression &#8211; <em>with negligible impact on search accuracy</em> (verified at &gt;0.95 recall) (<a href="https://developer.nvidia.com/blog/accelerating-vector-search-nvidia-cuvs-ivf-pq-deep-dive-part-1/#:~:text=To%20show%20an%20example%20of,subset%20of%20the%20DEEP%20dataset">Accelerating Vector Search: NVIDIA cuVS IVF-PQ Part 1, Deep Dive | NVIDIA Technical Blog</a>). Pushing further to 24 GiB (15&#215; compression) caused about a 1.5&#215; slowdown but still was feasible . This kind of compression enables fitting vast knowledge bases in memory (or even on a single GPU), which is crucial for RAG-based LLM applications. On the other hand, disk-based methods also show promise: <em>Sella 2024</em> demonstrated that DiskANN (a graph + PQ hybrid) could handle a <strong>50M, 768-D</strong> dataset with an <strong>89% reduction in DRAM</strong> usage vs HNSW, yet similar query throughput (<a href="https://files.futurememorystorage.com/proceedings/2024/20240807_AIML-203-1_Sella.pdf#:~:text=match%20at%20L245%20%E2%80%A2%20DiskANN,memory%20ANNS">HERE</a>). These results indicate that <strong>memory-bound scaling issues can be solved</strong> by PQ and related innovations, allowing LLM systems to retrieve from much larger document collections without sacrificing too much performance.</p></li></ul><p>In summary, the recent literature (2024&#8211;2025) paints a clear picture: Product quantization remains a linchpin for efficient vector search at scale, and ongoing research is actively improving its effectiveness. Practically, PQ indexing enables large LLM knowledge bases to be searched with reasonable resources, and newer variants (optimized, residual, neural PQ) are closing the accuracy gap. Meanwhile, alternatives like HNSW and IVF (with or without PQ) offer different sweet spots in the design space. System designers often combine these techniques to balance <strong>retrieval accuracy, speed, and cost</strong> for their specific LLM-driven applications (<a href="https://arxiv.org/html/2412.11854v1#:~:text=more%20memory%20efficient,offs%20between%20retrieval">Towards Understanding Systems Trade-offs in Retrieval-Augmented Generation Model Inference</a>) . The benchmarks confirm there is no one-size-fits-all: if maximum precision is needed, a high-memory HNSW or IVF-Flat index may be worth it; if memory or scale is a bottleneck, PQ-based compression is indispensable. As LLM deployments grow, we anticipate further hybrid approaches and learned quantization methods will define the state-of-the-art in vector search for AI.</p><p><strong>Sources:</strong> Recent research and technical reports from 2024&#8211;2025 have been cited to support this review, including arXiv preprints (<a href="https://arxiv.org/html/2501.10534v1#:~:text=Product%20quantization%20,centroid%20information%20of%20quantized%20buckets">4bit-Quantization in Vector-Embedding for RAG</a>) , conference papers (<a href="https://arxiv.org/pdf/2401.14732#:~:text=we%20propose%20QINCo%2C%20a%20neural,the%20BigANN1M%20and%20Deep1M%20datasets">HERE</a>) , and industry benchmarks (<a href="https://developer.nvidia.com/blog/accelerating-vector-search-nvidia-cuvs-ivf-pq-deep-dive-part-1/#:~:text=To%20show%20an%20example%20of,subset%20of%20the%20DEEP%20dataset">Accelerating Vector Search: NVIDIA cuVS IVF-PQ Part 1, Deep Dive | NVIDIA Technical Blog</a>). These provide the latest insights into PQ indexing and its role in LLM-scale retrieval.</p>]]></content:encoded></item><item><title><![CDATA[Locality-Sensitive Hashing in Document Retrieval and LLM Chunking A 2024-2025 Review]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/locality-sensitive-hashing-in-document</link><guid isPermaLink="false">https://www.rohan-paul.com/p/locality-sensitive-hashing-in-document</guid><pubDate>Mon, 16 Jun 2025 10:00:00 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!zhY_!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!zhY_!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!zhY_!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png 424w, https://substackcdn.com/image/fetch/$s_!zhY_!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png 848w, https://substackcdn.com/image/fetch/$s_!zhY_!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png 1272w, https://substackcdn.com/image/fetch/$s_!zhY_!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!zhY_!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png" width="1024" height="585" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:585,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:624332,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166055874?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!zhY_!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png 424w, https://substackcdn.com/image/fetch/$s_!zhY_!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png 848w, https://substackcdn.com/image/fetch/$s_!zhY_!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png 1272w, https://substackcdn.com/image/fetch/$s_!zhY_!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b41be36-5dd1-400c-875b-20d8421258b4_1024x585.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ul><li><p>Introduction</p></li><li><p>Recent Advancements in LSH Indexing 2024-2025</p></li><li><p>Performance Benchmarks and Comparisons</p></li><li><p>Applications in Document Retrieval and Chunking</p></li><li><p>Limitations and Trade-offs in Practice</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Introduction</strong></h2><p>Document digitization pipelines often convert scanned text into machine-readable form and then chunk the text into smaller segments before feeding it to large language models (LLMs) for tasks like retrieval-augmented generation. In a typical workflow, after OCR-based digitization, a large corpus is split into manageable text chunks, each encoded as a vector (embedding), and an index is built to enable fast similarity search (<a href="https://arxiv.org/html/2407.13193v3#:~:text=This%20section%20will%20explain%20how,value%20pairs">Retrieval-Augmented Generation for Natural Language Processing: A Survey</a>). Locality-Sensitive Hashing (LSH) is a longstanding technique for approximate nearest neighbor search that can serve as the indexing backbone in such pipelines. LSH works by hashing high-dimensional data into buckets such that similar items are likely to fall into the same bucket . This way, a query chunk&#8217;s hash can quickly retrieve other chunks with matching or close-by hashes, approximating a nearest-neighbor search without exhaustively scanning all chunks. The appeal of LSH for document retrieval lies in its sub-linear query time and theoretical guarantees on similarity preservation, making it a candidate for scaling LLM knowledge bases and document stores. Recent research (2024&#8211;2025) has produced several advancements in LSH indexing that improve its practicality and performance in real-world scenarios, from faster indexing algorithms to hybrid neural hashing approaches. This review summarizes these developments, compares LSH against alternative indexing methods, and discusses applications in document retrieval and chunking, as well as practical trade-offs observed in deployments.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Recent Advancements in LSH Indexing 2024-2025</strong></h2><p><strong>Faster and More Accurate LSH Schemes:</strong> One notable advance is <strong>DET-LSH</strong> (Dynamic Encoding Tree LSH) by Wei et al. (2024), which rethinks how LSH indexes are built (<a href="https://arxiv.org/abs/2406.10938#:~:text=approximate%20nearest%20neighbor%20,based%20tree%20called%20Dynamic"> DET-LSH: A Locality-Sensitive Hashing Scheme with Dynamic Encoding Tree for Approximate Nearest Neighbor Search</a>). Traditional LSH methods often spent most effort on the query phase, using pre-partitioned space structures, but paid less attention to indexing efficiency . DET-LSH introduces a dynamic encoding tree structure (DE-Tree) to partition data more efficiently and a novel multi-tree range query strategy to reduce missed neighbors. The result is a significant boost in both build and query performance: experiments demonstrated <strong>up to 6&#215; faster index construction and 2&#215; faster query times</strong> compared to prior state-of-the-art LSH methods, while also <strong>improving recall</strong> (retrieving more true nearest neighbors) . In essence, DET-LSH narrows the gap between LSH and other high-performance ANN methods by offering hashing-based indexing with lower latency and higher accuracy than was previously achievable.</p><p><strong>Space-Efficient LSH Data Structures:</strong> Another line of research addresses one of LSH&#8217;s historical pain points: memory usage. Classic LSH schemes tend to require a large number of hash tables or long hash codes to reach high recall, leading to <strong>very large space overheads (sometimes polynomial in the dataset size) (<a href="https://arxiv.org/abs/2407.02468#:~:text=,Fiat%20and%20Naor"> Improved Space-Efficient Approximate Nearest Neighbor Search Using Function Inversion</a>)</strong>. Past efforts to shrink LSH memory footprints often involved complex, hand-tailored tweaks that unfortunately traded off significantly slower queries . In 2024, McCauley introduced a method leveraging <em>function inversion</em> techniques to compress LSH structures without the usual performance penalty . By applying a theoretical construct from cryptography (Fiat&#8211;Naor function inversion), this approach provides a black-box way to reduce the number of stored hash buckets. The improved index not only uses <strong>less space</strong> but can even improve query time in certain regimes, outperforming earlier near-linear-space LSH constructions under Euclidean distance . This advancement is particularly relevant for deployments like document archives where memory is at a premium&#8212;storing millions of document chunk hashes can be done more compactly, making LSH more feasible at scale.</p><p><strong>Neural LSH for Complex Similarities:</strong> While standard LSH relies on predefined random projections or hash functions (e.g., for cosine or Jaccard similarity), real-world document retrieval may involve more complex or learned similarity measures. In 2024, Wang et al. proposed <strong>Neural LSH</strong> (NLSHBlock) to tackle this gap (<a href="https://arxiv.org/abs/2401.18064#:~:text=technique%20widely%20employed%20in%20large,In%20this%20research%2C%20we%20propose"> Neural Locality Sensitive Hashing for Entity Blocking</a>). They observed that one limitation of vanilla LSH is the need for careful design of hash functions aligned with the target similarity metric (which is straightforward for cosine distance or Jaccard, but very challenging for composite or task-specific metrics) . NLSHBlock addresses this by training a deep neural network to act as the hashing function, effectively &#8220;learning&#8221; an LSH scheme tailored to a given task&#8217;s notion of similarity . In the context of entity resolution (a task akin to matching records or documents referring to the same entity), this neural approach yielded <strong>significant performance improvements</strong> over traditional LSH that used generic similarity metrics . By fine-tuning a language model with a special LSH-based loss, they achieved more meaningful buckets&#8212;records that were similar under complex domain-specific rules ended up hashed together with high probability, simplifying downstream retrieval. This neural hashing concept can be extended to document chunks: for example, if an application requires grouping semantically similar paragraphs (where similarity might be defined by a mix of topical overlap and writing style), a learned hashing function could outperform any static hand-crafted hash. It&#8217;s an exciting direction that bridges LSH with representation learning, injecting more adaptability into the indexing process.</p><p><strong>Other Notable Improvements:</strong> Researchers have also looked at specialized scenarios, such as high-dimensional <em>tensor</em> data and LSH. For instance, Verma and Pratap (2024&#8211;2025) explored <strong>tensorized random projections</strong> to create LSH families that handle multi-dimensional arrays (like images or other tensor representations) more efficiently (<a href="https://arxiv.org/abs/2402.07189#:~:text=functions%20for%20Euclidean%20distance%20and,space%20efficient%20and%20can%20be"> Improving LSH via Tensorized Random Projection</a>). The naive approach of flattening such data for hashing can explode dimensionality exponentially, so they proposed methods (CP-LSH and TT-LSH) using tensor decomposition (CANDECOMP/PARAFAC and Tensor-Train) to generate hash codes that capture multi-way structure without blowing up memory usage . Although this is a more niche application, it showcases how LSH is being adapted for modern data types beyond plain text vectors. On another front, <strong>LSH in LLM internals</strong> has emerged: one example is <em>HashEvict</em> (Liu et al., 2024), which uses LSH inside the LLM&#8217;s attention mechanism rather than for external document retrieval. HashEvict hashes token keys and queries in the <em>attention cache</em> to identify and evict low-importance tokens, thereby compressing the context window. This method can shrink the effective context memory by 30&#8211;70% while maintaining model performance, leading to <strong>1.5&#8211;2&#215; speedups in generation</strong> for long-context scenarios (<a href="https://arxiv.org/abs/2412.16187#:~:text=computational%20costs,prefill%2F2x%20decoding%20speed%20against%20FastGen"> HashEvict: A Pre-Attention KV Cache Eviction Strategy using Locality-Sensitive Hashing</a>). While not an indexing method for external documents, it&#8217;s a novel application of LSH to manage <em>which</em> chunks of the conversation or document remain available to the model, hinting at the versatility of hashing techniques in aiding LLMs.</p><h2><strong>Performance Benchmarks and Comparisons</strong></h2><p>Contemporary benchmarks indicate that LSH-based indexing has both strengths and weaknesses relative to alternative ANN methods. <strong>Graph-based indexes</strong> (like HNSW) have risen to prominence in vector databases due to their excellent recall vs. speed trade-offs &#8211; in fact, graph-based ANN algorithms often demonstrate <em>superior retrieval performance</em> compared to hashing approaches on many datasets (<a href="https://arxiv.org/html/2407.07871v1#:~:text=The%20approximate%20nearest%20neighbor%20search,to%20as%20the%20%E2%80%98unreachable%20points">Enhancing HNSW Index for Real-Time Updates: Addressing Unreachable Points and Performance Degradation</a>). This means that for tasks such as document similarity search, an HNSW index might return more relevant chunks (higher recall) within a given query latency budget than a traditional LSH index. The gap is not just theoretical: many industrial-grade search systems default to graph or tree-based ANN structures over LSH. For example, a recent study on updating HNSW graphs reaffirms that HNSW and similar proximity graphs outperform other approaches in baseline retrieval efficiency . <strong>Product quantization (PQ)</strong> and inverted file hybrids (like IVF-PQ) are also popular; these compress embeddings and use clustering to limit search scope, competing with LSH in memory usage. The 2024 RAG survey notes that LSH and PQ both enable efficient storage and fast approximate search but at the risk of losing some semantic fidelity in the representations (<a href="https://arxiv.org/html/2407.13193v3#:~:text=et%C2%A0al,context%20into%20semantically%20shorter%20embeddings">Retrieval-Augmented Generation for Natural Language Processing: A Survey</a>). In other words, any heavy compression (be it via hashing or quantization) can omit fine-grained meaning, which might slightly reduce retrieval quality compared to using full embeddings with a graph index.</p><p>That said, the latest LSH improvements are narrowing the gap. DET-LSH&#8217;s results, for instance, show that <strong>modern LSH can achieve accuracy on par with state-of-the-art ANN methods</strong> while significantly cutting query and index times (<a href="https://arxiv.org/abs/2406.10938#:~:text=superiority%20of%20DET,paper%20was%20published%20in%20PVLDB"> DET-LSH: A Locality-Sensitive Hashing Scheme with Dynamic Encoding Tree for Approximate Nearest Neighbor Search</a>). This suggests that with the right innovations, hashing schemes remain competitive. Another consideration is <strong>index build time and flexibility</strong>. Building a graph index like HNSW is often more computationally intensive than hashing data points, and graphs can be tricky to update in real-time. In scenarios where the document collection changes frequently (new documents added, or chunks updated), LSH has an edge in simplicity: you can hash new chunks and insert them into hash tables in near-constant time. By contrast, graph structures suffer degradation when many insertions or deletions occur over time &#8211; the &#8220;unreachable node&#8221; problem is known to hamper HNSW, making portions of the index inaccessible without periodic rebuilds . Recent work addresses this (e.g. algorithms to maintain HNSW connectivity ), but it underscores a trade-off: <strong>LSH offers easier maintenance at the cost of potentially needing more buckets to reach equivalent recall</strong>. In practice, if an application demands frequent index updates (such as a live document feed in an enterprise search engine), an LSH-based index might be preferable for its robustness to updates, whereas a static corpus (like a fixed library of books) might lean toward a finely-tuned graph index for maximum retrieval quality.</p><p>Memory footprint and speed also come into play. Hashing methods traditionally required many hash tables or long bit codes to get high accuracy, which could inflate memory usage. Graph and quantization methods can be more memory-efficient for a given accuracy, though they involve more complex data structures. The space-efficiency breakthroughs in LSH (<a href="https://arxiv.org/abs/2407.02468#:~:text=,Fiat%20and%20Naor"> Improved Space-Efficient Approximate Nearest Neighbor Search Using Function Inversion</a>) are helping mitigate this issue, making it feasible to deploy LSH for very large document corpora without overwhelming storage. Benchmarks in 2024 indicate that a well-optimized LSH (like DET-LSH) vs. a well-optimized HNSW can perform comparably on mid-sized datasets in terms of queries per second at a given recall level &#8211; the difference often boils down to tuning and the specifics of the data distribution. It&#8217;s also worth noting that <strong>hybrid approaches</strong> are emerging: some systems combine coarse clustering or graphs with LSH-style hashing within clusters, aiming to get the best of both worlds (fast search at scale and high recall). Overall, the performance landscape in 2024&#8211;2025 shows that LSH is evolving from an &#8220;aging&#8221; baseline into a viable competitor again, especially when domain-specific needs (like custom similarity or rapid updates) put pure graph or quantization methods at a disadvantage.</p><h2><strong>Applications in Document Retrieval and Chunking</strong></h2><p>Locality-Sensitive Hashing has long been applied to text and document retrieval tasks, and recent work continues to showcase its value in practical settings. In <strong>document digitization projects</strong>, once raw text is obtained, LSH can be used to index documents or chunks for near-duplicate detection. For example, search engines and digital libraries have historically employed SimHash or MinHash (LSH variants) to identify duplicate or highly similar documents in large corpora. This remains relevant in 2024, as the scale of data grows &#8211; being able to quickly cluster or filter out redundant content is crucial before feeding information to an LLM. A new development in this arena is the recognition that naive hashing isn&#8217;t always robust to <em>adversarial changes</em> in text (like typos or paraphrasing). To address this, researchers introduced specialized embedding models like RETSim (2024), which was shown to be <em>&#8220;significantly more robust and accurate than MinHash&#8221;</em> for near-duplicate text retrieval (<a href="https://openreview.net/forum?id=23b9KSNQTX#:~:text=Similarity,are%20released%20under%20the%20MIT">RETSim: Resilient and Efficient Text Similarity | OpenReview</a>). RETSim essentially provides embeddings that make similar texts (even with minor obfuscations) land closer in vector space, complementing or outperforming LSH on tasks like dataset deduplication. This reflects a pattern in real-world systems: pure LSH is sometimes enhanced with learned embeddings or used in conjunction with them. For instance, one could use a neural embedding to represent each chunk of a document and then apply LSH on those embeddings to index them. This hybrid approach leverages the power of semantic embeddings and the speed of hashing. In a retrieval-augmented QA system, a user query might be encoded into the same embedding space, then hashed to probe the index and fetch candidate text chunks that are likely relevant. Those chunks (retrieved in milliseconds via LSH lookup) can then be fed into an LLM to generate a final answer. Such pipelines have been explored in recent systems: the retriever component is responsible for chunking, encoding, and fast lookup (<a href="https://arxiv.org/html/2407.13193v3#:~:text=This%20section%20will%20explain%20how,value%20pairs">Retrieval-Augmented Generation for Natural Language Processing: A Survey</a>), and LSH is one option to implement the lookup efficiently.</p><p>We also see LSH being adapted to <strong>domain-specific retrieval</strong> problems. The Neural LSH approach (NLSHBlock) mentioned earlier is a good example in the context of <em>entity resolution</em>, which is essentially a specific kind of document/text similarity search. By training on the idiosyncrasies of matching entity records, NLSHBlock could hash similar records (or text entries) together more effectively than generic methods (<a href="https://arxiv.org/abs/2401.18064#:~:text=a%20neuralization%20approach%20to%20enhance,over%20existing%20methods%2C%20exhibiting%20significant"> Neural Locality Sensitive Hashing for Entity Blocking</a>). This idea could carry over to, say, legal or medical document retrieval: if &#8220;similarity&#8221; in legal documents depends on complex factors (case citations, legal statutes, etc.), one could imagine training a neural LSH to hash chunks of legal texts in a way that groups related cases. While this is still an emerging concept, it points to practical deployments where off-the-shelf hashing might fall short, but a tuned LSH index becomes a powerful tool for custom retrieval needs.</p><p>Another application is in <strong>document clustering and organization</strong>. LSH can quickly group chunks or documents that are mutually similar without needing an exhaustive similarity matrix. In large-scale digital archives, LSH-based clustering has been used to organize content by topic or to preprocess data for more expensive algorithms. Because LSH buckets provide a candidate set of similar items, they can drastically reduce the work for downstream clustering or linking algorithms. For instance, if you have a million news articles, an LSH index can instantly tell you which articles are likely about the same story (because they hash to the same or nearby bucket). Recent improvements like space-efficient LSH mean even massive archives (think all articles published in a year) can be indexed in memory on a single server (<a href="https://arxiv.org/abs/2407.02468#:~:text=,Fiat%20and%20Naor"> Improved Space-Efficient Approximate Nearest Neighbor Search Using Function Inversion</a>), making these techniques practical outside of big tech companies, too.</p><p>Finally, in the <strong>LLM context specifically</strong>, beyond just retrieval, LSH is helping manage long contexts. The HashEvict technique (<a href="https://arxiv.org/abs/2412.16187#:~:text=that%20uses%20locality,compress%20the%20KV%20cache%20by"> HashEvict: A Pre-Attention KV Cache Eviction Strategy using Locality-Sensitive Hashing</a>), though internal to the model&#8217;s operation, is applied when dealing with long documents or transcripts that exceed the normal context window. It effectively performs a <em>chunking and pruning</em> on-the-fly: as an LLM generates text or processes a lengthy input, HashEvict uses LSH to decide which earlier chunks of the conversation/document can be dropped from the attention window. This ensures the model can handle longer inputs than it otherwise could, by continuously refreshing the &#8220;window&#8221; with the most salient pieces. In summarization or iterative document analysis, this kind of technique allows feeding an LLM far more text (in total) than its nominal limit, without a huge accuracy loss. It&#8217;s a clever use of LSH in service of chunk management for LLMs, highlighting that <em>practical implementations of LSH are not limited to classical retrieval</em>, but also extend to maintaining and retrieving pieces of context within the models themselves.</p><h2><strong>Limitations and Trade-offs in Practice</strong></h2><p>Despite the above advances and use cases, LSH-based indexing comes with <strong>trade-offs that practitioners must consider</strong>. One well-known limitation is the <strong>accuracy-memory trade-off</strong>: to achieve high recall (i.e. reliably retrieve all relevant chunks for a query), LSH may require increasing the number of hash tables or hash length, which in turn increases memory usage. If constrained to a small memory budget, an LSH index might miss some relevant neighbors unless carefully optimized. As noted, classic LSH data structures could even require polynomial growth in storage relative to dataset size (<a href="https://arxiv.org/abs/2407.02468#:~:text=,Fiat%20and%20Naor"> Improved Space-Efficient Approximate Nearest Neighbor Search Using Function Inversion</a>), which becomes impractical at extreme scales. Recent work alleviates this, but the fundamental trade-off remains: you tune LSH parameters to balance speed, space, and recall. In contrast, other ANN methods like HNSW tend to have more parameters influencing compute time rather than raw memory footprint. <strong>Tuning complexity</strong> is another factor &#8211; choosing the number of hash functions, tables, and thresholds for LSH can be non-trivial and often needs empirical adjustment for each new dataset. This is somewhat analogous to choosing the graph connectivity or ef_search parameters in HNSW; in both cases, suboptimal tuning can lead to poor results. The difference is that LSH&#8217;s theoretical guarantees give some guidance (e.g. how collision probability relates to distance), whereas graph performance is purely empirical. Still, in practice those guarantees don&#8217;t perfectly translate to real data distributions, so trial-and-error is common when deploying LSH at scale.</p><p>Another limitation is that <strong>LSH treats similarity in a specific mathematical sense</strong> (e.g. cosine similarity of embeddings, or Jaccard similarity of shingle sets). If your notion of relevance isn&#8217;t captured by that metric, vanilla LSH won&#8217;t be effective. We saw this in the entity resolution scenario, where task-specific combinations of fields required a learned hash function (<a href="https://arxiv.org/abs/2401.18064#:~:text=applicability%20in%20some%20real,We%20assess%20the"> Neural Locality Sensitive Hashing for Entity Blocking</a>). For document retrieval with LLMs, this means that if you rely on LSH over naive features (like hashing words or using simple embeddings), you might retrieve chunks that are textually similar but not contextually relevant to the query&#8217;s intent. Ensuring the embedding or feature space is appropriate is crucial &#8211; LSH will then do a good job of approximate matching in that space. In essence, LSH is only as useful as the representation of the documents; it&#8217;s not a magic bullet for relevance on its own. Modern best practice therefore pairs LSH with high-quality embeddings (often from transformers), and improvements like those in RETSim show that more robust representations can dramatically improve results in tasks like near-duplicate detection (<a href="https://openreview.net/forum?id=23b9KSNQTX#:~:text=Similarity,are%20released%20under%20the%20MIT">RETSim: Resilient and Efficient Text Similarity | OpenReview</a>), where basic hashing would falter on minor text perturbations.</p><p>When it comes to <strong>dynamic vs. static data</strong>, as discussed, LSH shines for dynamic datasets because adding or removing items is straightforward (compute hash, add or remove from buckets). If your document collection is a living one (e.g. continually ingesting new PDFs or knowledge base articles), LSH can maintain an up-to-date index with minimal latency. The trade-off is that at any given moment, its recall might be slightly lower than a well-curated static index structure. If absolute retrieval accuracy is paramount and the data is mostly static, many practitioners still favor graph-based indexes or exhaustive search on smaller subsets, accepting the overhead. However, with algorithms like DET-LSH narrowing the accuracy gap (<a href="https://arxiv.org/abs/2406.10938#:~:text=superiority%20of%20DET,paper%20was%20published%20in%20PVLDB"> DET-LSH: A Locality-Sensitive Hashing Scheme with Dynamic Encoding Tree for Approximate Nearest Neighbor Search</a>), the calculus is changing &#8211; it&#8217;s now feasible to have both dynamism and high accuracy.</p><p>Lastly, <strong>semantic loss</strong> is a subtle but important consideration. Because LSH compresses data into discrete buckets or bit codes, some nuance in the similarity may be lost (<a href="https://arxiv.org/html/2407.13193v3#:~:text=et%C2%A0al,context%20into%20semantically%20shorter%20embeddings">Retrieval-Augmented Generation for Natural Language Processing: A Survey</a>). For example, two document chunks might be semantically relevant to each other but if they don&#8217;t cross a certain threshold of hash similarity, they could fall into different buckets and not be retrieved together. This is usually mitigated by using multiple hash functions and by the fact that truly similar items have a high probability of collision. Nonetheless, in critical applications (legal, medical), missing a relevant document chunk could be costly. Practitioners often hedge against this by retrieving not just exact bucket matches but also nearby buckets, or by doing a re-ranking step: retrieve a larger candidate set via LSH, then use a more precise (but slower) scoring method to ensure nothing important was missed. This hybrid approach combines the speed of LSH with a backstop for quality, and is common in real-world retrieval systems.</p><p>In summary, LSH indexing methods have seen a resurgence of innovation in 2024&#8211;2025, addressing many of their historical limitations. They offer a compelling solution for <strong>document chunking and retrieval</strong> in LLM applications, especially when scaled to massive corpora or when fast, frequent updates are needed. Modern LSH techniques deliver speed and scalability, while new integrations with neural models and clever engineering (like in DET-LSH and HashEvict) push their effectiveness closer to that of leading alternatives. The choice between LSH and other indexing methods ultimately depends on the specific needs of the application &#8211; <strong>there is no one-size-fits-all</strong>. Factors like dataset size, update frequency, available memory, and required recall levels all play a role. Thanks to ongoing research, developers of LLM-based systems now have a richer toolkit of LSH-based approaches at their disposal, making it easier to deploy efficient and intelligent retrieval systems for digitized documents. With careful consideration of the trade-offs, LSH indexing can be a powerful component of practical, large-scale document understanding pipelines (<a href="https://arxiv.org/abs/2406.10938#:~:text=superiority%20of%20DET,paper%20was%20published%20in%20PVLDB"> DET-LSH: A Locality-Sensitive Hashing Scheme with Dynamic Encoding Tree for Approximate Nearest Neighbor Search</a>).</p><p><strong>References:</strong> Recent works (2024&#8211;2025) on LSH and indexing include DET-LSH for fast indexing , McCauley&#8217;s space-efficient LSH technique (<a href="https://arxiv.org/abs/2407.02468#:~:text=,Fiat%20and%20Naor"> Improved Space-Efficient Approximate Nearest Neighbor Search Using Function Inversion</a>), neural hashing for entity resolution (<a href="https://arxiv.org/abs/2401.18064#:~:text=a%20neuralization%20approach%20to%20enhance,over%20existing%20methods%2C%20exhibiting%20significant"> Neural Locality Sensitive Hashing for Entity Blocking</a>), and long-context LLM applications like HashEvict (<a href="https://arxiv.org/abs/2412.16187#:~:text=computational%20costs,prefill%2F2x%20decoding%20speed%20against%20FastGen"> HashEvict: A Pre-Attention KV Cache Eviction Strategy using Locality-Sensitive Hashing</a>), among others, highlighting a vibrant research landscape focused on making LSH more practical and powerful for modern AI workflows.</p>]]></content:encoded></item><item><title><![CDATA[How would you decide ideal search similarity metrics for the use case]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/how-would-you-decide-ideal-search</link><guid isPermaLink="false">https://www.rohan-paul.com/p/how-would-you-decide-ideal-search</guid><pubDate>Mon, 16 Jun 2025 09:57:09 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!c_Uw!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!c_Uw!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!c_Uw!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png 424w, https://substackcdn.com/image/fetch/$s_!c_Uw!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png 848w, https://substackcdn.com/image/fetch/$s_!c_Uw!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png 1272w, https://substackcdn.com/image/fetch/$s_!c_Uw!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!c_Uw!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png" width="1024" height="508" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:508,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:793195,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166055769?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!c_Uw!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png 424w, https://substackcdn.com/image/fetch/$s_!c_Uw!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png 848w, https://substackcdn.com/image/fetch/$s_!c_Uw!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png 1272w, https://substackcdn.com/image/fetch/$s_!c_Uw!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c6d1a8f-1ed1-438d-9de0-1ab3588aadbd_1024x508.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ul><li><p>Similarity Metrics for Document Chunking in RAG Systems</p></li><li><p>Semantic vs. Lexical Similarity</p></li><li><p>Efficiency and Scalability</p></li><li><p>Robustness to Noise and OCR Errors</p></li><li><p>Chunking Strategies and Similarity</p></li><li><p>Choosing an Optimal Similarity Metric: Key Considerations</p></li><li><p>Sources</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Similarity Metrics for Document Chunking in RAG Systems</strong></h2><p>Retrieval-Augmented Generation (RAG) systems rely on retrieving relevant document chunks to ground the outputs of large language models (LLMs). A critical design choice is the <strong>similarity metric</strong> used to match queries with document text. Recent literature (2024&#8211;2025) examines both lexical and semantic similarity approaches, comparing their efficiency, scalability, and robustness in the context of document digitization (OCR) and chunking strategies. Below, we review key findings and practical considerations from the latest research.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Semantic vs. Lexical Similarity</strong></h2><p><strong>Lexical similarity</strong> metrics (e.g. TF-IDF or BM25) represent documents as sparse term vectors and score overlap of query and document terms (<a href="https://arxiv.org/pdf/2401.14887#:~:text=1980s%20are%20the%20basis%20for,referred%20to%20as%20sparse">The Power of Noise: Redefining Retrieval for RAG Systems</a>) . This approach excels at exact keyword matching but struggles with semantic paraphrases. <strong>Semantic similarity</strong> uses dense vector embeddings (typically neural encoders) and measures distances (e.g. cosine similarity) in embedding space . Dense embeddings capture conceptual relationships beyond exact wording, addressing lexical gap issues . A 2024 RAG survey notes that pure vector-based semantic search may <em>&#8220;miss lexically important matches,&#8221;</em> while pure keyword search <em>&#8220;could overlook semantic relationships.&#8221;</em> Balancing the two is a known challenge (<a href="https://arxiv.org/html/2412.12322v1#:~:text=A%20critical%20challenge%20in%20RAG,yet%20this%20relationship%20remains%20understudied">RAG Playground: A Framework for Systematic Evaluation of Retrieval Strategies and Prompt Engineering in RAG Systems</a>). In practice, semantic retrieval often uses cosine similarity or dot product between query and chunk embeddings (<a href="https://arxiv.org/pdf/2410.19572?#:~:text=model%E2%80%99s%20ability%20to%20generate%20coherent,quantifies%20the%20similarity%20between%20the">HERE</a>), whereas lexical methods use BM25 or related scoring for term overlap.</p><p><strong>Hybrid retrieval</strong> combines both types: e.g. performing parallel dense and sparse searches and merging results. This can yield more robust retrieval, as dense methods retrieve conceptually relevant text while lexical matching ensures important keywords aren&#8217;t missed . Indeed, multiple studies in 2024 advocate hybrid strategies as best-of-both-worlds solutions (<a href="https://arxiv.org/html/2409.06464v1#:~:text=appear%20to%20be%20a%20compelling,%282024">Operational Advice for Dense and Sparse Retrievers: HNSW, Flat, or Inverted Indexes?</a>) . Empirical results show that hybrid search can significantly improve RAG performance compared to using only one method . Recent work also explores reranking top results with cross-encoder models for finer semantic matching , though this is computationally expensive for large candidate sets.</p><h2><strong>Efficiency and Scalability</strong></h2><p>A key consideration in choosing a similarity metric is <strong>computational efficiency</strong> &#8211; both at query time and during indexing &#8211; and scalability to large corpora. Classic lexical indices (inverted indexes for BM25) are highly optimized and can retrieve results in milliseconds even from millions of documents. Neural semantic search requires computing embeddings and performing nearest-neighbor search in a high-dimensional space, which is more compute- and memory-intensive. Recent empirical evaluations provide insight into these trade-offs:</p><ul><li><p><strong>Throughput (QPS)</strong>: Lin (2024) compared a dense bi-encoder model (BGE) vs. a sparse learned model (SPLADE) and BM25 on BEIR benchmarks (<a href="https://arxiv.org/html/2409.06464v1#:~:text=Table%C2%A01%20%20also%20provides%20a,still%20a%20role%20for%20BM25">Operational Advice for Dense and Sparse Retrievers: HNSW, Flat, or Inverted Indexes?</a>). They found <em>no overwhelming winner</em> in retrieval quality alone &#8211; learned sparse and dense models had similar effectiveness &#8211; but <strong>BM25 was much faster</strong>, especially on large corpora . In the largest corpus tested (~1M+ documents), BM25 achieved an order-of-magnitude higher queries per second than the neural models . This highlights that in high-throughput or real-time applications, lexical methods still offer a performance advantage.</p></li><li><p><strong>Indexing and Memory</strong>: Dense vector search typically uses approximate nearest neighbor structures (like HNSW graphs) to scale. Building these indexes can be time-consuming for millions of embeddings, though they enable fast approximate search. Lin&#8217;s study advises that for corpora under ~1M documents, a brute-force (flat) index or even exhaustive search may be sufficient, as HNSW adds little benefit . For larger corpora, HNSW indexes drastically improve query latency at the cost of longer indexing time and slight accuracy loss . Notably, approximate indexes and quantization introduce minor degradation in retrieval effectiveness (e.g. small drops in nDCG), an important practical detail often overlooked in research . In contrast, inverted indexes for lexical search are relatively lightweight to build and update incrementally, making them scalable for dynamic knowledge bases.</p></li><li><p><strong>Embedding Computation</strong>: Semantic similarity requires encoding each query (and document) with a neural model. This adds latency per query and scales with model size. However, advances in embedding model efficiency (smaller models, knowledge distillation) and hardware acceleration have made it feasible for many applications. Practitioners often cache document embeddings offline, so the main cost is query encoding at runtime. Still, if extremely low latency is needed, lexical retrieval (which only requires simple text processing on queries) has an edge.</p></li></ul><p>In summary, lexical similarity (BM25) offers <strong>speed and scalability</strong>, while dense semantic similarity offers <strong>richer matching</strong> at higher computational cost. Depending on system constraints, a hybrid setup or cascaded approach (fast lexical retrieval to narrow candidates, followed by semantic rerank) may be optimal.</p><h2><strong>Robustness to Noise and OCR Errors</strong></h2><p>Document digitization via OCR introduces noise &#8211; misrecognized characters, words, and formatting &#8211; which can disrupt both lexical and semantic retrieval. Recent studies have specifically evaluated how different retrievers handle noisy text:</p><ul><li><p><strong>OCR Impact on Retrieval</strong>: Zhang et al. (2024) introduced OHRBench, a benchmark to assess OCR noise in RAG pipelines (<a href="https://arxiv.org/html/2412.02592v1#:~:text=knowledge%20bases%20are%20commonly%20built,primary%20types%20of%20OCR%20noise">OCR Hinders RAG: Evaluating the Cascading Impact of OCR on Retrieval-Augmented Generation</a>) . They evaluated a sparse BM25 retriever versus a dense embedding model (BGE) under increasing noise. On clean text, BM25 slightly outperformed the dense model, but as <strong>noise increased, BM25&#8217;s performance dropped sharply, eventually falling below the dense retriever</strong> . This indicates lexical similarity is highly sensitive to spelling and formatting errors &#8211; if a query term is garbled in OCR, BM25 fails to match it. Dense embeddings showed more robustness to semantic noise (e.g. character swaps or minor errors) , likely because the encoder can still capture contextual meaning to some extent. However, dense methods are not immune to noise either; very severe OCR errors degrade any model&#8217;s understanding.</p></li><li><p><strong>Multilingual/OCR QA</strong>: A 2025 multilingual QA study found that QA systems <em>&#8220;are highly prone to OCR-induced errors&#8221;</em> and suffer notable performance degradation on noisy text (<a href="https://arxiv.org/html/2502.16781v1#:~:text=and%20German,degradation%20on%20noisy%20OCR%20text">MultiOCR-QA: Dataset for Evaluating Robustness of LLMs in Question Answering on Multilingual OCR Texts</a>). This underscores the importance of robust retrieval when working with digitized documents. Techniques like query expansion or fuzzy matching can help lexical methods handle typos, whereas for semantic retrieval, finetuning embeddings on noisy text or using character-aware models can improve resilience.</p></li><li><p><strong>Structured Data and Format</strong>: Noise isn&#8217;t only character errors &#8211; formatting differences (tables, formulas, special symbols) also pose challenges. OHRBench identifies <em>formatting noise</em> (like LaTeX artifacts in extracted text) which can confuse retrievers (<a href="https://arxiv.org/html/2412.02592v1#:~:text=knowledge%20bases%20are%20commonly%20built,To%20better%20understand">OCR Hinders RAG: Evaluating the Cascading Impact of OCR on Retrieval-Augmented Generation</a>) . The study showed that certain advanced LLM-based retrievers were relatively robust to formatting clutter, but overall retrieval performance dipped when extraneous tokens were present . For instance, table-heavy queries saw up to ~10% retrieval performance drop for BM25 under noisy formatting . This suggests that cleaning OCR output (removing artifacts) or using models trained to ignore formatting tokens is important for robust similarity matching.</p></li></ul><p><strong>Practical takeaway:</strong> In scenarios with noise (e.g. scanned documents, user-generated text with typos), semantic similarity metrics tend to be more forgiving to imperfect text than strict lexical matching . A hybrid approach can also help: BM25 can retrieve exact matches for correctly recognized parts, while an embedding-based search can catch semantically relevant text that lexical search misses due to OCR errors. Additionally, pre-processing steps (spell correction, OCR post-processing) improve lexical retrieval robustness.</p><h2><strong>Chunking Strategies and Similarity</strong></h2><p>Large documents must be split into chunks for retrieval, but how to chunk can influence retrieval success. <strong>Fixed-size chunking</strong> (splitting text into equal-length segments) is simple and efficient, whereas <strong>semantic chunking</strong> aims to break documents at semantically coherent boundaries (e.g. topic shifts) by using similarity metrics. This is directly related to similarity measures: semantic chunking algorithms often use an embedding model to decide chunk boundaries (for example, splitting where adjacent sentences have low cosine similarity) (<a href="https://arxiv.org/pdf/2410.13070#:~:text=sentences,number%20of%20sentences%20in%20the">HERE</a>) .</p><p>A comprehensive study by Qu et al. (2024) questioned the value of semantic chunking. They evaluated retrieval and QA performance using semantic-based chunks vs. fixed-size chunks across tasks . <strong>The surprising result: the benefits of semantic chunking were inconsistent and often not enough to justify its higher computational cost</strong> . In some cases semantic chunks improved retrieval of relevant passages, but many times a simple fixed window (with possibly slight overlap) worked as well or better . The advantages of semantic segmentation were <em>&#8220;highly task-dependent and often insufficient to justify the added computational costs&#8221;</em> . In other words, using embedding-based similarity to create chunks (which requires encoding and clustering sentences) didn&#8217;t consistently boost downstream RAG performance.</p><p>On the other hand, other researchers still see promise in smarter chunking for complex queries. A technique called ChunkRAG (2024) proposed forming <em>&#8220;semantically coherent and non-overlapping chunks&#8221;</em> to better align with information needs (<a href="https://arxiv.org/pdf/2410.19572?#:~:text=with%20recent%20studies%20,hallucinations%20in%20the%20responses%20generated">HERE</a>) . This method groups consecutive sentences until a drop in cosine similarity (below a threshold) triggers a new chunk, ensuring each chunk is topically unified . The ChunkRAG pipeline then applied hybrid retrieval (BM25 + embedding ensemble) on these chunks, and additional filtering to remove redundancy (by eliminating chunks with very high mutual similarity) . Such a pipeline showed reduced irrelevance and redundancy in retrieved context, which can help mitigate LLM hallucinations. The mixed findings suggest that while naive semantic chunking alone may not always pay off (<a href="https://arxiv.org/pdf/2410.13070#:~:text=%E2%80%A2%20We%20present%20a%20novel%2C,2%20Chunking%20Strategies">HERE</a>), domain-specific chunking combined with robust retrieval/filtering can still improve RAG results in certain settings .</p><p><strong>Chunk size</strong> also affects similarity retrieval: smaller chunks (fine-grained) increase the chances that a relevant piece is retrieved but also risk losing context. Larger chunks carry more context but may dilute relevance scoring if they contain mixed content. The optimal balance can depend on the retrieval metric &#8211; lexical BM25 might favor smaller chunks (so query terms aren&#8217;t diluted by unrelated text), whereas embeddings can handle larger chunks since they encode broader context. Researchers often use overlap between fixed chunks to maintain context continuity . In practice, starting with a moderate fixed length (e.g. 200-300 tokens) and using overlap has been a robust baseline, with semantic-based chunking considered if a particular task shows benefit.</p><h2><strong>Choosing an Optimal Similarity Metric: Key Considerations</strong></h2><p>Recent studies converge on a few practical guidelines for selecting similarity metrics in RAG and search systems:</p><ul><li><p><strong>Task and Content Characteristics:</strong> If exact terminology or precision is crucial (e.g. legal or technical documents, structured fields), lexical similarity may be necessary to hit exact matches. If queries are more conceptual or the corpus uses varied language (synonyms, paraphrases), semantic embeddings will dramatically improve recall of relevant information (<a href="https://arxiv.org/pdf/2401.14887#:~:text=in%20deep%20learning%3B%20they%20utilize,can%20compete%20with%20sparse%20methods">The Power of Noise: Redefining Retrieval for RAG Systems</a>). For heterogeneous information needs, a hybrid approach is safest (<a href="https://arxiv.org/html/2409.06464v1#:~:text=appear%20to%20be%20a%20compelling,%282024">Operational Advice for Dense and Sparse Retrievers: HNSW, Flat, or Inverted Indexes?</a>).</p></li><li><p><strong>Scale and Latency Requirements:</strong> For <strong>large-scale</strong> search with millions of documents or strict latency constraints, efficient sparse methods (BM25 or learned sparse models) are attractive due to their speed . Dense retrieval can be scaled with ANN indexes and hardware, but requires more resources and careful tuning . If using dense retrieval at scale, investing in index optimization (HNSW, quantization) is important, and one should account for a small loss in retrieval accuracy from approximate search . Smaller deployments (e.g. enterprise documents up to a few hundred thousand) can comfortably use dense embeddings with flat indexes or hybrid search for better accuracy.</p></li><li><p><strong>Robustness Needs:</strong> In settings with noisy data (OCR-digitized archives, user text with typos, multilingual mixtures), embedding-based similarity is generally more robust to imperfect text (<a href="https://arxiv.org/html/2412.02592v1#:~:text=Semantic%20Noise%20significantly%20influences%20both,perturbation%20involving%20only%20plain%20text">OCR Hinders RAG: Evaluating the Cascading Impact of OCR on Retrieval-Augmented Generation</a>). Lexical metrics can be augmented with pre-processing (spell correction, synonym expansion) to partially mitigate this. If the knowledge base text is generated via OCR, consider using an OCR-specific benchmark or testing retrieval efficacy under various error rates (<a href="https://arxiv.org/html/2502.16781v1#:~:text=and%20German,degradation%20on%20noisy%20OCR%20text">MultiOCR-QA: Dataset for Evaluating Robustness of LLMs in Question Answering on Multilingual OCR Texts</a>). For highly structured text (tables, code, forms), no single similarity metric may suffice &#8211; specialized parsing or treating structure separately might be needed, as both BM25 and vanilla embeddings struggle with non-linear text layouts.</p></li><li><p><strong>Resource Constraints:</strong> Computing embeddings for every document and query introduces overhead. If computational budget is limited, one might use lexical search as a first-stage filter (cheaply narrowing down candidates) then apply a semantic re-rank on the top results. This two-stage setup often yields a good balance: BM25 ensures relevant keyword matches are not missed, and the reranker (using a more powerful semantic metric or cross-attention model) ensures the final ranking prioritizes truly relevant, on-topic chunks.</p></li><li><p><strong>Hybrid and Ensemble Methods:</strong> The consensus in late-2024 literature is that <strong>hybrid retrieval is a strong default</strong> (<a href="https://arxiv.org/html/2409.06464v1#:~:text=appear%20to%20be%20a%20compelling,%282024">Operational Advice for Dense and Sparse Retrievers: HNSW, Flat, or Inverted Indexes?</a>). By combining cosine similarity of embeddings with lexical scoring (sometimes via a weighted sum or by simply merging result lists), systems can cover each method&#8217;s blind spots. For example, one can retrieve top-$k by BM25 and top-$k by a dense model, then union these sets and re-rank them (possibly by an LLM or a learned ranker). This approach was shown to improve answer recall and downstream QA accuracy in several studies . The only downside is added complexity and the need to maintain two index types, but frameworks are emerging to support this seamlessly.</p></li></ul><p>In conclusion, <strong>semantic similarity metrics (e.g. embedding cosine)</strong> and <strong>lexical metrics (e.g. BM25)</strong> each have distinct strengths. Lexical methods offer speed, interpretability, and exact matching &#8211; valuable for large-scale and precision-critical search. Semantic methods offer superior recall and understanding, crucial for open-ended queries and overcoming vocabulary mismatch. The most <strong>robust RAG systems in 2024&#8211;2025 tend to use a combination</strong>: intelligent chunking to optimize the units of retrieval, hybrid similarity search to retrieve diversely relevant context, and multi-step filtering to ensure the retrieved chunks are relevant and not redundant (<a href="https://arxiv.org/pdf/2410.19572?#:~:text=model%E2%80%99s%20ability%20to%20generate%20coherent,quantifies%20the%20similarity%20between%20the">HERE</a>) . As research suggests, one should choose the similarity metric (or mix of metrics) by weighing the domain requirements (speed vs. accuracy vs. noise tolerance) and even consider adaptive strategies that can switch or ensemble methods as needed. This balanced approach is key to building scalable, efficient, and reliable RAG pipelines grounded in the latest findings from literature.</p><h2><strong>Sources:</strong></h2><ol><li><p>Renyi Qu <em>et al.</em> (2024). <em>&#8220;Is Semantic Chunking Worth the Computational Cost?&#8221;</em> &#8211; Evaluation of semantic vs. fixed chunking (<a href="https://arxiv.org/pdf/2410.13070#:~:text=challenge%20prevailing%20assumptions%20about%20the,insufficient%20to%20justify%20the%20added">HERE</a>) .</p></li><li><p>Jimmy Lin (2024). <em>&#8220;Dense vs. Sparse Retrieval: Operational Trade-offs.&#8221;</em> &#8211; Efficiency and effectiveness comparison of BM25, SPLADE, and embeddings (<a href="https://arxiv.org/html/2409.06464v1#:~:text=Table%C2%A01%20%20also%20provides%20a,still%20a%20role%20for%20BM25">Operational Advice for Dense and Sparse Retrievers: HNSW, Flat, or Inverted Indexes?</a>) .</p></li><li><p>Junyuan Zhang <em>et al.</em> (2024). <em>&#8220;OCR Hinders RAG&#8221;</em> &#8211; Impact of OCR noise on lexical (BM25) vs. dense retrieval performance (<a href="https://arxiv.org/html/2412.02592v1#:~:text=Semantic%20Noise%20significantly%20influences%20both,perturbation%20involving%20only%20plain%20text">OCR Hinders RAG: Evaluating the Cascading Impact of OCR on Retrieval-Augmented Generation</a>).</p></li><li><p>RAG Playground (2024). <em>&#8220;Framework for Evaluating Retrieval Strategies.&#8221;</em> &#8211; Noted challenge of semantic vs lexical matching and benefits of hybrid search (<a href="https://arxiv.org/html/2412.12322v1#:~:text=A%20critical%20challenge%20in%20RAG,yet%20this%20relationship%20remains%20understudied">RAG Playground: A Framework for Systematic Evaluation of Retrieval Strategies and Prompt Engineering in RAG Systems</a>) .</p></li><li><p>ChunkRAG (2024). <em>&#8220;Mitigating Irrelevance and Hallucinations in RAG.&#8221;</em> &#8211; Uses semantic chunking + hybrid retrieval; demonstrates redundancy filtering with cosine similarity (<a href="https://arxiv.org/pdf/2410.19572?#:~:text=model%E2%80%99s%20ability%20to%20generate%20coherent,quantifies%20the%20similarity%20between%20the">HERE</a>) .</p></li><li><p>MultiOCR-QA (2025). <em>&#8220;Robustness of QA on Noisy OCR Text.&#8221;</em> &#8211; OCR errors significantly degrade QA performance, highlighting need for robust retrieval (<a href="https://arxiv.org/html/2502.16781v1#:~:text=the%20effects%20of%20OCR%20noise,degradation%20on%20noisy%20OCR%20text">MultiOCR-QA: Dataset for Evaluating Robustness of LLMs in Question Answering on Multilingual OCR Texts</a>).</p></li></ol>]]></content:encoded></item><item><title><![CDATA[Vector Databases for RAG Literature Review]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/vector-databases-for-rag-literature</link><guid isPermaLink="false">https://www.rohan-paul.com/p/vector-databases-for-rag-literature</guid><pubDate>Mon, 16 Jun 2025 09:54:47 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!K-0S!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!K-0S!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!K-0S!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png 424w, https://substackcdn.com/image/fetch/$s_!K-0S!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png 848w, https://substackcdn.com/image/fetch/$s_!K-0S!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png 1272w, https://substackcdn.com/image/fetch/$s_!K-0S!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!K-0S!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png" width="1024" height="583" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/d902d104-d345-48a2-b646-e977e808ccc6_1024x583.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:583,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:872382,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166055581?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!K-0S!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png 424w, https://substackcdn.com/image/fetch/$s_!K-0S!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png 848w, https://substackcdn.com/image/fetch/$s_!K-0S!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png 1272w, https://substackcdn.com/image/fetch/$s_!K-0S!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd902d104-d345-48a2-b646-e977e808ccc6_1024x583.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><p><strong>Table of Contents</strong></p><ul><li><p>Vector Databases for RAG Literature Review</p></li><li><p>Introduction</p></li><li><p>Evaluation Criteria for Vector Databases</p></li><li><p>Comparison of Leading Vector Databases 2024-2025</p><ul><li><p>Pinecone</p></li><li><p>Weaviate</p></li><li><p>Milvus</p></li><li><p>Qdrant</p></li><li><p>Chroma</p></li></ul></li><li><p>Comparative Insights and Recommendations</p></li><li><p>Conclusion</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Introduction</strong></h2><p>Retrieval-Augmented Generation (RAG) pipelines rely on vector databases to store and search document embeddings. In a typical RAG workflow, documents are <strong>digitized and chunked</strong> into passages, each encoded as a high-dimensional vector. A user query is likewise embedded and used to retrieve the most similar chunks from the vector store (<a href="https://arxiv.org/pdf/2402.05131#:~:text=a%20vector%20database%20%28vectordb%29,retrieved%20from%20the%20vector%20database">HERE</a>) . This integration of vector search allows large language models to ground their answers in relevant data, mitigating hallucinations by providing factual context (<a href="https://arxiv.org/html/2402.01763v3#:~:text=In%20the%20prototype%20of%20the,massive%20data%20owned%20by%20users">When Large Language Models Meet Vector Databases: A Survey</a>) . The past few years have seen a surge of interest in such <strong>Vector Database Management Systems (VDBMS)</strong> &#8211; with over 20 systems introduced in the last five years (<a href="https://arxiv.org/abs/2310.14021#:~:text=,to%20systems%20are%20new%20data"> Survey of Vector Database Management Systems</a>) &#8211; driven by the need for <strong>fast, scalable, and reliable</strong> similarity search to support LLMs . Below, we review recent 2024&#8211;2025 research (primarily arXiv and other reputable sources) on vector databases in RAG contexts, focusing on four key criteria: <strong>retrieval speed</strong>, <strong>storage efficiency</strong>, scalability, and <strong>query accuracy</strong>.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Evaluation Criteria for Vector Databases</strong></h2><ul><li><p><strong>Retrieval Speed:</strong> The end-to-end latency of similarity search queries and throughput (queries per second). Low-latency retrieval is critical for interactive LLM applications. Modern approximate nearest neighbor (ANN) algorithms (e.g. HNSW graphs) enable <strong>fast retrieval with high accuracy</strong> , often achieving sub-10ms response times on million-scale corpora.</p></li><li><p><strong>Storage Efficiency:</strong> Memory and disk footprint required to store embeddings and indexes. Vector indices can be memory-intensive, especially graph-based indexes, so techniques like product quantization and disk-based storage are used to compress vectors (<a href="https://arxiv.org/pdf/2310.14021#:~:text=zhang2016%20%2C%20other%20efforts%20have,sivic2003%20%3B%20jegou2011product"> Survey of Vector Database Management Systems</a>). Efficient storage is vital for scaling to billions of embeddings without exorbitant RAM usage.</p></li><li><p><strong>Scalability:</strong> The ability to handle very large corpora and high query loads by scaling up (more powerful hardware) or out (distributed clusters). Some vector DBs run on a single node (suitable for smaller datasets ), while others support sharding across many nodes for virtually unlimited scale . Robust scalability ensures performance remains high even as data grows.</p></li><li><p><strong>Query Accuracy:</strong> The precision/recall of nearest-neighbor search results (how often the true nearest vectors are retrieved). ANN methods trade a tiny drop in accuracy for speed; the best systems maintain &gt;95% recall of true neighbors (<a href="https://qdrant.tech/benchmarks/#:~:text=qdrant%20qdrant,angular%200.27%201.16%20393.31%20441.32">Vector Database Benchmarks - Qdrant</a>). In practice, <strong>high recall</strong> is needed so retrieved chunks are relevant to the query, which in turn improves the fidelity of the generated answers in RAG.</p></li></ul><h2><strong>Comparison of Leading Vector Databases 2024-2025</strong></h2><h3><strong>Pinecone</strong></h3><ul><li><p><strong>Retrieval Speed:</strong> Pinecone is a fully managed cloud vector DB known for low-latency queries. It employs advanced ANN indexes under the hood (proprietary, but likely graph-based or hybrid) to ensure millisecond-level search even on large scales. While specific benchmarks from research literature are sparse (Pinecone&#8217;s implementation is closed-source), it is designed to optimize for <strong>high throughput and low query latency</strong> across distributed infrastructure.</p></li><li><p><strong>Storage Efficiency:</strong> As a managed service, Pinecone handles storage behind the scenes. It reportedly uses a mix of in-memory and disk techniques to balance speed and cost. Details in literature are limited, but Pinecone likely leverages vector compression or quantization to reduce memory footprint when storing billions of embeddings. Users do not directly tune this, but benefit from <strong>storage optimizations</strong> implemented by the service.</p></li><li><p><strong>Scalability:</strong> Pinecone excels in scalability &#8211; it automatically shards and distributes indexes across nodes. It offers a <strong>seamless scalable system</strong>, where users can index massive corpora without managing servers (<a href="https://arxiv.org/pdf/2310.14021#:~:text=Pinecone%20pine%20%20offers%20a,meant%20for%20a%20single%20machine"> Survey of Vector Database Management Systems</a>). This distributed design is similar to systems like Vald, making Pinecone very <em>user-friendly for large-scale deployments</em> . Many organizations choose Pinecone when they require virtually unlimited scale and easy maintenance in production.</p></li><li><p><strong>Query Accuracy:</strong> Pinecone is engineered to preserve high accuracy in ANN searches. It likely uses high-recall index configurations by default, so that results closely match those of exact nearest neighbor search. In practice, Pinecone can achieve ~95&#8211;100% recall (depending on how it&#8217;s configured) while still maintaining speed. It supports tunable accuracy (e.g. adjusting search parameters) if users need to trade off latency for even higher precision.</p></li></ul><h3><strong>Weaviate</strong></h3><ul><li><p><strong>Retrieval Speed:</strong> Weaviate is an open-source vector DB (written in Go) that uses an HNSW graph index by default. It delivers fast retrieval; for instance, in a 1M vector dataset benchmark, Weaviate handled ~1,100 queries/sec with ~5ms average latency (<a href="https://qdrant.tech/benchmarks/#:~:text=qdrant%20qdrant,angular%200.27%201.16%20393.31%20441.32">Vector Database Benchmarks - Qdrant</a>). This is only slightly behind the fastest engines. Weaviate&#8217;s search performance has improved over time, though one report noted it showed the <strong>least improvement</strong> among peers in recent tests . Still, it provides interactive-speed queries and integrates well with RAG pipelines (as demonstrated in financial QA tasks using Weaviate for chunk retrieval (<a href="https://arxiv.org/pdf/2402.05131#:~:text=converted%20into%20a%20vector%20representation,a%20prompt%20based%20on%20the">HERE</a>)).</p></li><li><p><strong>Storage Efficiency:</strong> By default Weaviate stores all vectors and the HNSW index in memory, which can be memory-intensive for very large datasets. However, Weaviate supports optional <strong>Product Quantization (PQ) compression</strong> &#8211; it can construct HNSW indexes over compressed vectors . This significantly reduces memory usage (with minimal accuracy loss), making Weaviate more storage-efficient for large corpora. The index itself (HNSW) has moderate overhead, which is generally reasonable , but very large databases might require quantization or filtering to control memory growth.</p></li><li><p><strong>Scalability:</strong> Weaviate supports scaling out in a cluster configuration. It allows sharding of data classes across multiple nodes and has a hybrid architecture to combine vector search with symbolic filters. While not a managed service, it can be run distributed in production. Several companies run Weaviate on multi-node setups for datasets in the order of hundreds of millions of vectors. Its architecture provides <strong>native support for distributed search</strong> (scatter-gather across shards), although managing a cluster requires more effort than a managed solution .</p></li><li><p><strong>Query Accuracy:</strong> Thanks to HNSW, Weaviate achieves high recall. In benchmarks it reached ~97&#8211;99% precision/recall at 10 nearest neighbors , indicating that it retrieves nearly all relevant chunks. The ANN algorithm yields fast results <strong>without sacrificing much accuracy</strong> . Furthermore, Weaviate allows tuning HNSW parameters (M, ef) to adjust the speed-accuracy balance. In summary, Weaviate provides strong query accuracy out-of-the-box, suitable for RAG use cases that demand precise retrieval of supporting passages.</p></li></ul><h3><strong>Milvus</strong></h3><ul><li><p><strong>Retrieval Speed:</strong> Milvus (an open-source DB by Zilliz) supports multiple index types (HNSW, IVF, PQ, etc.). Its query speed can vary depending on the index chosen. On one extreme, Milvus can do brute-force (exact) search very quickly using optimized BLAS, but that doesn&#8217;t scale past small datasets. For ANN, if using HNSW, its query performance is comparable to other HNSW-based systems. However, one benchmark showed Milvus lagging in search throughput for high-dimensional data: e.g. ~219 QPS with ~393ms latency on 1M 1536-dim embeddings (with HNSW parameters M=16, ef=128) . This suggests default configurations may not be tuned for latency. On the other hand, Milvus was <strong>extremely fast in indexing</strong> new data &#8211; it built an index 10&#215; faster than some competitors . In summary, Milvus can retrieve quickly, but achieving top-tier query latency may require careful index selection and tuning.</p></li><li><p><strong>Storage Efficiency:</strong> A strength of Milvus is flexibility in index storage. It can use quantized indexes (IVF-PQ, SQ) to greatly reduce memory usage for embeddings. For example, IVF with Product Quantization compresses vectors into small codes, dramatically saving space at some cost to accuracy (<a href="https://arxiv.org/pdf/2310.14021#:~:text=Mem,R%20%E2%9C%97%20%20%20RPTree"> Survey of Vector Database Management Systems</a>). Milvus also offers a disk-based index (SPANN/DiskANN) for very large datasets, storing vectors on SSD while keeping only graphs or centroids in RAM . These options make Milvus highly efficient in storage &#8211; users can opt for an <em>IVF-PQ index with lower memory and moderate recall, or HNSW for higher memory and recall</em>. The ability to mix and match indexes means Milvus can be tailored to available hardware resources.</p></li><li><p><strong>Scalability:</strong> Milvus is built with a distributed architecture (Milvus 2.x) &#8211; it uses a cluster of components (query nodes, index nodes, etcd, etc.) to manage large workloads. It natively supports sharding and replicas, enabling it to scale to billions of vectors across multiple machines. Many large-scale vector search deployments (in 2024) use Milvus clusters in production. <strong>Distributed search</strong> is a core feature: the query is broadcast to all shards and partial results aggregated . This allows Milvus to maintain throughput as data grows. In short, Milvus handles scalability well, albeit with higher operational complexity since it&#8217;s self-hosted.</p></li><li><p><strong>Query Accuracy:</strong> Milvus can achieve <strong>high accuracy</strong> depending on index type. With HNSW or a fine-grained IVF (large number of centroids + residual PQ), Milvus can return ~99% recall of nearest neighbors . Its default HNSW settings in one test reached 0.99 precision . However, if using heavy compression (e.g. aggressive PQ), accuracy will drop. Research indicates graph-based approaches (like HNSW) generally <strong>surpass quantization-based methods (IVFPQ) in recall</strong> at the cost of more memory (<a href="https://arxiv.org/pdf/2406.19651#:~:text=generally%20surpass%20ranging,of%20increased%20memory%20usage%20leading">HERE</a>). Thus, for mission-critical accuracy, Milvus users might prefer HNSW or high-precision IVF settings. Milvus gives the user control to pick that accuracy/speed trade-off as needed.</p></li></ul><h3><strong>Qdrant</strong></h3><ul><li><p><strong>Retrieval Speed:</strong> Qdrant (open-source, in Rust) has distinguished itself with excellent speed. Recent benchmarks (2024) show Qdrant achieving the <strong>highest throughput and lowest query latencies</strong> among vector DBs in many scenarios (<a href="https://qdrant.tech/benchmarks/#:~:text=,or%20more%20number%20of%20vectors">Vector Database Benchmarks - Qdrant</a>). For example, on a 1M dataset (1536-dim embeddings), Qdrant handled ~1,238 queries/sec with ~3.5ms average latency, while maintaining 99% recall . This was the top performance, outperforming similar HNSW-based systems. Qdrant&#8217;s efficiency is attributed to its Rust optimizations and data structures. In summary, Qdrant offers <strong>state-of-the-art retrieval speed</strong>, making it ideal for latency-sensitive RAG applications.</p></li><li><p><strong>Storage Efficiency:</strong> Qdrant uses an HNSW index in memory by default, so its baseline memory usage is comparable to Weaviate or other HNSW implementations. However, the Qdrant team has incorporated techniques like <strong>binary vector compression</strong> and optimized IO to improve storage efficiency . While the full memory vs. accuracy benchmarks are still in progress (they indicated a memory consumption benchmark &#8220;coming soon&#8221;), Qdrant is actively adding support for on-disk indexes and quantization. This means Qdrant can trade some accuracy for a smaller footprint when needed. For now, with default settings, expect memory usage proportional to dataset size (plus HNSW overhead), which is fine up to many millions of vectors but could be heavy at billion-scale without compression.</p></li><li><p><strong>Scalability:</strong> Initially, Qdrant was single-node, but it now offers a <strong>distributed (cluster) mode</strong> to scale out across multiple nodes (released in late 2024). This allows sharding the vector data and parallelizing searches, similar to other distributed VDBMSs . Qdrant&#8217;s design, being cloud-native (they also offer a managed Qdrant Cloud), focuses on horizontal scalability while keeping latency low. Early indications are that Qdrant&#8217;s cluster mode preserves its speed advantage even as data grows. Additionally, Qdrant integrates well with ecosystem tools (like Azure Cognitive Search using Qdrant under the hood for vector queries (<a href="https://arxiv.org/html/2402.01763v3#:~:text=Search%20,5%7D5%20https%3A%2F%2Fvespa.ai">When Large Language Models Meet Vector Databases: A Survey</a>)), showing it can handle enterprise-scale workloads.</p></li><li><p><strong>Query Accuracy:</strong> Qdrant&#8217;s HNSW ensures high recall. In tests it achieved <strong>99% precision</strong> (essentially nearly exact results) while still being fastest . It supports tuning search parameters (ef search, etc.) to adjust accuracy. By default, Qdrant appears to target very high recall, which is beneficial for RAG (we want the correct supporting chunks). There is no notable accuracy penalty for using Qdrant&#8217;s ANN &#8211; like others, it can retrieve with &#8220;high accuracy&#8221; comparable to exact search (<a href="https://arxiv.org/pdf/2402.05131#:~:text=converted%20into%20a%20vector%20representation,a%20prompt%20based%20on%20the">HERE</a>). Overall, Qdrant reliably returns relevant neighbors, and its accuracy remains on par with the best of vector databases.</p></li></ul><h3><strong>Chroma</strong></h3><ul><li><p><strong>Retrieval Speed:</strong> Chroma is an open-source vector store often used in lightweight RAG setups (especially with LangChain). It is designed for simplicity and runs locally (Python environment). Chroma&#8217;s core is built on FAISS, so its retrieval speed on a single machine is decent &#8211; it can perform ANN searches in a few milliseconds for moderate dataset sizes. However, being Python-based, extremely high throughput could be limited by GIL and API overhead. Chroma is sufficient for prototyping or small-scale use (e.g. thousands to low millions of vectors), delivering interactive speeds, but it may not match the optimized C++/Rust systems on very large loads.</p></li><li><p><strong>Storage Efficiency:</strong> By default, Chroma stores embeddings in an SQLite or DuckDB and uses FAISS for indexes in memory. It does not (out-of-the-box) apply advanced compression unless you manually configure a FAISS index type like IVF or PQ. In standard use, it keeps full precision vectors, which means higher memory usage per vector (e.g. 1536-dim float vector &#8776; 6 KB). For many applications this is fine, but for larger scales, memory can become a bottleneck. Chroma&#8217;s simplicity trades off some efficiency; it does not yet have built-in distributed storage or automatic vector compression. Users looking to save space might need to manually compress embeddings before insertion.</p></li><li><p><strong>Scalability:</strong> <strong>Chroma is a single-node system</strong> &#8211; it&#8217;s not designed to be distributed across servers (<a href="https://arxiv.org/pdf/2310.14021#:~:text=Pinecone%20pine%20%20offers%20a,meant%20for%20a%20single%20machine"> Survey of Vector Database Management Systems</a>). It works great on a personal machine or a single server, but it cannot natively shard data across multiple machines. This limits its scalability to the constraints of one machine&#8217;s RAM and disk. In practice, Chroma is popular for managing <strong>small to mid-size corpora</strong> in RAG (e.g., a few hundred thousand chunks), but for very large document collections (tens of millions of chunks), one would have to move to a more scalable solution or run multiple Chromas manually partitioned.</p></li><li><p><strong>Query Accuracy:</strong> Chroma leverages FAISS for similarity search, so it can achieve high accuracy depending on the index used. By default, it might use a flat (exact) or HNSW index, which yields 100% or &gt;99% recall respectively, at the cost of speed (flat) or using more memory (HNSW). Thus, accuracy is usually not a concern &#8211; Chroma can return perfectly accurate nearest neighbors if configured to do so. If using approximate indexes, it&#8217;s as accurate as FAISS&#8217;s implementation (which is well-regarded). In summary, Chroma&#8217;s query accuracy is strong; the user can decide to use exact search for full accuracy or ANN for a balance, just as with other systems. The main limitation is not accuracy but rather performance at scale.</p></li></ul><h2><strong>Comparative Insights and Recommendations</strong></h2><p><strong>Retrieval Speed:</strong> If <strong>fast query processing</strong> is the top priority, Qdrant stands out as the leading choice, with benchmarks showing it outperforming other solutions in latency and throughput (<a href="https://qdrant.tech/benchmarks/#:~:text=,or%20more%20number%20of%20vectors">Vector Database Benchmarks - Qdrant</a>). Its Rust-based engine delivers consistently low query times even with million-scale data. Weaviate and Pinecone are also proven low-latency performers (both leveraging HNSW), suitable for real-time applications (<a href="https://arxiv.org/pdf/2402.05131#:~:text=converted%20into%20a%20vector%20representation,a%20prompt%20based%20on%20the">HERE</a>). Milvus can be fast, but may require tuning to reach the same level. For smaller-scale or development use, Chroma is usually &#8220;fast enough,&#8221; but for production at scale, a highly optimized engine like Qdrant or Weaviate is recommended.</p><p><strong>Storage Efficiency:</strong> When memory or disk footprint is the main concern, consider solutions that support vector compression. Milvus offers IVF and PQ indexes to drastically cut down storage needs, making it ideal for very large corpora on limited hardware. Weaviate&#8217;s support for PQ-compressed vectors is another advantage if you need to save RAM (<a href="https://arxiv.org/pdf/2310.14021#:~:text=As%20seen%20from%20Table%C2%A06%2C%20HNSW,a%20concern%20for%20very%20large"> Survey of Vector Database Management Systems</a>). If using Qdrant, look into its emerging compression features (e.g. binary quantization) or run it on hardware with fast SSDs to supplement RAM. Pinecone manages storage for you and likely uses its own optimizations, but you may incur costs for large datasets. In scenarios where <strong>storage efficiency outweighs raw accuracy</strong>, using Milvus with a compressed index (IVF-PQ) is a strong option &#8211; it will sacrifice a bit of recall but use significantly less memory (<a href="https://arxiv.org/pdf/2406.19651#:~:text=generally%20surpass%20ranging,of%20increased%20memory%20usage%20leading">HERE</a>).</p><p><strong>Scalability:</strong> For <strong>massive scale deployments</strong>, Pinecone is often the top recommendation due to its effortless scaling and managed infrastructure &#8211; you can index billions of vectors and let Pinecone handle the distribution . Among open-source systems, Milvus and Weaviate have proven distributed modes capable of handling very large data if you have the DevOps resources to manage a cluster. Qdrant&#8217;s new clustering is promising for scale-out as well. If your use case involves web-scale data or high availability requirements, a distributed vector DB (Pinecone, or self-hosted Milvus/Weaviate cluster) is the way to go. For smaller-scale (single node) needs, Chroma or a single-instance of Qdrant/Weaviate is simpler and will work just fine &#8211; don&#8217;t over-engineer scaling if you don&#8217;t need it.</p><p><strong>Query Accuracy:</strong> All modern vector databases can be tuned to achieve high recall. If <strong>precision of retrieval</strong> is paramount (e.g. in domains where missing a relevant document is unacceptable), consider using HNSW-based systems like <strong>Qdrant or Weaviate</strong>, which tend to preserve semantic relationships and yield very high recall by default (<a href="https://arxiv.org/pdf/2406.19651#:~:text=generally%20surpass%20ranging,of%20increased%20memory%20usage%20leading">HERE</a>). In fact, Qdrant and Weaviate both reached ~99% recall in evaluations (<a href="https://qdrant.tech/benchmarks/#:~:text=qdrant%20qdrant,angular%200.27%201.16%20393.31%20441.32">Vector Database Benchmarks - Qdrant</a>), meaning their ANN results were almost identical to exact search. Milvus can also attain high accuracy; just avoid overly aggressive compression if recall is critical. When maximum accuracy is needed, you can configure any of these systems with conservative ANN settings (or even brute-force search for smaller data) at the cost of some speed. In summary, <strong>for most RAG workflows, the slight differences in accuracy between top vector DBs are negligible</strong> &#8211; all can return highly relevant chunks &#8211; so you might decide based on other factors. Only if you plan to heavily compress vectors to save space will accuracy drop a bit, in which case favor a system that allows hybrid retrieval (e.g. rerank results or adjust ANN parameters).</p><h2><strong>Conclusion</strong></h2><p><strong>Choosing the &#8220;best&#8221; vector database depends on your priority:</strong> For sheer speed, Qdrant is a front-runner; for minimal storage use, Milvus (with compression) or Weaviate (with PQ) are excellent; for effortless massive scaling, Pinecone is compelling; and for balanced performance with open-source flexibility, Weaviate and Qdrant are great all-rounders. All these databases have been successfully used in 2024&#8211;2025 RAG pipelines to enable quick and accurate retrieval of document chunks (<a href="https://arxiv.org/pdf/2402.05131#:~:text=converted%20into%20a%20vector%20representation,a%20prompt%20based%20on%20the">HERE</a>). The research and benchmarks indicate that vector databases have matured to deliver <strong>millisecond-level retrieval, efficient indexing, horizontal scalability, and high recall</strong>, powering the next generation of LLM applications with relevant knowledge (<a href="https://arxiv.org/pdf/2310.14021#:~:text=match%20at%20L1207%20As%20seen,a%20concern%20for%20very%20large"> Survey of Vector Database Management Systems</a>). Future work will continue to refine these systems &#8211; improving consistency, hybrid query handling, and testing methodologies (<a href="https://arxiv.org/html/2502.20812v1#:~:text=propelled%20Vector%20Database%20Management%20Systems,begin%20by%20conducting%20an%20empirical">Towards Reliable Vector Database Management Systems: A Software Testing Roadmap for 2030</a>) &#8211; but even now, developers can pick a vector store that best fits their needs from a rich landscape of capable solutions.</p><p><strong>Sources:</strong> Recent literature and benchmarks on vector databases and RAG (2024&#8211;2025) (<a href="https://qdrant.tech/benchmarks/#:~:text=,or%20more%20number%20of%20vectors">Vector Database Benchmarks - Qdrant</a>), including surveys from arXiv and VLDB that compare design and performance aspects (<a href="https://arxiv.org/abs/2310.14021#:~:text=century%20and%20more,difficulty%20of%20efficiently%20answering%20hybrid"> Survey of Vector Database Management Systems</a>). Each of the databases discussed (Pinecone, Weaviate, Milvus, Qdrant, Chroma) is referenced in contemporary studies or official benchmarks to highlight their strengths and trade-offs. The recommendations above synthesize these findings to guide selection based on speed, memory, scale, and accuracy considerations.</p>]]></content:encoded></item><item><title><![CDATA[Clustering techniques used in document digitization and chunking for LLMs, focusing on their role in reducing search space]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/clustering-techniques-used-in-document</link><guid isPermaLink="false">https://www.rohan-paul.com/p/clustering-techniques-used-in-document</guid><pubDate>Mon, 16 Jun 2025 09:50:48 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!B1M1!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!B1M1!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!B1M1!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png 424w, https://substackcdn.com/image/fetch/$s_!B1M1!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png 848w, https://substackcdn.com/image/fetch/$s_!B1M1!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png 1272w, https://substackcdn.com/image/fetch/$s_!B1M1!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!B1M1!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png" width="1024" height="426" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:426,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:620376,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166055079?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!B1M1!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png 424w, https://substackcdn.com/image/fetch/$s_!B1M1!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png 848w, https://substackcdn.com/image/fetch/$s_!B1M1!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png 1272w, https://substackcdn.com/image/fetch/$s_!B1M1!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F21595a5b-23e9-4eb3-947e-6b0e87017a72_1024x426.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ul><li><p>Clustering for Search Space Reduction in LLM Retrieval</p></li><li><p>K-Means Clustering</p></li><li><p>Hierarchical Clustering</p></li><li><p>Spectral Clustering</p></li><li><p>Density-Based Clustering</p></li><li><p>Deep Clustering and LLM-Assisted Methods</p></li><li><p>When Clustering Falls Short and Mitigations</p></li><li><p>Alternatives to Clustering for Reducing Search Space</p></li><li><p>Sources</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Clustering for Search Space Reduction in LLM Retrieval</strong></h2><p>Clustering is a core technique in document digitization and chunking pipelines for large language models (LLMs) because it groups similar content, allowing searches to be confined to a few relevant clusters instead of the entire corpus. In vector databases for Retrieval-Augmented Generation (RAG), for example, partitioning the embedding datastore via <em>k</em>-means clustering (a popular inverted file index or IVF approach) means a query only compares against vectors in the closest cluster(s) (<a href="https://arxiv.org/html/2502.20969v1#:~:text=In%20this%20paper%2C%20we%20identify,the%20overall%20retrieval%20latency%20still">TeleRAG: Efficient Retrieval-Augmented Generation Inference with Lookahead Retrieval</a>). This significantly cuts down comparisons and latency. Akesson et al. (2024) demonstrate this in <em>Clustered RAG (CRAG)</em>: by clustering similar document reviews and summarizing each cluster, they reduced the prompt tokens by 46&#8211;90% without degrading answer quality (<a href="https://arxiv.org/html/2406.00029v1#:~:text=compared%20to%20a%20solution%20using,in">Clustered Retrieved Augmented Generation (CRAG)</a>). Lin et al. (2025) likewise note that IVF pre-clustering &#8220;limits the search space to relevant clusters&#8221; at runtime , transferring only those clusters to GPU memory for fast retrieval. In essence, clustering exploits the &#8220;cluster hypothesis&#8221; &#8211; relevant pieces of information tend to live together &#8211; to avoid exhaustive search.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>K-Means Clustering</strong></h2><p><em>K</em>-means is one of the most widely used clustering algorithms in document retrieval systems due to its simplicity and efficiency. It partitions embeddings into <em>k</em> clusters of roughly spherical shape by minimizing intra-cluster distance. Many RAG systems apply <em>k</em>-means during indexing; for instance, vector indexes often use <em>k</em>-means centroids as representatives so that a query first finds the nearest centroid(s) and then searches only that partition (<a href="https://www.pinecone.io/learn/a-developers-guide-to-ann-algorithms/#:~:text=A%20spatial%20partitioning%20index%20organizes,query%20at%20the%20red%20x">A Developer&#8217;s Guide to Approximate Nearest Neighbor (ANN) Algorithms | Pinecone</a>). This <em>two-stage search</em> greatly reduces candidate chunks to consider . CRAG uses <em>k</em>-means to group semantically similar reviews before summarization , and the authors suggest exploring alternative clustering algorithms to further improve results . However, a limitation of <em>k</em>-means is that it assumes convex clusters of similar size. When document embeddings don&#8217;t form neat spherical groups or when an item lies near a cluster boundary, <em>k</em>-means can miscluster relevant pieces. This can lead to missing information if a query&#8217;s answer spans multiple clusters. A common mitigation is to search multiple clusters: rather than only the top-1 closest cluster, retrieve from the top-<em>N</em> clusters to improve recall at some cost. Lin et al. (2025) address this by concurrently searching any &#8220;missed&#8221; clusters on CPU to merge with the main results, ensuring no relevant chunk is skipped . In practice, selecting a slightly larger <em>k</em> (more fine-grained clusters) or using overlapping cluster assignments can also alleviate boundary effects.</p><h2><strong>Hierarchical Clustering</strong></h2><p>Hierarchical methods build a tree of clusters at multiple granularity levels, which is very useful for organizing large documents or multi-topic corpora. Recent RAG frameworks store documents in hierarchical structures (e.g. chapters &#8594; sections &#8594; paragraphs) and perform <em>coarse-to-fine</em> retrieval. Goel and Chandak (2024) introduce HIRO, a hierarchical retrieval that performs a depth-first search through a document tree, pruning entire branches whose summary embeddings have low similarity to the query (<a href="https://arxiv.org/html/2406.09979v1#:~:text=LLMs%20struggle%20with%20long%20contexts%2C,the%20NarrativeQA%20dataset%20by%20an">HIRO: Hierarchical Information Retrieval Optimization</a>) . By recursively scoring parent nodes and only drilling into relevant branches, HIRO minimizes context passed to the LLM &#8220;without informational loss,&#8221; yielding a &gt;10% performance gain on NarrativeQA . Hierarchical clustering of chunks can thus reduce search space dramatically &#8211; the query ignores whole sections of data that are irrelevant. A similar idea is used in RAPTOR (2024), which recursively clusters and summarizes text into a tree structure for long-document QA. The challenge with hierarchical clustering is choosing cut-offs for pruning; if set too aggressively, relevant leaves might be pruned (a failure mode). To mitigate this, systems often use a threshold on similarity scores and ensure some exploration of sibling nodes. Overall, hierarchical clustering offers a balanced strategy: broad clusters quickly narrow down scope, then finer clusters ensure detailed coverage.</p><h2><strong>Spectral Clustering</strong></h2><p>Spectral clustering treats document chunks as nodes in a graph, using pairwise similarity (e.g. cosine of embeddings) to create a similarity matrix. By computing the eigenvectors of this matrix (Laplacian), spectral methods can partition the graph into clusters that are not necessarily spherical or equal-size. This flexibility means spectral clustering can capture complex topical structures &#8211; clusters of &#8220;diverse shapes [and] densities&#8221; in text data (<a href="https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0313238#:~:text=Spectral%20clustering%20methods%20are%20known,This%20link%20enables%20to%20provide">Explainable Graph Spectral Clustering of text documents | PLOS One</a>) &#8211; which might be missed by centroid-based methods. For instance, a spectral clustering on a citation graph or semantic network could group documents by theme even if their embeddings are not contiguous in vector space. The downside is computational cost: building and diagonalizing an <em>N&#215;N</em> similarity matrix is expensive for large corpora, making spectral clustering less common for real-time LLM retrieval. Moreover, the resulting clusters can be hard to interpret or explain in terms of original content . In practice, spectral clustering may be used on smaller subsets or offline to inform indexing. Recent text clustering surveys note that graph-based methods like spectral clustering &#8220;provide a structured approach to understanding the global structure of document relationships&#8221; (<a href="https://thegrenze.com/pages/servej.php?fn=358_1.pdf&amp;name=Recent%20Advances%20in%20Text%20Documents%20Clustering&amp;id=3316&amp;association=GRENZE&amp;journal=GIJET&amp;year=2024&amp;volume=10&amp;issue=2#:~:text=,structures%20to%20represent%20relationships"> Recent Advances in Text Documents Clustering</a>). In summary, spectral clustering can yield high-quality groupings (reducing search space by focusing on meaningful subgraphs), but careful tuning and scaling strategies (e.g. clustering in batches or using approximate spectral methods) are needed to apply it at LLM scale.</p><h2><strong>Density-Based Clustering</strong></h2><p>Density-based algorithms such as DBSCAN and HDBSCAN cluster points based on regions of high density in the embedding space. They do not require specifying the number of clusters <em>a priori</em>, and they naturally label sparse outliers as noise. This makes them attractive for document chunking when one wants to identify tight topical clusters and isolate off-topic or irrelevant chunks. For example, Castillo (2025) demonstrates using HDBSCAN to cluster news article embeddings, automatically discovering topic groupings without preset <em>k</em> (<a href="https://dylancastillo.co/posts/clustering-documents-with-openai-langchain-hdbscan.html#:~:text=Once%20you%20have%20the%20embeddings%2C,hdbscan">Clustering Documents with OpenAI embeddings, HDBSCAN and UMAP &#8211; Dylan Castillo</a>). Such clusters could be used to limit an LLM&#8217;s search to dense topic areas while filtering out noise. A benefit of HDBSCAN is robustness to varying cluster shapes &#8211; it can find a very irregular cluster of related documents if they form a dense manifold in the vector space. However, in high-dimensional text embeddings, density estimation faces the &#8220;curse of dimensionality&#8221; (distances tend to homogenize, making it tricky to set the &#949; or minimum density thresholds). If parameters are not tuned well, a density-based method might put most points in one giant cluster or conversely label too many points as outliers (failing to reduce the search space effectively). Mitigation strategies include dimensionality reduction (e.g. UMAP) before clustering to accentuate true neighborhoods, or using adaptive density thresholds. In practice, density clustering is often used in combination with other methods &#8211; for instance, first using <em>k</em>-means to partition broadly, then HDBSCAN within each partition to find fine-grained groups or detect anomalies.</p><h2><strong>Deep Clustering and LLM-Assisted Methods</strong></h2><p>Emerging approaches leverage neural networks and even LLMs themselves to improve clustering of document chunks. The idea is to learn representations or refine cluster assignments in ways classical algorithms cannot. Some 2023 methods (IDAS, ClusterLLM) directly incorporate LLM-generated insights: e.g. using an LLM to produce abstractive summaries or to predict semantic relations between sentences, then clustering based on those cues (<a href="https://aclanthology.org/2024.emnlp-main.1025.pdf#:~:text=possess%20powerful%20text%20understanding%20capabilities,generalization%2C%20or%20are%20not%20sufficiently">HERE</a>). These showed promise but often required many expensive LLM calls and did not generalize across domains . In 2024, Lin <em>et al.</em> proposed LLMEdgeRefine, a two-stage clustering approach that addresses clustering failures at the &#8220;edges.&#8221; First, they run <em>k</em>-means to get initial clusters. Then they identify <em>edge points</em> (outliers or ambiguous points near cluster boundaries) and group these via a secondary agglomerative clustering into &#8220;super-points&#8221; to reduce noise . In the second stage, LLMEdgeRefine uses an LLM&#8217;s understanding to <em>softly reassign or remove</em> these edge points based on semantic context . By letting the LLM reconsider borderline cases, the clusters become more semantically coherent. This yielded consistently higher clustering accuracy on text datasets compared to baseline methods . Deep clustering can also involve training neural encoders (e.g. via autoencoders or contrastive learning) to produce embedding spaces where clusters are more well-formed. The general advantage of deep clustering is adaptability &#8211; the clustering process can learn from the data or from an LLM&#8217;s vast knowledge. The risk is complexity and overfitting: if the LLM or model is not carefully constrained, it might create idiosyncratic clusters that don&#8217;t generalize. Nonetheless, techniques like LLMEdgeRefine illustrate that using LLMs in the loop can mitigate classic clustering pitfalls (like outliers and wrong assignments) by injecting high-level semantic judgment into the clustering process.</p><h2><strong>When Clustering Falls Short and Mitigations</strong></h2><p>Despite their utility, clustering techniques can fail to reduce search space effectively in certain scenarios. A known failure mode is when relevant information for a query is split across clusters. If the retrieval system only looks at one cluster, it may miss critical pieces (lowering recall). This is often due to imperfect clustering boundaries. As one study notes, cluster-partitioned ANN indexes typically need to scan more candidates to reach the same recall as graph-based indexes (<a href="https://www.pinecone.io/learn/a-developers-guide-to-ann-algorithms/#:~:text=Graph%20indexing%20algorithms%20have%20been,data%20that%20lie%20on%20SSDs">A Developer&#8217;s Guide to Approximate Nearest Neighbor (ANN) Algorithms | Pinecone</a>), implying some nearest neighbors fall outside the assigned cluster. One remedy is <strong>multi-cluster retrieval</strong> &#8211; querying top several clusters. TeleRAG&#8217;s design, for example, prefetches the likely relevant IVF clusters to GPU but also &#8220;ensur[es] complete retrieval&#8221; by searching any missed clusters on CPU in parallel (<a href="https://arxiv.org/html/2502.20969v1#:~:text=Although%20TeleRAG%20significantly%20reduces%20latency,GPU%20coordination">TeleRAG: Efficient Retrieval-Augmented Generation Inference with Lookahead Retrieval</a>). This hybrid approach protects accuracy at a minor cost. Another issue is cluster imbalance: if one cluster is very large or heterogeneous, searching within it is nearly as hard as searching the whole corpus. This can be mitigated by increasing the number of clusters (making each more fine-grained), or using hierarchical clustering to split large clusters into subclusters. <strong>Soft clustering</strong> (where documents can belong to multiple clusters or have fuzzy membership) is also a strategy to handle overlap &#8211; a document that touches multiple topics could be indexed in all relevant clusters, so a query for either topic still finds it. To address cluster quality problems, some methods use <em>cluster ensembles</em> or re-clustering: run multiple clustering algorithms and intersect results to find stable groupings. We also see <strong>fusion of clustering with other signals</strong> as a powerful mitigation. Yang (2024) proposes a cluster-based partial retrieval guided by sparse retrieval results (<a href="https://sigir-2024.github.io/proceedings.html#:~:text=proposes%20a%20cluster,retrieval%20results%20and%20document%20embedding">SIGIR '24: Proceedings of the 47th International ACM SIGIR Conference on Research and Development in Information Retrieval</a>). In that approach, keywords (BM25 results) help identify which learned clusters likely contain relevant docs, effectively correcting clustering mistakes by cross-referencing textual cues. This kind of dense-sparse fusion can retain strong relevance while still cutting down the search space . In summary, when clustering alone isn&#8217;t perfect, combining clusters with alternative retrieval strategies, increasing redundancy (searching a bit beyond the single best cluster), or refining cluster assignments with human-in-the-loop (LLM) adjustments are effective ways to ensure important information isn&#8217;t overlooked.</p><h2><strong>Alternatives to Clustering for Reducing Search Space</strong></h2><p>Clustering is not the only game in town. Several other techniques can narrow the search space in document retrieval and chunking:</p><ul><li><p><strong>Approximate Nearest Neighbor (ANN) Graphs:</strong> Graph-based indexes like HNSW (Hierarchical Navigable Small World) are a popular alternative to cluster-partitioning. Instead of grouping by centroids, they organize embeddings as a navigable graph. Queries traverse the graph to find nearest neighbors, often examining far fewer points to reach a target recall than cluster-based methods (<a href="https://www.pinecone.io/learn/a-developers-guide-to-ann-algorithms/#:~:text=Graph%20indexing%20algorithms%20have%20been,data%20that%20lie%20on%20SSDs">A Developer&#8217;s Guide to Approximate Nearest Neighbor (ANN) Algorithms | Pinecone</a>). These graph indexes have empirically the best computational complexity, being among &#8220;the fastest algorithms for in-memory vector search&#8221; . In practice, ANN graphs can achieve high recall with low latency, effectively reducing search space by pruning paths that are unlikely to lead to close neighbors. Many vector search libraries default to HNSW or similar graph algorithms for this reason.</p></li><li><p><strong>Semantic Indexing and Filters:</strong> Before resorting to full vector search, one can filter or index documents by high-level categories or keywords. For example, Jiang et al. (2025) use a <em>theme-scoped retrieval</em> that classifies queries into topic scopes to &#8220;efficiently narrow the search space while maintaining retrieval quality&#8221; (<a href="https://arxiv.org/html/2502.10996v1#:~:text=framework%20that%20dynamically%20constructs%20and,with">RAS: Retrieval-And-Structuring for Knowledge-Intensive LLM Generation</a>). By routing a query to only the subset of documents on that theme, the search load is drastically reduced. Similarly, classic inverted indexes (keyword-based) can quickly pre-filter candidate chunks by lexical cues; this can be combined with an embedding search for precision. Although simpler than clustering, these methods require predefined taxonomy or metadata. They work well when documents are already labeled or easily separable by context (e.g. search only in the &#8220;finance&#8221; section for a finance query).</p></li><li><p><strong>Hash-Based Methods:</strong> Locality-Sensitive Hashing (LSH) and related hashing techniques map embeddings to buckets so that similar items land in the same bucket with high probability. This allows sub-linear retrieval by only searching within a few buckets. LSH was traditionally used for high-dimensional data search, but recent reviews note that purely hash-based indexes have been surpassed by graph and clustering methods in performance (<a href="https://www.pinecone.io/learn/a-developers-guide-to-ann-algorithms/#:~:text=,based%20indexing%20%28e.g.%2C%20%2013">A Developer&#8217;s Guide to Approximate Nearest Neighbor (ANN) Algorithms | Pinecone</a>). Still, hashing remains an alternative for certain cases (it&#8217;s simple and can be combined with clustering: e.g. assign a hash within each cluster to further narrow search).</p></li><li><p><strong>Cascaded Retrieval and Caching:</strong> Multi-stage retrieval pipelines can cut down search space at each stage. For instance, a first stage might use a cheap model or smaller embedding to retrieve a rough set of candidate chunks, and later stages refine this set with stronger models. This cascade ensures only a small fraction of the corpus is ever examined with the expensive LLM or embedding. Additionally, <em>semantic caching</em> has been explored as a way to avoid repeated searches: results of frequent queries (or query embeddings) are cached so that similar new queries can reuse those results (<a href="https://jsaer.com/download/vol-11-iss-9-2024/JSAER2024-11-9-155-164.pdf#:~:text=performance%20and%20handle%20disconnections%20effectively,bottlenecks%20caused%20by%20long%20sequence">HERE</a>). By serving some queries from cache or memory, the system bypasses a full corpus scan. Gill et al. (2023) introduced RAGCache, a multilevel cache for RAG that stores intermediate results and was shown to significantly cut down redundant retrieval work .</p></li></ul><p>In conclusion, <strong>clustering techniques</strong> &#8211; from classical <em>k</em>-means and hierarchical clustering to advanced spectral, density-based, and LLM-assisted methods &#8211; play a pivotal role in structuring document data for LLM applications. They reduce the search space by grouping related information, thus making retrieval and chunk selection more efficient. Each technique has its strengths (e.g. speed of <em>k</em>-means, structure awareness of spectral, nuance of deep clustering) and failure modes (boundary cases, computational limits, etc.). Modern studies in 2024&#8211;2025 have shown not only how clustering boosts retrieval efficiency (<a href="https://arxiv.org/html/2502.20969v1#:~:text=In%20this%20paper%2C%20we%20identify,the%20overall%20retrieval%20latency%20still">TeleRAG: Efficient Retrieval-Augmented Generation Inference with Lookahead Retrieval</a>), but also how to address its shortcomings via smarter algorithms and hybrid strategies (<a href="https://sigir-2024.github.io/proceedings.html#:~:text=proposes%20a%20cluster,retrieval%20results%20and%20document%20embedding">SIGIR '24: Proceedings of the 47th International ACM SIGIR Conference on Research and Development in Information Retrieval</a>). Moreover, when clustering is not suitable, alternative approaches like ANN indexing, thematic filtering, and caching ensure that we can still tame the search space explosion that comes with large document collections. By judiciously choosing and sometimes combining these methods, practitioners can build RAG and chunking pipelines that scale to massive corpora while delivering relevant context to LLMs with high accuracy and low latency.</p><h2><strong>Sources</strong></h2><ol><li><p>Lin <em>et al.</em>, &#8220;TeleRAG: Efficient Retrieval-Augmented Generation Inference with Lookahead Retrieval,&#8221; <em>arXiv</em>, 2025 .</p></li><li><p>&#260;kesson &amp; Santos, &#8220;Clustered Retrieved Augmented Generation (CRAG),&#8221; <em>arXiv</em>, 2024 .</p></li><li><p>Goel &amp; Chandak, &#8220;HIRO: Hierarchical Information Retrieval Optimization,&#8221; <em>arXiv</em>, 2024 (<a href="https://arxiv.org/html/2406.09979v1#:~:text=LLMs%20struggle%20with%20long%20contexts%2C,the%20NarrativeQA%20dataset%20by%20an">HIRO: Hierarchical Information Retrieval Optimization</a>) .</p></li><li><p>Starosta <em>et al.</em>, &#8220;Explainable Graph Spectral Clustering of text documents,&#8221; <em>PLOS One</em>, 2024 (<a href="https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0313238#:~:text=Spectral%20clustering%20methods%20are%20known,This%20link%20enables%20to%20provide">Explainable Graph Spectral Clustering of text documents | PLOS One</a>).</p></li><li><p>Castillo, &#8220;Clustering Documents with OpenAI Embeddings, HDBSCAN and UMAP,&#8221; <em>Blog</em>, updated Feb 2025 (<a href="https://dylancastillo.co/posts/clustering-documents-with-openai-langchain-hdbscan.html#:~:text=Once%20you%20have%20the%20embeddings%2C,hdbscan">Clustering Documents with OpenAI embeddings, HDBSCAN and UMAP &#8211; Dylan Castillo</a>).</p></li><li><p>Lin <em>et al.</em>, &#8220;LLMEdgeRefine: Enhancing Text Clustering with LLM-Based Refinement,&#8221; <em>EMNLP 2024</em> (<a href="https://aclanthology.org/2024.emnlp-main.1025.pdf#:~:text=Our%20proposed%20LLMEdgeRefine%20text%20clustering,more%20granular%20examination%20of%20cluster">HERE</a>) .</p></li><li><p>Pinecone, <em>&#8220;A Developer&#8217;s Guide to ANN Algorithms,&#8221;</em> 2024 (<a href="https://www.pinecone.io/learn/a-developers-guide-to-ann-algorithms/#:~:text=A%20spatial%20partitioning%20index%20organizes,query%20at%20the%20red%20x">A Developer&#8217;s Guide to Approximate Nearest Neighbor (ANN) Algorithms | Pinecone</a>) .</p></li><li><p>Jiang <em>et al.</em>, &#8220;Retrieval-And-Structuring (RAS) for Knowledge-Intensive LLM Generation,&#8221; <em>arXiv</em>, 2025 (<a href="https://arxiv.org/html/2502.10996v1#:~:text=framework%20that%20dynamically%20constructs%20and,with">RAS: Retrieval-And-Structuring for Knowledge-Intensive LLM Generation</a>).</p></li><li><p>Yang <em>et al.</em>, &#8220;Cluster-based Partial Dense Retrieval Fused with Sparse Text Retrieval,&#8221; <em>SIGIR 2024</em> .</p></li><li><p>Akheel <em>et al.</em>, &#8220;Semantic Caching for LLM Applications: A Review,&#8221; <em>J. Sci. &amp; Eng. Research</em>, 2024 (<a href="https://jsaer.com/download/vol-11-iss-9-2024/JSAER2024-11-9-155-164.pdf#:~:text=performance%20and%20handle%20disconnections%20effectively,bottlenecks%20caused%20by%20long%20sequence">HERE</a>).</p></li></ol>]]></content:encoded></item><item><title><![CDATA[Vector Databases vs. Traditional Databases for LLM Document Retrieval]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/vector-databases-vs-traditional-databases</link><guid isPermaLink="false">https://www.rohan-paul.com/p/vector-databases-vs-traditional-databases</guid><pubDate>Mon, 16 Jun 2025 09:44:06 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!KO71!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!KO71!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!KO71!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png 424w, https://substackcdn.com/image/fetch/$s_!KO71!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png 848w, https://substackcdn.com/image/fetch/$s_!KO71!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png 1272w, https://substackcdn.com/image/fetch/$s_!KO71!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!KO71!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png" width="1024" height="486" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:486,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:525047,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166054946?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!KO71!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png 424w, https://substackcdn.com/image/fetch/$s_!KO71!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png 848w, https://substackcdn.com/image/fetch/$s_!KO71!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png 1272w, https://substackcdn.com/image/fetch/$s_!KO71!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff458f936-e382-4409-9c7c-bc812dbd5e26_1024x486.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ul><li><p>Vector Databases vs. Traditional Databases for LLM Document Retrieval</p></li><li><p>Retrieval Efficiency</p></li><li><p>Embedding Storage and Indexing</p></li><li><p>Hybrid Retrieval Approaches</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Retrieval Efficiency</strong></h2><p><strong>Vector databases</strong> are purpose-built for fast similarity search on high-dimensional embeddings, enabling rapid retrieval even as data scales to millions or billions of vectors. They rely on approximate nearest neighbor (ANN) indexes that dramatically outperform brute-force scans. For example, benchmarks show a <em>huge</em> performance gap between exhaustive search and ANN-based search, with graph-based indexes like HNSW achieving state-of-the-art speedups (<a href="https://arxiv.org/html/2402.01763v3#:~:text=ANN%20search%20within%20VDBMS%20include,Also%2C%20according%20to%20them">When Large Language Models Meet Vector Databases: A Survey</a>) . Specialized vector engines (e.g. FAISS, Milvus, Pinecone) treat vectors as first-class data, using custom data structures and optimizations to attain millisecond-level query times on large corpora (<a href="https://www.cs.purdue.edu/homes/csjgwang/pubs/ICDE24_VecDB.pdf#:~:text=by%20customers,implementing%20in%02dexes%20in%20the%20most">ICDE_PaperID_79.pdf</a>). In contrast, <strong>traditional relational databases</strong> (PostgreSQL, MySQL) and document stores (MongoDB) were not originally designed for high-dimensional similarity queries. Without specialized indexes, a relational DB must compare a query embedding to every stored vector (O(n) complexity), which becomes infeasible at scale. Even with recent extensions that add ANN indexing to relational systems, there is an observed slowdown: one study confirms that a PostgreSQL-based vector extension delivers significantly slower query performance than a dedicated vector search library under the same conditions . The overhead of the general-purpose engine (transaction layers, row format, etc.) means vector search in a traditional DB can be orders of magnitude less efficient for large datasets. For instance, attempts to index 15 million text embeddings (768 dimensions each) inside PostgreSQL led to system instability and excessive query times, underscoring scalability issues beyond small datasets (<a href="https://arxiv.org/pdf/2501.13442#:~:text=limited%20attention%20in%20the%20literature,15">BULGARIAN ACADEMY OF SCIENCES</a>). By contrast, specialized vector systems (often leveraging GPU acceleration and memory-optimized indexes) have demonstrated responsive searches on similarly massive corpora . In summary, when retrieving chunk embeddings for LLM augmentation, vector databases scale to far larger corpora with lower latency, whereas naive use of relational or document databases becomes a bottleneck as embedding count and dimensionality grow .</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Embedding Storage and Indexing</strong></h2><p><strong>Indexing techniques</strong> differ fundamentally between vector and relational databases. Vector databases typically store embeddings in compact binary or numeric forms and organize them with dedicated index structures (graph-based, tree-based, or quantization-based) optimized for <em>similarity</em> queries . These indexes (e.g. HNSW graphs, IVF inverted files with product quantization) prune the search space and compute distances only on a small fraction of candidates, greatly speeding up retrieval. Many vector DBs offer a choice of index types to balance accuracy, query speed, and memory footprint &#8211; for example, FAISS provides flat (exact), IVF+PQ (compressed), and HNSW (graph) indexes in its library . <strong>Relational databases</strong>, on the other hand, traditionally lack a native vector data type or index. Embeddings are often stored as arrays or blobs in a table row, which a standard B-tree index cannot accelerate for nearest-neighbor search. Newer extensions have emerged to bridge this gap: for instance, PostgreSQL&#8217;s <code>pgvector</code> (and Alibaba&#8217;s PASE) plugin defines a vector column type and implements ANN indexes (HNSW and IVF) inside the database . This allows similarity queries via SQL, but the underlying engine must still manage these indexes through its buffer manager and tuple structure. Research shows that such integrated approaches carry non-trivial overhead. One case study found that a Postgres-based HNSW index was slower and more memory-intensive than the same index in a standalone vector library, especially as index parameters (graph connectivity) increased . The performance gap widened for more complex indexes, due to extra pointer chasing and tuple access costs in the relational engine . In practice, specialized vector stores use low-level optimizations (e.g. contiguous memory layout, SIMD distance computations, GPU offloading) that general databases rarely exploit. While some document databases like MongoDB have added vector search features (using an underlying Lucene ANN index for up to 2048-dimensional vectors) , these are essentially embedding a vector index inside a text-search engine. Overall, vector DBs excel by storing embeddings in tailor-made indexes for fast similarity lookup, whereas relational and general-purpose databases must either forego indexing (resorting to brute force) or bolt on limited ANN indexes that struggle to match the efficiency of purpose-built solutions .</p><h2><strong>Hybrid Retrieval Approaches</strong></h2><p>To get the best of both worlds, modern systems explore <strong>hybrid approaches</strong> that combine vector searches with traditional database filtering or storage. One strategy is to integrate vector indexes into a relational database engine (as in <strong>AnalyticDB-V</strong> or Postgres+pgvector) so that a single query can perform semantic embedding matching alongside structured filters (<a href="https://www.cs.purdue.edu/homes/csjgwang/pubs/ICDE24_VecDB.pdf#:~:text=design%20rationale%20of%20%E2%80%9Cone,g">ICDE_PaperID_79.pdf</a>). This enables, for example, an SQL query that finds the top-10 similar document chunks (via an ANN index) constrained by a date or author field. The challenge is choosing the optimal query plan: scanning all candidate vectors versus using the ANN index. Recent research proposes adaptive execution based on filter selectivity (<a href="https://arxiv.org/pdf/2403.15807#:~:text=driven%20by%20relational%20selectivity%2C%20and,number%20of%20concurrent%20search%20queries"> Efficient Data Access Paths for Mixed Vector-Relational Search</a>). If a metadata filter (e.g. a specific document category) reduces the candidate set significantly, a sequential scan over those few embeddings may be faster than engaging a global index . Conversely, for broad queries with low selectivity, the vector index avoids costly distance computations on the entire dataset . Sanca and Ailamaki (2024) show that there is a crossover point (dependent on data dimensionality and hardware concurrency) where the engine should switch from brute-force to indexed search to minimize latency . Another hybrid pattern keeps vector and traditional databases side by side: embeddings are stored in a vector database for fast similarity ranking, while the original documents and metadata reside in a relational or document store. In a retrieval-augmented generation pipeline, a query embedding is used to fetch top-K similar chunk IDs from the vector database, then those IDs are used to retrieve full text or records from the document database. This two-tier design leverages the strength of each system &#8212; high-dimensional search in the vector store and reliable storage/lookup in the document store. Many vector databases now also support storing metadata with vectors and offer boolean filters or keyword search, effectively merging this two-tier approach into one system (<a href="https://arxiv.org/html/2402.01763v3#:~:text=ChromaDB%20%282022%29%201536%20Vec,V%20%282020%29%20%20512%20Rel.%2BFtx">When Large Language Models Meet Vector Databases: A Survey</a>). For example, Weaviate and Qdrant allow hybrid queries that combine ANN similarity ranking with traditional term filters, using an internal full-text index alongside the vector index . Such solutions confirm that combining semantic vector search with classical filtering can greatly improve retrieval quality and flexibility without sacrificing performance. Ongoing research indicates that with careful system design, a unified hybrid approach can achieve near-specialized performance: there appear to be <em>no fundamental barriers</em> preventing a relational database from matching a vector database&#8217;s speed, given sufficient engineering effort . In practice, organizations choose a hybrid architecture that balances the convenience of a one-stop system against the absolute performance gains of dedicated vector stores (<a href="https://zilliz.com/blog/relational-databases-vs-vector-databases#:~:text=With%20their%20advanced%20indexing%20and,the%20added%20complexity%20is%20important">Choosing Between Relational and Vector Databases - Zilliz blog</a>) , ensuring that LLMs can be efficiently fed with relevant document chunks at scale.</p>]]></content:encoded></item><item><title><![CDATA[Vector Databases in Document Retrieval and RAG Applications]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/vector-databases-in-document-retrieval</link><guid isPermaLink="false">https://www.rohan-paul.com/p/vector-databases-in-document-retrieval</guid><pubDate>Mon, 16 Jun 2025 09:41:19 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!yunM!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!yunM!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!yunM!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png 424w, https://substackcdn.com/image/fetch/$s_!yunM!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png 848w, https://substackcdn.com/image/fetch/$s_!yunM!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png 1272w, https://substackcdn.com/image/fetch/$s_!yunM!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!yunM!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png" width="1024" height="574" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:574,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:789826,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166054832?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!yunM!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png 424w, https://substackcdn.com/image/fetch/$s_!yunM!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png 848w, https://substackcdn.com/image/fetch/$s_!yunM!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png 1272w, https://substackcdn.com/image/fetch/$s_!yunM!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F327b11b6-6c41-4edb-bf07-47e22ca7aa5e_1024x574.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ul><li><p>Introduction</p></li><li><p>How Vector Databases Work - Architecture and Indexing</p></li><li><p>Vector Index vs. Vector Database vs. Vector Plugin</p></li><li><p>Comparison of Key Vector Database Technologies</p><ul><li><p>FAISS (Facebook AI Similarity Search)</p></li><li><p>Milvus</p></li><li><p>Weaviate</p></li><li><p>Pinecone</p></li></ul></li><li><p>Recent Research and Trends (2024-2025)</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Introduction</strong></h2><p>Large Language Models (LLMs) excel at generating text but struggle with up-to-date domain-specific knowledge and can hallucinate facts. Retrieval-augmented generation (RAG) addresses this by feeding LLMs with relevant context retrieved from an external knowledge base (<a href="https://arxiv.org/abs/2402.01763#:~:text=Models%20,on%20the%20speculative%20future%20developments">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>). In practice, documents are digitized, split into manageable <em>chunks</em> of text, encoded into high-dimensional vectors (embeddings), and stored in a <em>vector database</em>. At query time, the user&#8217;s question is also embedded as a vector and used to retrieve the most similar document chunks from the vector store (<a href="https://arxiv.org/pdf/2402.05131#:~:text=More%20specifically%20on%20document%20chunking,financial%20reporting%2C%20except%20for%20some">HERE</a>). These retrieved chunks (e.g. passages) are provided to the LLM to ground its answer in factual references. This pipeline leverages vector databases (VecDBs) as efficient semantic memory, mitigating LLM limitations like hallucination and outdated knowledge (<a href="https://arxiv.org/pdf/2402.01763#:~:text=VecDBs%20can%20either%20be%20incorporated,LLMs%20can%20be%20seamlessly%20solved">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>). VecDBs offer an efficient way to store and manage the high-dimensional representations needed for semantic search and RAG (<a href="https://arxiv.org/abs/2402.01763#:~:text=Models%20,on%20the%20speculative%20future%20developments">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>). They have become integral to modern AI applications such as RAG-based QA systems, knowledge retrieval, and semantic search engines.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>How Vector Databases Work - Architecture and Indexing</strong></h2><p>A vector database is a specialized data management system optimized for <em>similarity search</em> in high-dimensional vector spaces. Its core operation is <em>k</em>-nearest neighbor (kNN) search to find vectors most similar to a query vector, typically using cosine or dot-product similarity. The major challenge is that brute-force search scales poorly as data grows. High-dimensional vectors (often hundreds or thousands of dimensions) lack easy partitioning and require expensive distance computations (<a href="https://arxiv.org/abs/2310.14021#:~:text=addressing%20these%20needs%2C%20however%20there,for%20storage%20and%20indexing%2C%20techniques">[2310.14021] Survey of Vector Database Management Systems</a>). Thus, vector DBs rely on advanced <em>indexing methods</em> for Approximate Nearest Neighbor (ANN) search, which trade a tiny amount of accuracy for drastic speedups. Common ANN index approaches include:</p><ul><li><p><strong>Tree-based indexes:</strong> e.g. vantage-point or KD-trees, which partition space hierarchically. These work for lower dimensions but degrade as dimensionality grows (<a href="https://arxiv.org/pdf/2402.01763#:~:text=accuracy,based%20methods%C2%A0Malkov%20and%20Yashunin">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>).</p></li><li><p><strong>Hash-based indexes (LSH):</strong> Use random projections or hashing (e.g. SimHash, LSH) to bucket similar vectors. They offer sub-linear search but often require many hash tables to reach high recall (<a href="https://arxiv.org/pdf/2402.01763#:~:text=accuracy,based%20methods%C2%A0Malkov%20and%20Yashunin">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>).</p></li><li><p><strong>Quantization-based indexes:</strong> Use vector quantization to compress and cluster vectors. A prominent example is <em>inverted file</em> (IVF) with <em>product quantization (PQ)</em> (<a href="https://arxiv.org/pdf/2402.01763#:~:text=accuracy,based%20methods%C2%A0Malkov%20and%20Yashunin">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>). Vectors are quantized into discrete codes, and search probes a few nearest cluster centroids (reducing candidates) then refines results with compressed codes (<a href="https://arxiv.org/pdf/2402.01763#:~:text=accuracy,based%20methods%C2%A0Malkov%20and%20Yashunin">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>). This significantly cuts memory and accelerates search at some cost to recall.</p></li><li><p><strong>Graph-based indexes:</strong> Build a proximity graph of vectors (each node links to nearest neighbors). The <strong>Hierarchical Navigable Small World (HNSW)</strong> graph is state-of-the-art, enabling fast greedy search through the graph layers (<a href="https://www.pinecone.io/blog/hnsw-not-enough/#:~:text=HNSW%20is%20a%20highly%20performant,such%20as%20NMSLIB%20and%20Faiss">Great Algorithms Are Not Enough | Pinecone</a>). HNSW yields excellent recall at high throughput and ANN benchmarks show it has a large performance advantage over brute-force (<a href="https://arxiv.org/pdf/2402.01763#:~:text=match%20at%20%20performance%20gap,widely%20used%20within%20most%20VecDB">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>). Indeed, HNSW is widely used in most vector databases for its strong accuracy-speed balance (<a href="https://arxiv.org/pdf/2402.01763#:~:text=performance%20gap%20between%20brute,widely%20used%20within%20most%20VecDB">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>). The downside is complex index construction and more challenging dynamic updates (e.g. deletions require graph maintenance) (<a href="https://github.com/facebookresearch/faiss/wiki/Faiss-indexes#:~:text=match%20at%20L323%20In%20addition,would%20destroy%20the%20graph%20structure">Faiss indexes &#183; facebookresearch/faiss Wiki &#183; GitHub</a>).</p></li></ul><p>A vector DB&#8217;s architecture often combines these indexes with additional system components to handle scale and data management. Many systems partition data into shards to distribute load across nodes, since there is no natural relational partition key for vectors (<a href="https://arxiv.org/abs/2310.14021#:~:text=to%20vector%20data%20management%2C%20namely,and%20navigable%20partitioning%3B%20for%20query">[2310.14021] Survey of Vector Database Management Systems</a>). They use compression (PQ, PCA, etc.) to cope with large vector sizes (<a href="https://arxiv.org/abs/2310.14021#:~:text=to%20vector%20data%20management%2C%20namely,and%20navigable%20partitioning%3B%20for%20query">[2310.14021] Survey of Vector Database Management Systems</a>). Some support hybrid queries that combine vector similarity with structured filters (e.g. date or category) (<a href="https://arxiv.org/abs/2310.14021#:~:text=addressing%20these%20needs%2C%20however%20there,for%20storage%20and%20indexing%2C%20techniques">[2310.14021] Survey of Vector Database Management Systems</a>). To enable this, the system may maintain auxiliary indexes for metadata or integrate vector and scalar search in query execution. For example, Weaviate stores both vectors and scalar attributes, allowing queries like &#8220;find articles on <em>X</em> in the last 7 days,&#8221; by first retrieving by vector similarity then filtering by date (<a href="https://www.restack.io/p/weaviate-knowledge-properties-cat-ai#:~:text=Weaviate%27s%20ability%20to%20combine%20vector,precise%20filtering%20alongside%20semantic%20relevance">Weaviate Properties Overview | Restackio</a>) . Advanced vector DBs also handle streaming data (inserts/deletes) with minimal downtime, using techniques like incremental index updates or background rebuilds. Supporting real-time updates is challenging for certain indexes (e.g. HNSW) but modern implementations provide workarounds (lazy deletions, rebuild triggers, etc.) .</p><p>In terms of storage, some vector DBs keep indexes in memory for speed, while others leverage on-disk indexes for billion-scale datasets. Recent research explores hybrid memory architectures (CPU, GPU, SSD). For example, <em>FusionANNS</em> (2024) proposes a multi-tier CPU/GPU cooperative index with SSD storage to achieve high throughput on billion-scale data using a single GPU (<a href="https://arxiv.org/abs/2409.16576#:~:text=component%20of%20database%20and%20AI,tiered%20indexing%20to%20avoid">[2409.16576] FusionANNS: An Efficient CPU/GPU Cooperative Processing Architecture for Billion-scale Approximate Nearest Neighbor Search</a>). Overall, the architecture of a vector database is a layered design: a data ingestion layer (for embedding and inserting vectors), an indexing layer (ANN structures for search), and a query execution layer (to combine vector scores with optional filters and ranking). By addressing key obstacles &#8211; high dimensionality, computational cost, lack of natural partitions, and hybrid query support &#8211; modern vector databases provide fast, scalable, and accurate semantic search on unstructured data (<a href="https://arxiv.org/abs/2310.14021#:~:text=addressing%20these%20needs%2C%20however%20there,for%20storage%20and%20indexing%2C%20techniques">[2310.14021] Survey of Vector Database Management Systems</a>) (<a href="https://arxiv.org/abs/2310.14021#:~:text=led%20to%20new%20approaches%20to,variety%20of%20VDBMSs%20across%20a">[2310.14021] Survey of Vector Database Management Systems</a>).</p><h2><strong>Vector Index vs. Vector Database vs. Vector Plugin</strong></h2><p>It&#8217;s important to distinguish a <em>vector index</em> from a <em>vector database</em>. A <strong>vector index</strong> is the low-level data structure or algorithm that enables ANN search (such as an HNSW graph or IVF-PQ index) (<a href="https://arxiv.org/pdf/2402.01763#:~:text=between%20brute,have%20also%20showcased%20the%20great">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>). It can be seen as one component of the system &#8211; focused purely on retrieval efficiency. In contrast, a <strong>vector database</strong> is a full-fledged database management system built around vector data. A vector DB incorporates one or more indexing algorithms internally, but also provides features like data ingestion APIs, persistence, replication, scaling, security, and query interfaces (e.g. SQL/GraphQL or SDKs). Simply &#8220;bolting on&#8221; a vector index to an existing DB does not automatically yield a robust vector database (<a href="https://www.pinecone.io/blog/hnsw-not-enough/#:~:text=integrating%20a%20vector%20index%20into,and%20calling%20it%20a%20day">Great Algorithms Are Not Enough | Pinecone</a>). As Pinecone&#8217;s engineers note, an existing non-vector DB with a sidecar ANN index may struggle with the memory, compute, and scaling requirements of AI workloads . A true vector DB is <em>purpose-built</em> to meet those needs, often designed for low latency, high recall search at scale, live index updates, and easy operations .</p><p>Meanwhile, a <strong>vector plugin</strong> refers to an integration layer that connects LLMs or other applications to a vector database. For example, OpenAI&#8217;s <em>ChatGPT Retrieval Plugin</em> is a middleware that takes user-provided documents, chunks them, computes embeddings, and stores them in a vector DB, exposing endpoints for query and upsert (<a href="https://io.traffine.com/en/articles/chatgpt-retrieval-plugin#:~:text=The%20ChatGPT%20Retrieval%20Plugin%20works,providers%2C%20each%20with%20different">ChatGPT Retrieval Plugin - Traffine I/O</a>). The plugin itself isn&#8217;t storing data long-term; it relies on a chosen backend (Milvus, Pinecone, etc.) for the actual vector index and database functionalities (<a href="https://openai.com/index/chatgpt-plugins/#:~:text=As%20an%20open,opens%20in%20a%20new">ChatGPT plugins - OpenAI</a>) . In essence, the plugin provides a standardized API and tooling so that an LLM (like ChatGPT) can query the vector database for relevant context. This separation of concerns allows developers to swap out vector DB backends or support multiple databases through the same plugin interface. In summary, the <em>vector index</em> is the algorithmic engine, the <em>vector database</em> is the complete system managing vector data at scale, and the <em>vector plugin</em> is an integration interface enabling external services (like LLMs) to leverage the vector database in applications like RAG.</p><h2><strong>Comparison of Key Vector Database Technologies</strong></h2><h3><strong>FAISS (Facebook AI Similarity Search)</strong></h3><p>FAISS is an open-source library (C++ with Python bindings) for efficient vector similarity search, originally from Facebook AI Research. It provides a suite of ANN index types (flat brute-force, IVFFlat/IVFPQ for product quantization, HNSW, etc.) and is highly optimized for CPU and GPU execution (<a href="https://www.cs.toronto.edu/~mgabel/csc2233/#:~:text=,%28GTS">Vector Databases in Modern AI Applications</a>). FAISS was one of the first libraries to enable billion-scale vector search on a single machine by leveraging GPUs for massive parallelism . Its strength lies in raw performance and flexibility: developers can choose index types and parameters to balance speed vs accuracy, and even combine multiple techniques (e.g. HNSW on top of IVF). FAISS supports batching and can compute results with very high throughput. However, FAISS is not a standalone database service &#8211; it&#8217;s essentially a library. It lacks built-in networking, user management, or distribution across nodes. Using FAISS typically means embedding it in your application or another system. For instance, Milvus v1.0 was built on FAISS as its indexing layer (<a href="https://www.cs.purdue.edu/homes/csjgwang/pubs/SIGMOD21_Milvus.pdf#:~:text=In%20terms%20of%20implementation%2C%20Milvus,3">Milvus: A Purpose-Built Vector Data Management System</a>). The downside is that managing dynamic data can be non-trivial; some FAISS indexes don&#8217;t support deletion or incremental updates easily (requiring index rebuilds). FAISS is ideal when you need a fast in-memory vector search and you are handling persistence and scaling at the application level. It remains a popular choice to power custom semantic search pipelines and is often the baseline for ANN performance comparisons.</p><h3><strong>Milvus</strong></h3><p>Milvus is an open-source vector database designed from the ground up to manage large-scale embedding data. It emerged from the need to handle not only similarity search but also the <em>data management lifecycle</em> (ingestion, updates, filtering, etc.) for AI applications . Milvus 1.0 (SIGMOD 2021) introduced a purpose-built engine using FAISS and other ANN libraries under the hood , adding a gRPC service layer and management features. It supported real-time insertion of vectors, deletions, and provided a SQL-like interface. Milvus 2.0 (code-named &#8220;Manu&#8221;, VLDB 2022) re-architected the system to be cloud-native and distributed across nodes . It uses a cluster of services (coordination via etcd, data nodes, query nodes, index nodes) to enable horizontal scalability and high availability. A key strength of Milvus is its support for <strong>dynamic data and hybrid queries</strong>: it can ingest streaming data (e.g. millions of new embeddings) while concurrently serving searches, and it allows filtering by metadata fields and even multi-vector queries (where an entity is represented by multiple vectors) . For example, a query can ask for &#8220;images similar to X <em>and</em> labeled &#8216;cat&#8217;&#8221; &#8211; Milvus can first apply the label filter and then vector search within that subset. It achieves this by storing scalar attributes and coordinating between a vector index and an inverted index for filtering. Milvus supports various index types (HNSW, IVF, etc., some via plugins) and can even utilize GPUs for indexing/search. Its performance is improved by optimizations like minimized CPU cache misses when scanning vectors . Milvus is known for handling billion-scale data by sharding across nodes and using disk storage for older data if needed. The trade-off is the complexity of deployment &#8211; running a Milvus cluster involves multiple services (though Docker-compose and Kubernetes Helm charts exist). Milvus is well-suited for enterprises needing an open-source, scalable vector DB that integrates with existing data pipelines (it has clients in Python, Java, etc. and can be integrated with LLM frameworks).</p><h3><strong>Weaviate</strong></h3><p>Weaviate is another prominent open-source vector database, implemented in Go, with a strong focus on combining unstructured and structured data. Weaviate represents data as <em>objects</em> that can have both a vector embedding and additional properties (fields). Its default indexing method is a customized HNSW index that supports full CRUD (inserts, updates, deletes) (<a href="https://weaviate.io/developers/weaviate/concepts/vector-index#:~:text=Weaviate%27s%20hnsw%20index%20is%20a,">Vector Indexing - Weaviate</a>). Weaviate&#8217;s standout feature is native <strong>hybrid search</strong>: you can query by vector similarity, by keyword (BM25 full-text search), or a combination. For instance, it can find documents semantically similar to a query <em>and</em> satisfying a structured filter (e.g. a time range or category) in a single query (<a href="https://www.restack.io/p/weaviate-knowledge-properties-cat-ai#:~:text=Weaviate%27s%20ability%20to%20combine%20vector,precise%20filtering%20alongside%20semantic%20relevance">Weaviate Properties Overview | Restackio</a>) . Under the hood, it maintains both a vector index and a shard-specific keyword index to support such queries. Weaviate is designed for <strong>horizontal scalability</strong> via sharding: data is partitioned into classes and shards which can be distributed across nodes, allowing the index to scale beyond memory of a single machine . This sharding is crucial since HNSW graphs can become memory-hungry for very large datasets; Weaviate mitigates that by splitting data. It also provides consistency and replication controls for fault tolerance. In terms of performance, Weaviate claims sub-100ms query latency even for complex (vector + filter) queries, and it can handle high query volumes by scaling out . Integration-wise, Weaviate offers a GraphQL API and a REST API, and has modules that can automatically vectorize data using pre-trained models (for text, images, etc.), making it convenient to set up end-to-end. A possible drawback is that being an all-in-one system, it requires running the server (or using their managed cloud service) and tuning HNSW parameters for optimal trade-offs. But its ease of use, rich feature set, and strong community support (including LangChain integration) make it a popular choice for semantic search and RAG, especially when one needs to combine semantic similarity with symbolic filters for more precise results .</p><h3><strong>Pinecone</strong></h3><p>Pinecone is a fully managed vector database service, notable for abstracting away all infrastructure and index management. Unlike open-source solutions, Pinecone is proprietary SaaS &#8211; users access it via an API while Pinecone handles the backend. Pinecone&#8217;s design philosophy centers on production <em>readiness</em>: it was built with the idea that great algorithms alone aren&#8217;t enough without operational excellence (<a href="https://www.pinecone.io/blog/hnsw-not-enough/#:~:text=Part%20of%20the%20reason%20bolt,to%20a%20great%20vector%20database">Great Algorithms Are Not Enough | Pinecone</a>). Pinecone emphasizes <em>ease of use</em>, <em>flexibility</em>, and <em>performance at scale</em> as its core tenets . In practice, this means developers can get started by simply creating an index through the API, upserting vectors, and querying, without worrying about index types or memory allocation. Pinecone automatically indexes the data using its internal algorithms (which include graph-based methods &#8211; Pinecone has hinted at its own optimized graph index on a purpose-built architecture ). It handles scaling behind the scenes: as your dataset grows or query load increases, Pinecone can distribute the index and balance queries (the details are hidden, but likely involve sharding and replicas in their cloud). Data persistence, replication, and uptime are managed for you. One of Pinecone&#8217;s strengths is <strong>fast data refresh and consistency</strong> &#8211; inserted vectors become searchable within seconds, enabling near real-time applications . It also supports metadata filtering with queries, though heavy filtering might have performance considerations. In terms of accuracy and speed, Pinecone&#8217;s indexes can be tuned indirectly via &#8220;pods&#8221; and index configurations that trade off cost vs recall. For many standard use cases, Pinecone achieves high recall with low latency out-of-the-box. A 2024 benchmark by Timescale found that a specialized Postgres with pgvector could rival Pinecone in 99% recall latency (<a href="https://www.timescale.com/blog/pgvector-vs-pinecone#:~:text=Image%3A%20Compared%20to%20Pinecone%20s1%2C,featured%20PostgreSQL%20database%20and%20ecosystem">Pgvector vs. Pinecone: Vector Database Comparison | Timescale</a>), highlighting that Pinecone targets a sweet spot of high recall; applications that need lower recall for more speed might find self-hosted solutions competitive. The <strong>integration with LLMs</strong> is straightforward: Pinecone has well-documented Python/JavaScript client libraries and is supported by frameworks like LangChain, making it easy to plug into RAG pipelines. The main drawbacks are cost and vendor lock-in &#8211; you pay for the managed convenience and rely on Pinecone&#8217;s closed infrastructure. Nevertheless, Pinecone is widely adopted in industry for production AI systems due to its robustness (no ops burden) and ability to handle &#8220;AI-scale&#8221; workloads without significant performance tuning.</p><h2><strong>Recent Research and Trends (2024-2025)</strong></h2><p>The vector database field is evolving rapidly, with research in 2024 and 2025 focused on pushing the boundaries of performance, scalability, and intelligent retrieval. On the indexing front, researchers are exploring learned index structures and adaptive algorithms. For example, new methods like <em>LoRANN</em> (NeurIPS 2024) apply low-rank matrix factorization to ANN search (<a href="https://www.cs.toronto.edu/~mgabel/csc2233/#:~:text=,NeurIPS%2724%20%28LoRANN">Vector Databases in Modern AI Applications</a>). and other works study balanced clustering and graph optimizations to improve recall/cost trade-offs. Hardware-aware indexes are a major theme: techniques for GPU acceleration, cache-optimized search, and SSD-based indices (e.g. <em>DiskANN</em>, <em>SPANN</em>) are being refined to handle billion-scale data efficiently (<a href="https://arxiv.org/abs/2409.16576#:~:text=component%20of%20database%20and%20AI,tiered%20indexing%20to%20avoid">[2409.16576] FusionANNS: An Efficient CPU/GPU Cooperative Processing Architecture for Billion-scale Approximate Nearest Neighbor Search</a>) . Another active area is <strong>hybrid search and filtering</strong> &#8211; ensuring that adding metadata filters or range queries doesn&#8217;t drastically slow down vector search. Approaches like iRangeGraph (2024) extend HNSW graphs to handle numeric range constraints alongside similarity search (<a href="https://arxiv.org/abs/2409.02571#:~:text=...%20arxiv.org%20%20Range,to%20the%20query%20vector">iRangeGraph: Improvising Range-dedicated Graphs for Range-filtering ...</a>). Moreover, the synergy between LLMs and vector DBs is spurring new ideas. One notable direction is optimizing the <em>chunking</em> of documents for better retrieval. A 2025 study proposed <em>Mix-of-Granularity</em>, where the chunk size is dynamically chosen per query (small snippets vs larger passages) via a trained router, improving RAG accuracy by capturing the most relevant context granularity (<a href="https://arxiv.org/abs/2406.00456#:~:text=,Graph">[2406.00456] Mix-of-Granularity: Optimize the Chunking Granularity for Retrieval-Augmented Generation</a>) (<a href="https://arxiv.org/abs/2406.00456#:~:text=retrieval%20of%20distantly%20situated%20snippets,released%20in%20this%20https%20URL">[2406.00456] Mix-of-Granularity: Optimize the Chunking Granularity for Retrieval-Augmented Generation</a>). This shows that the interface between how we split/index data and how the LLM consumes it is being actively researched.</p><p>Comprehensive surveys in 2024 have also catalogued these developments. Jing <em>et al.</em> (2024) survey the intersection of LLMs and vector databases, concluding that tightly integrating VecDBs addresses LLM challenges and forecasting future research on better LLM-VecDB co-design (<a href="https://arxiv.org/abs/2402.01763#:~:text=Models%20,on%20the%20speculative%20future%20developments">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>) (<a href="https://arxiv.org/abs/2402.01763#:~:text=issues%20by%20offering%20an%20efficient,handling%20and%20knowledge%20extraction%20capabilities">[2402.01763] When Large Language Models Meet Vector Databases: A Survey</a>). Pan <em>et al.</em> (VLDBJ 2024) survey over 20 recent vector databases, identifying common obstacles and design techniques across systems (<a href="https://arxiv.org/abs/2310.14021#:~:text=addressing%20these%20needs%2C%20however%20there,for%20storage%20and%20indexing%2C%20techniques">[2310.14021] Survey of Vector Database Management Systems</a>) (<a href="https://arxiv.org/abs/2310.14021#:~:text=led%20to%20new%20approaches%20to,variety%20of%20VDBMSs%20across%20a">[2310.14021] Survey of Vector Database Management Systems</a>). They emphasize that managing vector data at scale requires innovations in storage (quantization, compression), indexing (from randomization to navigable small-world graphs), and query optimization (new operators for hybrid queries and hardware utilization) (<a href="https://arxiv.org/abs/2310.14021#:~:text=to%20vector%20data%20management%2C%20namely,operators%20for%20hybrid%20queries%2C%20as">[2310.14021] Survey of Vector Database Management Systems</a>). In summary, the latest research underscores that vector databases are a critical piece of AI infrastructure. We can expect continued improvements in their indexing algorithms, closer integration with large models, and more intelligent retrieval methods &#8211; all geared toward making knowledge retrieval faster, more accurate, and seamlessly scalable in the era of ever-larger LLMs and ever-growing unstructured data.</p>]]></content:encoded></item><item><title><![CDATA[Challenges and techniques of filtering in vector databases for document digitization and chunking in LLMs]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/challenges-and-techniques-of-filtering</link><guid isPermaLink="false">https://www.rohan-paul.com/p/challenges-and-techniques-of-filtering</guid><pubDate>Mon, 16 Jun 2025 09:38:54 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!8_TO!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!8_TO!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!8_TO!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png 424w, https://substackcdn.com/image/fetch/$s_!8_TO!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png 848w, https://substackcdn.com/image/fetch/$s_!8_TO!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png 1272w, https://substackcdn.com/image/fetch/$s_!8_TO!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!8_TO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png" width="1024" height="573" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/ffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:573,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1073255,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166054635?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!8_TO!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png 424w, https://substackcdn.com/image/fetch/$s_!8_TO!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png 848w, https://substackcdn.com/image/fetch/$s_!8_TO!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png 1272w, https://substackcdn.com/image/fetch/$s_!8_TO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fffc4cbf6-0cc3-4925-bd3f-46dcdc5c02cb_1024x573.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><ul><li><p>Introduction</p></li><li><p>Relevance Filtering</p></li><li><p>Deduplication</p></li><li><p>Semantic Filtering</p></li><li><p>Bias Filtering</p></li><li><p>Security Filtering</p></li><li><p>Conclusion</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Introduction</strong></h2><p>Document digitization and chunking pipelines often rely on vector databases as a &#8220;long-term memory&#8221; for large language models (LLMs) (<a href="https://arxiv.org/html/2411.05034v1#:~:text=embedding%20vector%20databases%20serve%20as,we%20introduce%20Eguard%2C%20a%20novel">Mitigating Privacy Risks in LLM Embeddings from Embedding Inversion</a>). Chunks of text (e.g. pages or passages) are embedded as high-dimensional vectors so that at query time, similar vectors can be retrieved as relevant context. However, ensuring the retrieval of useful and safe information from these vector stores is non-trivial. Recent research (2024&#8211;2025) highlights several filtering challenges that must be addressed to maintain quality, efficiency, fairness, and security in such systems. Key filtering types include relevance filtering, deduplication, semantic filtering, bias mitigation, and security safeguards. In the following, we review each category, citing recent findings and best practices applicable across different LLM implementations.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Relevance Filtering</strong></h2><p><strong>Relevance filtering</strong> aims to surface only high-quality, contextually pertinent embeddings from the vector store in response to a query. Without it, irrelevant or noisy chunks can degrade LLM performance and waste context space (<a href="https://arxiv.org/abs/2501.00332#:~:text=by%20incorporating%20external%2C%20real,filtering%20threshold%20based%20on%20score"> MAIN-RAG: Multi-Agent Filtering Retrieval-Augmented Generation</a>). Basic approaches rely on similarity scores: for example, computing cosine similarity between the query embedding and candidate document embeddings, then keeping only those above a threshold or top-<em>k</em> by score (<a href="https://arxiv.org/html/2410.15978v1#:~:text=Relevance%20Filtering%20Using%20Sentence%20Similarity,the%20selected%20studies%2C%20providing%20a">PROMPTHEUS: A Human-Centered Pipeline to Streamline SLRs with LLMs</a>). This ensures that only the most pertinent chunks (by embedding similarity) are fed into the LLM, focusing its attention on relevant content. In a literature review pipeline, such a method using Sentence-BERT embeddings was shown to markedly improve the focus and relevance of selected documents .</p><p>More advanced methods go beyond static thresholds. Adaptive or multi-stage filtering can improve precision. For instance, Chang <em>et al.</em> (2024) introduce a multi-agent RAG framework where multiple LLM agents collaboratively score retrieved documents . Their <strong>MAIN-RAG</strong> system dynamically adjusts the cutoff threshold based on the distribution of similarity scores, <strong>&#8220;minimizing noise while maintaining high recall of relevant documents.&#8221;</strong> This adaptive relevance filtering yielded a 2&#8211;11% accuracy improvement by pruning irrelevancies without losing useful context . Another strategy is <strong>LLM-based re-ranking or chunk grading</strong>: after an initial vector search, an LLM (or cross-encoder) evaluates each retrieved chunk&#8217;s actual relevance to the query and filters out off-topic chunks (<a href="https://www.captide.co/insights/how-to-do-agentic-rag-on-sec-edgar-filings#:~:text=%2A%20Self,telling%20it%20to%20do%20so">Captide | How to do Agentic RAG on SEC EDGAR Filings</a>). This adds a semantic check on top of raw embedding similarity. In an &#8220;agentic RAG&#8221; setup for financial documents, an LLM was used to grade retrieved passages and discard those not truly relevant, ensuring that only high-quality, pertinent information enters the final answer . Such feedback loops and re-rankers leverage deeper language understanding to refine retrieval results. In practice, a combination of these techniques may be used: e.g. retrieve top-<em>N</em> by similarity, then re-rank or drop low-relevance items via a stronger model. The overarching best practice is to <strong>filter aggressively for relevance</strong> &#8211; even simple similarity cutoff can help, and adaptive or LLM-in-the-loop filtering further boosts quality by catching subtle irrelevance that embedding distance alone might misjudge.</p><h2><strong>Deduplication</strong></h2><p>Vector databases for document corpora can easily accumulate redundant or near-duplicate entries, especially when documents have overlapping text (common in legal, news, or scraped data) or when chunking windows slide over text. Deduplication filters out these duplicates to reduce index size and avoid repetitive retrieval results. Redundant vectors not only waste storage and computation but can also lead an LLM to see the same content multiple times, which at best is inefficient and at worst can skew generation.</p><p>A straightforward deduplication approach is to perform exact or fuzzy matching on the text before or during insertion into the vector store. For instance, maintaining a hash of each chunk&#8217;s text (or normalized text) can catch exact duplicates. However, exact matching misses paraphrases or format variations. Recent work therefore explores <strong>semantic deduplication</strong>: identifying duplicates based on embedding similarity. Documents (or chunks) whose embeddings are extremely close (within a small distance threshold) can be assumed near-duplicates and removed (<a href="https://arxiv.org/pdf/2405.15523#:~:text=for%20GPT,1%2C%2034">HERE</a>). In other words, if two vectors lie closer than some epsilon in the embedding space, one of them is likely redundant and can be filtered out . This method, used in large-scale dataset cleaning, helps eliminate content that is essentially the same but not byte-identical. For example, <strong>Zhang et al. (2024)</strong> note that removing documents with embedding cosine similarity above a threshold effectively prunes repeated content to create higher-quality training corpora .</p><p>In practice, a combination of levels can be applied: <em>document-level dedup</em> (drop identical files), <em>chunk-level dedup</em> (drop overlapping text segments), and <em>embedding-level dedup</em> (drop semantically identical entries). Many vector database implementations don&#8217;t automatically prevent inserting duplicates, so it is up to the pipeline to enforce this. Best practices include:</p><ul><li><p><strong>Pre-insertion filtering:</strong> Use hashing or checksum to skip exact duplicates. For configurable chunkers, ensure chunks align with document boundaries to avoid excessive overlap.</p></li><li><p><strong>Post-insertion or periodic cleaning:</strong> Cluster or index vectors and remove those that cluster too tightly. Using an ANN search on each new vector to see if a very close vector already exists is one way to prevent storing near-duplicates.</p></li><li><p><strong>Prune duplicate retrievals:</strong> Even with a deduplicated index, similarity search may return multiple adjacent chunks from the same source that cover the same info. It&#8217;s beneficial to filter out repeats in the top results (e.g., keep only the highest-scoring chunk from any given document section). This avoids retrieving homogeneous, redundant chunks that add no new information (<a href="https://arxiv.org/html/2502.06864v1#:~:text=Existing%20studies%20in%20RAG%C2%A0Lewis%20et%C2%A0al,lead%20to%20isolated%20pieces%20of">Knowledge Graph-Guided Retrieval Augmented Generation</a>).</p></li></ul><p>By removing redundancy, we not only streamline the vector database (smaller index, faster search), but also present the LLM with a <strong>diverse set of information</strong> rather than echoing the same point multiple times. This tends to improve the informativeness and efficiency of LLM responses.</p><h2><strong>Semantic Filtering</strong></h2><p>While relevance filtering focuses on retrieval score or topical matching, <strong>semantic filtering</strong> goes a step further &#8211; ensuring that retrieved chunks align with the <em>intended meaning</em> of the query, not just surface-level similarity. The goal is to capture the user&#8217;s intent and context, retrieving texts that truly answer the question or provide the needed information, rather than those that merely share keywords or vague themes.</p><p>Modern vector search itself is a form of semantic search: it uses dense embeddings to find items related in meaning, overcoming the limitations of pure keyword matching (<a href="https://www.timescale.com/blog/what-is-semantic-search-with-filters-and-how-to-implement-it-with-pgvector-and-python#:~:text=Traditionally%2C%20keyword%20search%20using%20algorithms,meaning%20and%20context%20of%20words">What Is Semantic Search With Filters and How to Implement It With Pgvector and Python | Timescale</a>). However, even embedding-based retrieval can sometimes return results that are <strong>semantically off-target</strong> if not carefully constrained. For example, a query with an ambiguous term (&#8220;apple&#8221;) might retrieve chunks about Apple Inc. when the user meant the fruit. Both might be considered &#8220;relevant&#8221; in a loose sense (since the word overlaps), but only one matches the user&#8217;s intended context. Semantic filtering techniques aim to discriminate such cases.</p><p>One approach is to incorporate <strong>metadata or context constraints</strong> that reflect semantic categories. For instance, if a query is asking about a botanical topic, the system can filter results to those tagged as biology-related, ensuring the meaning context matches. Many vector databases support hybrid queries combining vector similarity with structured filters (e.g., require a certain field/value) (<a href="https://aws.amazon.com/blogs/machine-learning/streamline-rag-applications-with-intelligent-metadata-filtering-using-amazon-bedrock/#:~:text=Streamline%20RAG%20applications%20with%20intelligent,filtering%20the">Streamline RAG applications with intelligent metadata filtering using ...</a>). By using these filters (such as document type, source, date, language), the retrieval narrows to segments that semantically align with what&#8217;s needed. This was highlighted in an AWS implementation where metadata like product or department could be used to <strong>&#8220;limit retrieval to the most relevant subset of data for a given query,&#8221;</strong> thereby reducing off-topic results (<a href="https://aws.amazon.com/blogs/machine-learning/access-control-for-vector-stores-using-metadata-filtering-with-knowledge-bases-for-amazon-bedrock/#:~:text=With%20metadata%20filtering%20now%20available,your%20specific%20use%20case%20needs">Access control for vector stores using metadata filtering with Amazon Bedrock Knowledge Bases | AWS Machine Learning Blog</a>).</p><p>Another technique is <strong>re-ranking for semantic correctness</strong>. As discussed earlier, cross-encoders or LLM-based re-rankers can evaluate if a passage truly answers the query or has the required information. This goes beyond raw similarity; it&#8217;s a form of semantic verification. For example, GPT-4 used as a reranker has shown impressive zero-shot ability to judge relevance in context, often matching or beating traditional methods (<a href="https://arxiv.org/html/2403.10407v1#:~:text=of%20documents%20to%20re,and%20efficiency%20in%20search%20systems">A Thorough Comparison of Cross-Encoders and LLMs for Reranking SPLADE</a>). This can catch cases where a chunk is topically related but doesn&#8217;t actually contain the answer. The LLM might identify that &#8220;Chunk A mentions <em>apple</em> as a company, which is not relevant to the fruit query&#8221; &#8211; and filter it out. Similarly, retrieval pipelines in 2024 began to use <strong>LLM-based classifiers</strong> to flag when a chunk&#8217;s content does not semantically address the user&#8217;s prompt, even if keywords overlap (<a href="https://www.captide.co/insights/how-to-do-agentic-rag-on-sec-edgar-filings#:~:text=%2A%20Self,telling%20it%20to%20do%20so">Captide | How to do Agentic RAG on SEC EDGAR Filings</a>).</p><p>In summary, semantic filtering ensures that retrieved knowledge isn&#8217;t just loosely relevant by keywords or vector proximity, but truly <strong>on-point in meaning</strong>. Implementations should leverage context cues (via metadata or query understanding) and consider second-stage semantic checks. By doing so, the system can, for example, prefer a passage that directly answers a question over one that merely has related terms. This improves the usefulness of retrieval-augmented generation, reducing instances where the LLM sees related-but-irrelevant context that could lead to confusion or hallucination. The best practice is to <em>prioritize meaning over literal match</em> &#8211; use all available signals (semantic embeddings, metadata, LLM reasoning) to filter out material that, while superficially similar, doesn&#8217;t meet the true information need.</p><h2><strong>Bias Filtering</strong></h2><p><strong>Bias filtering</strong> in the context of vector-based LLM memory refers to detecting and mitigating problematic biases in the embedded content or in the retrieval process. Without checks, a vector database could reinforce historical or societal biases present in the source documents, which then get surfaced by the LLM. Recent studies have shown that retrieval-augmented generation can even <strong>amplify biases</strong> present in the document collection: <em>&#8220;the biases in document collections are often amplified in the generated responses, even when the generating LLM exhibits a low level of bias.&#8221;</em> (<a href="https://arxiv.org/html/2502.17611v1#:~:text=in%20RAG%20responses%20from%20document,world%20deployment">Evaluating the Effect of Retrieval Augmentation on Social Biases</a>). This finding (Zhang <em>et al.</em>, 2025) is concerning: it means that if your knowledge corpus leans a certain way (e.g. stereotypes in news articles), an LLM using it for answers might produce <strong>even more biased outputs</strong>. Therefore, it&#8217;s crucial to filter and balance the content going into the vector index and the content coming out.</p><p>Several approaches for bias filtering and mitigation have been explored:</p><ul><li><p><strong>Dataset curation and balancing:</strong> At ingestion time, one can attempt to balance the vector store&#8217;s contents to represent multiple perspectives. For example, ensure that for a contentious topic, documents from different viewpoints are included, so the nearest neighbors to a query aren&#8217;t one-sided. If the source data is known to be skewed (e.g., over-representation of one demographic), augmentation or re-weighting can be done. This is essentially a pre-filtering of what goes into the database. It doesn&#8217;t &#8220;remove&#8221; bias per se, but aims for a fair representation so that retrieval doesn&#8217;t consistently favor one angle.</p></li><li><p><strong>Content filtering for harmful or extreme bias:</strong> Using classifiers or rule-based detectors to flag chunks containing hate speech, extreme prejudice, or other undesirable bias and exclude them from the vector index (or at least mark them). For instance, an organization might exclude any content with overtly racist or sexist language from the knowledge base that the LLM will draw on. This prevents those vectors from ever being retrieved as context. If removal isn&#8217;t feasible, tagging such content and having the LLM avoid or downplay it is another strategy.</p></li><li><p><strong>Bias-aware retrieval/ranking:</strong> The retrieval process itself can be tuned to mitigate bias. One idea is to inject diversity into the results &#8211; rather than returning 5 very similar perspectives, return a mix. Another idea is to post-filter results by running a <strong>bias evaluation</strong> on them. For example, if a query asks a question about a specific group of people and all top results are from a single biased source, the system could detect this and replace some with alternative sources. Research in 2024 proposed metrics to quantify bias in retrieval results and differences between the retrieved snippets and a ground truth distribution (<a href="https://arxiv.org/html/2502.17611v1#:~:text=in%20RAG%20responses%20from%20document,world%20deployment">Evaluating the Effect of Retrieval Augmentation on Social Biases</a>), which could guide such adjustments.</p></li><li><p><strong>Embedding-level debiasing:</strong> Since embeddings capture semantic properties of text, they may also carry biases present in language (e.g., associating certain professions with a gender). Prior work on word embeddings showed that neutralizing or removing the <em>bias vector</em> component can reduce biased associations. In LLM embedding contexts, there are emerging techniques to post-process embeddings to reduce bias while preserving meaning. These include projecting embeddings into a subspace that filters out sensitive attributes. For instance, one might attempt to remove the dimension that correlates with sentiment toward a certain group. Some 2024 methods like UniBias go even further by manipulating internal model representations to eliminate biased components (<a href="https://openreview.net/forum?id=luQiVmnviX#:~:text=investigating%20how%20feedforward%20neural%20networks,alleviates%20prompt%20brittleness%20of%20LLMs">UniBias: Unveiling and Mitigating LLM Bias through Internal Attention and FFN Manipulation | OpenReview</a>) . While these are complex and at research stage, they point toward future tools for bias mitigation at the vector level.</p></li></ul><p>In practice, a <strong>combination of strategies</strong> is recommended. As Zhang <em>et al.</em> (2025) conclude, we must carefully evaluate and monitor biases in RAG applications (<a href="https://arxiv.org/html/2502.17611v1#:~:text=in%20RAG%20responses%20from%20document,world%20deployment">Evaluating the Effect of Retrieval Augmentation on Social Biases</a>). This means testing the system with queries that could reveal bias (e.g., questions about different demographic groups) and analyzing the retrieved context and LLM outputs for fairness. If biased content is found influencing answers, one should refine the filtering &#8211; whether by removing certain data, adding counter-balancing data, or adjusting the retrieval algorithm. Ultimately, bias filtering is about <strong>maintaining fairness and factuality</strong>: ensuring the augmentation data doesn&#8217;t skew the LLM into unwanted or discriminatory behavior. Given that LLMs can amplify biases from retrieved text , proactive filtering and bias audits are now seen as necessary steps before deploying these systems in the real world.</p><h2><strong>Security Filtering</strong></h2><p>As vector databases become integrated into LLM workflows, <strong>security concerns</strong> have come to the forefront. In particular, safeguards are needed against adversarial manipulations, data leakage, and unauthorized access involving the vector store and embeddings. <strong>Security filtering</strong> refers to a collection of measures to protect both the data and the LLM application from these threats. Recent research (late 2024) underscores that Retrieval-Augmented Generation systems can be vulnerable to a range of attacks if such defenses are not in place (<a href="https://arxiv.org/html/2412.18295v1#:~:text=of%20RAG%20systems%20raises%20significant,retrieved%20pieces%20of%20private%20knowledge">Pirates of the RAG: Adaptively Attacking LLMs to Leak Knowledge Bases</a>).</p><p>One major concern is <strong>adversarial data poisoning</strong> &#8211; an attacker inserting or altering vectors in the database to influence the LLM&#8217;s outputs. Xian <em>et al.</em> (2024) show that RAG systems are <em>&#8220;vulnerable to adversarial poisoning attacks, where attackers manipulate the retrieval corpus.&#8221;</em> By adding specially crafted fake documents or vector entries, an attacker might cause irrelevant or malicious content to be retrieved for certain queries (e.g., injecting misinformation that the LLM then uses as &#8220;context&#8221;). These attacks can bypass many existing defenses and raise serious safety issues . To mitigate this, security filtering can include <strong>anomaly detection</strong> on the embeddings. For example, a defense named DRS (Directional Relative Shifts) was proposed to detect poisoned vectors by spotting subtle distribution shifts in embedding space . The idea is to filter out or flag new data that causes suspicious changes along low-variance directions in the vector space, which is a sign of potential poisoning. In practice, maintaining statistical profiles of the vector distribution and using outlier detection can help catch illicit injections. Additionally, all write or update operations to the vector database should be authenticated and monitored. Only trusted pipelines should add embeddings, and if user-contributed content is allowed (e.g., users adding their own documents), it should be vetted (scanned for malicious content) before being embedded.</p><p>Another aspect is <strong>data leakage and privacy</strong>. The embeddings in a vector database encode information from the original documents. Researchers have demonstrated that attackers might perform <em>embedding inversion</em> &#8211; reconstructing or approximating the original text from its embedding (<a href="https://arxiv.org/html/2411.05034v1#:~:text=main%20types%3A%20embedding%20inversion%20attacks%C2%A0,information%20from%20the%20original%20input">Mitigating Privacy Risks in LLM Embeddings from Embedding Inversion</a>) &#8211; or <em>membership inference</em> &#8211; determining if a certain data point was included in the database or training set . Liu <em>et al.</em> (2024) warn that <em>&#8220;embedding vector databases are particularly vulnerable to inversion attacks, where adversaries can exploit embeddings to reverse-engineer sensitive information.&#8221;</em> In response, they developed Eguard, a defense that projects embeddings into a &#8220;safer&#8221; space to thwart inversion while preserving utility . On the practical side, one of the simplest and most effective safeguards is encryption of the vectors. Encrypting the stored embedding vectors (and handling search through techniques like secure enclaves or partially homomorphic encryption) can prevent an attacker who gains access to the database from directly using the vectors to leak data. In fact, the updated OWASP Top 10 for LLMs (2025) explicitly includes <em>&#8220;Vector and Embedding Weaknesses&#8221;</em> as a security risk (<a href="https://ironcorelabs.com/blog/2025/owasp-llm-top10-2025-update/#:~:text=Image%3A%20OWASP%20Diagram%20Excerpt%20Showing,LLM08">OWASP's Updated Top 10 LLM Includes Vector and Embedding Weaknesses | IronCore Labs</a>) and recommends application-layer encryption of embeddings. As one security blog noted, <em>&#8220;when you encrypt vectors, you stop embedding inversion attacks&#8221;</em> . Several vendors now offer tools for searchable encryption on vector stores, enabling similarity search to operate on encrypted data . While full encryption can be complex, at minimum sensitive data embeddings should be stored with strong access controls and possibly encryption at rest.</p><p><strong>Unauthorized data access</strong> can also occur if the retrieval API is not properly restricted. In multi-user or multi-tenant applications, one user should not accidentally (or maliciously) retrieve vectors from another user&#8217;s private data. Since vector search is essentially a nearest-neighbor lookup, queries might surface data that the user isn&#8217;t meant to see if no restrictions are in place. Best practice here is to use <strong>metadata-based access filtering or namespace partitioning</strong>. For example, Amazon&#8217;s RAG service introduced <strong>metadata filters to enforce access control</strong>, so that each query is automatically restricted to documents the user is allowed to access (<a href="https://aws.amazon.com/blogs/machine-learning/access-control-for-vector-stores-using-metadata-filtering-with-knowledge-bases-for-amazon-bedrock/#:~:text=Access%20control%20with%20metadata%20filters">Access control for vector stores using metadata filtering with Amazon Bedrock Knowledge Bases | AWS Machine Learning Blog</a>). By tagging each vector with attributes like user ID, department, or confidentiality level, and then applying a <code>WHERE</code> filter on queries, the system ensures <em>&#8220;the retrieval only fetches information that a particular user or application is authorized to access.&#8221;</em> . Some vector DBs allow creating separate indexes or namespaces per user to silo data, though this can be less flexible than a unified index with filtered querying (<a href="https://myscale.com/blog/filtered-vector-search-in-myscale/#:~:text=This%20demands%20exceptionally%20high%20query,separate%20namespace%2C%20ensuring%20query%20precision">Filtered Vector Search: The Importance and Behind the Scenes</a>). In any case, not relying on obscurity: implement explicit filters so that even if two users query something similar, their results come from their respective data silos.</p><p>Finally, there is the issue of <strong>prompt injection and output leakage</strong> &#8211; where an attacker crafts a query that causes the LLM to divulge private info from the retrieved context (sometimes called a &#8220;knowledge base leak&#8221; attack). Recent work titled <em>&#8220;Pirates of the RAG&#8221;</em> demonstrated a black-box method to systematically extract hidden knowledge base contents via adaptive querying (<a href="https://arxiv.org/html/2412.18295v1#:~:text=sensitive%20information,and%20deployment%20of%20RAG%20systems">Pirates of the RAG: Adaptively Attacking LLMs to Leak Knowledge Bases</a>) . Essentially, if an internal document is stored, a clever sequence of prompts might trick the LLM into regurgitating it. Mitigating this is hard, but security filters can include: rate limiting and monitoring unusual query patterns (to catch automated data harvesting attempts), and using the LLM&#8217;s own refusals or toxicity filters to block responses that look like verbatim dumps of internal text. One can also design the system such that particularly sensitive pieces of data are not directly given to the LLM but rather handled via controlled templates or summaries.</p><p>In summary, <strong>security filtering is multi-faceted</strong>: it ranges from preventing <strong>poisoned inputs</strong> (drop or detect anomalous vectors), to protecting against <strong>data leakage</strong> (encryption, inversion defenses), to enforcing <strong>access controls</strong> (metadata filters, auth checks), and monitoring for abuse (rate limits, anomaly detection on queries and outputs). As LLM deployments on private data grow, these safeguards are becoming as important as the core retrieval itself. The best practices are to <strong>treat the vector database with the same security rigor as any sensitive data store</strong>, apply principle of least privilege to queries, and incorporate emerging defenses from the latest research (e.g. dynamic filtering of suspected malicious entries). By building security filtering into the pipeline, one can significantly reduce risks of adversaries manipulating the system or extracting what they should not, thereby maintaining user trust and compliance.</p><h2><strong>Conclusion</strong></h2><p>Filtering challenges in vector databases for LLM document retrieval are an active area of research in 2024 and 2025. Effective <strong>relevance filtering</strong> ensures that LLMs are grounded in high-quality, on-topic context (<a href="https://arxiv.org/abs/2501.00332#:~:text=multiple%20LLM%20agents%20to%20collaboratively,the%20number%20of%20irrelevant%20retrieved"> MAIN-RAG: Multi-Agent Filtering Retrieval-Augmented Generation</a>). Deduplication techniques remove noise from repeated content, leading to more efficient and diverse information retrieval (<a href="https://arxiv.org/pdf/2405.15523#:~:text=for%20GPT,1%2C%2034">HERE</a>). <strong>Semantic filtering</strong> emphasizes true meaning alignment, often employing additional understanding to refine results beyond raw similarity (<a href="https://www.timescale.com/blog/what-is-semantic-search-with-filters-and-how-to-implement-it-with-pgvector-and-python#:~:text=Traditionally%2C%20keyword%20search%20using%20algorithms,meaning%20and%20context%20of%20words">What Is Semantic Search With Filters and How to Implement It With Pgvector and Python | Timescale</a>). <strong>Bias filtering</strong> is increasingly recognized as vital, as studies show that an unfiltered knowledge base can inject and even amplify biases into LLM outputs (<a href="https://arxiv.org/html/2502.17611v1#:~:text=in%20RAG%20responses%20from%20document,world%20deployment">Evaluating the Effect of Retrieval Augmentation on Social Biases</a>) &#8211; calling for careful curation and balance of retrieved content. Lastly, <strong>security filtering</strong> measures guard the vector store and its data against malicious exploits and privacy breaches, using methods like access control, encryption, and anomaly detection (<a href="https://aws.amazon.com/blogs/machine-learning/access-control-for-vector-stores-using-metadata-filtering-with-knowledge-bases-for-amazon-bedrock/#:~:text=Metadata%20filtering%20in%20knowledge%20bases,data%20governance%20policies%20and%20regulations">Access control for vector stores using metadata filtering with Amazon Bedrock Knowledge Bases | AWS Machine Learning Blog</a>).</p><p>In practice, these filtering layers often work in combination. A robust RAG system might first weed out duplicates, then retrieve by semantic similarity, filter by user permissions and relevance score, re-rank results with an LLM for semantic accuracy, and finally exclude any content that violates bias or safety criteria before prompting the model. By following the emerging best practices &#8211; from adaptive relevance thresholds to secure vector encryption , practitioners can build document-grounded LLM applications that are not only <em>accurate and efficient</em> but also <em>trustworthy and safe</em>. The literature suggests that investing in these filtering steps yields substantial gains in the quality of LLM responses while mitigating risks, making them an essential part of modern AI system design.</p><p><strong>Sources:</strong> The information and best practices above are synthesized from recent research and technical reports (2024&#8211;2025) on vector databases and LLM retrieval augmentation, including peer-reviewed papers and industry whitepapers (<a href="https://arxiv.org/abs/2501.00332#:~:text=reliability,four%20QA%20benchmarks%20demonstrate%20that"> MAIN-RAG: Multi-Agent Filtering Retrieval-Augmented Generation</a>), as cited throughout.</p>]]></content:encoded></item><item><title><![CDATA[Multilingual & Multimodal LLMs for Document Digitization: A Literature Review]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/multilingual-and-multimodal-llms</link><guid isPermaLink="false">https://www.rohan-paul.com/p/multilingual-and-multimodal-llms</guid><pubDate>Mon, 16 Jun 2025 09:33:58 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!bnt5!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!bnt5!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!bnt5!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png 424w, https://substackcdn.com/image/fetch/$s_!bnt5!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png 848w, https://substackcdn.com/image/fetch/$s_!bnt5!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png 1272w, https://substackcdn.com/image/fetch/$s_!bnt5!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!bnt5!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1950247,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166054406?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!bnt5!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png 424w, https://substackcdn.com/image/fetch/$s_!bnt5!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png 848w, https://substackcdn.com/image/fetch/$s_!bnt5!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png 1272w, https://substackcdn.com/image/fetch/$s_!bnt5!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8c8ba970-360b-48c0-b895-b5a6b234f356_1920x1080.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ul><li><p>Multilingual And Multimodal LLMs for Document Digitization A Literature Review</p></li><li><p>Overview</p></li><li><p>Architectural Adaptations for Multilingual and Multimodal Input</p></li><li><p>Key Challenges in Multilingual Multimodal Processing</p></li><li><p>Benchmarks and State-of-the-Art Performance</p></li><li><p>Practical Engineering Considerations</p></li><li><p>Key Takeaways</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Overview</strong></h2><p>Large language models (LLMs) are being extended to handle multiple languages and data modalities (text, images, tables, speech, etc.) to better support document digitization and analysis. Traditionally, many foundation models have focused on English text, but recent research emphasizes inclusivity across diverse languages and input types (<a href="https://arxiv.org/abs/2410.16153#:~:text=,a%20holistic%20evaluation%20suite%20encompassing"> Pangea: A Fully Open Multilingual Multimodal LLM for 39 Languages</a>). This review synthesizes the latest (2024&#8211;2025) research on system design changes required for multilingual, multimodal LLMs, the challenges encountered (from tokenization to OCR and cross-modal alignment), benchmark performance of state-of-the-art models, and practical engineering considerations for deploying these systems.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Architectural Adaptations for Multilingual and Multimodal Input</strong></h2><p><strong>Unified Tokenization and Embeddings:</strong> Multilingual support often begins with a shared subword tokenizer (e.g. SentencePiece or BPE) covering many scripts. A single vocabulary enables one model to ingest different languages, but if training data is heavily English-centric, the tokenizer may fragment other languages into inefficient byte-level tokens (<a href="https://arxiv.org/html/2502.12560v2#:~:text=towards%20English%20and%20code,the%20maximum%20input%20and%20output">How does a Language-Specific Tokenizer affect LLMs?</a>). Modern LLMs like LLaMA-2 were ~90% trained on English, causing non-Latin languages to be broken into many small tokens, which <em>limits effective context length and representation quality</em> . One remedy is <em>vocabulary extension</em>: adding language-specific tokens and merge rules to better encode under-represented languages . For example, recent studies show that extending a tokenizer for Korean yields more stable, sensible outputs and lower perplexity on that language . While extending the vocab requires retraining embeddings, it is far cheaper than training a new model from scratch and markedly improves multilingual performance .</p><p><strong>Multimodal Input Encoders:</strong> To handle non-text modalities, LLM architectures incorporate additional encoders or embedding pipelines. A common design is to prepend visual or audio features as special tokens to the text transformer. For document images, one approach is to use a vision transformer to generate <strong>visual patch embeddings</strong> (plus 2D position coordinates) that are fed into the LLM alongside text tokens (<a href="https://arxiv.org/abs/2408.15045#:~:text=introduce%20DocLayLLM%2C%20an%20efficient%20and,Experimental%20results%20demonstrate%20that%20our"> DocLayLLM: An Efficient and Effective Multi-modal Extension of Large Language Models for Text-rich Document Understanding</a>). Liao et al. (2024) follow this strategy in DocLayLLM, seamlessly integrating image patches and layout positions into a language model, which lets the LLM leverage its natural text comprehension while <strong>enhancing perception of spatial OCR information</strong> . This avoids treating text and layout as separate streams &#8211; the unified transformer can attend across both, after minimal adaptation. Another strategy is <strong>lightweight modality adapters</strong>: for instance, Apple&#8217;s FLoRA method attaches small low-rank adapter layers to a pre-trained text LLM to ingest new modalities (<a href="https://machinelearning.apple.com/research/llm-fusion-low-rank#:~:text=or%20video%20improves%20performance%2C%20but,dropout%2C%20FLoRA%20is%20robust%20to">Multimodal Large Language Models with Fusion Low Rank Adaptation for Device Directed Speech Detection - Apple Machine Learning Research</a>). Palaskar et al. (2024) showed that with FLoRA, a text-only model can be augmented to handle audio inputs (for speech detection) with only a fraction of parameters updated, yet matching the performance of full multimodal fine-tuning . This modular approach simplifies adding modalities (audio, video) on top of existing LLMs without costly re-training.</p><p><strong>Layout and Structure Modeling:</strong> Documents often contain structured layouts (forms, tables, multi-column text) that pure text models miss. Recent systems explicitly incorporate layout features or tasks into LLM training. <em>LayoutLLM</em> (CVPR 2024) introduced <strong>layout-aware instruction tuning</strong>, with pre-training tasks at document-level, region-level, and segment-level to teach the model how to utilize spatial structure (e.g. reading order, section boundaries) (<a href="https://arxiv.org/abs/2404.05225#:~:text=understanding%20have%20not%20fully%20explored,a%20novel%20module%20called%20layout"> LayoutLLM: Layout Instruction Tuning with Large Language Models for Document Understanding</a>). They also use a <em>Layout Chain-of-Thought</em> mechanism, guiding the model to focus on the region relevant to a query before answering . Another approach is found in <em>DocLLM</em> (JPMorgan AI, 2024), which avoids heavy image encoders entirely and instead feeds the model textual content plus each text segment&#8217;s bounding-box coordinates (<a href="https://arxiv.org/abs/2401.00908#:~:text=effectively,approach%20allows%20us%20to%20address"> DocLLM: A layout-aware generative language model for multimodal document understanding</a>). By decomposing the transformer&#8217;s attention into text vs. spatial sub-matrices, DocLLM achieves <strong>cross-modal alignment</strong> between content and position without processing raw pixels . This <em>lightweight layout encoding</em> captures document structure while saving computation, illustrating that effective multimodal design doesn&#8217;t always require end-to-end image modeling.</p><h2><strong>Key Challenges in Multilingual Multimodal Processing</strong></h2><ul><li><p><strong>Tokenization &amp; Script Diversity:</strong> As noted, a single vocabulary can struggle with diverse scripts. Excessive splitting of words (e.g. into bytes or characters) in low-resource languages leads to longer input sequences and lost semantic context (<a href="https://arxiv.org/html/2502.12560v2#:~:text=tokenizer%E2%80%99s%20ability%20to%20effectively%20process,may%20need%20to%20absorb%20too">How does a Language-Specific Tokenizer affect LLMs?</a>). Morphologically rich languages or those without whitespace (Chinese, Thai) are particularly affected. Ensuring the tokenizer respects word boundaries or common morphemes in each language is hard when sharing across 30+ languages. Researchers address this by increasing vocabulary size or using language-specific subtoken additions , but this raises embedding alignment issues (making sure new tokens integrate meaningfully with original ones). Maintaining a balanced training mix is also critical &#8211; if one language dominates, others suffer (the <em>curse of multilinguality</em>). Recent multilingual LLMs like <strong>Pangea-7B</strong> found that performance in each language depends on having the right proportion of English vs. non-English data and on language popularity; under-sampling high-resource languages can help elevate low-resource ones (<a href="https://arxiv.org/abs/2410.16153#:~:text=,a%20holistic%20evaluation%20suite%20encompassing"> Pangea: A Fully Open Multilingual Multimodal LLM for 39 Languages</a>).</p></li><li><p><strong>Cross-Lingual Embedding Alignment:</strong> Beyond tokenization, the model&#8217;s internal representations need to align semantically across languages. If &#8220;bank account&#8221; in English and its Arabic equivalent end up in very different embedding subspaces, the model cannot easily transfer knowledge or do cross-lingual tasks. Multilingual pre-training on parallel corpora can induce some alignment, but additional techniques are being explored. Li et al. (2024) propose a <em>post-pretraining alignment</em> using translation pairs with a contrastive loss to explicitly pull together embeddings of sentences that mean the same thing in different languages (<a href="https://openreview.net/forum?id=3PaVCdeEmW#:~:text=Abstract%3A%20Multilingual%20generative%20models%20obtain,training%20tokens%2C%20our%20alignment">Align after Pre-train: Improving Multilingual Generative Models with Cross-lingual Alignment | OpenReview</a>). Even using &lt;0.1% of the original training data for such alignment, they significantly improved cross-lingual downstream performance . This indicates that a relatively small intervention can mitigate the isolation of representations for different languages.</p></li><li><p><strong>Multimodal Fusion &amp; Alignment:</strong> Integrating modalities poses its own alignment challenges. Visual and textual information must be mapped into a common latent space or at least made mutually understandable to the model. A classic solution is contrastive image-text pretraining (exemplified by CLIP), but generative LLMs require deeper fusion than just matching captions to images. Many multimodal LLMs adopt a <strong>two-stage architecture</strong>: a <em>modality encoder</em> (e.g. CNN or ViT for images, audio encoder for speech) produces embeddings, and an <em>integration layer</em> (often a projector or cross-attention module) feeds those into the language model (<a href="https://aclanthology.org/2024.findings-acl.738.pdf#:~:text=Models%20aclanthology,2%29%2C%20LLM"> MM-LLMs: Recent Advances in MultiModal Large Language Models</a>). Tuning these components jointly is tricky &#8211; early layers must learn modality-specific features (pixels vs. phonemes) while later layers align them with text semantics. Some research (e.g. Huang et al., 2023 with AudioGPT) treats <em>speech as another token stream</em> via an intermediate recognition step (<a href="https://aclanthology.org/2024.emnlp-main.690.pdf#:~:text=Models%20aclanthology,specific"> Self-Powered LLM Modality Expansion for Large Speech-Text Models</a>), essentially converting audio to text tokens using an ASR model (like Whisper) and then using the LLM as normal. This pipeline simplifies integration but relies on the quality of the speech-to-text component, which may falter for dialects or code-switching. Fully end-to-end speech+text LLMs (like Meta&#8217;s SeamlessM4T) jointly learn multiple modalities but need huge training resources. Recent work on <strong>adapter fusion</strong> (as noted with FLoRA) suggests we can attach audio or vision understanding to a frozen LLM incrementally . Ensuring that the LLM &#8220;pays attention&#8221; to these new modality tokens appropriately (and not overwhelmed by the abundant text weights) remains an open challenge.</p></li><li><p><strong>Optical Character Recognition (OCR) for Low-Resource Languages:</strong> Document digitization often starts with OCR to convert images of text into characters. For many languages, especially those with complex scripts or limited training data, OCR quality is a major bottleneck. A 2023 survey highlights open problems in scaling OCR to low-resource languages, from lack of annotated data to diverse font/printing variations (<a href="https://aclanthology.org/2024.americasnlp-1.10/#:~:text=In%20this%20paper%2C%20we%20share,and%20outline%20several%20open%20challenges">A Concise Survey of OCR for Low-Resource Languages</a>). The creators of Pangea-7B specifically flagged multilingual OCR as <strong>particularly challenging</strong> in their multimodal LLM system (<a href="https://neulab.github.io/Pangea/#:~:text=Preliminary%20Explorations%20of%20Multilingual%20OCR%3A,in%20Figure%208%2C%20the%20results">Pangea: A Fully Open Multilingual Multimodal LLM for 39 Languages</a>). They augmented training with 500K synthetic OCR examples across 10 languages (by screenshotting websites in those languages) to improve the model&#8217;s ability to read text in images . This did boost OCR accuracy, but <strong>non-Latin scripts (Chinese, Japanese, etc.) still lagged</strong> significantly behind Latin ones . The results suggest that much more data (and possibly new OCR-specific model components) are needed for equitable performance. Integrating specialized OCR engines into the LLM pipeline is a practical workaround: e.g. use Google&#8217;s OCR for Telugu text then feed the recognized text to the LLM. However, this two-step process can break the end-to-end flow and may not capture layout or font nuances that an integrated multimodal model could. Finding the right balance between end-to-end learning and modular OCR remains an active area &#8211; some models like DocLayLLM demonstrate that an LLM augmented with visual tokens can even outperform traditional OCR-based pipelines (<a href="https://arxiv.org/abs/2408.15045#:~:text=techniques%20of%20CoT%20Pre,free%20competitors"> DocLayLLM: An Efficient and Effective Multi-modal Extension of Large Language Models for Text-rich Document Understanding</a>), hinting at the potential of tightly-coupled vision-language reasoning.</p></li><li><p><strong>Handling Diverse Modalities (Tables, Forms, Math, etc.):</strong> Beyond plain text and images, real documents include tables, charts, formulas, and other formats. Each requires special treatment. Tables, for instance, carry a 2D grid structure and sometimes calculations; simply reading left-to-right might scramble their meaning. LLMs can struggle with tables if given as linearized text. One solution is to detect tables and convert them to a structured form (JSON or Markdown) before feeding to the model, preserving cell boundaries. Some benchmarks like EXAMS-V explicitly include tables, diagrams, and equations in their multimodal questions (<a href="https://arxiv.org/abs/2403.10378#:~:text=multilingual%20exam%20benchmark%20for%20evaluating,for%20intricate%20reasoning%20across%20diverse"> EXAMS-V: A Multi-Discipline Multilingual Multimodal Exam Benchmark for Evaluating Vision Language Models</a>), requiring models to jointly interpret text and visual elements. Current top models (e.g. GPT-4V) still find this difficult . For math equations or scientific charts, a combination of OCR (to get printed math as LaTeX) and domain-specific parsing might be necessary alongside the LLM. In short, each modality demands <strong>embedding alignment</strong> with text: e.g. a table&#8217;s row/column headers need to align with how a question refers to them. Custom encoders (like graph neural nets for tables or latex parsers for math) may be integrated into future LLM systems to handle these seamlessly. So far, most multimodal LLMs handle images and text; handling <em>nested modalities</em> (an image that contains a table with text) is an evolving challenge.</p></li></ul><h2><strong>Benchmarks and State-of-the-Art Performance</strong></h2><p>To evaluate these multilingual, multimodal capabilities, new benchmarks have emerged. PangeaBench (2024) is a suite of 14 datasets covering 47 languages, testing models on image-based tasks in diverse cultural contexts (<a href="https://neulab.github.io/Pangea/#:~:text=understanding%20tasks.%20Pangea,multilingual%20and%20culturally%20diverse%20contexts">Pangea: A Fully Open Multilingual Multimodal LLM for 39 Languages</a>) . On this benchmark, <em>Pangea-7B</em> (a 7B-parameter vision-language model trained on 39 languages) achieves state-of-the-art results &#8211; <strong>on par with the best open models in English, and substantially better in multilingual settings</strong> . Notably, Pangea-7B outperforms other open-source models in tasks requiring cross-lingual understanding and cultural nuance, highlighting the impact of its inclusive training data . This demonstrates that targeted multilingual multimodal training can close the gap with English-centric models, at least on academic benchmarks.</p><p>Another comprehensive benchmark, <strong>M5 (Multilingual Multicultural Multimodal Benchmark)</strong>, examines model performance across 8 datasets, 5 task types, and 41 languages (<a href="https://aclanthology.org/2024.findings-emnlp.250/#:~:text=M5%2C%20the%20first%20comprehensive%20benchmark,ones%20in%20a%20multilingual%20setting">M5 &#8211; A Diverse Benchmark to Assess the Performance of Large Multimodal Models Across Multilingual and Multicultural Vision-Language Tasks - ACL Anthology</a>). Schneider and Sitaram (2024) found <em>substantial performance disparities</em> between high-resource and low-resource languages on vision-language tasks . Surprisingly, they also noted that <strong>bigger is not always better</strong> &#8211; larger models did not consistently outperform smaller ones in multilingual tests . This suggests that simply scaling parameters won&#8217;t solve multilingual generalization; data diversity and training strategy matter more. M5 also introduced a challenging <em>Visio-Linguistic Outlier Detection</em> task (finding culturally out-of-context elements in images), where all tested models performed near random chance . Such results pinpoint remaining blind spots of current LLMs, especially for culturally specific reasoning that wasn&#8217;t covered in training.</p><p>For document-specific tasks, standard benchmarks include form understanding (e.g. XFUND for multilingual forms), document QA (DocVQA, InfoVQA), and table QA (WikiTables, ChartQA). On many of these, specialized models are starting to overtake general LLMs. For example, DocLLM&#8217;s layout-aware model, after fine-tuning on four core document tasks, <strong>outperformed prior state-of-the-art LLMs on 14 out of 16 datasets</strong> evaluated (<a href="https://arxiv.org/abs/2401.00908#:~:text=documents.%20The%20pre,of%205%20previously%20unseen%20datasets"> DocLLM: A layout-aware generative language model for multimodal document understanding</a>). It also generalized well to most unseen datasets, indicating robust learning of document structures . In visual document question answering, <em>stepwise reasoning</em> approaches are proving valuable. Zhang et al. (2024) augment a smaller multimodal model with intermediate reasoning steps (using a larger LLM to generate synthetic chain-of-thought data), achieving +5% accuracy on the complex InfoVQA benchmark and +7% on ChartQA relative to direct answering (<a href="https://arxiv.org/html/2403.00816v2#:~:text=as%20data%20generators%20to%20generate,We%20hope%20our%20work">Read and Think: An Efficient Step-wise Multimodal Language Model for Document Understanding and Reasoning</a>). This demonstrates that forcing the model to <em>&#8220;think step-by-step&#8221;</em> can yield better comprehension of charts and densely formatted pages.</p><p>At the high end, proprietary models like <strong>GPT-4V</strong> (OpenAI) and Google&#8217;s Gemini (multimodal successor to PaLM) currently lead many benchmarks, but even they struggle on the hardest tasks. The EXAMS-V benchmark &#8211; 20k multimodal high-school exam questions in 11 languages &#8211; stumps these advanced models, with GPT-4 Vision and Gemini underperforming on many questions (<a href="https://arxiv.org/abs/2403.10378#:~:text=systems,significance%20as%20a%20future%20benchmark"> EXAMS-V: A Multi-Discipline Multilingual Multimodal Exam Benchmark for Evaluating Vision Language Models</a>). The questions often require combining text, image, and world knowledge in a specific language, illustrating that <em>no model yet fully masters joint multilingual and multimodal reasoning in open domains</em>. We are beginning to see head-to-head evaluations: for instance, Xie et al. (2024) report their <em>PDF-WuKong</em> model (designed for long academic PDFs) outperforms "proprietary products" by 8.6% F1 on a long-document QA task (<a href="https://arxiv.org/html/2410.05970v2#:~:text=MLLM,code%20and%20dataset%20will%20be">{cutout}03.2cm55cm1 empty PDF-WuKong : A Large Multimodal Model for Efficient Long PDF Reading with End-to-End Sparse Sampling</a>). This hints that focused research prototypes can sometimes beat general-purpose commercial systems on niche tasks, though the gap may not last long as industry models rapidly incorporate similar ideas.</p><p>In summary, benchmarks are evolving to test both breadth (many languages, modalities, and cultures as in M5 and PangeaBench) and depth (complex, multi-hop reasoning as in EXAMS-V). The best open models are closing the performance gap in multilingual settings (<a href="https://neulab.github.io/Pangea/#:~:text=holistic%20evaluation%20suite%20encompassing%2014,multilingual%20and%20culturally%20diverse%20contexts">Pangea: A Fully Open Multilingual Multimodal LLM for 39 Languages</a>), but <strong>significant challenges remain evident whenever the input is far from the training domain</strong> &#8211; e.g. a low-resource language script, a densely formatted scientific table, or an image requiring cultural context to interpret.</p><h2><strong>Practical Engineering Considerations</strong></h2><p>Designing and deploying multilingual, multimodal LLM systems for documents involves trade-offs in <strong>computational cost, complexity, and integration</strong>. Key considerations include:</p><ul><li><p><strong>Computational Cost &amp; Model Size:</strong> Supporting dozens of languages and multiple modalities typically increases model size and training data requirements. Vocabulary extension and extra encoder modules add parameters. Training a model like Pangea-7B (multilingual vision-LM) means handling a 6M example instruction corpus across 39 languages (<a href="https://arxiv.org/abs/2410.16153#:~:text=,a%20holistic%20evaluation%20suite%20encompassing"> Pangea: A Fully Open Multilingual Multimodal LLM for 39 Languages</a>), which is computationally expensive. One way to mitigate costs is to leverage <em>frozen pre-trained components</em> (e.g. a pre-trained ViT for images or Whisper for speech) and only train a bridging layer. This reuse, however, requires careful alignment. Another strategy is <strong>Mixture-of-Experts (MoE)</strong>, where separate expert subnetworks handle different languages or modalities, activating only a subset per input to save computation. While MoE can scale to many languages without blowing up inference cost, it adds system complexity (routing, load-balancing experts) and is an area of ongoing research.</p></li><li><p><strong>Inference Efficiency:</strong> Multimodal LLMs can be slow at runtime. Processing an image or audio input involves running a hefty encoder (like a ResNet or transformer) before the text generation even begins. If documents have multiple pages or many images, inference latency multiplies. Engineers are exploring <em>sparse computation</em> and retrieval to speed this up. The <strong>PDF-WuKong</strong> system introduces a <em>sparse sampler</em> that learns to pick only the most relevant parts of a long document (both text paragraphs and figures) to feed into the model (<a href="https://arxiv.org/html/2410.05970v2#:~:text=introduce%20PDF,Experimental">{cutout}03.2cm55cm1 empty PDF-WuKong : A Large Multimodal Model for Efficient Long PDF Reading with End-to-End Sparse Sampling</a>) . By filtering irrelevant sections, the model avoids wasting its limited context and compute on the entire 100-page PDF, focusing instead on, say, the one page that likely contains the answer. This kind of <strong>smart chunking</strong> or content selection dramatically improves efficiency and even accuracy, since the model isn&#8217;t distracted by extraneous data. In production document pipelines, a similar approach is to use an external search index: first split a large document into chunks (by page or section), embed them and retrieve top-k chunks relevant to the query, and only feed those into the LLM. This retrieval-augmented strategy is popular to cope with long texts and is naturally language-agnostic (it works as long as your embeddings can handle multilingual text).</p></li><li><p><strong>Integration into Pipelines:</strong> Many real-world document processing systems are modular &#8211; e.g. scan -&gt; OCR -&gt; translate -&gt; analyze -&gt; summarize. Replacing all modules with one giant multimodal LLM is tempting but may be impractical. Instead, hybrid solutions are used. For example, one can use <strong>specialized OCR or ASR tools</strong> for each language (since they might be more accurate than a general LLM at raw transcription), then feed the extracted text into an LLM for understanding. This pipeline allows swapping out the OCR component for improvements without retraining the LLM. However, tight integration can yield better results as shown by DocLayLLM, which directly learns from OCR outputs and visual features together, beating systems that do OCR separately (<a href="https://arxiv.org/abs/2408.15045#:~:text=techniques%20of%20CoT%20Pre,free%20competitors"> DocLayLLM: An Efficient and Effective Multi-modal Extension of Large Language Models for Text-rich Document Understanding</a>). A practical compromise is to have the LLM <strong>call tools on the fly</strong> &#8211; e.g. an LLM could detect it&#8217;s dealing with an image in an unfamiliar script and invoke an OCR API (this is akin to the <em>ReAct/Toolformer</em> paradigm). Such dynamic tool use can combine the strengths of specialist models with the reasoning of LLMs. Engineering these pipelines requires careful orchestration and may involve frameworks for LLM agents.</p></li><li><p><strong>Memory and Scaling:</strong> Serving a multilingual model can be memory-intensive due to the large vocabulary and parameters needed to cover many languages. If a use-case only needs a few languages or one modality, a slimmed-down model might be preferred for speed and cost. Techniques like <strong>LoRA (Low-Rank Adapters)</strong> or <strong>prompt tuning</strong> enable maintaining a single big model but loading small adaptation weights for specific domains or languages on demand. For instance, an AI service might keep an English-only LLM and only activate a multilingual extension component when non-English text is detected. This conditional routing saves time. Additionally, quantization of models (down to 8-bit or 4-bit weights) is often applied to large multimodal LLMs to fit them on GPUs for inference, though one must ensure that quantization doesn&#8217;t disproportionately hurt performance on certain languages (which might happen if those languages rely on subtle embedding distinctions that get lost with low precision).</p></li><li><p><strong>Evaluation and Monitoring:</strong> From an engineering standpoint, supporting multiple languages means expanded testing &#8211; one must evaluate the system&#8217;s accuracy on each language and modality combination of interest. New benchmarks like M5 (<a href="https://aclanthology.org/2024.findings-emnlp.250/#:~:text=M5%2C%20the%20first%20comprehensive%20benchmark,ones%20in%20a%20multilingual%20setting">M5 &#8211; A Diverse Benchmark to Assess the Performance of Large Multimodal Models Across Multilingual and Multicultural Vision-Language Tasks - ACL Anthology</a>) and EXAMS-V (<a href="https://arxiv.org/abs/2403.10378#:~:text=features%20such%20as%20text%2C%20images%2C,the%20inherent%20complexity%20of%20the"> EXAMS-V: A Multi-Discipline Multilingual Multimodal Exam Benchmark for Evaluating Vision Language Models</a>) are useful guides, but organizations often develop internal test sets (e.g. company documents in various languages) to ensure the system meets specific needs. Monitoring a live system requires logging not just overall success but tracking if certain languages or formats consistently fail. This can inform data collection for the next training cycle (e.g. if the system struggles with Arabic handwriting, gather more of that data). <strong>Fairness and bias</strong> also come into play: a multilingual model should be checked for any bias in how it handles different scripts or cultures &#8211; a known issue since many LLMs inherited skews from predominantly English internet data. Ongoing maintenance is needed to keep performance balanced.</p></li></ul><h2><strong>Key Takeaways</strong></h2><ul><li><p><strong>Multilingual LLM Design:</strong> Requires inclusive tokenization and training data. Using a shared subword vocabulary across languages is common, but additional steps (vocab expansion, alignment objectives) are needed to avoid favoring high-resource languages (<a href="https://arxiv.org/html/2502.12560v2#:~:text=tokenizer%E2%80%99s%20ability%20to%20effectively%20process,may%20need%20to%20absorb%20too">How does a Language-Specific Tokenizer affect LLMs?</a>). Properly balanced data and slight architecture tweaks can yield strong cross-lingual performance, as seen with models like Pangea-7B (<a href="https://neulab.github.io/Pangea/#:~:text=holistic%20evaluation%20suite%20encompassing%2014,multilingual%20and%20culturally%20diverse%20contexts">Pangea: A Fully Open Multilingual Multimodal LLM for 39 Languages</a>).</p></li><li><p><strong>Multimodal Integration:</strong> Demands new system components (vision/audio encoders or adapters) and alignment mechanisms. Effective approaches include feeding image patches and layout tokens into the transformer (<a href="https://arxiv.org/abs/2408.15045#:~:text=introduce%20DocLayLLM%2C%20an%20efficient%20and,Experimental%20results%20demonstrate%20that%20our"> DocLayLLM: An Efficient and Effective Multi-modal Extension of Large Language Models for Text-rich Document Understanding</a>), or using lightweight adapters to plug modalities into an existing LLM (<a href="https://machinelearning.apple.com/research/llm-fusion-low-rank#:~:text=or%20video%20improves%20performance%2C%20but,dropout%2C%20FLoRA%20is%20robust%20to">Multimodal Large Language Models with Fusion Low Rank Adaptation for Device Directed Speech Detection - Apple Machine Learning Research</a>). Ensuring the model can attend to both textual and visual/spatial context is crucial for document tasks.</p></li><li><p><strong>Core Challenges:</strong> Tokenization of diverse scripts, cross-lingual semantic alignment, and reliable OCR for low-resource languages remain tough problems. Even advanced models see accuracy drop on non-Latin scripts and under-represented languages . Complex layouts (tables, forms) and mixed-modality content (diagrams with text) require the model to reason beyond sequential text, often with specialized training (e.g. layout-aware tuning, chain-of-thought) to guide it.</p></li><li><p><strong>Performance Trends:</strong> Specialized multimodal LLMs are closing the gap with or exceeding general models on document understanding benchmarks (<a href="https://arxiv.org/abs/2401.00908#:~:text=documents.%20The%20pre,of%205%20previously%20unseen%20datasets"> DocLLM: A layout-aware generative language model for multimodal document understanding</a>). However, evaluation suites like M5 and EXAMS-V reveal that no current model excels across <em>all</em> languages and modalities &#8211; high resource languages still greatly outperform low-resource ones , and tasks combining vision, language, and cultural knowledge push models to their limits . There is active research to address these gaps, including using larger diverse training sets and explicit alignment techniques.</p></li><li><p><strong>Engineering Best Practices:</strong> In practice, systems often combine LLMs with traditional tools. Chunking long documents (via retrieval or learned sparse sampling) is essential for efficiency (<a href="https://arxiv.org/html/2410.05970v2#:~:text=introduce%20PDF,Experimental">{cutout}03.2cm55cm1 empty PDF-WuKong : A Large Multimodal Model for Efficient Long PDF Reading with End-to-End Sparse Sampling</a>) . Adapters and modular architectures enable adding capabilities (new language or modality) without rebuilding from scratch. Finally, evaluation and iteration are key &#8211; a multilingual multimodal system requires continuous tuning to handle new document types, languages, and use cases as they arise, ensuring that the benefits of broad language and modality support are fully realized in real-world deployments.</p></li></ul>]]></content:encoded></item><item><title><![CDATA[Fine-Tuning vs Retrieval-Augmented Generation in Modern LLMs]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/fine-tuning-vs-retrieval-augmented</link><guid isPermaLink="false">https://www.rohan-paul.com/p/fine-tuning-vs-retrieval-augmented</guid><pubDate>Mon, 16 Jun 2025 09:28:56 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!3Cze!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!3Cze!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!3Cze!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png 424w, https://substackcdn.com/image/fetch/$s_!3Cze!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png 848w, https://substackcdn.com/image/fetch/$s_!3Cze!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png 1272w, https://substackcdn.com/image/fetch/$s_!3Cze!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!3Cze!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png" width="1024" height="462" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:462,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:732749,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166054227?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!3Cze!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png 424w, https://substackcdn.com/image/fetch/$s_!3Cze!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png 848w, https://substackcdn.com/image/fetch/$s_!3Cze!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png 1272w, https://substackcdn.com/image/fetch/$s_!3Cze!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5a5889db-bb3d-4296-9eb4-5c0558d68562_1024x462.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><p><strong>Table of Contents</strong></p><ul><li><p>Model Performance and Data Efficiency</p></li><li><p>Computational Cost and Latency</p></li><li><p>Scalability and Domain Adaptability</p></li><li><p>Long-Term Maintainability</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Model Performance and Data Efficiency</strong></h2><p><strong>Fine-Tuning for Specialized Accuracy:</strong> Fine-tuning an LLM on domain-specific data can yield higher accuracy and more precise outputs in that domain. By updating the model&#8217;s weights with in-domain examples, fine-tuning enables the model to internalize jargon and nuances, often outperforming a generic model on specialized tasks (<a href="https://www.f22labs.com/blogs/llm-fine-tuning-vs-retrieval-augmented-generation-rag/#:~:text=">LLM Fine-Tuning vs Retrieval-Augmented Generation (RAG)</a>). For instance, a model fine-tuned on legal documents or medical text will adhere to the domain&#8217;s terminology and style, providing consistent and relevant answers. In scenarios requiring a controlled output format or tone, fine-tuning is advantageous &#8211; the model can be trained to follow templates or guidelines (e.g. always output JSON, maintain a formal tone), which is hard to enforce via retrieval alone . This makes fine-tuning ideal when <strong>precision and consistency</strong> are paramount.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p><strong>RAG&#8217;s Strength in Factual Recall:</strong> When the goal is to inject new factual knowledge, retrieval-augmented generation (RAG) often shows superior performance with less training data. Studies in 2024 found that unsupervised fine-tuning provides only modest gains on knowledge-based QA, whereas a RAG approach &#8220;consistently outperforms&#8221; fine-tuning for both previously seen and entirely new facts (<a href="https://aclanthology.org/2024.emnlp-main.15/#:~:text=a%20variety%20of%20knowledge,training%20could%20alleviate%20this%20problem">Fine-Tuning or Retrieval? Comparing Knowledge Injection in LLMs - ACL Anthology</a>). LLMs struggle to learn a brand-new fact from a small corpus &#8211; they may need exposure to many rephrasings of that fact during training to truly internalize it . In contrast, a RAG system can incorporate a single document containing the fact and reliably retrieve it at query time. This means that if you have <em>very limited</em> data on new information, fine-tuning is data-inefficient: you might need to generate or collect extensive Q&amp;A pairs or text augmentations to teach the model, which is costly (<a href="https://arxiv.org/html/2403.01432v3#:~:text=amplified%20by%20improving%20retrieval%20and,with%20less%20popular%20factual%20knowledge">Fine Tuning vs. Retrieval Augmented Generation for Less Popular Knowledge</a>). RAG directly leverages the raw text as external memory, avoiding this training data bottleneck.</p><p><strong>When Fine-Tuning Excels:</strong> Despite RAG&#8217;s edge in low-data factual injection, fine-tuning shines when the model needs to generalize or reason with domain knowledge rather than just look it up. A fine-tuned model can synthesize information from across its trained knowledge to answer novel questions, even if no single document in a repository perfectly answers them. It preserves and integrates knowledge in its parameters, which can help in multi-hop reasoning or when the query is abstract. Additionally, for smaller LMs that lack broad knowledge, fine-tuning on a focused dataset substantially boosts their performance across all covered topics . (Notably, Soudani et al. (2024) report that fine-tuning improves accuracy on both popular and less-popular entities, though RAG still had an advantage on the very least frequent facts .) In summary, if you have <strong>sufficient high-quality training data</strong> and require the model to deeply assimilate domain knowledge and style, fine-tuning can produce a model that is both expert and coherent in that domain &#8211; something RAG alone may not achieve if the model&#8217;s inherent understanding is lacking.</p><h2><strong>Computational Cost and Latency</strong></h2><p><strong>Training vs. Inference Cost:</strong> Fine-tuning a large pre-trained model demands significant computational resources upfront. Full fine-tuning of billion-parameter LLMs is resource-intensive (both GPU time and memory) and often requires specialized techniques to avoid catastrophic forgetting. Recent research explicitly notes that &#8220;fine tuning&#8230;requires extensive resources,&#8221; especially when augmenting an LLM with new knowledge (<a href="https://arxiv.org/html/2403.01432v3#:~:text=amplified%20by%20improving%20retrieval%20and,with%20less%20popular%20factual%20knowledge">Fine Tuning vs. Retrieval Augmented Generation for Less Popular Knowledge</a>). This can involve costly data preparation and many training iterations. However, this cost is <strong>one-time</strong> (per model update). Once fine-tuned, serving the model is relatively lightweight &#8211; the model directly generates outputs without extra steps. This makes fine-tuning <strong>cost-effective for high query volumes</strong>: the expensive part (training) can be amortized, and each inference call is fast and cheap (<a href="https://www.f22labs.com/blogs/llm-fine-tuning-vs-retrieval-augmented-generation-rag/#:~:text=">LLM Fine-Tuning vs Retrieval-Augmented Generation (RAG)</a>). For example, in a production system handling millions of requests, a fine-tuned model might offer lower overall cost than a RAG system, because RAG pays a runtime cost on every single query.</p><p><strong>RAG&#8217;s Runtime Overhead:</strong> RAG avoids retraining cost by using an external knowledge base at inference, but it shifts the burden to each query. Every request triggers a retrieval operation (vector search, database lookup) and increases the prompt length by injecting documents. This <strong>adds latency and compute per inference</strong>. A systems study found that RAG introduces significant latency overhead &#8211; retrieval can account for ~41% of end-to-end response time, roughly doubling the time to first token compared to a non-RAG model (<a href="https://arxiv.org/html/2412.11854v1#:~:text=We%20show%20RAG%20introduces%20significant,30%20seconds%2C%20precluding%20production%20deployment">Towards Understanding Systems Trade-offs in Retrieval-Augmented Generation Model Inference</a>). In fact, naively retrieving more often (for accuracy) can push latencies to <strong>nearly 30 seconds</strong>, which is untenable for real-world use . Even with optimized retrievers, the additional few hundred milliseconds or more per query can accumulate. This means that for applications requiring <strong>low latency or real-time interactions</strong> (e.g. an interactive assistant, or embedded systems with strict timing), a fine-tuned model is often the better choice. It responds directly using its internal knowledge, avoiding the multi-step pipeline that RAG entails. RAG&#8217;s inference cost is also higher in terms of computation &#8211; the model must process the user query <em>plus</em> the retrieved context, leading to larger token counts and memory usage per request . In contrast, a fine-tuned model usually takes just the query as input, which is leaner.</p><p><strong>Throughput and Efficiency:</strong> If you need to serve a high throughput of requests, fine-tuning offers a simpler scaling path: spin up more replicas of the model to handle load. RAG, on the other hand, can become bottlenecked by the retrieval subsystem, especially under heavy load or with large indexes. Empirical analysis shows that as the knowledge index grows and query frequency rises, the retrieval stage&#8217;s throughput degrades (e.g. a 20% drop when scaling from 1M to 100M documents) . This is partly due to database search complexity and memory bandwidth limits. Therefore, for <strong>large-scale deployments with stable knowledge</strong>, a fine-tuned model can be more <strong>scalable in throughput</strong>, delivering faster, more consistent response times.</p><h2><strong>Scalability and Domain Adaptability</strong></h2><p><strong>Scaling Knowledge Updates:</strong> One major appeal of RAG is the ability to update the model&#8217;s knowledge without retraining &#8211; simply add or edit documents in the external datastore. This is crucial when information changes frequently or the knowledge base is vast (e.g. enterprise data or world news). In fact, as LLMs grow and the pace of new information increases, &#8220;constant retraining is impractical&#8221; due to high costs (<a href="https://arxiv.org/html/2412.11854v1#:~:text=Given%20their%20growing%20adoption%2C%20it,8">Towards Understanding Systems Trade-offs in Retrieval-Augmented Generation Model Inference</a>). RAG offers a remedy by decoupling knowledge from the frozen model; it&#8217;s clearly the better choice for <strong>rapidly evolving domains or real-time information needs</strong>. For example, a support chatbot that needs up-to-the-minute product info can&#8217;t be fine-tuned for every minor update &#8211; RAG is the pragmatic solution. Fine-tuning in such a scenario would lag behind and consume enormous resources to keep the model current. Thus, in terms of <em>knowledge scalability</em>, RAG is more flexible.</p><p><strong>System Complexity at Scale:</strong> However, scaling a RAG system comes with engineering complexity. The datastore and retrieval index must handle growth in documents (which can reach terabyte-scale storage) and still return relevant results quickly . This requires careful maintenance: indexing pipelines, retriever model tuning, sharding or memory management for very large corpora, etc. Over time, a RAG system might face scalability challenges in <em>practice</em>, such as needing to prune or compress old data, re-embed documents for a new retriever model, or handle polyglot queries. In contrast, a fine-tuned model is a self-contained artifact. Scaling to more knowledge in a fine-tuned approach often means scaling up the model size or training data &#8211; which is costly, but once done, usage is straightforward. If the domain&#8217;s knowledge volume is within what an LLM can internalize, a fine-tuned solution avoids the complexities of an external store.</p><p><strong>Adapting to New Domains:</strong> The choice between fine-tuning and RAG also depends on how <em>different</em> the new domain is from the model&#8217;s original training domain. RAG can quickly equip an LLM with facts from a new domain by providing reference text, but if the domain has a very distinct style or requires understanding new concepts, the base model might misinterpret the retrieved context. Research has observed that LLMs &#8220;not trained on [a] specific domain exhibit lower RAG accuracy in that domain&#8221; (<a href="https://arxiv.org/pdf/2501.11929#:~:text=,secure">HERE</a>). In other words, if an LLM lacks background in, say, financial jargon, simply retrieving finance documents won&#8217;t guarantee it uses them effectively &#8211; it might still hallucinate or pick irrelevant info. Here, fine-tuning can <strong>truly adapt</strong> the model to the new domain. By training on domain texts (even unlabeled), we imbue the model with domain semantics. For example, Devine (2025) shows that fine-tuning a local LLM on domain-specific data improved a RAG system&#8217;s answer accuracy by an average of 3% (and citation accuracy by 8%) across many domains . This indicates that a bit of fine-tuning can significantly boost the model&#8217;s ability to understand and use retrieved information. In scenarios where <strong>domain transfer</strong> includes new reasoning patterns or task formats, fine-tuning is essential &#8211; RAG alone cannot teach a model how to solve problems in a new format (for instance, performing medical diagnosis or legal reasoning steps). Fine-tuning (potentially combined with parameter-efficient methods) can inject these new skills while &#8220;preserving the reasoning abilities&#8221; the model already had (<a href="https://arxiv.org/html/2403.01432v3#:~:text=encoder,tuning%20by%20developing">Fine Tuning vs. Retrieval Augmented Generation for Less Popular Knowledge</a>). Thus, when entering a <strong>vastly different domain or task</strong>, fine-tuning provides a deeper, more robust form of adaptation, whereas RAG provides a quick but shallow fix.</p><h2><strong>Long-Term Maintainability</strong></h2><p><strong>Evolving Knowledge vs. Static Models:</strong> Maintainability involves how easy it is to keep the system up-to-date and reliable over time. If your application&#8217;s knowledge base is dynamic, RAG offers easier maintainability: updates are as simple as adding new documents or refreshing the index, with no need to retrain the model for each change. This ability to <em>refresh content</em> without touching the model weights is invaluable for long-term upkeep in fast-changing fields (<a href="https://arxiv.org/html/2412.11854v1#:~:text=Given%20their%20growing%20adoption%2C%20it,8">Towards Understanding Systems Trade-offs in Retrieval-Augmented Generation Model Inference</a>). On the other hand, a fine-tuned model&#8217;s knowledge will gradually become stale; maintaining accuracy long-term means scheduling periodic re-training on new data. This retraining cycle is heavier to manage &#8211; it requires pipelines for data collection, model fine-tuning, validation, and deployment of the new model version. For continually changing knowledge, this is a significant ongoing investment.</p><p><strong>System Simplicity and Reliability:</strong> Conversely, from a <strong>systems engineering</strong> perspective, a fine-tuned model can be easier to maintain in production because it consolidates everything into one component (the model itself). There are fewer moving parts that could fail or require expertise. RAG systems demand maintaining a separate database or vector index and a search service in tandem with the model, which introduces more points of failure and complexity (<a href="https://www.f22labs.com/blogs/llm-fine-tuning-vs-retrieval-augmented-generation-rag/#:~:text=1,limit%2C%20posing%20challenges%20for%20handling">LLM Fine-Tuning vs Retrieval-Augmented Generation (RAG)</a>). Organizations need IR expertise to ensure the retriever stays effective, and they must monitor the retrieval quality over time. In long-term operation, tasks like re-indexing data, updating embedding models, and scaling the datastore hardware become routine. If the domain is <strong>stable or regulated</strong> (e.g. law, where changes are infrequent but correctness and consistency are critical), many teams prefer fine-tuning a model and doing minimal updates, rather than continuously curating a knowledge base. The fine-tuned model approach can be tested and versioned like traditional software &#8211; each fine-tune is a release that undergoes QA &#8211; making maintainability more predictable in the long run.</p><p><strong>Choosing for Longevity:</strong> In practice, AI engineers often strike a balance. For relatively static knowledge bases, fine-tuning yields a maintainable solution with fewer operational dependencies, focusing maintenance on occasional model updates. Parameter-efficient fine-tuning methods (adapters, LoRA, etc.) further improve maintainability by allowing incremental updates without retraining from scratch, and by isolating domain-specific parameters that can be versioned separately. Meanwhile, for live knowledge sources (news, user-generated data), RAG is the clear winner for maintainability of content. It&#8217;s also worth considering that fine-tuning and RAG are not mutually exclusive &#8211; one can fine-tune a model on a core dataset and still use retrieval for the freshest information. But when asked <strong>&#8220;When is fine-tuning a better choice over RAG?&#8221;</strong>, the answer comes down to scenarios with <strong>static or slowly-changing data, a need for low-latency high-throughput performance, and requirements for output control and deep domain expertise</strong>. In those cases, investing in a fine-tuned model provides superior long-term value: strong in-domain performance, simpler scaling, and a self-contained system that, with occasional updates, can be maintained for the long haul.</p><p><strong>Sources:</strong></p><ol><li><p>Soudani et al., <em>&#8220;Fine Tuning vs. Retrieval Augmented Generation for Less Popular Knowledge,&#8221;</em> SIGIR-AP 2024 (<a href="https://arxiv.org/html/2403.01432v3#:~:text=different%20fine%20tuning%2C%20data%20augmentation%2C,enriching%20LMs%20with%20less%20popular">Fine Tuning vs. Retrieval Augmented Generation for Less Popular Knowledge</a>) .</p></li><li><p>Ovadia et al., <em>&#8220;Fine-Tuning or Retrieval? Comparing Knowledge Injection in LLMs,&#8221;</em> EMNLP 2024 (<a href="https://aclanthology.org/2024.emnlp-main.15/#:~:text=a%20variety%20of%20knowledge,training%20could%20alleviate%20this%20problem">Fine-Tuning or Retrieval? Comparing Knowledge Injection in LLMs - ACL Anthology</a>).</p></li><li><p>Devine, <em>&#8220;ALoFTRAG: Automatic Local Fine Tuning for Retrieval Augmented Generation,&#8221;</em> arXiv 2025 (<a href="https://arxiv.org/pdf/2501.11929#:~:text=,secure">HERE</a>) .</p></li><li><p>Kishore et al., <em>&#8220;Towards Understanding Systems Trade-offs in RAG Model Inference,&#8221;</em> arXiv 2024 (<a href="https://arxiv.org/html/2412.11854v1#:~:text=We%20show%20RAG%20introduces%20significant,30%20seconds%2C%20precluding%20production%20deployment">Towards Understanding Systems Trade-offs in Retrieval-Augmented Generation Model Inference</a>) .</p></li><li><p>F22 Labs, <em>&#8220;LLM Fine-Tuning vs Retrieval-Augmented Generation,&#8221;</em> Blog 2023 (<a href="https://www.f22labs.com/blogs/llm-fine-tuning-vs-retrieval-augmented-generation-rag/#:~:text=">LLM Fine-Tuning vs Retrieval-Augmented Generation (RAG)</a>) .</p></li></ol>]]></content:encoded></item><item><title><![CDATA[Methodologies and architectures that improve accuracy, reliability, and verifiability in Retrieval-Augmented Generation (RAG) systems]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/methodologies-and-architectures-that</link><guid isPermaLink="false">https://www.rohan-paul.com/p/methodologies-and-architectures-that</guid><pubDate>Mon, 16 Jun 2025 09:25:01 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!SBRN!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!SBRN!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!SBRN!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png 424w, https://substackcdn.com/image/fetch/$s_!SBRN!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png 848w, https://substackcdn.com/image/fetch/$s_!SBRN!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png 1272w, https://substackcdn.com/image/fetch/$s_!SBRN!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!SBRN!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png" width="1024" height="573" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:573,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1053201,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166054018?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!SBRN!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png 424w, https://substackcdn.com/image/fetch/$s_!SBRN!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png 848w, https://substackcdn.com/image/fetch/$s_!SBRN!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png 1272w, https://substackcdn.com/image/fetch/$s_!SBRN!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F37577fdb-24c7-4414-9d0f-a55151ce9b41_1024x573.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><ul><li><p>Methodologies and architectures that improve accuracy, reliability, and verifiability in Retrieval-Augmented Generation (RAG) systems</p></li><li><p>Introduction</p></li><li><p>1. Optimized Retrieval Mechanisms</p></li><li><p>2. Embedding Strategies</p></li><li><p>3. Hybrid Search Techniques</p></li><li><p>4. Advanced Chunking Techniques</p></li><li><p>5. Verification Mechanisms</p></li><li><p>6. Reducing Hallucinations</p></li><li><p>7. Pipeline Optimization</p></li><li><p>8. Integration with LangChain &amp; LlamaIndex</p></li><li><p>Conclusion</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Introduction</strong></h2><p>Retrieval-Augmented Generation (RAG) systems combine an information retriever with a text generator to ground LLM outputs in external data. Optimizing each stage of the RAG pipeline is critical for accuracy, reliability, and verifiability. Recent advances (within the past year) have focused on improving how relevant documents are retrieved, how they&#8217;re chunked and embedded, and how the LLM utilizes them, using frameworks like LangChain and LlamaIndex for implementation. Below, we dive into eight key areas of RAG optimization with technical rigor, practical strategies, trade-offs, and real-world considerations.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>1. Optimized Retrieval Mechanisms</strong></h2><p>High-quality retrieval is the backbone of RAG &#8211; if relevant documents aren&#8217;t fetched, the generation will falter. Modern RAG systems employ <strong>multi-stage retrieval</strong> and <strong>intelligent query processing</strong> for maximum recall and precision:</p><ul><li><p><strong>Multi-Stage Retrieval &amp; Re-Ranking</strong>: A common approach is a two-stage pipeline: first use a fast, high-recall retriever (e.g. BM25 or a dual encoder) to get a broad candidate set, then apply a more precise re-ranker (often a cross-encoder or reranking model) to sort the results (<a href="https://aclanthology.org/2024.findings-emnlp.103.pdf#:~:text=Existing%20efficient%20IR%20systems%20typically,precision%20of%20the%20final%20results">HERE</a>). This ensures that even if the initial top-k misses some relevant hits, the reranker can promote the truly relevant passages to the top . For example, one can retrieve top-1000 with BM25, then re-rank those with a transformer-based cross encoder to pick the top-10 (<a href="https://blog.gopenai.com/day-11-building-and-evaluating-advanced-rag-systems-4daf1c62125c#:~:text=Multi,step.%20For%20example">Day 11: Building and Evaluating Advanced RAG Systems | by Nikhil Kulkarni | GoPenAI</a>). This significantly boosts precision of the final retrieved context. Re-ranking models score query&#8211;document pairs in a calibrated way (<a href="https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking#:~:text=model,response%20payload%20of%20the%20query">Optimizing RAG with Hybrid Search &amp; Reranking | VectorHub by Superlinked</a>), often leading to more relevant passages for the generator. The trade-off is additional latency and computation for the rerank stage, but it often pays off with better answer quality.</p></li><li><p><strong>Query Expansion and Reformulation</strong>: Improving the query itself can dramatically increase document recall. Techniques like <strong>LLM-based query expansion</strong> generate alternate query formulations or relevant keywords to capture documents that the original query might miss. Recent research uses LLMs to produce &#8220;pseudo-queries&#8221; or hypothetical answers which are then added to the original query . For example, methods like <em>HyDE</em> or <em>MuGI</em> prompt an LLM to first imagine an answer or related context, and then use that to enrich the search query . This can add synonyms, related terms, or clarifying details that retrieve more relevant documents. LangChain provides a <code>SelfQueryRetriever</code> that uses an LLM to parse the user query and automatically add filters or metadata terms (<a href="https://dev.to/jamesli/rag-retrieval-performance-enhancement-practices-detailed-explanation-of-hybrid-retrieval-and-self-query-techniques-59ja#:~:text=match%20at%20L126%20A%20Self,Retriever%20can">RAG Retrieval Performance Enhancement Practices: Detailed Explanation of Hybrid Retrieval and Self-Query Techniques - DEV Community</a>) . These approaches make retrieval more flexible &#8211; handling vague or under-specified queries by broadening them intelligently. Care must be taken to avoid drift (expanding beyond the user&#8217;s intent), but when done right, query expansion markedly improves recall with minimal user effort.</p></li><li><p><strong>Advanced Search Strategies</strong>: Instead of a single retrieval query, RAG pipelines can perform <strong>multiple queries or iterative retrieval</strong>. For example, a complex question might be decomposed into sub-questions, each retrieved separately (a strategy often called <em>query decomposition</em>). Another approach is <strong>&#8220;step-back&#8221; retrieval</strong> &#8211; after an initial answer is generated, the system can verify it by issuing a follow-up query (e.g. searching for a doubtful claim). These strategies, covered in recent RAG optimization literature, ensure that the retrieval phase leaves no stone unturned (<a href="https://aclanthology.org/2024.findings-emnlp.607.pdf#:~:text=To%20alleviate%20the%20aforementioned%20issues,and%20judgment%2C%20including%20reference_correctness%2C%20answer_correctness">HERE</a>) . They trade extra retrieval passes for higher confidence in the supporting data. In practice, one must balance thoroughness with latency; a few well-chosen extra retrievals can boost answer accuracy, but too many will slow the system.</p></li></ul><p><strong>Trade-offs</strong>: Optimizing retrieval may involve more computation (expanding queries, multi-stage ranking, iterative searches), so caching results and tuning the number of candidates at each stage is important to manage latency. However, these methods greatly enhance the chance that the needed information is present in the context given to the LLM. Frameworks like LangChain make it straightforward to compose retrievers and rerankers &#8211; e.g. using <code>BM25Retriever</code> for initial recall and a custom LLM chain for reranking. Overall, an optimized retrieval mechanism increases the RAG system&#8217;s reliability by ensuring the generator always has high-quality evidence to work with.</p><h2><strong>2. Embedding Strategies</strong></h2><p>When using vector similarity search, the choice of embedding model and how it&#8217;s tuned is pivotal for relevant retrieval. Embeddings convert text into high-dimensional vectors; good embeddings place related content close together in vector space. Several strategies help maximize embedding effectiveness for a given domain:</p><ul><li><p><strong>Choosing the Right Model</strong>: Generic pre-trained embeddings (like OpenAI&#8217;s <code>text-embedding-ada-002</code> or Cohere&#8217;s embeddings) provide strong semantic search out-of-the-box, but they may not capture domain-specific terminology or nuances. For specialized domains (medical, legal, technical), consider models trained on similar domain text (e.g. BioBERT for biomedical papers) or use open-source embedding models known for strong performance (e.g. InstructorXL or GTR). Key factors include the vector dimensionality, model size, and training data &#8211; these affect the embedding&#8217;s ability to capture fine-grained meaning. It&#8217;s often worth <strong>experimenting with multiple embedding providers</strong> and evaluating retrieval recall/precision on sample queries (<a href="https://www.mongodb.com/developer/products/atlas/choosing-chunking-strategy-rag/#:~:text=As%20with%20choosing%20embedding%20or,terms%20of%20retrieval%20precision%20and">How to Choose the Right Chunking Strategy for Your LLM Application | MongoDB</a>) .</p></li><li><p><strong>Fine-Tuning Embeddings</strong>: A major trend in 2024 has been fine-tuning embedding models on in-domain data to significantly boost retrieval accuracy (<a href="https://www.databricks.com/blog/improving-retrieval-and-rag-embedding-model-finetuning#:~:text=What%20We%20Found%3A%20We%20finetuned,leveraging%20only%20your%20existing%20data">Improving Retrieval and RAG with Embedding Model Finetuning | Databricks Blog</a>) . Fine-tuning aligns the vector space with the specific language and relevance criteria of your documents. For example, by fine-tuning a model on your company&#8217;s product manuals Q&amp;A pairs, you teach it to embed related question-answer text closer together. Databricks demonstrated that finetuning embedding models on enterprise datasets yielded large gains in Recall@10 and overall RAG accuracy without any manual labeling . This is often done by generating synthetic training pairs from the documents (using an LLM to create question&#8211;context pairs), and then training the embedding model (typically a bi-encoder) to embed those pairs similarly. The result is an embedding that is <em>specialized</em> for your knowledge base, improving both precision (fewer irrelevant hits) and recall (more of the truly relevant pieces appear in top results) . The trade-off is the extra effort of fine-tuning and hosting a custom model, but the payoff can be significant in domains where out-of-the-box embeddings fall short.</p></li><li><p><strong>Hybrid or Multi-Vector Representations</strong>: Sometimes a single embedding isn&#8217;t sufficient to capture all aspects of relevance. Multi-vector indexing (as described in LangChain&#8217;s optimization guides) involves creating multiple embeddings per document, each focusing on different content aspects (<a href="https://dev.to/jamesli/optimizing-rag-indexing-strategy-multi-vector-indexing-and-parent-document-retrieval-49hf#:~:text=Multi,idea%20of%20this%20method%20is">Optimizing RAG Indexing Strategy: Multi-Vector Indexing and Parent Document Retrieval - DEV Community</a>). For instance, you might embed a document both in a general semantic space and a keyword-oriented space, or create separate embeddings for each section of a long document. This increases recall (more chances for a query to match some aspect) at the cost of storage and some precision. Another strategy is to store <strong>additional metadata embeddings</strong> &#8211; e.g. an embedding of the document title or metadata fields &#8211; to help retrieval for topic-specific queries. LlamaIndex and LangChain both allow using composite embeddings or multiple vector indexes to this end (LangChain&#8217;s <code>MultiVectorRetriever</code> or custom retrieval logic). These approaches can be seen as fine-grained tuning of embedding strategy to domain characteristics: e.g. for code search, you might combine a code-specific embedding with a natural language embedding to capture both syntactic and semantic similarity.</p></li></ul><p><strong>Trade-offs</strong>: Using larger or multiple embedding models improves result relevance but will increase indexing time, index size, and query latency (if multiple searches are combined). One should monitor these and possibly limit embedding complexity based on application needs. A practical tip is to start with a strong base model (OpenAI or Cohere&#8217;s default) and only consider fine-tuning if evaluation on real queries shows gaps in relevance. When fine-tuning, leverage cloud platforms or libraries (like BERT fine-tuning on sentence pairs) &#8211; as demonstrated by recent blogs, fine-tuning can often be done with synthetic data and bring <strong>game-changing accuracy improvements</strong> (<a href="https://www.databricks.com/blog/improving-retrieval-and-rag-embedding-model-finetuning#:~:text=What%20We%20Found%3A%20We%20finetuned,leveraging%20only%20your%20existing%20data">Improving Retrieval and RAG with Embedding Model Finetuning | Databricks Blog</a>).</p><h2><strong>3. Hybrid Search Techniques</strong></h2><p>No single retrieval method is perfect &#8211; sparse keyword search (e.g. BM25) excels at precise keyword matching, while dense vector search excels at semantic matching. Hybrid search combines their strengths to improve both recall and precision. In practice, hybrid search can be implemented in various ways:</p><ul><li><p><strong>Parallel Retrieval Fusion</strong>: Run both a sparse search (BM25/TF-IDF) and a dense vector search for each query, then merge the results. The merging can be done by scoring (e.g. a weighted sum of BM25 score and vector similarity) or by rank fusion. A simple linear combination allows tuning the contribution of each source (<a href="https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking#:~:text=H%20%3D%20%281,%CE%B1V">Optimizing RAG with Hybrid Search &amp; Reranking | VectorHub by Superlinked</a>) &#8211; e.g. weight semantic similarity higher for conceptual queries, or boost keyword matches for very specific terms. Reciprocal Rank Fusion (RRF) is a robust method that merges rankings from each retriever by summing the reciprocal of their rank positions . This method doesn&#8217;t require hand-tuning a weight and tends to improve diversity of results. By using such fusion, hybrid retrieval ensures that if either method (sparse or dense) finds something relevant, it gets surfaced in the final top results. Recent studies have confirmed that a <strong>three-way hybrid</strong> (full-text + sparse vector + dense vector) outperforms pure vector or two-way hybrid in recall (<a href="https://infiniflow.org/blog/best-hybrid-search-solution#:~:text=How%20to%20do%20reranking%3F">Dense vector + Sparse vector + Full text search + Tensor reranker = Best retrieval for RAG? | Infinity</a>) , albeit with added complexity.</p></li><li><p><strong>Hierarchical or Conditional Hybrid</strong>: Another approach is to use sparse retrieval to shortlist candidates and then use dense retrieval or re-rank on that subset (a form of multi-stage retrieval). For example, retrieve 100 documents with BM25, then encode those and do a semantic similarity search among them to pick the best 5. This approach was outlined in an advanced RAG architecture: BM25 finds a broad set, dense model re-ranks to a smaller subset (<a href="https://blog.gopenai.com/day-11-building-and-evaluating-advanced-rag-systems-4daf1c62125c#:~:text=Multi,step.%20For%20example">Day 11: Building and Evaluating Advanced RAG Systems | by Nikhil Kulkarni | GoPenAI</a>). It&#8217;s effectively hybrid retrieval spread over stages. The benefit is you only need to embed and score a limited set of documents with the dense model, saving computation while still getting semantic matching on the final set. LangChain and LlamaIndex can support this by retrieving with one retriever and feeding those results into another retriever or reranker in code.</p></li><li><p><strong>Benefits of Hybrid</strong>: By covering both exact term matches and conceptual similarity, hybrid search greatly increases the chance of retrieving all relevant information for a query. Empirically, hybrid methods have achieved <strong>higher accuracy on QA benchmarks</strong> than either method alone (<a href="https://goatstack.ai/topics/blended-rag-improving-rag-accuracy-with-semantic-search-and-hybrid-query-based-retrievers-akoepf#:~:text=,tuned%20model%20performances">Blended RAG: Improving RAG Accuracy with Semantic Search and Hybrid Query-Based Retrievers</a>). For instance, a 2024 study (&#8220;Blended RAG&#8221;) combined dense and sparse indexes and set new state-of-the-art retrieval accuracy on datasets like NaturalQuestions and TREC-COVID . In generative QA, hybrid retrieval led to better answers, even outperforming some fine-tuned single-model systems . The main cost of hybrid search is running two searches instead of one, which can increase latency. However, many vector databases now support hybrid queries natively (e.g. Weaviate&#8217;s hybrid search, or Qdrant&#8217;s ability to store sparse + dense vectors) (<a href="https://python.langchain.com/v0.2/docs/integrations/retrievers/weaviate-hybrid/#:~:text=Weaviate%20Hybrid%20Search%20,shows%20how%20to%20use">Weaviate Hybrid Search | &#129436;&#65039; LangChain</a>), making the overhead minimal. When native support isn&#8217;t available, LangChain&#8217;s <code>EnsembleRetriever</code> can be used to combine a BM25 retriever with a vector retriever and unify results in code (<a href="https://dev.to/jamesli/rag-retrieval-performance-enhancement-practices-detailed-explanation-of-hybrid-retrieval-and-self-query-techniques-59ja#:~:text=Implementing%20Hybrid%20Retrieval%20in%20the,LangChain%20framework">RAG Retrieval Performance Enhancement Practices: Detailed Explanation of Hybrid Retrieval and Self-Query Techniques - DEV Community</a>) . This was demonstrated by weighting BM25 and vector retrievers 50/50 to create an ensemble retriever that yields a single list of results . The ability to adjust weights provides flexibility to tune performance on your dataset.</p></li></ul><p>In summary, hybrid search is a <strong>best-of-both-worlds</strong> solution that improves recall (catching info that one method might miss) and often the precision of top results. The configuration can be tailored (simple fusion vs multi-stage) based on the size of data and performance needs. For most non-trivial RAG applications, hybrid retrieval is a recommended default given its demonstrated impact on accuracy.</p><p>(<a href="https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking">Optimizing RAG with Hybrid Search &amp; Reranking | VectorHub by Superlinked</a>) <em>Illustration of a hybrid retrieval pipeline:</em> The user&#8217;s query is run through both a keyword BM25 search and a dense vector search in parallel. Retrieved candidate chunks are then <strong>re-ranked</strong> (e.g. by a cross-encoder), producing a final list of relevant documents with relevance scores . This approach ensures both exact matches and semantically relevant content are considered in the RAG context.</p><h2><strong>4. Advanced Chunking Techniques</strong></h2><p>How you split documents into chunks can profoundly affect retrieval accuracy and the quality of generated answers. The goal is to chunk in a way that each piece is self-contained and relevant, without losing context. Key techniques include:</p><ul><li><p><strong>Adaptive Chunk Sizing</strong>: Instead of fixed-length chunks, <strong>adaptive chunking</strong> uses content structure to decide breakpoints. For example, splitting at paragraph or sentence boundaries produces more coherent chunks than arbitrary 512-character blocks. LangChain&#8217;s <code>RecursiveCharacterTextSplitter</code> can split by sections (e.g. first by double newline, then by single newline if needed, etc.), preserving natural boundaries. A step further is <strong>Semantic Chunking</strong> &#8211; using embeddings to decide where to split. LlamaIndex provides a <code>SemanticSplitter</code> that finds points between sentences where the context shift is largest (measured by embedding similarity), thus keeping each chunk topically unified (<a href="https://blog.lancedb.com/chunking-techniques-with-langchain-and-llamaindex/#:~:text=Semantic%20chunking%20offers%20a%20new,sentences%2C%20based%20on%20embedding%20similarity">Chunking techniques with Langchain and LlamaIndex</a>) . This means if two sentences are very related, they stay in the same chunk, but if the topic jumps, a new chunk begins. Semantic chunking avoids cutting in the middle of a concept, which can improve retrieval because each chunk represents a distinct idea. Notably, in semantic splitting there isn&#8217;t a rigid &#8220;chunk size&#8221; &#8211; instead a similarity threshold is used (<a href="https://www.mongodb.com/developer/products/atlas/choosing-chunking-strategy-rag/#:~:text=of%20the%20chunk%20size%20is,recommended%20for%20most%20datasets">How to Choose the Right Chunking Strategy for Your LLM Application | MongoDB</a>). The trade-off is a slightly more complex splitting process (requires computing embeddings as you split), but it yields chunks that align with meaning.</p></li><li><p><strong>Overlapping Windows</strong>: Introducing overlap between chunks ensures that no relevant detail near a boundary is dropped. A common practice is to overlap chunks by some tokens (e.g. 10-20% of the chunk size) . This means if one chunk ends in the middle of a paragraph, the next chunk will include the end of that paragraph as well. Overlap improves the chances that a query will find the info even if it falls at a chunk boundary. The overlap size is a tuning parameter &#8211; too large and you store a lot of redundant text; too small and you risk missing info. Empirically, overlaps around 10% of chunk length are a good balance for most data . Both LangChain and LlamaIndex splitters support an <code>overlap</code> parameter. One clever technique is the <strong>&#8220;sliding window&#8221;</strong> approach at query time: some systems retrieve not just the single best chunk but also adjacent chunks as context, effectively simulating overlap on the fly if needed. Overlapping windows marginally increase index size and may bring slight redundancy, but they strongly guard against boundary-induced omissions.</p></li><li><p><strong>Hierarchical Chunking</strong>: This approach creates multiple levels of chunks &#8211; e.g. splitting a document into sections, then splitting each section into paragraphs. The result is a tree of chunks (chapter &#8594; section &#8594; paragraph). Hierarchical chunking (and the related <strong>parent-child indexing</strong>) preserves the document structure. LangChain&#8217;s ParentDocumentRetriever and LlamaIndex&#8217;s <code>HierarchicalNodeParser</code> implement this idea (<a href="https://dev.to/jamesli/optimizing-rag-indexing-strategy-multi-vector-indexing-and-parent-document-retrieval-49hf#:~:text=,the%20document%20through%20hierarchical%20structures">Optimizing RAG Indexing Strategy: Multi-Vector Indexing and Parent Document Retrieval - DEV Community</a>). Each chunk knows its &#8220;parent&#8221; document or section. This enables retrieval at different granularities: one can first retrieve at section level, then dive into specific paragraphs (if needed), or retrieve a relevant paragraph and still easily fetch its sibling paragraphs or overall section for additional context. The RAPTOR technique (Recursive Approach for Passage Tree Organization and Retrieval) is an advanced example that builds a hierarchical index and retrieves through the tree . The advantage of hierarchical chunking is better <strong>context integrity</strong> &#8211; it&#8217;s easier to reconstruct full context and provenance because chunks carry an ID of their source. It also can improve retrieval of long documents: rather than storing huge chunks, you store manageable ones but can still assemble them. One trade-off is a more complex retrieval logic (needing to traverse the tree), but frameworks handle much of this under the hood. In practice, hierarchical approaches like ParentDocument retrieval have been shown to maintain higher answer accuracy for long documents by avoiding fragmentation of context .</p></li><li><p><strong>Semantic Headings and Metadata</strong>: Another slicing technique is to use document structure (headings, XML/HTML tags, etc.) to create semantically meaningful chunks. For instance, treat each top-level heading and its content as one chunk, or include the section title in the chunk&#8217;s metadata. This &#8220;semantic metadata chunking&#8221; doesn&#8217;t change the text itself but augments chunks with descriptors. At query time, retrievers can use this metadata (for filtering or as additional context in embeddings). For example, if a chunk has metadata <code>{"section": "Introduction"}</code>, a self-query retriever might automatically filter or boost chunks whose section matches a query asking for &#8220;background&#8221; information. The LangChain text splitters in combination with <code>Document</code> metadata fields allow injecting such info during the splitting step (<a href="https://dev.to/jamesli/in-depth-understanding-of-langchains-document-splitting-technology-46mk#:~:text=,data%20between%20various%20processing%20components">In-Depth Understanding of LangChain's Document Splitting Technology - DEV Community</a>) . The benefit is more targeted retrieval &#8211; queries that implicitly refer to a part of the document (like &#8220;in the conclusion, what did they say&#8230;&#8221;) can be satisfied more easily.</p></li></ul><p>In summary, advanced chunking is about <strong>balancing chunk size and context</strong>: too large and irrelevant text may confuse the LLM or dilute vector relevance; too small and context is lost. Techniques like overlap and hierarchical indexing mitigate these issues. Adaptive and semantic splitting produce higher-quality chunks that align with content boundaries, improving both retrieval (since chunks map well to query intents) and generation (since each chunk is coherent). LangChain and LlamaIndex offer flexible splitting utilities &#8211; from simple <code>CharacterTextSplitter</code> to advanced semantic and hierarchical parsers &#8211; allowing customization of chunking to the dataset at hand (<a href="https://blog.lancedb.com/chunking-techniques-with-langchain-and-llamaindex/#:~:text=This%20node%20parser%20divides%20nodes,reference%20to%20its%20parent%20node">Chunking techniques with Langchain and LlamaIndex</a>) . The trade-off is often in preprocessing time and index complexity, but the result is a more robust RAG knowledge base where relevant info is accessible in logically separated pieces.</p><h2><strong>5. Verification Mechanisms</strong></h2><p>Even with optimized retrieval, a RAG system should verify and attribute the information it provides. Verification mechanisms enhance trustworthiness by tracking provenance and assessing confidence:</p><ul><li><p><strong>Document Provenance &amp; Citation Tracking</strong>: A reliable RAG system should always know <em>where</em> an answer came from. This is typically done by carrying document identifiers and metadata along with each chunk and final answer. When the LLM generates an answer, the system can attach source citations (e.g. document titles or URLs). This not only boosts user confidence but allows users (or auditors) to drill down to the original source (<a href="https://docs.typingmind.com/typingmind-custom/branding-and-customizations/enable-llms-to-cite-sources-when-using-rag#:~:text=transparency%20to%20the%20AI%20response,makes%20your%20system%20more%20reliable">Enable LLMs to cite sources when using RAG</a>) . For instance, LangChain&#8217;s <code>RetrievalQA</code> can return source documents alongside the answer, and one can format the answer to include citations (like &#8220;[Source: Document XYZ]&#8221;). Prompt engineering can also enforce this: instruct the LLM to always cite its sources in the answer . TypingMind&#8217;s guidelines for RAG suggest including explicit instructions like <em>&#8220;Always cite source titles in every response to ensure accuracy and credibility.&#8221;</em> . This helps mitigate hallucinations because the model is steered to base its answer on provided sources and makes it obvious when it <em>doesn&#8217;t</em> have a source. The trade-off is that answers become a bit longer or more structured (with citations), but most users consider that a worthwhile exchange for verifiable information. LlamaIndex by default associates each retrieved <code>Node</code> with a source reference, enabling automatic source listing in responses. Ensuring document provenance also means storing and exposing metadata like author, publication date, etc. &#8211; useful for judging source reliability or relevance (e.g., prefer the most recent source).</p></li><li><p><strong>Confidence Scoring</strong>: Introducing a quantitative confidence measure helps decide how to handle uncertain answers. One mechanism is <strong>retrieval score thresholds</strong> &#8211; e.g. use the similarity scores from the vector search or BM25 score. If no retrieved chunk exceeds a certain relevance score, the system can decide that it doesn&#8217;t have high-confidence support and refuse to answer or respond with a fallback (&#8220;I&#8217;m not sure&#8221;). This guards against the model winging an answer from little evidence. In LangChain, some vector stores support a <code>score_threshold</code> in the retriever query; as an example, one can check the scores of retrieved docs and if none are above, say, 0.5 similarity, have the LLM respond with &#8220;I don&#8217;t know&#8221; (<a href="https://github.com/langchain-ai/langchain/discussions/17792#:~:text=cases%20where%20the%20retriever%20does,not%20be%20accurate%20or%20relevant">langchain RAG should not hallucinate &#183; langchain-ai langchain &#183; Discussion #17792 &#183; GitHub</a>) . This effectively acts as a guardrail against hallucination when knowledge is lacking. Another form of confidence scoring is to have the LLM itself output a self-rated confidence (although LLM self-assessment is not very reliable without further calibration). More robust is to use an ensemble of retrievals: if multiple documents from different sources all agree, confidence is higher; if they conflict, confidence is lower. Some research (RA-RAG) has proposed estimating the reliability of sources in the knowledge base and weighting the retrieval results by source reliability (<a href="https://openreview.net/forum?id=J3xRByRqOz#:~:text=incorporating%20external%20databases,relevant%20documents%20from%20a%20few">RETRIEVAL-AUGMENTED GENERATION WITH ESTIMATION OF SOURCE RELIABILITY | OpenReview</a>) . For example, if a particular website is known to be more trustworthy, increase its documents&#8217; scores; if another source is dubious, require stronger similarity to use it. Over time, the system can even learn which sources lead to correct answers and which lead to errors, and adjust retrieval accordingly. This kind of reliability-aware retrieval ensures <strong>misinformation is less likely to creep in</strong> &#8211; a highly relevant concern in multi-source RAG systems.</p></li><li><p><strong>Cross-Verification and Validation</strong>: Beyond scoring, some pipelines add a verification step after generation. One pattern is the <em>chain-of-verification</em>: after the LLM produces an answer, a secondary process (which could be another LLM prompt or a script) checks each factual claim in the answer against the sources (<a href="https://aclanthology.org/2024.findings-emnlp.607.pdf#:~:text=verification,iteration%20RAG">HERE</a>). If a claim isn&#8217;t supported, the system could issue another query or mark the answer as unverified. CoT (chain-of-thought) prompting can be used where the model is asked to explicitly list evidence from the docs for each part of its answer before finalizing it, essentially having it double-check itself. There are also evaluation LLMs: you pass the question, answer, and retrieved docs to another LLM and ask &#8220;Is the answer fully supported by these documents?&#8221; to get a judgment (possibly with a score). This can be used to refuse or flag answers that aren&#8217;t verifiable. In practice, such heavy validation is used in high-stakes domains (like medical or legal assistant scenarios) given it adds overhead. However, even a lightweight check &#8211; e.g. searching the answer text back into the documents to see if all key entities/values appear &#8211; can catch obvious hallucinations. LlamaIndex supports a simple form of this via its <code>ResponseEvaluator</code> which can compare an answer and source texts to rate correctness.</p></li></ul><p>By integrating provenance tracking and verification, RAG systems become <strong>transparent and trustworthy</strong>. Users can see citations and have confidence the answer isn&#8217;t just invented. Moreover, the development team can more easily debug when the system errs (was it a retrieval miss or a generation mistake?). The main cost of these mechanisms is complexity: formatting answers with citations, maintaining score thresholds, and additional verification steps can complicate the pipeline. But frameworks have started providing abstractions (e.g. <code>Guardrails</code>, <code>OutputParsers</code> in LangChain, and evaluator modules in LlamaIndex) to make it easier. Ultimately, verification features transform RAG from a black-box QA to a <strong>glass-box</strong> system where every piece of information can be traced to a source and assessed for confidence.</p><h2><strong>6. Reducing Hallucinations</strong></h2><p>Hallucination &#8211; when the LLM produces plausible-sounding but false information &#8211; is a known failure mode that RAG aims to minimize. Even with retrieval, hallucinations can occur if the model doesn&#8217;t properly use the context or if the context is insufficient. Several techniques help reduce hallucinations:</p><ul><li><p><strong>Strict Retrieval Utilization</strong>: Encourage or enforce that the LLM only uses retrieved content for answering. Prompt engineering is crucial here: the system instruction can say <em>&#8220;If the answer is not in the provided documents, say you don&#8217;t know.&#8221;</em> Also providing the context in a format that makes it obvious (like quoted passages with citations) can anchor the model. In LangChain&#8217;s standard QA chain, one can prepend a reminder: <em>&#8220;Your answers should be based only on the following documents.&#8221;</em> By reinforcing this, we reduce the model&#8217;s tendency to inject outside knowledge or assumptions. Some implementations take this further by disallowing answers when confidence is low (as discussed with thresholding). The GitHub example above shows returning &#8220;I don&#8217;t know&#8221; if no retrieved doc score is high (<a href="https://github.com/langchain-ai/langchain/discussions/17792#:~:text=cases%20where%20the%20retriever%20does,not%20be%20accurate%20or%20relevant">langchain RAG should not hallucinate &#183; langchain-ai langchain &#183; Discussion #17792 &#183; GitHub</a>) . This prevents the LLM from answering from partial or unrelated context.</p></li><li><p><strong>Retrieval Consistency Checks</strong>: Use multiple evidence pieces to cross-verify before answering. For instance, require at least two independent sources in the retrieved set to contain a key fact before trusting it. If only one source has the info and others are blank, the system might decide to either retrieve more or answer cautiously. This can be implemented by analyzing the overlap or agreement between top documents. Another approach is performing a second retrieval on the drafted answer (or on uncertain parts of it) &#8211; e.g. the model drafts an answer, then the system searches for a sentence of that answer to see if it can find it in the corpus (a bit like fact-checking). If not found, that sentence might be a hallucination, and the answer can be revised or rejected. Such <strong>iterative retrieval-generation</strong> loops, as in CoV-RAG, help refine the answer with additional context until the answer and references align (<a href="https://aclanthology.org/2024.findings-emnlp.607.pdf#:~:text=verification,iteration%20RAG">HERE</a>) . The trade-off is longer interaction (multiple LLM calls and searches), but it can dramatically improve factuality in critical applications.</p></li><li><p><strong>Source Filtering and Quality Control</strong>: Ensure the knowledge base itself is high-quality and relevant. If your document corpus contains speculative or low-accuracy documents, the model might pull in those inaccuracies. Applying filters on the documents &#8211; either manually vetting them or using an automated credibility score (like domain trust level) &#8211; can mitigate this. RA-RAG&#8217;s idea of source reliability weighting is relevant: it down-weights documents from less reliable sources (<a href="https://openreview.net/forum?id=J3xRByRqOz#:~:text=incorporating%20external%20databases,relevant%20documents%20from%20a%20few">RETRIEVAL-AUGMENTED GENERATION WITH ESTIMATION OF SOURCE RELIABILITY | OpenReview</a>). In practice, one can tag sources with a reliability score and incorporate that into the retrieval ranking (e.g. subtract a penalty from the similarity score for lower-quality sources). This way, the model is more likely to see trustworthy information. Additionally, keep the index up-to-date; outdated documents might lead to hallucinations when the model tries to reconcile conflicting info.</p></li><li><p><strong>Prompt Optimization &amp; Instructions</strong>: Lastly, fine-tune the prompt given to the LLM. Besides instructing it to cite and to refuse if unsure, one can use few-shot examples demonstrating what to do when information is missing (e.g. an example QA pair where the answer is &#8220;I&#8217;m sorry, I don&#8217;t have that information in the provided text.&#8221;). If using OpenAI models, the system message can include guidelines explicitly about not guessing and sticking to sources. Some practitioners use a format like: <em>&#8220;If you don&#8217;t find the answer in the docs, respond with a disclaimer.&#8221;</em> The prompt can also be structured to first have the model extract relevant snippets from the sources (like a two-step prompt: <em>first list the facts from the text that address the query, then formulate the answer using only those facts</em>). This enforces that every part of the answer has a grounding in the retrieved text. Such techniques have been shown to cut down hallucinations significantly by essentially boxing the model into the retrieved evidence (<a href="https://medium.com/@nirdiamant21/llm-hallucinations-explained-8c76cdd82532#:~:text=LLM%20Hallucinations%20Explained,step">LLM Hallucinations Explained. LLMs like the GPT family, Claude&#8230;</a>). The trade-off with heavy prompt constraints is that the model&#8217;s responses might become more literal or terse, as it avoids any creative extrapolation. Tuning is needed to maintain helpfulness while eliminating fabrications.</p></li></ul><p>In practice, reducing hallucinations is about alignment &#8211; aligning the model&#8217;s output strictly with what the retriever provides. It often involves adding checks: either before answering (not letting an ill-supported answer through) or after answering (post-hoc validation). Both LangChain and LlamaIndex are flexible enough to insert these controls. For example, with LangChain one can wrap the LLM call in a function that performs the score threshold check as shown above (<a href="https://github.com/langchain-ai/langchain/discussions/17792#:~:text=cases%20where%20the%20retriever%20does,not%20be%20accurate%20or%20relevant">langchain RAG should not hallucinate &#183; langchain-ai langchain &#183; Discussion #17792 &#183; GitHub</a>) . LlamaIndex allows custom query engines where you can override the response generation step to add your logic. By combining strong retrieval with these consistency measures, a RAG system can dramatically reduce hallucinated content, giving users factual and reliable outputs.</p><h2><strong>7. Pipeline Optimization</strong></h2><p>All these enhancements &#8211; hybrid searches, re-rankers, verification steps &#8211; can introduce complexity and latency. Pipeline optimization techniques ensure that a RAG system remains efficient and scalable:</p><ul><li><p>Caching: Caching intermediate results can improve latency and throughput. There are two key places to cache: embeddings and <strong>LLM outputs</strong>. Embedding caching means if you have to embed the same document (or query) multiple times, reuse the vector instead of recomputing. LangChain provides an in-memory cache for embeddings, and vector databases inherently cache stored embeddings. LLM output caching is also useful: for repeated or similar queries, you can cache the final answer. If an identical question comes again, the system can return the cached answer instantly. A simple LRU (least-recently-used) cache of query&#8594;answer speeds up frequent queries (<a href="https://www.pedroalonso.net/blog/building-rag-system-langchain-js-part-3/#:~:text=3">www.pedroalonso.net</a>) . Care must be taken with caching queries that include user-specific context (to avoid irrelevant reuse), but for many knowledge-base QA use cases, identical queries can be served from cache confidently. Caching dramatically increases throughput under load by avoiding duplicate work. Both LangChain and LlamaIndex can utilize external caches or in-memory stores to save embeddings and even chain results. There are also specialized cache implementations (like Redis caching for LLM responses or PromptCache) that can integrate with these frameworks. The trade-off is memory usage for the cache and cache invalidation complexity if the underlying data changes (you should invalidate related cache entries when documents are updated).</p></li><li><p><strong>Pre-indexing and Efficient Data Structures</strong>: The indexing step (converting all docs to embeddings or another retrieval structure) should be done offline ahead of time. Use efficient vector indices such as HNSW (Hierarchical Navigable Small World graphs) which is the default in many vector DBs for approximate nearest neighbor search. These indices significantly speed up similarity search at query time &#8211; billions of vectors can be searched in fractions of a second. Ensure that the index is built with appropriate parameters (efConstruction, M for HNSW, etc.) to balance search accuracy and speed. If using a self-hosted solution like FAISS, you might choose a clustering or PQ index for very large scales. Many RAG pipelines use hosted vector databases (Pinecone, Weaviate, Milvus) that handle the optimization internally &#8211; you just need to load your data and the service will maintain indexes. Also, consider <strong>sharding or filtering</strong>: if your corpus is multi-domain, using metadata filters to restrict the search scope can reduce the amount of data to search (thus speeding it up). For example, if you have documents labeled by category, first identify the category relevant to the query (perhaps via classification or keywords) and only search that subset&#8217;s index. LangChain&#8217;s retrievers can take search filters, and LlamaIndex allows composing indices (so you can pick the relevant index dynamically). Pre-indexing also implies persisting indexes to disk so you don&#8217;t have to rebuild in memory on every run &#8211; both frameworks support saving and loading indexes. Overall, use the most efficient data structures available for your store &#8211; e.g. if your vector DB offers a hybrid index or uses disk ANN indices, leverage those to keep latency low.</p></li><li><p><strong>Parallel and Async Processing</strong>: Pipeline stages that can be parallelized should be. For instance, embedding multiple documents at ingestion is embarrassingly parallel &#8211; you can spawn many threads or async tasks to embed chunks concurrently, drastically cutting indexing time (LlamaIndex&#8217;s toolkit includes parallel ingestion utilities (<a href="https://docs.llamaindex.ai/en/stable/examples/ingestion/parallel_execution_ingestion_pipeline/#:~:text=Parallelizing%20Ingestion%20Pipeline%20,batched%20parallel%20execution%20are">Parallelizing Ingestion Pipeline - LlamaIndex</a>)). At query time, if you are querying multiple retrievers (as in hybrid search or multi-step retrieval), those can often be done in parallel threads or async calls. For example, run the BM25 search and the vector search simultaneously and wait for both &#8211; this saves overall time versus running one then the other sequentially. Python&#8217;s <code>asyncio</code> or multi-threading can be used (though be mindful of GIL for CPU-bound tasks &#8211; thread pools or multiprocessing may be needed). LangChain&#8217;s design is generally synchronous but you can parallelize outside of it; LlamaIndex has experimental async query pipelines to execute multiple queries at once and merge results (<a href="https://docs.llamaindex.ai/en/stable/examples/pipeline/query_pipeline_async/#:~:text=LlamaIndex%20docs,once%2C%20and%20combines%20the%20results">Query Pipeline with Async/Parallel Execution - LlamaIndex</a>). Additionally, if using external APIs (like OpenAI embeddings or LLM calls), issuing requests concurrently (within rate limit constraints) can improve throughput. Another angle is streaming: many LLMs support streaming outputs, so the user can start seeing the answer while the model is still generating. This doesn&#8217;t reduce total token generation time but improves perceived latency. Techniques like retrieving <em>while</em> the user is reading the question (as a prefetch) are also explored in interactive settings.</p></li><li><p><strong>Scaling and Resource Management</strong>: Use batching where possible. Some embedding models (open-source ones) can batch multiple texts per forward pass to utilize GPU better. If using a cross-encoder reranker, batch the candidate pairs for scoring rather than one by one. Monitor memory usage of the vector store; if using a large in-memory index, ensure the machine has enough RAM or use a disk-based index. Deploying the RAG components on appropriate hardware is key &#8211; e.g. a GPU for the reranker or generator, CPU for the lightweight retriever. If throughput is a priority, you might even replicate the vector index across multiple machines and load balance queries. Also consider caching at the web service layer (e.g. Cloudflare cache for certain Q&amp;A results) if applicable, to reduce hits to your service. The goal is to make the RAG system real-time for users: sub-second retrieval and a few seconds for generation. Many optimizations, like caching and efficient ANN, can bring retrieval to a few hundred milliseconds even on millions of docs, and generation can often be done in 1-2 seconds for a concise answer on modern models.</p></li></ul><p>In practice, profiling the pipeline helps identify bottlenecks. You might find that embedding on-the-fly is slow (solution: pre-embed and cache), or that the LLM is the slowest component (solution: try a smaller model or prompt that yields shorter answers, or use a faster inference engine). Use asynchronous patterns to overlap operations where you can. LangChain and LlamaIndex are mostly high-level orchestration frameworks, so they rely on underlying databases and models for performance &#8211; ensure those are tuned (for example, set appropriate <code>k</code> in retrieval &#8211; don&#8217;t retrieve 100 documents if you only ever use top 5). By combining these optimizations, it&#8217;s possible to build RAG systems that are not only accurate and reliable but also efficient, serving users at scale. In fact, one case study noted that tuning chunk size, caching responses, and using streaming can yield a much snappier user experience without sacrificing accuracy (<a href="https://www.pedroalonso.net/blog/building-rag-system-langchain-js-part-3/#:~:text=1">www.pedroalonso.net</a>).</p><h2><strong>8. Integration with LangChain &amp; LlamaIndex</strong></h2><p>LangChain and LlamaIndex (GPT Index) have become go-to frameworks for building RAG applications, each offering components that implement the above optimizations:</p><ul><li><p><strong>LangChain Integration</strong>: LangChain provides a modular way to construct RAG pipelines with its retriever and chain abstractions. Many of the advanced retrieval techniques are available out-of-the-box. For example, LangChain&#8217;s <code>BM25Retriever</code> and <code>EnsembleRetriever</code> allow easy setup of hybrid search (<a href="https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking#:~:text=Now%2C%20we%20create%20the%20ensemble,keyword%20and%20semantic%20retrievers%20above">Optimizing RAG with Hybrid Search &amp; Reranking | VectorHub by Superlinked</a>). You can combine a BM25 retriever with a vectorstore retriever with one line, specifying weights or using rank fusion automatically. For query expansion, LangChain&#8217;s <code>SelfQueryRetriever</code> leverages an LLM (like GPT-3.5) to generate filter queries and metadata for a vector search (<a href="https://dev.to/jamesli/rag-retrieval-performance-enhancement-practices-detailed-explanation-of-hybrid-retrieval-and-self-query-techniques-59ja#:~:text=Using%20LangChain%20to%20implement%20Self,Retrieval">RAG Retrieval Performance Enhancement Practices: Detailed Explanation of Hybrid Retrieval and Self-Query Techniques - DEV Community</a>) . Chunking in LangChain is handled by various <code>TextSplitter</code> classes (e.g. <code>RecursiveCharacterTextSplitter</code> for adaptive splitting by separators, or you can integrate custom logic by subclassing). These splitters can include overlaps and are optimized in Python for large documents. LangChain&#8217;s design encourages attaching metadata (source, page number, etc.) to each <code>Document</code> chunk, which is then carried through the retrieval process, enabling source citation in the final output easily. For hallucination reduction, LangChain doesn&#8217;t enforce it internally (that&#8217;s more on the prompt/user logic side), but it offers tools like <code>LLMCheckerChain</code> or you can wrap the QA chain output in a custom function to do verification. In terms of pipeline, LangChain is flexible: you can insert custom logic between steps. For example, you could create a chain that first calls one retriever, then an LLM to reformulate the query, then another retriever &#8211; all expressed as a sequence of <code>Chain</code> objects. This makes experimenting with multi-step retrieval strategies easier. LangChain also supports caching at the LLM level; setting the environment variable <code>LANGCHAIN_HANDLER</code> or using <code>langchain.cache</code> can cache LLM calls during development to avoid repeat costs. Overall, LangChain acts as the glue that lets you swap in the right components (retrievers, vector stores, LLMs) and orchestrate them. It shines in allowing customization &#8211; if you need a special re-ranker, you can integrate it as a tool or chain link. The trade-off is that LangChain has many moving parts and can be abstract, so one must carefully configure it to get optimal performance. But it&#8217;s continually evolving with new retriever classes and integration for new vector DB features (like Weaviate&#8217;s hybrid search, etc.) being added rapidly.</p></li><li><p><strong>LlamaIndex Integration</strong>: LlamaIndex is tailored specifically for creating indexes and querying them with LLMs, making many advanced strategies very convenient. It excels in <strong>index structuring</strong> &#8211; you can create a vector index, a keyword table, a knowledge graph index, or even a composite that combines them. For instance, LlamaIndex allows building a <strong>composed index</strong> where it first uses a keyword lookup to narrow down, then a vector search on that subset (a form of multi-stage retrieval). Many of the chunking methods we discussed (semantic splitting, sentence windows, hierarchical) are provided in LlamaIndex&#8217;s <code>node_parser</code> module (<a href="https://blog.lancedb.com/chunking-techniques-with-langchain-and-llamaindex/#:~:text=Sentence%20Splitting">Chunking techniques with Langchain and LlamaIndex</a>) . With a few lines, you can split documents semantically or hierarchically, and the library handles storing references to parent nodes, etc. This saves time implementing custom chunk logic. LlamaIndex also naturally handles <strong>source tracking</strong> &#8211; each Node in the index can carry a reference (like file name or source URL), and when you query, you can ask for <code>source_nodes</code> in the response to get the exact chunks that were used to construct the answer. This makes building a QA with citations essentially a built-in feature (just format the sources into the answer). For retrieval enhancements, LlamaIndex&#8217;s query engine supports <strong>query transformations</strong>: you can plug in a query expansion module (they have examples using GPT-3 to generate <code>similar_queries</code> which are then searched as well). It also supports <strong>multi-vector queries</strong> (you can query multiple indices in parallel and combine results). The framework is optimized for <strong>index querying</strong> &#8211; once an index is built, querying it is straightforward and efficient (<a href="https://stackoverflow.com/questions/76990736/differences-between-langchain-llamaindex#:~:text=match%20at%20L282%20One%20key,be%20easily%20queried%20like%20so">chatbot - Differences between Langchain &amp; LlamaIndex - Stack Overflow</a>) . LlamaIndex is generally more efficient in terms of data handling for large numbers of documents, and some users report it scales better with large indices than LangChain (which relies on external vector stores for scaling) . Another strength is the ability to do <strong>retrieval augmentation beyond text</strong> &#8211; for example, LlamaIndex can integrate with APIs or databases and treat them as &#8220;indices&#8221; to retrieve from (useful for hybrid knowledge sources). If we consider LangChain vs LlamaIndex: LangChain is a broad framework for chaining any LLM task (tools, agents, etc.), whereas LlamaIndex is specialized for document indexing and retrieval. In fact, they can be used together &#8211; e.g. use LlamaIndex to build an index, and use LangChain to orchestrate an agent that uses that index as a tool.</p></li><li><p><strong>Best Practices and Customization</strong>: Both frameworks allow customization, but in different ways. LangChain often requires writing a bit of glue code to implement a new retriever or filter logic (though many are built-in as discussed). LlamaIndex allows custom callbacks and query plan modifications; for example, you can override how it selects nodes from an index or inject a verification step in the response synthesis. In terms of prompt engineering, LangChain offers <code>PromptTemplate</code> and easy ways to format the final prompt given to the LLM, whereas LlamaIndex uses the concept of <code>ResponseSynthesizer</code> where you can choose different synthesis modes (concatenate sources vs refine iteratively, etc.). An important point is that <strong>LlamaIndex is optimized for indexing, and retrieving data</strong> &#8211; it abstracts a lot of the data handling and offers efficient indices . LangChain is more of an orchestration layer with a very large toolkit but might rely on external components for efficiency (like a vector database). If your application is primarily about QA over documents, LlamaIndex can be slightly simpler to get a high-performing index and query system. If your application involves more steps (like multi-turn conversation, tool use, or complex agent behaviors), LangChain&#8217;s broader capabilities might be needed, with LlamaIndex possibly plugged in for the retrieval part . Many practitioners actually use them together: LlamaIndex for building the index and doing retrieval, and then feeding that into a LangChain conversation chain for memory or agent reasoning. They are complementary.</p></li></ul><p>In summary, <em>LangChain</em> provides the building blocks to implement all these RAG optimizations, and <em>LlamaIndex</em> provides purpose-built implementations of many optimizations (various index types, chunking strategies, etc.). LlamaIndex tends to be more <strong>efficient and straightforward for retrieval tasks</strong> (its core focus) (<a href="https://stackoverflow.com/questions/76990736/differences-between-langchain-llamaindex#:~:text=LlamaIndex%20is%20specifically%20designed%20for,for%20querying%20LLMs%20and%20retrieving">chatbot - Differences between Langchain &amp; LlamaIndex - Stack Overflow</a>) , while LangChain offers <strong>flexibility and extensibility</strong> for integrating retrieval with other LLM capabilities. Both are evolving rapidly, adding support for new embedding models, vector stores, and techniques. The best practice is to leverage their strengths: for example, use LlamaIndex&#8217;s semantic splitter to preprocess docs, and use LangChain&#8217;s ensemble retriever to do hybrid search across that index and maybe a second knowledge source. These frameworks handle much of the heavy lifting, so you can focus on tuning parameters (like chunk size, number of results, thresholds) and ensuring the prompts and logic align with your application&#8217;s needs. With LangChain and LlamaIndex, even advanced techniques like dynamic weight hybrid retrieval or recursive verification can be implemented with relatively little code, accelerating the development of <strong>accurate, reliable, and verifiable</strong> RAG systems.</p><h2><strong>Conclusion</strong></h2><p>Modern Retrieval-Augmented Generation systems can be significantly enhanced through careful optimization of retrieval, embedding, and generation components. By using hybrid search to retrieve comprehensive evidence (<a href="https://blog.gopenai.com/day-11-building-and-evaluating-advanced-rag-systems-4daf1c62125c#:~:text=In%20advanced%20RAG%20systems%2C%20a,matches%20and%20semantically%20similar%20content">Day 11: Building and Evaluating Advanced RAG Systems | by Nikhil Kulkarni | GoPenAI</a>), chunking documents in a smart way to preserve context (<a href="https://blog.lancedb.com/chunking-techniques-with-langchain-and-llamaindex/#:~:text=Semantic%20chunking%20offers%20a%20new,sentences%2C%20based%20on%20embedding%20similarity">Chunking techniques with Langchain and LlamaIndex</a>) , and enforcing verification and source citation (<a href="https://docs.typingmind.com/typingmind-custom/branding-and-customizations/enable-llms-to-cite-sources-when-using-rag#:~:text=Here%20are%20some%20key%20tips,to%20guide%20the%20AI%20model">Enable LLMs to cite sources when using RAG</a>), we greatly improve the accuracy and trustworthiness of LLM outputs. These improvements must be balanced with efficient pipeline design &#8211; caching, batching, and parallelism &#8211; to ensure the system remains fast and scalable. Frameworks like LangChain and LlamaIndex serve as powerful allies in this process, providing implementable solutions and abstractions for these techniques. By applying these methodologies with rigorous attention to detail, one can build a RAG system that not only answers correctly, but also provides answers with reliable sources and in a timely manner. The result is an AI system that users can trust and verify &#8211; a goal increasingly within reach thanks to the advances in RAG architectures over the past year.</p><p><strong>Sources:</strong> The insights and techniques above are drawn from recent research and industry best-practices in Retrieval-Augmented Generation, including 2024 papers and implementations that demonstrate improved RAG accuracy through hybrid retrieval (<a href="https://goatstack.ai/topics/blended-rag-improving-rag-accuracy-with-semantic-search-and-hybrid-query-based-retrievers-akoepf#:~:text=,tuned%20model%20performances">Blended RAG: Improving RAG Accuracy with Semantic Search and Hybrid Query-Based Retrievers</a>), embedding model fine-tuning (<a href="https://www.databricks.com/blog/improving-retrieval-and-rag-embedding-model-finetuning#:~:text=What%20We%20Found%3A%20We%20finetuned,leveraging%20only%20your%20existing%20data">Improving Retrieval and RAG with Embedding Model Finetuning | Databricks Blog</a>), advanced chunking strategies , and verification-enhanced pipelines (<a href="https://aclanthology.org/2024.findings-emnlp.607.pdf#:~:text=verification,iteration%20RAG">HERE</a>) , as well as documentation and blogs for LangChain and LlamaIndex that reflect the current state-of-the-art in RAG system development. Each citation corresponds to a specific supporting source or example for the mentioned technique.</p>]]></content:encoded></item><item><title><![CDATA[Handling Graphs and Charts in RAG Pipelines 2024-2025]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/handling-graphs-and-charts-in-rag</link><guid isPermaLink="false">https://www.rohan-paul.com/p/handling-graphs-and-charts-in-rag</guid><pubDate>Mon, 16 Jun 2025 09:21:00 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!vw5d!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!vw5d!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!vw5d!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png 424w, https://substackcdn.com/image/fetch/$s_!vw5d!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png 848w, https://substackcdn.com/image/fetch/$s_!vw5d!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png 1272w, https://substackcdn.com/image/fetch/$s_!vw5d!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!vw5d!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png" width="1024" height="572" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/b0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:572,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:791645,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166053917?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!vw5d!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png 424w, https://substackcdn.com/image/fetch/$s_!vw5d!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png 848w, https://substackcdn.com/image/fetch/$s_!vw5d!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png 1272w, https://substackcdn.com/image/fetch/$s_!vw5d!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb0155378-9e1b-4b93-b81e-89e5996546a6_1024x572.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><p><strong>Table of Contents</strong></p><ul><li><p>Extracting and Processing Graphs-Charts in RAG</p></li><li><p>Embedding Charts and Graphs into Vector Stores</p></li><li><p>Challenges in Integrating Graph-Chart Data</p></li><li><p>Best Practices and Industry Applications</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Extracting and Processing Graphs-Charts in RAG</strong></h2><p>Retrieval-Augmented Generation (RAG) has evolved to handle <strong>multimodal content</strong>, including graphs and charts embedded in documents. In industry settings (finance, healthcare, scientific publishing), critical information is often conveyed in figures. Recent work in 2024 and 2025 emphasizes techniques to <strong>digitize and chunk</strong> these visuals for LLMs, integrating them into retrieval pipelines alongside text. This review highlights methods for extracting chart data, embedding visual content into vector stores, challenges of integrating these modalities, and best practices from industry applications.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p><strong>Document Parsing and Segmentation:</strong> The first step is identifying and extracting charts/graphs from documents. Modern document parsing tools can split PDFs into textual sections and images. For example, Azure&#8217;s Document Intelligence can isolate text and even <em>OCR any images</em> within a file (<a href="https://techcommunity.microsoft.com/blog/azuredevcommunityblog/integrating-vision-into-rag-applications/4239460#:~:text=,002%20model">Integrating vision into RAG applications | Microsoft Community Hub</a>). Many pipelines now <strong>separate images from text content</strong> during ingestion (<a href="https://developer.nvidia.com/blog/an-easy-introduction-to-multimodal-retrieval-augmented-generation/#:~:text=">An Easy Introduction to Multimodal Retrieval-Augmented Generation | NVIDIA Technical Blog</a>), so each chart or graph can be processed independently. Research highlights that handling figures is more complex than plain text: <em>&#8220;Documents with charts, tables, maths are more complex&#8230; Some parsers combine OCR with computer vision and LLMs&#8221;</em> (<a href="https://discovery.graphsandnetworks.com/graphAI/graphRAG.html#:~:text=budget,spectrum%20of%20solutions%20and%20features">Graph RAG &#8211; Orbifold Consulting</a>). This means chart handling often requires a combination of techniques (e.g. detecting text in the image, analyzing visual elements, and using language models to interpret context).</p><p><strong>OCR and Text Extraction:</strong> Charts usually contain textual elements (titles, axis labels, legends, data labels). OCR-based methods are essential to extract this embedded text. Industry OCR services like Amazon Textract or Azure OCR can pull out these strings, which are then included in the metadata or textual representation of the chart. A recent benchmark, <strong>CHART-Info 2024</strong>, defines multiple sub-tasks needed for full chart understanding: <em>chart text detection and recognition, text role classification (e.g. distinguish axis labels vs. data labels), axis and legend analysis, and data extraction</em> (<a href="https://cdn.iiit.ac.in/cdn/cvit.iiit.ac.in/images/ConferencePapers/2024/chart_info.pdf#:~:text=sense%20of%20a%20chart%20image%2C,The">HERE</a>). These tasks underscore that beyond raw OCR, understanding a chart involves interpreting the roles of text and the visual structure. In practice, specialized vision-language models are emerging to handle this. For instance, Google&#8217;s DePlot model is designed to comprehend charts and plots. NVIDIA demonstrated using DePlot to convert bar chart images into a &#8220;linearized&#8221; table or text form in a RAG pipeline . By generating a structured textual representation of a chart (essentially reading the chart&#8217;s data), the chart can be <em>treated as text</em> for downstream processing. This approach was applied to technical documentation with complex figures, ensuring the <strong>key information from charts is extracted and expressed in text</strong> . In cases where such specialized models are unavailable, a simpler alternative is to produce an <strong>image caption or summary</strong> of the chart via a vision-capable model, describing the trends or insights it conveys.</p><p><strong>Chunking and Metadata:</strong> Once a chart&#8217;s content is extracted (via OCR or model), it becomes its own &#8220;chunk&#8221; in the RAG pipeline. Best practices include attaching relevant metadata &#8211; e.g. the figure caption, source, or a tag indicating this chunk is an image. Some pipelines store the full OCR text or data of the chart but use a <em>summary for the actual embedding</em>, because raw extracted data (like a list of numbers) may not be semantically meaningful for retrieval (<a href="https://developer.nvidia.com/blog/an-easy-introduction-to-multimodal-retrieval-augmented-generation/#:~:text=Image%20descriptions%20generated%20by%20an,performing%20a%20search%20during%20inference">An Easy Introduction to Multimodal Retrieval-Augmented Generation | NVIDIA Technical Blog</a>). A 2024 NVIDIA workflow recommends summarizing the linearized chart data and using that summary as the chunk to vectorize, which improved retrieval relevance . Additionally, maintaining references between the chart chunk and its parent document/page helps with citations and downstream usage (<a href="https://discovery.graphsandnetworks.com/graphAI/graphRAG.html#:~:text=Metadata%20matters%20especially%20if%20the,not%20text%20but%20in%20general">Graph RAG &#8211; Orbifold Consulting</a>).</p><h2><strong>Embedding Charts and Graphs into Vector Stores</strong></h2><p><strong>Multimodal Embeddings:</strong> A core challenge is how to represent a chart or graph in the vector store so that it can be retrieved given a user&#8217;s query. One approach is using <strong>multimodal embedding models</strong> that map images and text into a shared vector space. For example, Microsoft&#8217;s Florence model (available via Azure AI Vision) generates 1024-dimensional embeddings for images such that similar content yields vectors close to relevant text queries (<a href="https://techcommunity.microsoft.com/blog/azuredevcommunityblog/integrating-vision-into-rag-applications/4239460#:~:text=Azure%20also%20offers%20a%20multimodal,Florence%20model%20from%20Microsoft%20Research">Integrating vision into RAG applications | Microsoft Community Hub</a>) . Using this, an image of a rising line chart could be retrieved for a query about &#8220;increasing trends,&#8221; even if the query doesn&#8217;t explicitly describe the image . In practice, systems like Azure Cognitive Search allow adding an <em>&#8220;imageEmbedding&#8221;</em> field alongside text embeddings for each document page . During retrieval, a hybrid search can combine text semantic search with image-vector search to find matches in either modality . This multi-vector approach ensures that a query can surface a chart even if the chart&#8217;s textual metadata is sparse, by relying on visual similarity in the embedding space.</p><p><strong>Textual Embeddings of Chart Content:</strong> Another technique is to represent the chart via text (as noted earlier) and use a standard text embedding model (like OpenAI&#8217;s Ada-002 or similar) on that description. The KX engineering team, for instance, demonstrated this kind of approach for tables &#8211; extracting each table and generating a descriptive context, then converting the table to a uniform text format for embedding (<a href="https://kx.com/blog/mastering-rag-precision-techniques-for-table-heavy-documents/#:~:text=Let%E2%80%99s%20approach%20these%20challenges%20with,four%20key%20concepts">Mastering RAG: Precision techniques for table-heavy documents | KX: Vector Database, Time Series And Real Time Analytics</a>). A similar logic can apply to charts: one can create a textual summary of the chart&#8217;s data (e.g. <em>&#8220;a line chart showing patient heart rate rising from 70 to 90 bpm over 5 minutes&#8221;</em>) and embed that. The advantage is that it leverages well-understood text-vector models and can capture the semantics of the chart in natural language. The disadvantage is loss of some precision (the model might not list every data point). In practice, many industry pipelines combine approaches: <strong>store the image&#8217;s own embedding and a text-derived embedding</strong>. For example, Microsoft&#8217;s RAG system kept both the text content embedding and an image embedding for each page , enabling queries to hit on either representation.</p><p><strong>Vector Index Organization:</strong> It&#8217;s common to treat each figure (chart) as a separate entry in the vector database, often linked to a caption or figure number. This allows the RAG retriever to return a chart &#8220;chunk&#8221; similarly to a text chunk. Some advanced retrievers also store <em>modality flags</em> or use separate indexes per modality (text vs image) and then merge results. LangChain&#8217;s 2024 multi-vector retriever and other frameworks can handle multiple embedding fields per document chunk, as seen in open-source cookbooks for text+image RAG (<a href="https://blog.langchain.dev/semi-structured-multi-modal-rag/#:~:text=Seamless%20question,to%20unlock%20RAG%20on%20images">Multi-Vector Retriever for RAG on tables, text, and images</a>) (though such 2023 references laid groundwork, the concept carries into 2024 implementations).</p><h2><strong>Challenges in Integrating Graph-Chart Data</strong></h2><p><strong>Semantic Gap and Retrieval Accuracy:</strong> Integrating charts introduces a semantic gap &#8211; the meaning in a chart must be captured either in an embedding or textual form. If using image embeddings, a challenge noted by practitioners is that <em>visual similarity doesn&#8217;t always equate to relevance</em>. For example, an image embedding model might consider a mostly blank chart similar to many queries (due to lack of distinctive features), causing irrelevant retrievals (<a href="https://techcommunity.microsoft.com/blog/azuredevcommunityblog/integrating-vision-into-rag-applications/4239460#:~:text=More%20selective%20embeddings%3A%20Our%20ingestion,storing%20the%20image%20embeddings%20themselves">Integrating vision into RAG applications | Microsoft Community Hub</a>). Pamela Fox at Microsoft observed that embedding every page image naively could surface blank or irrelevant pages as top hits (an image of an empty page might appear &#8220;similar&#8221; to everything in latent space) . Mitigations include filtering out images with little content, or using a captioning model to generate a descriptive text for the image instead of the raw image embedding . There is also the issue that charts with very domain-specific visuals might confuse a general embedding model. A biomedical plot of gene expression might not be well-understood by a generic vision model. In such cases, custom embeddings or fine-tuned models may be needed.</p><p><strong>LLM Context and Reasoning:</strong> Once retrieved, using chart data in generation is non-trivial. Standard LLMs accept text, not images, so an <strong>LLM with vision capability</strong> (like GPT-4V or open-source Multimodal LLMs) must be leveraged, or a two-stage approach must be used. One approach is to include the chart&#8217;s text summary in the prompt (so the LLM only sees text). This works for questions answerable by the summary, but fails if the question requires details only visible in the image (e.g. exact trends or values not fully captured by the summary). The more robust approach is a pipeline: if an image chunk is retrieved, feed the actual image (or its data) into a vision model to get the answer, then incorporate that into the final LLM response. NVIDIA&#8217;s 2024 demo implemented this: upon retrieving a relevant chart image, they passed it (with the user&#8217;s question) into a vision-question answering model, which interpreted the chart (e.g. reading the exact value difference between two bars) and produced an answer snippet (<a href="https://developer.nvidia.com/blog/an-easy-introduction-to-multimodal-retrieval-augmented-generation/#:~:text=Here%20are%20some%20key%20steps,the%20top%20five%20relevant%20chunks">An Easy Introduction to Multimodal Retrieval-Augmented Generation | NVIDIA Technical Blog</a>). That snippet (80% higher performance in their example) was then included as context for the final answer generation . This kind of <strong>late-stage fusion</strong> ensures accuracy but adds complexity (you need a vision VQA module alongside your LLM). Alternatively, when using a single multimodal LLM like GPT-4, one can directly provide the image (e.g. via base64 in the prompt, as done in Azure&#8217;s implementation) and ask the model to answer using both text and image sources . However, reliance on closed models like GPT-4 may raise data privacy concerns for industry and can be expensive.</p><p><strong>Accuracy and Limitations:</strong> Even with advanced models, understanding charts is not perfect. A study on <em>ChartQA</em> in late 2024 evaluated 19 multimodal LLMs on reading charts and found the average accuracy was only ~39.8%, with the best (GPT-4V) around 69% on &#8220;low-level&#8221; tasks (like identifying specific correlations or values) (<a href="https://aclanthology.org/2024.findings-emnlp.710/#:~:text=multimodal%20large%20language%20models%20,we%20conduct%20experiments%20that%20alter">ChartInsights: Evaluating Multimodal Large Language Models for Low-Level Chart Question Answering - ACL Anthology</a>). This indicates current models often misread or overlook fine details in charts. The research introduced improved prompting strategies (like a <em>Chain-of-Charts</em> method to guide the model&#8217;s attention) that boosted accuracy to ~84% . For RAG systems, this implies that even if the correct chart is retrieved, the system may need tailored prompts or logic to ensure the LLM extracts the right answer from it. Challenges like varying chart styles, image noise, or unusual layouts can further hinder interpretation . Integrators must anticipate errors &#8211; for instance, an LLM might hallucinate a trend if the chart is complex &#8211; and possibly include validation (if underlying data is available, cross-check the LLM&#8217;s reading).</p><p><strong>Computational Overhead:</strong> Storing and searching images alongside text increases storage and compute needs. Image embeddings (e.g. 1024-d vectors for each page image) can be heavy at scale. Some industry solutions address this by selectivity &#8211; e.g. only embedding pages or figures that contain significant visual information (<a href="https://techcommunity.microsoft.com/blog/azuredevcommunityblog/integrating-vision-into-rag-applications/4239460#:~:text=More%20selective%20embeddings%3A%20Our%20ingestion,storing%20the%20image%20embeddings%20themselves">Integrating vision into RAG applications | Microsoft Community Hub</a>). Likewise, running a vision model at query time for potentially multiple images can be slow. Caching analyses for frequently asked-about charts or using lightweight models can mitigate latency.</p><h2><strong>Best Practices and Industry Applications</strong></h2><p><strong>Financial Reports:</strong> In finance, RAG systems deal with earnings reports, filings, and presentations that mix narrative text with charts of trends and tables of numbers. Best practices here include <strong>treating tables and charts as first-class citizens</strong> in the knowledge base. One industry approach is to convert every chart and table into a textual summary during ingestion, so that the LLM can retrieve and quote facts from them reliably. For example, a pipeline for a financial report might extract a revenue trend chart and generate a sentence like <em>&#8220;Figure 5: Revenue increased from $10M in Q1 to $15M in Q2&#8221;</em>, which is stored as a chunk with a reference to the figure. This ensures queries about &#8220;revenue in Q2&#8221; retrieve that info. KX&#8217;s solution for table-heavy documents combined table markdown with contextual descriptions for robust retrieval (<a href="https://kx.com/blog/mastering-rag-precision-techniques-for-table-heavy-documents/#:~:text=Let%E2%80%99s%20approach%20these%20challenges%20with,four%20key%20concepts">Mastering RAG: Precision techniques for table-heavy documents | KX: Vector Database, Time Series And Real Time Analytics</a>) &#8211; a similar enrichment can be applied to charts by including their caption or a brief analysis. Additionally, using multi-modal search can catch questions phrased visually (e.g. &#8220;show me any charts of rising costs&#8221;), retrieving the actual chart image via vector similarity (<a href="https://techcommunity.microsoft.com/blog/azuredevcommunityblog/integrating-vision-into-rag-applications/4239460#:~:text=3,the%20text%20content%20and%20the">Integrating vision into RAG applications | Microsoft Community Hub</a>). Microsoft reports that enabling image-based retrieval was <em>&#8220;a great fit for diagram-heavy domains like finance&#8221;</em>, allowing users to get answers entirely from charts when needed . For accuracy, financial applications often double-check any numeric values read from charts, since an error can be critical. If possible, storing the raw data behind a chart (from CSV or reports) and linking it to the image can allow the system to use the exact numbers instead of relying on image reading.</p><p><strong>Medical Documents:</strong> Healthcare documents can contain patient charts (like vital sign trends), medical imagery (X-rays, MRIs), and annotated diagrams. Integrating these in RAG is emerging. A key practice is to <strong>use domain-specific models</strong> when available &#8211; for instance, a general chart parser might not handle an EKG graph well, but a specialized healthcare AI could. NVIDIA suggests either fine-tuning a single model to handle all image types or using an ensemble of models for different image categories (<a href="https://developer.nvidia.com/blog/an-easy-introduction-to-multimodal-retrieval-augmented-generation/#:~:text=This%20example%20focuses%20on%20charts,for%20different%20types%20of%20images">An Easy Introduction to Multimodal Retrieval-Augmented Generation | NVIDIA Technical Blog</a>). In a medical setting, one could route line-chart type images (like lab results over time) to a chart-reading module, while sending anatomical images to an entirely different analyzer. Maintaining the context is also crucial: a medical chart&#8217;s meaning is tied to the patient and measurement. So linking the extracted chart info with patient metadata (patient ID, date) in the vector store is a best practice, to retrieve the correct record for a query like &#8220;Show me John Doe&#8217;s blood pressure trend in March&#8221;. Privacy and compliance are particularly important; if using a service like Bedrock&#8217;s multimodal RAG (which now supports images and tables (<a href="https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-knowledge-bases-processes-multimodal-data/#:~:text=Amazon%20Bedrock%20Knowledge%20Bases%20now,This%20enables%20users">Amazon Bedrock Knowledge Bases now processes multimodal data - AWS</a>)), healthcare providers must ensure the data stays encrypted and within approved systems. In terms of OCR, medical charts often have handwritten annotations or scans, so high-quality OCR (or human-in-the-loop validation) may be needed to avoid critical mistakes.</p><p><strong>Scientific and Technical Papers:</strong> Scientific literature contains numerous graphs and plots that are essential to understanding results. RAG-powered literature assistants (for example, tools to query academic papers) need to handle questions about these figures. A best practice here is to leverage the figure captions and surrounding text heavily. Typically, a well-written paper describes each figure in the caption or body; ensuring the caption is indexed and chunked with the figure can answer many questions without needing complex image processing. However, for questions requiring reading values off a plot (e.g. &#8220;According to Figure 2, what is the peak intensity?&#8221;), a vision model is needed. Industry solutions like <strong>SciNLP assistants</strong> have begun to incorporate figure parsing libraries (like pdffigures2) to isolate each figure, then applying a model such as DePlot or an MLLM (Multimodal LLM) to generate a textual explanation of the figure. This explanation can be indexed for retrieval. The 2024 NVIDIA example of an AI reading an NVIDIA research blog&#8217;s charts is analogous to doing so for a scientific paper: the system successfully answered a performance comparison question by interpreting a bar chart from the document . For scientific use, it&#8217;s also recommended to classify the figure type (line graph, scatter plot, diagram, etc.) because certain models perform better on certain types (e.g. a chemistry diagrams parser vs. a data plot parser). By 2025, we see early deployments of such systems in enterprise research departments and publishing platforms to enable querying documents beyond just text.</p><p><strong>General Recommendations:</strong> Across domains, some universal best practices have emerged:</p><ul><li><p><strong>Multimodal Indexing:</strong> Index both text and visual information. Use a unified embedding space if possible for cross-modal search (<a href="https://techcommunity.microsoft.com/blog/azuredevcommunityblog/integrating-vision-into-rag-applications/4239460#:~:text=Azure%20also%20offers%20a%20multimodal,Florence%20model%20from%20Microsoft%20Research">Integrating vision into RAG applications | Microsoft Community Hub</a>) , and/or store separate embeddings with a retriever that can combine them. This hybrid approach yields more complete results.</p></li><li><p><strong>Contextual Chunking:</strong> When chunking documents, keep charts and their explanatory text together. If a chart has a caption or is referred to in the paragraph above, linking those in the vector store (through metadata or even combining them in one chunk) can improve retrieval relevance and provide context for the LLM to understand the image.</p></li><li><p><strong>Efficient Image Use:</strong> Avoid indexing meaningless images (e.g. decorative graphics or blank pages) to reduce noise (<a href="https://techcommunity.microsoft.com/blog/azuredevcommunityblog/integrating-vision-into-rag-applications/4239460#:~:text=More%20selective%20embeddings%3A%20Our%20ingestion,storing%20the%20image%20embeddings%20themselves">Integrating vision into RAG applications | Microsoft Community Hub</a>). Focus on informative charts/graphs. Optionally, generate captions for images and index those rather than raw pixel embeddings if the visual model isn&#8217;t reliable.</p></li><li><p><strong>Leverage VQA at Runtime:</strong> For critical applications, incorporate a vision-QA step when an image is retrieved. This ensures the final answer is grounded in what the chart actually shows, not just the description. As shown by industry prototypes, combining an MLLM&#8217;s answer from the image with the main LLM&#8217;s answer yields accurate and citeable results (<a href="https://developer.nvidia.com/blog/an-easy-introduction-to-multimodal-retrieval-augmented-generation/#:~:text=Here%20are%20some%20key%20steps,the%20top%20five%20relevant%20chunks">An Easy Introduction to Multimodal Retrieval-Augmented Generation | NVIDIA Technical Blog</a>).</p></li><li><p><strong>Metadata and Source Attribution:</strong> Always store the source of the chart (document name, figure number) and include it in the LLM prompt or answer for transparency. AWS&#8217;s Bedrock multimodal RAG now even provides source attribution for visual data (<a href="https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-knowledge-bases-processes-multimodal-data/#:~:text=data%2C%20such%20as%20images%2C%20charts%2C,and%20building%20trust%20in%20the">Amazon Bedrock Knowledge Bases now processes multimodal data - AWS</a>), which is important for user trust. Microsoft&#8217;s approach of stamping the image with its filename and citing that in answers is one way to handle this (<a href="https://techcommunity.microsoft.com/blog/azuredevcommunityblog/integrating-vision-into-rag-applications/4239460#:~:text=The%20documents%20contain%20text%2C%20graphs%2C,tables%20and%20images">Integrating vision into RAG applications | Microsoft Community Hub</a>).</p></li></ul><p>By following these practices, organizations in 2024 and beyond have started to successfully incorporate graphs and charts into their RAG pipelines, making LLMs far more knowledgeable on visual information. This unlocks advanced use-cases like querying financial trends directly from report charts or asking scientific questions that require reading a graph &#8211; tasks that pure text models would have missed. While challenges remain (in accuracy and complexity), ongoing research and industry innovation are rapidly closing the gap, making multimodal RAG a practical reality for document intelligence.</p><p><strong>References:</strong></p><ul><li><p>NVIDIA (2024), <em>Multimodal RAG pipeline</em> &#8211; techniques for chart interpretation and image-text integration (<a href="https://developer.nvidia.com/blog/an-easy-introduction-to-multimodal-retrieval-augmented-generation/#:~:text=The%20post%20in%20question%20contains,model%20is%20available%20on%20NGC">An Easy Introduction to Multimodal Retrieval-Augmented Generation | NVIDIA Technical Blog</a>) .</p></li><li><p>Microsoft Azure Tech Community (2024), <em>Vision in RAG</em> &#8211; using multimodal embeddings and GPT-4V to handle diagrams in finance (<a href="https://techcommunity.microsoft.com/blog/azuredevcommunityblog/integrating-vision-into-rag-applications/4239460#:~:text=3,the%20text%20content%20and%20the">Integrating vision into RAG applications | Microsoft Community Hub</a>) .</p></li><li><p>AWS Bedrock (Dec 2024), <em>Knowledge Bases multimodal support</em> &#8211; announcement of end-to-end RAG on text and images (charts, tables) (<a href="https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-knowledge-bases-processes-multimodal-data/#:~:text=Amazon%20Bedrock%20Knowledge%20Bases%20now,This%20enables%20users">Amazon Bedrock Knowledge Bases now processes multimodal data - AWS</a>) .</p></li><li><p>Davila et al. (2024), <em>CHART-Info Dataset</em> &#8211; defines OCR and analysis tasks for chart recognition (<a href="https://cdn.iiit.ac.in/cdn/cvit.iiit.ac.in/images/ConferencePapers/2024/chart_info.pdf#:~:text=sense%20of%20a%20chart%20image%2C,The">HERE</a>).</p></li><li><p>Wu et al. (2024), <em>ChartInsights (EMNLP 2024)</em> &#8211; evaluation of LLMs on chart QA, highlighting accuracy limits and improvements (<a href="https://aclanthology.org/2024.findings-emnlp.710/#:~:text=multimodal%20large%20language%20models%20,we%20conduct%20experiments%20that%20alter">ChartInsights: Evaluating Multimodal Large Language Models for Low-Level Chart Question Answering - ACL Anthology</a>) .</p></li><li><p>Orbifold Consulting (2024), <em>Graph RAG blog</em> &#8211; notes on document parsing challenges with charts and combined OCR/CV approaches (<a href="https://discovery.graphsandnetworks.com/graphAI/graphRAG.html#:~:text=budget,spectrum%20of%20solutions%20and%20features">Graph RAG &#8211; Orbifold Consulting</a>).</p></li></ul>]]></content:encoded></item><item><title><![CDATA[Building a Production-Grade Retrieval-Augmented Generation (RAG) System: Literature Review]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/building-a-production-grade-retrieval</link><guid isPermaLink="false">https://www.rohan-paul.com/p/building-a-production-grade-retrieval</guid><pubDate>Mon, 16 Jun 2025 09:18:14 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!W6ud!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!W6ud!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!W6ud!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png 424w, https://substackcdn.com/image/fetch/$s_!W6ud!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png 848w, https://substackcdn.com/image/fetch/$s_!W6ud!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png 1272w, https://substackcdn.com/image/fetch/$s_!W6ud!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!W6ud!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png" width="1024" height="509" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:509,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:750194,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166053695?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!W6ud!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png 424w, https://substackcdn.com/image/fetch/$s_!W6ud!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png 848w, https://substackcdn.com/image/fetch/$s_!W6ud!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png 1272w, https://substackcdn.com/image/fetch/$s_!W6ud!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4673bc8d-dfba-41e2-affb-934791de5a36_1024x509.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><ul><li><p>Document Ingestion, Preprocessing &amp; Chunking</p></li><li><p>Vector Database Selection &amp; Indexing</p></li><li><p>Retrieval Mechanisms Exact vs Approximate Hybrid Search</p></li><li><p>LLM Selection and Inference Optimization</p></li><li><p>Response Generation and Answer Ranking</p></li><li><p>System Monitoring and Maintenance</p></li><li><p>Popular Frameworks and Tools</p></li><li><p>Performance Optimizations and Trade-offs</p></li><li><p>Recent Research and Advancements (2024&#8211;2025)</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Document Ingestion, Preprocessing &amp; Chunking</strong></h2><p>Effective RAG systems begin with robust <strong>document ingestion</strong> and preprocessing. This involves collecting relevant data (e.g. PDFs, web pages, text files) and converting it to text that the system can process (<a href="https://www.multimodal.dev/post/how-to-chunk-documents-for-rag#:~:text=The%20first%20step%20in%20setting,as%20articles%2C%20books%2C%20and%20reports">How to Chunk Documents for RAG</a>). Key preprocessing steps include cleaning (removing noise/HTML) and normalizing text. Large documents are then chunked into smaller, self-contained segments to improve retrieval granularity . Each chunk is typically a few hundred tokens long and may overlap with others to preserve context continuity . Chunking prevents context overflow and ensures that each retrieved piece is meaningful and relevant to queries. Incorporating metadata (e.g. document ID, section headings) for each chunk further enhances retrieval precision . This ingestion pipeline forms the knowledge base that the RAG system will draw from during query-time.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Vector Database Selection &amp; Indexing</strong></h2><p>Processed chunks are transformed into vector embeddings that capture their semantic content. These embeddings are stored in a <strong>vector database</strong> or index optimized for similarity search. Choosing the right vector store is crucial for production. FAISS (Facebook AI Similarity Search) is a popular library for in-memory indexing, offering options like flat indexes (exact brute-force) and hierarchical navigable small world (HNSW) graphs or IVF for approximate search. Production systems at scale often use dedicated vector databases like Weaviate, Milvus, Pinecone, or Qdrant which support distributed storage, filtering, and hybrid queries. Indexing strategies impact performance: a flat index ensures exact nearest-neighbor retrieval but scales poorly, whereas approximate indexes (HNSW, IVF+PQ) trade a tiny loss in recall for significantly lower latency and memory footprint. Recent literature emphasizes building <strong>scalable indexing pipelines</strong> that can handle continuous data updates and re-indexing for new documents (<a href="https://arxiv.org/abs/2312.10997#:~:text=RAG%2C%20the%20Advanced%20RAG%2C%20and,avenues%20for%20research%20and%20development"> Retrieval-Augmented Generation for Large Language Models: A Survey</a>). Vector store selection also relates to features; for example, Weaviate natively supports hybrid searches (combining lexical and vector search) which might otherwise require custom implementation (<a href="https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking#:~:text=,while%20ChromaDB%20needs%20custom%20setup">Optimizing RAG with Hybrid Search &amp; Reranking | VectorHub by Superlinked</a>).</p><h2><strong>Retrieval Mechanisms: Exact vs. Approximate, Hybrid Search</strong></h2><p>At query time, the system encodes the user query into an embedding and performs a <strong>similarity search</strong> in the vector index (<a href="https://www.ibm.com/think/topics/rag-techniques#:~:text=1,that%20synthesizes%20a%20coherent%20and">RAG | IBM</a>). Two main retrieval paradigms are used: <em>exact</em> and <em>approximate</em>. <strong>Exact retrieval</strong> in the vector space (brute-force search) guarantees the top-k most similar embeddings are found, but is only feasible for smaller corpora. <strong>Approximate nearest neighbor (ANN)</strong> algorithms (like HNSW or product quantization in FAISS) dramatically speed up search in large datasets with minimal loss in accuracy, making them standard for production RAG. In addition, <strong>hybrid search</strong> combines semantic vector search with traditional lexical search (e.g. BM25). This approach improves results for queries with exact keywords, numbers, or rare terms by merging keyword matches with embedding similarity . Hybrid retrieval can be implemented by score fusion (e.g. weighted sum of BM25 and vector scores) or by retrieving candidates from each method and then re-ranking . Research shows hybrid techniques handle edge cases (like specific names or code) better and improve overall recall in RAG pipelines . After initial retrieval, many systems apply a <strong>re-ranking</strong> step using a stronger language model or cross-encoder to sort the candidate passages by relevance before passing them to the generator, further boosting answer accuracy.</p><h2><strong>LLM Selection and Inference Optimization</strong></h2><p>The choice of <strong>Large Language Model (LLM)</strong> for generation is a pivotal decision in a production RAG system. Proprietary models like OpenAI&#8217;s GPT-4/GPT-3.5 offer strong performance out-of-the-box, while open-source models (Llama 2, FLAN-T5, etc.) provide more control and data privacy. Recent experience reports highlight using OpenAI GPT APIs versus fine-tuned Llama models &#8211; GPT tends to achieve higher quality with zero-shot usage, whereas open models can be customized and optimized for cost-efficiency. To serve LLMs in production, <strong>inference optimizations</strong> are essential. Techniques like model quantization (8-bit or 4-bit weights) can reduce GPU memory and latency with minimal quality loss, enabling deployment of larger models at lower cost. Model distillation is another strategy: a smaller model is trained to imitate a large model&#8217;s outputs, significantly cutting down runtime cost at some accuracy trade-off. Other optimizations include prompt truncation or retrieval filtering (to limit token count), batching multiple requests for throughput, and using high-performance inference engines or model serving frameworks (e.g. Hugging Face Transformers with Accelerate or vLLM). The goal is to meet latency SLAs and scale horizontally (multiple replicas or sharded models) without sacrificing answer quality or skyrocketing costs.</p><h2><strong>Response Generation and Answer Ranking</strong></h2><p>Once relevant context passages are retrieved, they are appended to the user query (often as a prompt) and fed to the LLM for <strong>response generation</strong>. The LLM uses the provided context to produce a grounded answer that cites or incorporates facts from the retrieval. This generation step is where the RAG system delivers added value: by combining the LLM&#8217;s language fluency with factual grounding from documents, the system greatly <strong>reduces hallucinations</strong> and increases answer accuracy. Best practices include formatting the prompt with clear separators between chunks, and possibly indicating source metadata so the LLM can refer to or quote them. Some production RAG architectures also implement an <strong>answer ranking or verification</strong> mechanism. For instance, the system might generate multiple candidate answers (varying wording or using different top-k retrievals) and then rank them, or use a separate verifier model to cross-check the answer against the source text. Another approach is to let the LLM itself "reflect" on its answer or rate its confidence (as seen in some 2024 research that routes queries between RAG vs. long-context based on self-reflection (<a href="https://aclanthology.org/2024.emnlp-industry.66/#:~:text=context%20,LLMs%20using%20RAG%20and%20LC%5D">Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach - ACL Anthology</a>). These ranking and verification steps, while adding complexity, can further improve reliability by ensuring the final answer is supported by the retrieved evidence and is the best among alternatives.</p><h2><strong>System Monitoring and Maintenance</strong></h2><p>Building a production-grade RAG system requires ongoing <strong>monitoring and maintenance</strong> after deployment. One aspect is performance monitoring: tracking query latency (for both retrieval and generation), throughput, and uptime of the vector database and LLM services. Another critical aspect is <strong>quality monitoring</strong> &#8211; measuring answer accuracy, detecting hallucinations or irrelevant answers, and logging user feedback. Techniques like automated evals or spot-checking responses against known ground truth can alert engineers to degradation. Maintaining the knowledge corpus is an active process as well. RAG systems shine in allowing continuous knowledge updates (<a href="https://arxiv.org/abs/2312.10997#:~:text=,comprehensive%20review%20paper%20offers%20a"> Retrieval-Augmented Generation for Large Language Models: A Survey</a>), so workflows for adding new documents, re-embedding updated content, and pruning outdated information are necessary to keep the system&#8217;s knowledge current. Regular re-indexing or incremental indexing of new data (possibly using background jobs or streaming ingestion) ensures the retrieval component stays up-to-date. Additionally, one must manage the drift of embeddings or model changes &#8211; for example, if a new embedding model is adopted for better semantic representations, a re-embedding of all documents might be required. Logging and analytics can help identify popular queries and potential gaps in the knowledge base, guiding further data ingestion or fine-tuning. Security and privacy maintenance is also key: controlling access to sensitive documents and monitoring for data leaks in generated text. Overall, a production RAG system is not set-and-forget; it demands careful monitoring and iteration to maintain its accuracy and efficiency over time.</p><h2><strong>Popular Frameworks and Tools</strong></h2><p>Building RAG pipelines has been simplified by various open-source frameworks and tools:</p><ul><li><p>LangChain &#8211; A framework that provides components to chain LLMs with retrieval. It simplifies constructing the RAG pipeline (ingestion, vector store connection, prompt templating) with minimal code. LangChain supports multiple vector DB integrations and LLM providers out of the box.</p></li><li><p><strong>LlamaIndex (GPT Index)</strong> &#8211; Another library focused on document ingestion and index creation. It offers higher-level abstractions for chunking, indexing (often using underlying vector stores like FAISS or Qdrant), and querying, making it easier to manage large knowledge bases.</p></li><li><p>FAISS &#8211; A library for efficient vector similarity search. FAISS can be used standalone (in-memory or on-disk indexes) and is often employed under the hood by other tools for its fast ANN search implementations.</p></li><li><p>Weaviate &#8211; A popular open-source vector database that can be self-hosted or used as a managed service. It supports scalability (sharding/replication), filtering with hybrid (vector + keyword) queries, and offers a GraphQL API for queries (<a href="https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking#:~:text=,while%20ChromaDB%20needs%20custom%20setup">Optimizing RAG with Hybrid Search &amp; Reranking | VectorHub by Superlinked</a>).</p></li><li><p><strong>OpenAI API</strong> &#8211; Provides access to pretrained LLMs (GPT-3.5, GPT-4) and embedding models. Many RAG systems use OpenAI&#8217;s <code>text-embedding-ada-002</code> to vectorize text for retrieval, and then call a GPT model for generation. This offers strong performance without managing model infrastructure, though it comes with usage costs and latency considerations.</p></li><li><p><strong>Hugging Face Transformers</strong> &#8211; An ecosystem for open-source models. It provides a hub of LLMs (e.g. Flan-XXL, Llama2 variants) and tools like <code>transformers</code> pipelines or the <code>text-generation-inference</code> server for deploying models. Along with libraries like SentenceTransformers (for embedding generation), these tools allow building RAG with custom models and local inference. Hugging Face datasets and evaluation tools can also assist in benchmarking RAG system performance.</p></li><li><p>Haystack &#8211; (By deepset) A specialized framework for QA and RAG systems that supports document stores, retrievers (BM25, DPR, embeddings), and generator models. It provides an end-to-end solution with components that can be swapped out (e.g., use FAISS or Elastic search as backend, use a Transformers model for generation), suitable for production use cases.</p></li></ul><p>These frameworks and tools provide building blocks so developers don't have to start from scratch, and they incorporate many best practices from the community.</p><h2><strong>Performance Optimizations and Trade-offs</strong></h2><p>Achieving an optimal balance of <strong>cost, latency, scalability, and accuracy</strong> is a core theme in recent RAG literature. Key optimization strategies include:</p><ul><li><p><strong>Index Efficiency</strong>: Use approximate indexing structures (HNSW, IVF) to speed up retrieval, at the cost of a slight recall drop. Tune the index parameters (graph efSearch, number of centroids, etc.) to balance latency and accuracy for your data size.</p></li><li><p><strong>Adaptive Retrieval</strong>: Dynamically adjust how many documents to retrieve based on query complexity. For straightforward queries, retrieving fewer passages keeps the prompt short (lower latency and cost), whereas complex queries may justify a broader sweep.</p></li><li><p>Caching: Cache intermediate results where possible. For instance, cache embeddings of frequently seen queries or documents, and even cache final answers for recurring questions (FAQ-style usage) to directly serve without hitting the LLM each time.</p></li><li><p><strong>Model Pruning &amp; Quantization</strong>: Leverage smaller or optimized models when appropriate. A quantized 8-bit model can drastically cut inference time and memory usage with minor impact on answer quality. Some production setups use a two-tier model approach: a lightweight model handles simple queries, while a large model is reserved for only the hardest queries (reducing average cost).</p></li><li><p><strong>Batching and Parallelism</strong>: Batch multiple retrieval or generation requests together if using GPU-backed services to improve throughput. Also distribute the vector index across multiple nodes (sharding) for parallel search on very large corpora, which improves scalability linearly.</p></li><li><p><strong>Hybrid Retrieval Trade-offs</strong>: Combining lexical and vector search can slightly increase retrieval time due to dual queries, but it often improves answer accuracy, reducing expensive follow-up questions. There is a trade-off in complexity and maintenance, but hybrid methods can yield better precision for enterprise data (<a href="https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking#:~:text=,GAN%20abbreviations%20and%20person%20names">Optimizing RAG with Hybrid Search &amp; Reranking | VectorHub by Superlinked</a>).</p></li><li><p><strong>Monitoring &amp; Tuning</strong>: Continuously monitor performance metrics. Identify bottlenecks (e.g. if retrieval is fast but LLM generation dominates latency, focus on optimizing the model or prompt length). Use this data to tune components&#8212;such as reducing chunk size if too much irrelevant text is being pulled in, or increasing vector dimensions if semantic search isn&#8217;t accurate enough.</p></li></ul><p>Every design choice involves trade-offs. For example, using a larger LLM improves accuracy but increases cost and latency, whereas a smaller model or distilled model is cheaper but might require more retrieved context to compensate for knowledge gaps. The 2024 EMNLP study comparing RAG vs. long-context LLMs underscores such trade-offs: long-context models can outperform RAG given sufficient resources, but RAG remains far more cost-efficient for most use cases (<a href="https://aclanthology.org/2024.emnlp-industry.66/#:~:text=context%20,LLMs%20using%20RAG%20and%20LC">Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach - ACL Anthology</a>). Engineers must balance these factors based on application requirements, often iteratively tuning the system to reach a satisfactory equilibrium.</p><h2><strong>Recent Research and Advancements (2024&#8211;2025)</strong></h2><p>Recent literature (2024&#8211;2025) has enriched the RAG paradigm with new insights and techniques. A comprehensive survey by Gao et al. (2024) formalized RAG evolution into <em>Naive</em>, <em>Advanced</em>, and <em>Modular RAG</em> paradigms (<a href="https://arxiv.org/html/2407.21059v1#:~:text=In%20this%20context%2C%20this%20paper,the%20paper%20explores%20the%20potential">Modular RAG: Transforming RAG Systems into LEGO-like Reconfigurable Frameworks</a>). <em>Naive RAG</em> refers to the basic retrieve-then-generate setup, <em>Advanced RAG</em> adds enhancements like feedback loops or joint retriever-generator training, and <em>Modular RAG</em> proposes a LEGO-like reconfigurable pipeline where components (retrieval, generation, reranking, etc.) can be arranged in flexible patterns to handle complex workflows . This modular view is aimed at addressing the increasing complexity of real-world systems that require conditional logic (e.g. different retrieval methods per query type) and integration of additional modules like translators or reasoning engines.</p><p>Another thread of research explores the intersection of RAG with <strong>long-context LLMs</strong>. As transformer models with 16k+ or even 100k token contexts emerge, one question is whether feeding documents directly (long context) might replace retrieval. An EMNLP 2024 study found that extremely large-context models can surpass RAG in accuracy if context windows are fully utilized, but RAG is far more cost-effective for large knowledge bases (<a href="https://aclanthology.org/2024.emnlp-industry.66/#:~:text=context%20,LLMs%20using%20RAG%20and%20LC">Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach - ACL Anthology</a>). Follow-up work proposes hybrid systems that route queries to either a RAG pipeline or a long-context model depending on the query&#8217;s complexity and the availability of relevant context, achieving better efficiency while retaining accuracy .</p><p>Improving the retrieval quality itself is another focus. Chan et al. (2024) introduced <strong>RQ-RAG (Refine Query RAG)</strong>, which has the LLM refine or decompose user queries before retrieval (<a href="https://arxiv.org/abs/2404.00610#:~:text=Generation%20,Our%20experimental%20results"> RQ-RAG: Learning to Refine Queries for Retrieval Augmented Generation</a>). By clarifying ambiguous questions or breaking complex questions into sub-queries, the system retrieves more relevant passages, yielding better answers. Their approach showed a 1.9% gain over state-of-the-art on complex QA benchmarks using a Llama2-based RAG . This indicates that smarter query processing can enhance RAG without changing the underlying knowledge corpus.</p><p>Researchers are also looking at jointly optimizing retrievers and generators. Rather than treating retrieval and generation as separate, some methods train them together end-to-end, so that the retriever selects passages that the generator truly finds useful. There&#8217;s emerging work on using feedback signals (like whether the generated answer was correct) to update the retriever, creating a reinforcement loop for continual learning (<a href="https://arxiv.org/abs/2312.10997#:~:text=RAG%2C%20the%20Advanced%20RAG%2C%20and,avenues%20for%20research%20and%20development"> Retrieval-Augmented Generation for Large Language Models: A Survey</a>). Additionally, new evaluation benchmarks specific to RAG have been proposed to measure not just answer accuracy but also faithfulness to sources and the correctness of citations .</p><p>In summary, the latest RAG research is pushing the envelope on multiple fronts: extending context through hybrid LLM approaches, refining queries and retrieval for better precision, making system architectures more modular and adaptable, and ensuring evaluations capture the unique benefits of retrieval augmentation. These advancements aim to make production-grade RAG systems more accurate, efficient, and reliable, bridging the gap between static trained models and the dynamic, knowledge-rich applications they serve.</p>]]></content:encoded></item><item><title><![CDATA[Fine-Tuning Architectures (PEFT) for LLMs]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/fine-tuning-architectures-peft-for</link><guid isPermaLink="false">https://www.rohan-paul.com/p/fine-tuning-architectures-peft-for</guid><pubDate>Mon, 16 Jun 2025 09:13:53 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!sb6K!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!sb6K!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!sb6K!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png 424w, https://substackcdn.com/image/fetch/$s_!sb6K!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png 848w, https://substackcdn.com/image/fetch/$s_!sb6K!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png 1272w, https://substackcdn.com/image/fetch/$s_!sb6K!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!sb6K!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png" width="1024" height="572" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/eeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:572,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1021486,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166053401?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!sb6K!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png 424w, https://substackcdn.com/image/fetch/$s_!sb6K!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png 848w, https://substackcdn.com/image/fetch/$s_!sb6K!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png 1272w, https://substackcdn.com/image/fetch/$s_!sb6K!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feeb034bd-d28a-4533-94ea-b71842628cb3_1024x572.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><ul><li><p>Fine-Tuning Architectures (PEFT) for LLMs</p></li><li><p>Retrieval-Augmented Generation (RAG)</p></li><li><p>Adapters and Modular Architectures in LLMs</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><p><strong>Parameter-Efficient Fine-Tuning (PEFT)</strong> methods enable adapting large language models by updating only small additional parameters instead of all model weights (<a href="https://arxiv.org/pdf/2403.14608#:~:text=that%20are%20strategically%20positioned%20within,approaches%20involve%20the%20insertion%20of">HERE</a>). This drastically reduces memory and compute needed for fine-tuning. Popular PEFT techniques include low-rank adaptation and prompt/adapters injection. Key approaches in recent research (2024&#8211;2025) are:</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><ul><li><p><strong>LoRA (Low-Rank Adaptation):</strong> Introduces trainable <em>low-rank</em> update matrices into the model&#8217;s layers (e.g. replacing a weight W with W+BA, where B and A<em> </em>are small matrices of rank r&#8810;dim(W)). The original model weights stay frozen, and only these adapter matrices are learned . This <strong>bottleneck adapter</strong> structure (down-project then up-project with residual) allows the model to be fine-tuned with only a few million parameters. Once training is done, the low-rank weights are merged with the base model with no latency penalty. Variants like AdaLoRA and DyLoRA further improve LoRA by <em>dynamically adjusting the rank</em> per layer during training to allocate capacity where needed, enhancing efficiency on a fixed parameter budget (e.g. training on a range of ranks instead of a fixed rank) .</p></li><li><p><strong>QLoRA (Quantized LoRA):</strong> A 2023 method that combines quantization with LoRA to minimize memory usage. QLoRA first <strong>quantizes the pretrained model to 4-bit weights</strong>, then fine-tunes using LoRA adapters on top of this compressed model (<a href="https://arxiv.org/abs/2305.14314#:~:text=,new%20data%20type%20that%20is"> QLoRA: Efficient Finetuning of Quantized LLMs</a>). Gradients are backpropagated through the frozen 4-bit model into the low-rank adapters. This approach preserves full 16-bit fine-tuning quality while allowing, for example, a 65B model to be finetuned on a single 48GB GPU . QLoRA introduced techniques like a new 4-bit NormalFloat data type and double quantization to maintain accuracy with aggressive compression. It achieved near state-of-the-art results on benchmarks with a fraction of the hardware. Recent research pushes this further: <strong>LowRA (2025)</strong> demonstrated accurate LoRA fine-tuning with effective precision <em>below 2 bits per parameter</em>, by using fine-grained mixed-precision assignments and custom kernels (<a href="https://arxiv.org/html/2502.08141v1#:~:text=To%20unleash%20the%20full%20potential,each%20of%20the%20three%20challenges">LowRA: Accurate and Efficient LoRA Fine-Tuning of LLMs under 2 Bits</a>) . This cuts memory usage dramatically (30&#8211;50% less memory than 4-bit LoRA) with minimal performance loss .</p></li></ul><p><strong>Fine-Tuning with Hugging Face PEFT (Example):</strong> Below is a Python example using Hugging Face Transformers and the PEFT library to apply LoRA fine-tuning to an LLM. The base model is loaded in 4-bit precision (using <a href="https://github.com/TimDettmers/bitsandbytes">bitsandbytes</a> for quantization) and then wrapped with a LoRA adapter configuration:</p><pre><code><code>from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer
from peft import LoraConfig, get_peft_model, TaskType

## Load a base model in 4-bit (quantized) mode
model_name = "facebook/opt-1.3b"  # example base model
base_model = AutoModelForCausalLM.from_pretrained(
    model_name, load_in_4bit=True, device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)

## Prepare a LoRA config (low-rank adaptation)
lora_config = LoraConfig(
    task_type=TaskType.CAUSAL_LM, r=16, lora_alpha=32, lora_dropout=0.1,
    target_modules=["q_proj", "v_proj"]  # apply LoRA to attention projection matrices
)
## Wrap the base model with the LoRA adapters
model = get_peft_model(base_model, lora_config)
print("Trainable parameters:", model.print_trainable_parameters())

## ... (Prepare training data) ...
training_args = TrainingArguments(output_dir="outputs", per_device_train_batch_size=4, num_train_epochs=3)
trainer = Trainer(model=model, args=training_args, train_dataset=my_dataset, tokenizer=tokenizer)
trainer.train()
</code></code></pre><p>This code freezes the core model weights and inserts LoRA adapter weights into the query/value projection of each transformer layer. Only the LoRA adapter parameters (a few million vs. billions in the full model) will be updated during training, making fine-tuning memory-efficient.</p><h2><strong>Retrieval-Augmented Generation (RAG)</strong></h2><p>RAG architectures enhance LLMs by coupling them with a <strong>retrieval system</strong> to ground generation on external data. The model is augmented with a <em>non-parametric memory</em> (e.g. a vector database of documents or knowledge) and an embedding-based retriever (<a href="https://arxiv.org/abs/2312.10997#:~:text=,comprehensive%20review%20paper%20offers%20a"> Retrieval-Augmented Generation for Large Language Models: A Survey</a>). This helps mitigate hallucinations and provide up-to-date or domain-specific information beyond the LLM&#8217;s fixed training data.</p><p><strong>How RAG Works:</strong> At query time, the system converts the user query into an embedding and performs a <strong>vector similarity search</strong> over the external database (using tools like FAISS, ScaNN, etc.) to fetch relevant text passages. These retrieved passages are then fed into the LLM alongside the original query to <strong>augment the context</strong>. The LLM&#8217;s generation is conditioned on both its internal knowledge and the retrieved evidence, leading to more factual and informed responses . In essence, RAG <em>merges the LLM&#8217;s parametric knowledge with a large external knowledge store</em>, allowing continuous updates and reducing the model&#8217;s reliance on stale training data .</p><p>A typical RAG pipeline involves the following steps:</p><ol><li><p><strong>Embedding &amp; Retrieval:</strong> Encode the input query into a vector and query the vector store for nearest neighbors. The vector store (e.g. a FAISS index) holds embeddings of proprietary documents or knowledge base entries. It returns the top-k<em>k</em> relevant documents based on cosine similarity or inner product.</p></li><li><p><strong>Augmentation:</strong> The retrieved documents (or their relevant snippets) are then combined with the original query, for example by prepending them to the prompt or as separate input segments. Some architectures feed the documents through an encoder and give the LLM cross-attention to those encoder representations (as in the original RAG model by Lewis et al., 2020). Simpler implementations just concatenate the text.</p></li><li><p><strong>Generation:</strong> The LLM generates an answer conditioned on the query plus the retrieved context. The generation mechanism remains the same (e.g. causal decoding), but the presence of retrieved facts helps ensure accuracy and allows referencing information not stored in the model weights.</p></li></ol><p>Modern RAG systems often use a <em>distributed vector database</em> (like FAISS, Milvus, etc.) to store and query embeddings efficiently, enabling retrieval in a few milliseconds even for millions of documents. The retrieval component can be updated independently (e.g. adding new documents) without retraining the LLM, making RAG attractive for enterprise use with proprietary data.</p><p><strong>Latest Advancements:</strong> Research in 2024 has introduced <strong>adaptive retrieval</strong> techniques that make the retrieval step more context-aware. For example, the model can <strong>decide whether or not to retrieve</strong> for a given query, to avoid distracting the LLM with external text it already knows. Huang et al. (2024) propose an <em>Adaptive RAG</em> approach that retrieves <em>only when the query asks for knowledge the LLM lacks</em>. They determine this by inspecting the LLM&#8217;s own token embedding space: if the internal embeddings suggest the answer is not in the model&#8217;s stored knowledge, then trigger retrieval (<a href="https://arxiv.org/abs/2404.03514#:~:text=competent%20in%20various%20NLP%20tasks,such%20embeddings%20capture%20rich%20information"> Embedding-Informed Adaptive Retrieval-Augmented Generation of Large Language Models</a>). This embedding-informed strategy lets the system skip retrieval for questions the model can answer on its own, improving efficiency and not degrading answers with unnecessary context. Similarly, Liu et al. (2024) develop an <strong>inherent confidence-based controller</strong> that monitors the LLM&#8217;s certainty during generation and triggers retrieval only when confidence is low (<a href="https://arxiv.org/abs/2405.18727#:~:text=solution%20for%20mitigating%20hallucinations%20of,We%20also"> CtrlA: Adaptive Retrieval-Augmented Generation via Inherent Control</a>). These adaptive retrieval models dynamically switch between pure generation and retrieval-augmented generation, achieving a better balance of accuracy vs. speed. Other improvements include training retrievers end-to-end with the LLM (so the retriever learns to fetch what the model truly needs) and employing multi-hop retrieval for complex queries. Emerging systems like <strong>Open-RAG (2024)</strong> even integrate a mixture-of-experts mechanism to let the model reason over retrieved evidence in multiple steps (<a href="https://arxiv.org/abs/2410.01782#:~:text=capabilities%20in%20RAG%20with%20open,a%20hybrid%20adaptive%20retrieval%20method"> Open-RAG: Enhanced Retrieval-Augmented Reasoning with Open-Source Large Language Models</a>), illustrating the trend of tightly coupling retrieval with the model&#8217;s reasoning module.</p><p><strong>RAG Implementation Example (FAISS):</strong> Below is a simple example demonstrating how to use a vector store for RAG. We use FAISS to index document embeddings and retrieve relevant text for a query, then show how it can be fed to an LLM:</p><pre><code><code>import faiss
import numpy as np

## Suppose we have document embeddings and their texts
document_embeddings = np.load("doc_embeds.npy")   # shape (N_docs, dim)
documents = open("documents.txt").read().splitlines()  # list of N_docs texts

## Build a FAISS index for efficient similarity search
dim = document_embeddings.shape[1]
index = faiss.IndexFlatIP(dim)  # using inner-product similarity
index.add(document_embeddings)

## Encode a user query into the same embedding space (using a suitable embedding model)
query = "What are the revenue projections for product X in 2025?"
query_embedding = embed_model.encode(query)       # embed_model: e.g. SentenceTransformer or LLM embedding
query_embedding = query_embedding.reshape(1, -1)

## Retrieve top-5 most similar documents
D, I = index.search(query_embedding, k=5)
retrieved_texts = [documents[i] for i in I[0]]
print("Top documents:\n", retrieved_texts)

## Augment the query with retrieved context for the LLM
augmented_prompt = query + "\n" + "\n".join(retrieved_texts)
response = llm_model.generate(augmented_prompt)
print("LLM Response:", response)
</code></code></pre><p>In this snippet, <code>embed_model</code> could be a transformer model that generates embeddings (e.g. <code>InstructorXL</code> or a smaller LLM used for embedding). We add all document embeddings to a FAISS index and then find the nearest neighbors to the query. The retrieved texts are concatenated to the query before passing into <code>llm_model</code> for generation. In practice, one might use a dedicated <code>RagRetriever</code> and <code>RagSequenceForGeneration</code> model (as available in &#129303; Transformers) which handle the retrieval and generation steps in one framework. The example above illustrates the core idea: <strong>use vector similarity search to supply an LLM with external knowledge</strong>, enabling customized Q&amp;A or generation based on proprietary data.</p><h2><strong>Adapters and Modular Architectures in LLMs</strong></h2><p>Adapters are lightweight neural modules inserted into an LLM&#8217;s architecture to allow efficient customization <strong>without altering the core model weights</strong>. During fine-tuning, only the adapter parameters are trained (the original pretrained weights remain frozen), greatly reducing the number of updated parameters and preserving the base model for reus (<a href="https://arxiv.org/pdf/2403.14608#:~:text=that%20are%20strategically%20positioned%20within,approaches%20involve%20the%20insertion%20of">HERE</a>). After training, the adapter can be <em>plugged in</em> to modify the model&#8217;s behavior on a new task or domain. This modular design means multiple adapters (for different tasks or data domains) can be attached to the same base LLM as needed.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!BZVS!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!BZVS!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png 424w, https://substackcdn.com/image/fetch/$s_!BZVS!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png 848w, https://substackcdn.com/image/fetch/$s_!BZVS!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png 1272w, https://substackcdn.com/image/fetch/$s_!BZVS!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!BZVS!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png" width="929" height="476" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f534ed15-de9d-434d-a600-582446f19c2e_929x476.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:476,&quot;width&quot;:929,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:127445,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166053401?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!BZVS!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png 424w, https://substackcdn.com/image/fetch/$s_!BZVS!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png 848w, https://substackcdn.com/image/fetch/$s_!BZVS!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png 1272w, https://substackcdn.com/image/fetch/$s_!BZVS!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff534ed15-de9d-434d-a600-582446f19c2e_929x476.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong>Prefix and Prompt Tuning:</strong> Another modular customization approach is <em>prefix tuning</em>, which does not add new layers but instead prepends learnable vectors to the model&#8217;s input at each layer. In <strong>prefix tuning</strong>, a set of trained continuous vectors are inserted as a prefix to the key and value sequences in the self-attention mechanism of every transformer layer (<a href="https://arxiv.org/pdf/2403.14608#:~:text=Prefix,43%5D%20removes%20reparameterization%20and">HERE</a>). The model treats these as additional &#8220;virtual&#8221; tokens that guide the attention, effectively priming the model for the new task. Only these prefix vectors are trained (often through a small MLP that generates them), and after training, they are stored (on the order of a few thousand parameters) and the model uses them to influence generation. This technique can store <em>1000&#215; fewer parameters</em> than fine-tuning the whole model, enabling one LLM to support many tasks by switching out prefixes (<a href="https://huggingface.co/docs/peft/main/en/task_guides/seq2seq-prefix-tuning#:~:text=Prefix%20tuning%20is%20an%20additive,language%20model%20for%20many%20tasks">Prefix tuning for conditional generation</a>). Variants like <strong>prompt tuning</strong> or <strong>P-tuning</strong> operate similarly but often only add learnable tokens at the input layer instead of every layer. These methods shine especially with very large models (billions of parameters) where tuning a few tokens can effectively steer the model. Recent research has also introduced <strong>adaptive prefix tuning</strong> (APT), which learns per-layer gating to adjust the influence of the prefix at different layers , further improving efficiency and control.</p><p><strong>Control Mechanisms &amp; Dynamic Adapters:</strong> <em>Dynamic adapters</em> refer to adapter modules that are conditionally applied or whose configuration changes based on the input. Instead of a one-size-fits-all adapter, the model can <strong>select different adapter &#8220;experts&#8221; or settings on the fly</strong>. This idea is often implemented with a <strong>Mixture-of-Experts (MoE)</strong> or gating mechanism. For example, multiple LoRA or adapter modules might be trained (each specializing in a subset of data or a particular style), and a gating network chooses which adapter to apply for a given input segment. Liu et al. (2024) describe dynamic adapters as <em>&#8220;conditionally computed lightweight adapters&#8221;</em> that allow <strong>selective fine-tuning</strong> of the model and greatly increase adaptability (<a href="https://arxiv.org/html/2405.17741v1#:~:text=facilitating%20efficient%20model%20customization%20and,increases%20its%20adaptability%20and%20capacity">LoRA-Switch: Boosting the Efficiency of Dynamic LLM Adapters via System-Algorithm Co-design</a>). By retaining the pretrained model&#8217;s original weights and only swapping in different adapters or combining their outputs, the model can handle a wider range of tasks or domains without a separate full model for each. This modular approach was shown to maintain the base model&#8217;s strengths while substantially boosting capacity on new tasks .</p><p>One challenge with dynamic or multiple adapters is the potential overhead of routing and combining experts at runtime. Recent work has addressed this with system-level optimizations. <strong>LoRA-Switch (2024)</strong>, for instance, introduced a token-wise routing mechanism that merges the chosen low-rank adapters for each token into the model weight during inference, thereby avoiding multiple sequential passes per layer . This brought the latency overhead of dynamic MoE adapters down significantly (improving decoding speed ~2.4&#215;) while preserving their accuracy gain . Such advances indicate that adapter-based tuning can scale not just in parameter efficiency but also in runtime efficiency, making it practical to deploy <strong>multiple adaptive experts</strong> within an LLM.</p><p><strong>Integrating Adapters &#8211; Example:</strong> Using the &#129303; <em>peft</em> library, we can attach an adapter to a pretrained model with just a few lines of code. For example, to apply <strong>prefix tuning</strong> on a GPT-2 model:</p><pre><code><code>from transformers import AutoModelForCausalLM
from peft import PrefixTuningConfig, get_peft_model, TaskType

base_model = AutoModelForCausalLM.from_pretrained("gpt2-medium")
## Configure prefix tuning: e.g., 20 virtual tokens as prefix in each layer
prefix_config = PrefixTuningConfig(task_type=TaskType.CAUSAL_LM, num_virtual_tokens=20)
## Wrap the model with the prefix tuning adapter
model_with_prefix = get_peft_model(base_model, prefix_config)

## Now model_with_prefix has additional prefix-tuning parameters that can be trained.
print("Added prompt param count:", model_with_prefix.peft_config.num_virtual_tokens * base_model.config.n_layer)
</code></code></pre><p>In this snippet, <code>PrefixTuningConfig</code> defines the adapter type (for a causal language model) and the length of the prefix. <code>get_peft_model</code> injects the prefix tuning vectors into each transformer layer of GPT-2. We could then fine-tune <code>model_with_prefix</code> on a new task (e.g. domain-specific text generation) &#8211; only the prefix vectors (and possibly a small MLP if configured) will be updated during training. The core GPT-2 weights remain untouched. After training, the prefix adapter (which might be only a few thousand parameters) can be stored or shared, and applied to the GPT-2 model whenever we want it to perform the new task. Similarly, other adapter types (LoRA, AdaLora, etc.) can be integrated by choosing the appropriate <code>PeftConfig</code>. This modular approach allows <strong>customizing large models with proprietary data</strong> in a lightweight manner, reusing the same base LLM for many purposes by simply loading different adapters as needed.</p><p><strong>References:</strong> Recent surveys and papers provide comprehensive overviews of these techniques, for example <em>He et al., 2024</em> on PE (<a href="https://arxiv.org/pdf/2403.14608#:~:text=In%20this%20survey%2C%20we%20systematically,detail%20additive%20algo%02rithms%20that%20either">HERE</a>) and <em>Gao et al., 2024</em> on R (<a href="https://arxiv.org/abs/2312.10997#:~:text=,comprehensive%20review%20paper%20offers%20a"> Retrieval-Augmented Generation for Large Language Models: A Survey</a>), as well as specific works like <em>Dettmers et al., 2023</em> for QLo (<a href="https://arxiv.org/abs/2305.14314#:~:text=,new%20data%20type%20that%20is"> QLoRA: Efficient Finetuning of Quantized LLMs</a>), <em>Huang et al., 2024</em> for adaptive R (<a href="https://arxiv.org/abs/2404.03514#:~:text=competent%20in%20various%20NLP%20tasks,such%20embeddings%20capture%20rich%20information"> Embedding-Informed Adaptive Retrieval-Augmented Generation of Large Language Models</a>), and <em>Liu et al., 2024</em> for dynamic adapters (<a href="https://arxiv.org/html/2405.17741v1#:~:text=facilitating%20efficient%20model%20customization%20and,increases%20its%20adaptability%20and%20capacity">LoRA-Switch: Boosting the Efficiency of Dynamic LLM Adapters via System-Algorithm Co-design</a>). These advancements from 2024&#8211;2025 underscore a common theme: <strong>efficiently fine-tuning and extending LLMs by isolating small, trainable components</strong> (low-rank matrices, prefixes, or adapters) while leveraging powerful pretrained models as unchanged backbones. This enables organizations to <strong>customize LLMs with proprietary data</strong> and domain knowledge at low cost, and to continually update or switch out those customizations without retraining or serving an entire new model each time. The result is a flexible, modular LLM paradigm combining the strengths of large foundation models with the agility of smaller task-specific adaptations.</p>]]></content:encoded></item><item><title><![CDATA[Recent Advancements in Reasoning-Optimized LLMs and Inference-Time Compute Scaling]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/recent-advancements-in-reasoning</link><guid isPermaLink="false">https://www.rohan-paul.com/p/recent-advancements-in-reasoning</guid><pubDate>Mon, 16 Jun 2025 09:06:20 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!B_Bv!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!B_Bv!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!B_Bv!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png 424w, https://substackcdn.com/image/fetch/$s_!B_Bv!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png 848w, https://substackcdn.com/image/fetch/$s_!B_Bv!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png 1272w, https://substackcdn.com/image/fetch/$s_!B_Bv!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!B_Bv!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png" width="1024" height="610" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/d30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:610,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1112417,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166053233?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!B_Bv!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png 424w, https://substackcdn.com/image/fetch/$s_!B_Bv!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png 848w, https://substackcdn.com/image/fetch/$s_!B_Bv!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png 1272w, https://substackcdn.com/image/fetch/$s_!B_Bv!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd30bdf77-0b14-4772-b918-4e0548863ec0_1024x610.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ul><li><p>Introduction and Background</p></li><li><p>Four Main Approaches to Improving LLM Reasoning</p></li><li><p>Inference-Time Compute Scaling Methods</p><ul><li><p>s1: Simple Test-Time Scaling - Budget Forcing with Wait Tokens</p></li><li><p>Test-Time Preference Optimization (TPO)</p></li><li><p>Thoughts Are All Over the Place - Mitigating Underthinking</p></li><li><p>Trading Inference-Time Compute for Adversarial Robustness</p></li><li><p>Chain-of-Associated-Thoughts (CoAT)</p></li><li><p>Step Back to Leap Forward - Self-Backtracking</p></li><li><p>Scaling Up Test-Time Compute with Latent Reasoning</p></li><li><p>Can a 1B LLM Surpass a 405B LLM - Compute-Optimal Scaling</p></li><li><p>Inference-Time Computations for Reasoning and Planning - Benchmark &amp; Insights</p></li><li><p>Inner Thinking Transformer (ITT) - Dynamic Depth Allocation</p></li><li><p>Test-Time Scaling for Code Generation (S*)</p></li><li><p>Chain-of-Draft (CoD)</p></li></ul></li><li><p>Industry Applications and Framework Support</p></li><li><p>Trade-offs, Cost Considerations, and Emerging Trends</p></li></ul><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><h2><strong>Introduction and Background</strong></h2><p>Large language models (LLMs) have made great strides in complex reasoning tasks by generating and evaluating intermediate steps &#8211; an ability often called &#8220;reasoning&#8221; or &#8220;slow thinking.&#8221; Unlike basic Q&amp;A models that directly output an answer, reasoning-optimized LLMs break a problem into sub-steps or &#8220;thoughts&#8221; (sometimes explicitly shown as a chain of reasoning) before finalizing an answer (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=Since%20most%20readers%20are%20likely,coding%20challenges%2C%20and%20mathematical%20problems">The State of LLM Reasoning Models</a>). Recent research has focused on <em>improving LLM reasoning capabilities</em>, and in general there are two broad strategies: (1) <strong>increasing training compute</strong> (e.g. special training/fine-tuning to instill reasoning skills) or (2) <strong>increasing inference-time compute</strong> (allowing the model to do more work <em>at inference</em> to solve a query) . The latter, known as <em>inference-time scaling</em> or <em>test-time scaling</em>, is analogous to giving the model more &#8220;time to think&#8221; when answering a question . This review concentrates on recent advances in inference-time compute scaling techniques for reasoning, especially those emerging <em>after the release of DeepSeek R1 in January 2025</em> . We will first outline the main categories of methods for improving reasoning in LLMs, then dive into detailed developments in inference-time scaling, followed by industry applications, code examples, and analysis of trade-offs.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Four Main Approaches to Improving LLM Reasoning</strong></h2><p>Current methods to enhance reasoning in LLMs can be grouped into four main approaches (often used in combination) :</p><ol><li><p><strong>Inference-Time Compute Scaling</strong> &#8211; Techniques that improve reasoning <em>without changing model weights</em>, by using more computation during inference (e.g. generating multiple solutions or multi-step reasoning per query). These methods trade extra compute for better answers and can, in principle, be applied to any pretrained model (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=1.%20Inference">The State of LLM Reasoning Models</a>) . This category includes strategies like chain-of-thought prompting, self-consistency (majority voting), tree search, iterative refinement, etc., which effectively let the model &#8220;think longer&#8221; during generation.</p></li><li><p><strong>Reinforcement Learning (RL)</strong> &#8211; Training-based approaches where the model learns better reasoning via RL, using reward signals from problem-solving tasks (math, code, etc.). RL can encourage strategic thinking and self-correction abilities, as seen in OpenAI&#8217;s <em>o1</em> model (which used RL to achieve advanced reasoning) . Pure RL approaches can yield powerful reasoners but are challenging due to high compute cost and potential issues like reward hacking or instability .</p></li><li><p><strong>Hybrid RL + Supervised Fine-Tuning (SFT)</strong> &#8211; A combination of supervised training and reinforcement learning. Typically, the model is first <em>supervised-finetuned</em> on high-quality reasoning data (e.g. human-written solutions or chain-of-thoughts), then further refined with RL to target specific reasoning behaviors (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=3,tuning">The State of LLM Reasoning Models</a>). This hybrid can stabilize training (leveraging SFT to provide a strong base) while still using RL to push the model&#8217;s reasoning performance beyond what supervised data alone can achieve .</p></li><li><p><strong>Supervised Fine-Tuning and Distillation</strong> &#8211; Approaches that rely on supervised learning, sometimes augmented by <em>knowledge distillation</em>. Here an LLM is finetuned on curated reasoning datasets, which may be generated by a stronger model (making it a form of distillation) . For example, a large model&#8217;s chain-of-thought outputs can serve as training data to teach a smaller model to reason. This improves the smaller model&#8217;s reasoning by imitating the larger model&#8217;s thought process. (This differs from classic distillation in that often only final answers or explanations are used, not full logits .) Such methods yield models that inherently produce step-by-step solutions, albeit the <em>inference-time compute</em> they require scales with the length of those solutions (since longer answers mean more tokens) .</p></li></ol><p>All four approaches above aim to produce LLM &#8220;Reasoners&#8221; that can tackle multi-step problems like math word questions, coding challenges, logic puzzles, etc., by generating intermediate reasoning steps. Notably, approaches 2&#8211;4 (RL, RL+SFT, SFT/Distillation) result in models that <em>by design</em> output longer explanations or chains-of-thought, so they implicitly use more inference compute (longer outputs cost more) (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=Methods%202,correction%20mechanisms%2C%20or%20other%20methods">The State of LLM Reasoning Models</a>). However, our focus here is on methods that <em>explicitly control or increase inference-time computation</em> beyond just having a longer response . In the next section, we explore the latest <em>inference-time compute scaling methods</em> in detail, organized by specific techniques and papers.</p><h2><strong>Inference-Time Compute Scaling Methods</strong></h2><p>Inference-time scaling methods aim to boost reasoning by allocating more computation during the model&#8217;s response generation. Intuitively, this is like allowing an AI to use extra &#8220;brain power&#8221; on demand, much as a person might take more time or scratch paper to solve a hard problem. Techniques range from simple adjustments in decoding to complex multi-step search procedures. Below we review recent advancements (mostly from 2024&#8211;2025) in this area, including theoretical innovations and how they are implemented.</p><h3><strong>1. s1: Simple Test-Time Scaling - Budget Forcing with Wait Tokens</strong></h3><p>One notable work is <em>s1: Simple test-time scaling</em> (Muennighoff et al., 2025) (<a href="https://arxiv.org/abs/2501.19393#:~:text=,this%20version%2C%20v3"> s1: Simple test-time scaling</a>), which sought the simplest possible method to replicate the powerful reasoning seen in OpenAI&#8217;s o1 model. The technique they introduce is <strong>budget forcing</strong>, implemented via a special <em>&#8220;Wait&#8221; token</em> in the model&#8217;s outputs . The idea is straightforward: when the model is about to conclude an answer, it instead appends a &#8220;Wait...&#8221; prompt to itself, prompting additional reasoning before finalizing the answer. By inserting one or more &#8220;Wait&#8221; tokens, the model is forced to <em>lengthen its reasoning process</em> or, conversely, the generation can be forcefully stopped early to simulate a constrained &#8220;time budget&#8221; . This method acts like a knob to control how much the model thinks during inference. Importantly, the authors found that appending <em>&#8220;Wait&#8221; often makes the model double-check and correct its reasoning</em>, leading to higher accuracy . They created a small high-quality dataset (s1K) of 1,000 reasoning traces and <strong>supervised-finetuned</strong> a 32B-parameter model on it to respond to &#8220;Wait&#8221; appropriately . The resulting model <em>s1-32B</em>, equipped with budget forcing, achieved remarkable results: it <em>outperformed OpenAI&#8217;s o1-preview by up to 27%</em> on challenging math benchmarks (MATH and AIME24) . Moreover, by increasing the number of &#8220;Wait&#8221; tokens (i.e. scaling up inference steps), s1-32B&#8217;s performance could be extrapolated even beyond its finetuned capability &#8211; e.g. raising accuracy on AIME24 from 50% to 57% by allowing extra &#8220;thinking&#8221; time . In essence, <em>s1 demonstrated that even a relatively small custom dataset and a simple token-based control can yield a reasoning boost rivaling far larger models</em>, just by smartly allocating inference compute.</p><p><strong>Implementation strategy:</strong> The &#8220;Wait&#8221; token approach can be implemented by modifying the decoding loop. For example, one can monitor the generated tokens and if an end-of-answer is detected too early, inject a special token like <code>&lt;WAIT&gt;</code> and continue generation. Below is a simplified pseudocode illustrating the concept of <em>parallel</em> and <em>sequential</em> test-time scaling with a scoring function (representing a reward model or verification step):</p><pre><code><code>import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "your_reasoning_llm"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)

prompt = "Question: [some complex problem]? Solve step by step."
inputs = tokenizer(prompt, return_tensors='pt').to(model.device)

## Parallel inference-time scaling: generate N candidate answers (increased compute via multiple samples)
N = 5
outputs = model.generate(**inputs, do_sample=True, num_return_sequences=N, max_length=256)
candidates = [tokenizer.decode(output, skip_special_tokens=True) for output in outputs]

## Suppose we have a function score_answer(ans) -&gt; higher is better (could be a learned reward model)
best_answer = max(candidates, key=score_answer)

## Sequential inference-time scaling: if model tries to end early, append "Wait" and continue
response = ""
for step in range(5):  # allow up to 5 "Wait" extensions
    output = model.generate(**inputs, max_length=50)  # generate up to 50 tokens
    text = tokenizer.decode(output[0], skip_special_tokens=True)
    if "&lt;EOM&gt;" in text or "Final Answer:" in text:
        # If the model indicates an end-of-thought, append "Wait" token and continue generation
        inputs = tokenizer(prompt + text + " Wait.", return_tensors='pt').to(model.device)
        continue  # loop again to extend reasoning
    response = text
    break

print("Best answer (parallel):", best_answer)
print("Extended reasoning answer (sequential):", response)
</code></code></pre><p>In practice, frameworks like Hugging Face Transformers (built on PyTorch) make it easy to generate multiple outputs (<code>num_return_sequences=N</code>) and to manipulate prompts for iterative refinement as shown. The <em>score_answer</em> could be a separate reward model evaluating each candidate (<a href="https://research.ibm.com/blog/inference-scaling-reasoning-ai-model#:~:text=Anyone%20who%20has%20played%20with,answer%20with%20the%20highest%20score">Reasoning in Granite 3.2 using inference scaling - IBM Research</a>) .</p><h3><strong>2. Test-Time Preference Optimization (TPO)</strong></h3><p>While most inference scaling methods focus on <em>accuracy</em>, <em>Test-Time Preference Optimization (TPO)</em> (Li et al., 2025) targets <em>alignment</em>: guiding a model&#8217;s outputs to better match human preferences <strong>at inference time</strong>, without any weight updates (<a href="https://arxiv.org/abs/2501.12895#:~:text=,improves%20alignment%20with%20human%20preferences"> Test-Time Preference Optimization: On-the-Fly Alignment via Iterative Textual Feedback</a>). TPO is an <strong>iterative refinement framework</strong>: the model generates an initial answer, then a preference model or heuristic provides <em>textual feedback</em> (like a critique or suggestion) on that answer, and the model revises its output accordingly . Crucially, instead of using numerical reward signals or requiring RL training, TPO translates reward model outputs into <em>natural language feedback</em> (e.g. &#8220;The response should be more detailed on X, and avoid using Y language&#8221;) which the original LLM can understand and act on . By iterating this process (generate &#8594; get feedback &#8594; regenerate), the LLM &#8220;aligns&#8221; its response on the fly to the desired style, safety, or other preferences . Empirical evaluations showed that after only a few rounds of TPO, an initially <em>unaligned</em> model (Llama-3.1-70B-SFT) <strong>surpassed the performance of its aligned counterpart</strong> (Llama-3.1-70B-Instruct) on preference tests . In other words, TPO can take a vanilla model and make it perform like an instruction-tuned model <em>during inference</em>, simply by using feedback loops. It was also found to scale efficiently with the &#8220;search width and depth&#8221; &#8211; meaning more feedback iterations or exploring multiple drafts can further improve outcomes with manageable cost . TPO represents a novel use of inference-time compute for <em>on-the-fly alignment</em>, showing that even without additional training, an LLM can be <em>steered</em> toward preferable outputs through iterative self-correction.</p><h3><strong>3. Thoughts Are All Over the Place - Mitigating Underthinking</strong></h3><p>A January 2025 study by Wang et al. observed a shortcoming in advanced reasoning models like OpenAI&#8217;s o1: a tendency to rapidly jump between different solution paths without fully pursuing any &#8211; a phenomenon the authors term <strong>&#8220;underthinking&#8221;</strong> (<a href="https://arxiv.org/abs/2501.18585#:~:text=,like%20models%2C%20revealing%20that"> Thoughts Are All Over the Place: On the Underthinking of o1-Like LLMs</a>). Despite o1&#8217;s impressive multi-step reasoning, it often didn&#8217;t dig deep enough on promising paths, leading to shallow or incorrect answers on tough problems . In <em>Thoughts Are All Over the Place: On the Underthinking of o1-Like LLMs</em>, they systematically analyze this behavior and introduce a remedy: a decoding strategy with a <strong>Thought Switching Penalty</strong>, abbreviated <em>TIP</em> . TIP works by detecting when the model&#8217;s output is switching to a new line of thought (for example, abandoning a calculation midway to try a different approach) and slightly <em>penalizing</em> such switches in the model&#8217;s token probabilities (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=To%20address%20this%20%E2%80%9Cunderthinking%E2%80%9D%20issue%2C,discourage%20premature%20reasoning%20path%20transitions">The State of LLM Reasoning Models</a>). By reducing the likelihood of abruptly changing course, the model is encouraged to <strong>stick with a reasoning thread longer</strong> and explore it thoroughly before considering alternatives . This simple modification, implemented at inference, led to notable accuracy gains on challenging math datasets . Impressively, TIP required <em>no model retraining or fine-tuning</em> &#8211; it is a pure decoding-time intervention. The researchers reported that adding a thought-switch penalty improved correctness across multiple benchmarks, indicating the model was indeed delving deeper into problems and overcoming the &#8220;underthinking&#8221; issue . In sum, this work identifies that even state-of-the-art reasoners can suffer from <em>superficial reasoning</em>, and that careful control of inference (in this case, biasing the decoding process to favor continued thoughts) can yield more coherent and successful problem solving .</p><h3><strong>4. Trading Inference-Time Compute for Adversarial Robustness</strong></h3><p>Inference-time reasoning not only improves accuracy, but it can also bolster robustness. An OpenAI research (Zaremba et al., 2025) asked: if an LLM &#8220;thinks longer,&#8221; does it become harder to trick with adversarial prompts? Their findings suggest yes &#8211; <em>scaling up inference-time compute leads to improved resilience against adversarial attacks in many cases</em> (<a href="https://arxiv.org/abs/2501.18841#:~:text=,Our%20results%20suggest%20that"> Trading Inference-Time Compute for Adversarial Robustness</a>). They experimented with reasoning LLMs under various prompt-based attacks and observed that as the models were allowed more reasoning steps (for instance, using chain-of-thought prompting or iterative self-reflection), the success rate of attacks dropped, often approaching zero on many attack types . Notably, this was achieved <strong>without any adversarial training or fine-tuning</strong> &#8211; purely by leveraging the model&#8217;s existing reasoning ability and giving it more internal deliberation time . In practical terms, an attack that might derail a quick answer could be thwarted when the model takes multiple steps to verify or justify its answer, effectively catching inconsistencies or malicious twists. There were important exceptions: certain attack strategies (like ones exploiting the model&#8217;s policy choices or attempting to trick it into <em>&#8220;thinking less&#8221;</em> or getting stuck on irrelevant details, dubbed &#8220;Nerd Sniping&#8221;) could still succeed . Thus, inference scaling isn&#8217;t a silver bullet for all adversarial inputs. But overall, the research provides <em>&#8220;initial evidence that reasoning models such as o1 become more robust to adversarial attacks as they think for longer.&#8221;</em> (<a href="https://openai.com/index/trading-inference-time-compute-for-adversarial-robustness/#:~:text=Initial%20evidence%20that%20reasoning%20models,as%20they%20think%20for%20longer">Trading inference-time compute for adversarial robustness | OpenAI</a>) In other words, <em>more computation per query can act as a defense mechanism</em>. This insight is influencing safety strategies &#8211; rather than solely relying on fine-tuned filters, simply enabling a model&#8217;s multi-step reasoning (when a query is suspected to be adversarial or tricky) might make it inherently safer .</p><h3><strong>5. Chain-of-Associated-Thoughts (CoAT)</strong></h3><p>Most chain-of-thought methods have the model generate a single linear sequence of reasoning steps. The <strong>Chain-of-Associated-Thoughts (CoAT)</strong> framework (Pan et al., 2025) instead marries <em>classical search algorithms</em> with the LLM&#8217;s generative prowess (<a href="https://arxiv.org/abs/2502.02390#:~:text=increasing%20attention%20because%20its%20process,pathways%20and%20dynamically%20update%20its"> CoAT: Chain-of-Associated-Thoughts Framework for Enhancing Large Language Models Reasoning</a>). CoAT introduces an <strong>associative memory</strong> that the LLM can read from and write to during reasoning, combined with a Monte Carlo Tree Search (MCTS) procedure to explore multiple reasoning paths . Think of it as the model building a search tree of possible &#8220;trains of thought,&#8221; while continually updating a shared memory of important facts or partial results it has discovered (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=The%20researchers%20combine%20classic%20Monte,information%20during%20the%20response%20generation">The State of LLM Reasoning Models</a>) . The associative memory serves as a dynamic knowledge base &#8211; as the model considers one path, it can store intermediate insights (&#8220;clues&#8221;) that might be useful if it backtracks and tries an alternate path, mimicking how humans associate ideas when thinking. MCTS then guides the exploration, balancing depth (following a path deeply) versus breadth (trying different approaches), using the memory to avoid repeating mistakes or forgetting earlier clues . In experiments across various tasks, CoAT significantly improved accuracy, coherence, and diversity of solutions compared to standard single-chain reasoning . By <em>expanding the search space of possible thoughts and allowing the model to dynamically incorporate new information</em>, CoAT achieved more comprehensive reasoning without additional training on that specific process . This showcases how integrating search-based planning algorithms at inference can push LLMs closer to human-like problem solving &#8211; recalling relevant knowledge, revisiting earlier steps, and exploring alternatives &#8211; all within one coherent framework.</p><h3><strong>6. Step Back to Leap Forward - Self-Backtracking</strong></h3><p>Inspired by how humans solve problems by occasionally backtracking (going back to reconsider earlier steps when current approach fails), <em>Self-Backtracking</em> methods enable an LLM to <strong>undo or revise parts of its reasoning</strong> autonomously. In <em>Step Back to Leap Forward: Self-Backtracking for Boosting Reasoning of LMs</em> (Yang et al., 2025), researchers implemented a system where the model can mark a point in its reasoning to &#8220;step back&#8221; to later . During training, the model learned to insert a special token (e.g. &#10178; or the word &#8220;backtrack&#8221;) when it sensed a reasoning dead-end, and how to resume from that point with an alternate attempt . At inference, a tree-search procedure utilizes this: the model can generate a reasoning path, and if it outputs a backtrack token, the search branches off from the last known good point and tries a different reasoning route . Notably, this approach does <strong>not rely on external reward models</strong> for evaluating each step (unlike many search-based methods that need a value or reward model to guide them) . The result is a built-in search capability: the LLM effectively learns <em>when and where to abandon a line of thought</em> and explore alternatives. Empirical results were striking &#8211; the self-backtracking approach improved reasoning accuracy significantly, in one case noting a &gt;40% performance gain over a baseline that only followed the single best path found by supervised fine-tuning (<a href="https://huggingface.co/papers/2502.04404#:~:text=ability%20to%20backtrack%20during%20both,more%20advanced%20and%20robust%20Reasoners">Paper page - Step Back to Leap Forward: Self-Backtracking for Boosting Reasoning of Language Models</a>). In essence, giving the model a &#8220;self-corrective rewind button&#8221; made it much more effective at solving complex tasks, as it could recover from mistakes and try a different way, all during inference. This method does require special training (to teach the model the backtracking token usage), but the heavy lifting of exploring alternatives happens at inference via compute-intensive search. It&#8217;s a compelling example of <em>trading more inference compute for higher reliability</em>, without needing an outside judge model.</p><h3><strong>7. Scaling Up Test-Time Compute with Latent Reasoning</strong></h3><p>Most inference scaling methods make the model generate more tokens (longer explanations, multiple answers, etc.). Geiping et al. (2025) propose an alternative: increase computation <em>without increasing output length</em>, by doing more work in the model&#8217;s <strong>latent space</strong> (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=Instead%20of%20improving%20reasoning%20by,without%20requiring%20longer%20token%20outputs">The State of LLM Reasoning Models</a>). Their approach, <em>Latent Recurrent Depth</em>, introduces a special block within the transformer that can be <strong>iterated multiple times internally</strong> for a given input . In other words, instead of stacking more transformer layers (which would be training-time scaling), they allow the model to <em>re-use</em> a block of layers repeatedly at inference to deepen its computation on a token representation (<a href="https://arxiv.org/abs/2502.05171#:~:text=,the%20resulting%20model%20can%20improve"> Scaling up Test-Time Compute with Latent Reasoning: A Recurrent Depth Approach</a>). This effectively turns the model into a recurrent network that can &#8220;think&#8221; for an arbitrary number of steps per token by looping through the same parameters. Unlike typical chain-of-thought, this latent reasoning doesn&#8217;t produce an explicit step-by-step text that humans can read &#8211; it&#8217;s all internal to the model&#8217;s hidden state. The authors note this has some advantages: it requires <strong>no special training data</strong> (the model is trained normally, aside from architecture changes) and can work even with small context windows, since the iterative reasoning isn&#8217;t stored as additional tokens . It can also, in principle, capture types of reasoning not easily expressed in natural language (since the latent state isn&#8217;t constrained to words) . They built a 3.5B parameter &#8220;Deep Reasoning LM&#8221; with this recurrent depth feature and found that by increasing the number of latent iterations at test time, the model&#8217;s performance on reasoning benchmarks improved &#8211; in some cases dramatically &#8211; corresponding to what one would expect from a <em>much larger (e.g. 50B) model</em> in standard setup . Essentially, a smaller model given enough internal compute could rival a bigger model&#8217;s reasoning ability . The drawback noted is a lack of <em>interpretability</em> &#8211; because the reasoning steps aren&#8217;t output as text, we can&#8217;t see <em>how</em> it&#8217;s solving the problem, which is one benefit of explicit chain-of-thought methods . Nonetheless, this work shows a promising direction: <strong>architectural innovation for dynamic-depth transformers</strong>, where the model allocates more layers/iterations to hard tokens and fewer to easy ones, achieving better accuracy without always having to output lengthy explanations.</p><h3><strong>8. Can a 1B LLM Surpass a 405B LLM - Compute-Optimal Scaling</strong></h3><p>A provocative question posed by Liu et al. (2025) was whether a <em>tiny</em> model, armed with the right inference strategy, could beat a <em>giant</em> model that doesn&#8217;t use such strategies. Their paper, <em>Can 1B LLM Surpass 405B LLM? Rethinking Compute-Optimal Test-Time Scaling</em>, demonstrates that in some cases the answer is yes (<a href="https://arxiv.org/abs/2502.06703#:~:text=experiments%20on%20MATH,indicate%20that%20TTS%20is%20a"> Can 1B LLM Surpass 405B LLM? Rethinking Compute-Optimal Test-Time Scaling</a>). They examine how different factors &#8211; the <em>policy model</em> (the main LLM generating answers), the <em>process reward model (PRM)</em> used to evaluate or choose among outputs, and the <em>difficulty of the problem</em> &#8211; all influence the optimal way to spend a fixed inference compute budget . Through extensive experiments on math benchmarks (MATH-500 and AIME24), they found that with a <strong>compute-optimal test-time scaling (TTS) strategy</strong>, extremely small models can indeed outperform much larger ones . For example, a carefully orchestrated test-time routine enabled a 1B parameter model to <em>exceed the performance of a 405B model (GPT-4 sized)</em> on a math test . They also showed a 0.5B model beating a fine-tuned GPT-4o, a 3B model surpassing a 405B, and a 7B model even outdoing DeepSeek-R1 &#8211; all while using similar or less total compute than those larger models spent generating one answer . How is this possible? The smaller models were paired with efficient <em>search and evaluation procedures</em> at inference: for instance, generating many candidate solutions and using a strong PRM to pick the right one, or dynamically adjusting how many solutions to sample based on problem complexity. Larger models, if they only generate a single answer, can miss the correct solution or make careless errors that a thorough search by a small model could catch. The takeaway is that <em>inference-time algorithms can be as important as model size</em>. By smartly allocating a compute budget &#8211; say, deciding whether to do 1 run with a 405B model vs. 100 runs with a 1B model and a voting mechanism &#8211; one might achieve better results with the latter in some domains . This research provides a framework to decide <strong>how to trade model size for inference computation</strong> optimally. It underscores a theme: the era of purely judging models by parameter count is over; we must also consider how they use compute at runtime.</p><h3><strong>9. Inference-Time Computations for Reasoning and Planning - Benchmark &amp; Insights</strong></h3><p>Given the flurry of inference-time reasoning methods, Parashar et al. (2025) introduced <em>Sys2Bench</em>, a benchmark to systematically evaluate them (<a href="https://arxiv.org/abs/2502.12521#:~:text=and%20verification,well%20across%20all%20reasoning%20and"> Inference-Time Computations for LLM Reasoning and Planning: A Benchmark and Insights</a>). In <em>Inference-Time Computations for LLM Reasoning and Planning: A Benchmark and Insights</em>, they assess a variety of techniques (chain-of-thought prompting, tree-of-thought search, self-consistency voting, etc.) across <strong>eleven diverse tasks</strong> covering arithmetic, logic, commonsense reasoning, algorithmic puzzles, and high-level planning . This study provides a broad view of how different methods stack up and, importantly, the <em>trade-offs between compute cost and performance</em> . One key finding is that simply throwing more inference computation at a problem <em>does not guarantee a win across the board</em> . No single technique dominated all tasks &#8211; for instance, a tree-search might excel at math proofs but underperform a simpler chain-of-thought on commonsense questions, whereas self-consistency might help for logic puzzles but not for planning tasks . In other words, <em>the effectiveness of inference scaling is context-dependent</em>. They also highlight diminishing returns in some cases: certain tasks saturate in performance after a moderate amount of inference effort, suggesting that beyond a point extra steps are wasted compute . This benchmark serves as a reality check and a guide for practitioners. It encourages focusing on <strong>adaptive inference</strong>, where the approach is tuned to the task at hand (e.g., use a heavy search only for tasks known to be very hard, otherwise use a cheaper method). The authors conclude that scaling inference-time compute is a powerful tool but not a silver bullet &#8211; it should be applied judiciously and often in combination with other improvements . Their work also facilitates future research by providing a common yardstick to measure new inference-time reasoning methods against a variety of challenges.</p><h3><strong>10. Inner Thinking Transformer (ITT) - Dynamic Depth Allocation</strong></h3><p>A novel architectural approach to inference scaling is the <em>Inner Thinking Transformer (ITT)</em> by Chen et al. (2025). ITT modifies the standard Transformer architecture to allow <strong>dynamic depth</strong> per token at inference (<a href="https://arxiv.org/abs/2502.13842#:~:text=standard%20Transformers,By%20enabling%20elastic"> Inner Thinking Transformer: Leveraging Dynamic Depth Scaling to Foster Adaptive Internal Thinking</a>). The motivation is that not every part of the input requires equal &#8220;thinking&#8221; &#8211; some tokens (like numbers in a math problem, or tricky logic phrases) are more challenging and should receive more processing, while others (simple words or known facts) need less. ITT achieves this through three mechanisms : (1) <em>Adaptive Token Routing</em> &#8211; tokens deemed &#8220;difficult&#8221; (detected via signs like large attention or gradient spikes in intermediate layers) are routed through additional layers multiple times, effectively giving them extra compute ; (2) <em>Residual Thinking Connections</em> &#8211; analogous to doing several mental passes, the model can refine a token&#8217;s representation iteratively by looping it through the same layer and adding the updates; and (3) <em>Thinking Step Encoding</em> &#8211; a way to mark which iteration of processing a token is in, so the model can differentiate a token&#8217;s first-pass representation from a later refined representation . In practice, ITT allows the model to <strong>focus compute where it&#8217;s most needed</strong> during inference, without expanding the model&#8217;s size. In experiments with relatively small models (162M to 466M parameters), ITT was able to reach <em>near the performance of a standard Transformer almost 3&#215; its size</em>, and did so with significantly less training data . For example, a 162M-parameter ITT model achieved 96.5% of the performance of a 466M normal transformer on a suite of reasoning tasks, while using 43% less training data . It also outperformed naive &#8220;transformer with loops&#8221; baselines on 11 different benchmarks . These results imply that <em>fine-grained, token-level inference scaling</em> (as opposed to whole-sequence scaling) is highly effective &#8211; the model essentially learns to spend its &#8220;thinking budget&#8221; exactly where needed. From a theoretical standpoint, this touches on ideas of conditional computation and algorithmic depth: easy parts of the input get shallow processing, hard parts get deep processing, all within one model. For implementation, such dynamic routing can be done in frameworks like PyTorch by controlling layer execution per token (though it&#8217;s non-trivial and often requires custom CUDA kernels for efficiency). ITT&#8217;s success opens a path to more <em>compute-efficient reasoning models</em>, where we get the benefits of huge model depth but only use it sparingly when required.</p><h3><strong>11. Test-Time Scaling for Code Generation (S*)</strong></h3><p>Reasoning in code generation often means writing code, running it, and debugging &#8211; a process that naturally fits iterative refinement. <em>S</em>** (pronounced &#8220;S star&#8221;) is a test-time compute scaling framework specifically for code generation tasks (Li et al., 2025). It combines parallel and sequential inference scaling: first, the model generates multiple candidate programs in parallel, then it enters a loop of executing those programs on test cases and having the model fix any errors (sequential refinement) (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=The%20model%20generates%20multiple%20code,provided%20in%20the%20problem%20prompt">The State of LLM Reasoning Models</a>) . Essentially, S* turns an LLM into a coding competitor that writes some code, tests it, debugs it, and potentially compares solutions. Concretely, S* works in two stages : <strong>(1) Generation &amp; Debugging:</strong> The model produces, say, 5 different solutions for a given coding problem. Each solution is run against a set of unit tests (included in the prompt or provided as examples). If a solution fails a test (errors or wrong output), the error trace and results are fed back into the model (appended to the prompt) to prompt a correction, generating a new improved version of that solution . This can loop until the solution passes all tests or a time limit is reached. <strong>(2) Selection:</strong> If multiple solutions pass the public tests, the model then needs to pick the best one to output. Rather than random choice, S* uses an <em>adaptive input generation</em> approach: it asks the model to come up with an additional test case that would distinguish between two candidate solutions (i.e., find an input where they might behave differently) . It then runs both solutions on that new input and sees if one fails. This is akin to adversarial testing between the solutions. By pairwise tournament of candidates with model-generated test cases, S* identifies the most correct solution (or determines they&#8217;re equivalent and picks one) . This clever selection mechanism reduces the chance of choosing a wrong solution that just happened to pass the limited tests. The results with S* are impressive: it consistently improved code generation accuracy for models of various sizes (<a href="https://arxiv.org/html/2502.14382v1#:~:text=We%20evaluate%20across%2012%20Large,AI%2FSkyThought">^&#8727;: Test Time Scaling for Code Generation</a>). For instance, using S*, a 3B parameter code model was able to <strong>outperform OpenAI&#8217;s GPT-4o-mini</strong> on a coding benchmark . It also enabled models that are <em>not specifically trained for reasoning</em> to outperform those that are &#8211; e.g., GPT-4o-mini (which presumably has reasoning tuned off) with S* surpassed o1-preview (a reasoning-tuned model) by 3.7% on the LiveCodeBench challenge . Furthermore, applying S* to one of the strongest reasoning models (DeepSeek-R1-Distill-Qwen-32B) pushed its score to 85.7% on that benchmark, nearly reaching the level of OpenAI&#8217;s top code model (o1-high reasoning effort, at 88.5%) . These gains underline how <em>tools + inference-time computation can raise the ceiling of performance</em>, even in domains where LLMs are already strong. S* essentially integrates a testing loop into the generation process, highlighting a practical industry use-case: AI coding assistants that not only write code but test and verify it in one go.</p><h3><strong>12. Chain-of-Draft (CoD)</strong></h3><p>While many methods above make LLMs <em>do more</em> (generate more steps, more candidates, etc.), <strong>Chain-of-Draft (CoD)</strong> takes a different angle: <em>do the same (or more) with less output</em>. Proposed by Xu et al. (2025) and inspired by human note-taking, CoD has the model generate <strong>minimalistic intermediate steps</strong> instead of verbose ones (<a href="https://arxiv.org/abs/2502.18600#:~:text=in%20solving%20complex%20reasoning%20tasks,and%20latency%20across%20various%20reasoning"> Chain of Draft: Thinking Faster by Writing Less</a>). Traditional chain-of-thought prompting often encourages the model to spell out every detail (&#8220;think step by step&#8230;&#8221;), which, while effective, is very token-intensive. Humans, on the other hand, often jot quick drafts or outlines of reasoning &#8211; just enough to not lose the train of thought &#8211; before solving a problem. CoD mimics this by prompting the LLM to produce concise &#8220;draft thoughts&#8221; that capture the essential reasoning, then arrive at the final answer . For example, instead of a 100-token detailed explanation, the model might write a 10-token summary of the key idea, then jump to the answer. The striking result: Chain-of-Draft <strong>matched or even surpassed Chain-of-Thought in accuracy while using only ~7.6% of the tokens</strong> . That is a 92% reduction in solution length for equal or better performance, across various reasoning tasks . This has huge practical implications &#8211; it means far less latency and cost per query (since API costs scale with token count), making &#8220;slow thinking&#8221; economically viable. Essentially CoD finds a sweet spot between zero reasoning and fully verbose reasoning: the model still does multi-step reasoning, but it internalizes or abbreviates most of it, outputting just a terse representation of the process. The challenge is ensuring the model doesn&#8217;t omit critical details that affect the answer. The authors addressed this through prompt engineering and possibly some finetuning so that the model&#8217;s drafts remain informative enough. CoD can be seen as an <em>efficiency-oriented</em> inference-time technique, trading verbosity for conciseness. In a way, it &#8220;compresses&#8221; the chain-of-thought. The fact it can maintain accuracy suggests the extra words in a normal chain-of-thought aren&#8217;t always necessary &#8211; the model can keep track of details internally. For deployment, a CoD approach could be toggled as a &#8220;fast reasoning mode&#8221; that yields cheaper but still accurate results, an attractive option for industry applications where cost is a factor (<a href="https://venturebeat.com/ai/less-is-more-how-chain-of-draft-could-cut-ai-costs-by-90-while-improving-performance/#:~:text=Less%20is%20more%3A%20How%20%27chain,economics%20of%20language%20model%20deployment">Less is more: How 'chain of draft' could cut AI costs by 90% while ...</a>).</p><h2><strong>Industry Applications and Framework Support</strong></h2><p>The rapid progress in inference-time reasoning techniques has already made its way into industry and large-scale deployments. AI providers are keen to offer <strong>reasoning-as-a-feature</strong> in their models, often giving users control over how much inference compute to use (&#8220;fast mode&#8221; vs &#8220;deep reasoning mode&#8221;). For example, Anthropic&#8217;s latest Claude and other commercial models introduced <em>tunable reasoning modes</em> &#8211; Claude 3.7 &#8220;Sonnet&#8221; and Grok 3 now have a <em>&#8220;thinking mode&#8221; toggle</em> that, when enabled, engages more thorough inference-time reasoning for better answers (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=An%20interesting%20trend%20on%20the,reasoning%20capabilities%20to%20their%20offerings">The State of LLM Reasoning Models</a>) . If the user doesn&#8217;t need elaborate reasoning (and wants a quick response), they can disable it, saving costs. OpenAI&#8217;s approach was to offer separate models: GPT-4 <em>vs.</em> GPT-4o (optimized), or the o1 reasoning model <em>vs.</em> standard models, though future releases aim to unify this . Even IBM&#8217;s Granite series, an enterprise LLM, added an explicit &#8220;reasoning&#8221; toggle in version 3.2, which internally activates an inference-scaling pipeline . This trend, dubbed <strong>&#8220;thinking on demand&#8221;</strong>, shows that reasoning is becoming an <em>optional service</em> that can be turned on when needed .</p><p>Several industry case studies highlight the benefits. IBM Research reported that by applying inference scaling techniques (specifically a combination of an LLM, a process reward model, and a search algorithm), their 8B-parameter Granite-3.2 model saw &#8220;<strong>upwards of 20 point</strong>&#8221; jumps on code and math reasoning benchmarks (<a href="https://research.ibm.com/blog/inference-scaling-reasoning-ai-model#:~:text=Using%20inference%20scaling%2C%20we%20wanted,code%20and%20math%20reasoning%20tasks">Reasoning in Granite 3.2 using inference scaling - IBM Research</a>) . This boost allowed Granite-3.2 (8B) to <strong>exceed the performance of larger proprietary models like GPT-4o-0513 and Claude-3.5</strong> on those tasks . Essentially, IBM leveraged a Tree-of-Thought style search guided by a reward model (what they call a PRM) to enhance Granite&#8217;s reasoning. They describe that <em>&#8220;you can enable reasoning using inference scaling by combining three ingredients: an LLM, a PRM, and a search algorithm to explore possible reasoning paths&#8221;</em> &#8211; which is exactly the kind of setup many of the research papers above use. IBM&#8217;s integration of this into a product suggests that even smaller models can be turned into powerful reasoners with the right inference-time recipe, saving the need to train gigantic models from scratch.</p><p>On the engineering side, mainstream AI frameworks have begun supporting these advanced inference workflows. PyTorch and TensorFlow (often via high-level libraries like Hugging Face Transformers) provide features to facilitate multi-step generation. For instance, Hugging Face&#8217;s <code>generate</code> API allows <em>beam search</em>, <em>sampling multiple outputs</em>, and <em>temperature control</em>, which are building blocks of methods like self-consistency and tree search. Developers can also utilize callbacks or custom decoding loops to implement iterative refinement (as we illustrated with pseudocode earlier). PyTorch&#8217;s dynamic computation graph is particularly handy for methods like ITT or latent loops, where the model&#8217;s forward pass can include conditional logic (e.g., routing certain tokens through layers multiple times). On the Google side, the T2I framework and seq2seq models in TensorFlow can also be coerced into multi-round generation with <code>tf.while_loop</code> constructs, albeit with less flexibility than PyTorch. Industry toolkits are emerging: for example, <strong>NVIDIA NeMo</strong> and Triton Inference Server allow deployment of models with <em>controlled decoding strategies</em> and even include plugins for beam search and ensemble voting over multiple outputs. OpenAI&#8217;s own inference API, while not exposing internals, likely uses such techniques under the hood for their &#8220;instruct&#8221; vs &#8220;reasoning&#8221; models.</p><p>Hardware providers are optimizing for inference-time scaling as well. <strong>NVIDIA&#8217;s blog</strong> on DeepSeek-R1 highlights that enabling real-time chain-of-thought for a 671B parameter MoE model required massive throughput &#8211; and their upcoming Blackwell GPU architecture is explicitly tuned for this, offering <em>up to 20 petaflops of FP4 compute and large NVLink domains</em> to handle extensive token-parallel and expert-parallel inference (<a href="https://blogs.nvidia.com/blog/deepseek-r1-nim-microservice/#:~:text=Getting%20every%20floating%20point%20operation,domain%20specifically%20optimized%20for%20inference">DeepSeek-R1 Now Live With NVIDIA NIM | NVIDIA Blog</a>). This indicates that hardware and software advances are going hand-in-hand: as researchers push more complex inference computations, industry is responding with systems to support them in production.</p><p>To summarize, these reasoning-optimized inference techniques are <em>not just academic curiosities</em> &#8211; they are being adopted in real-world AI systems. From an engineering perspective, one must weigh the latency and cost (which we discuss next), but the payoff is improved model capability without waiting for a new model training run. As a result, many AI products in 2025 allow users to dial up inference effort when they need higher quality reasoning, effectively offering <em>&#8220;compute-as-currency&#8221;</em> to buy better answers on demand.</p><h2><strong>Trade-offs, Cost Considerations, and Emerging Trends</strong></h2><p>Every silver lining has a cloud: inference-time scaling, for all its benefits, comes with significant <strong>cost and complexity trade-offs</strong>. The most immediate cost is computational. Using these methods means more FLOPs per query &#8211; generating 100 samples or a 1,000-token reasoning chain can be orders of magnitude slower and more expensive than a single 1-shot answer. For companies deploying LLMs at scale, this raises infrastructure costs. It&#8217;s no coincidence that OpenAI&#8217;s o1 (reasoning model) was more expensive to use than a standard model, or that not every user query is run with maximum reasoning. Some tasks don&#8217;t <em>need</em> it &#8211; a simple factual question would waste cycles if we let the model &#8220;ponder&#8221; unnecessarily. A key emerging best practice is <strong>adaptive reasoning</strong>: <em>use inference scaling selectively</em>. Systems can be designed to detect query difficulty and only invoke heavy reasoning when likely beneficial (<a href="https://arxiv.org/abs/2502.12521#:~:text=categories%2C%20including%20arithmetic%20reasoning%2C%20logical,all%20reasoning%20and%20planning%20tasks"> Inference-Time Computations for LLM Reasoning and Planning: A Benchmark and Insights</a>). Another approach is multi-tiered service: e.g., a chatbot might first try a fast shallow answer, and only if that fails or the user insists, escalate to a more intensive reasoning mode.</p><p>The <strong>compute/latency vs. accuracy</strong> trade-off can also be mitigated by methods like Chain-of-Draft (CoD) which focus on efficiency, or by distilling the benefits of inference-time reasoning into faster models. Interestingly, some works have looked at <em>distilling inference-time behaviors</em>: e.g., train a model to produce the final answer directly that matches the accuracy of a model using chain-of-thought with voting. This crosses the boundary between train-time and test-time improvements &#8211; effectively using inference-time reasoning as a teacher to create a more efficient student model.</p><p>From a cost standpoint, we should note <strong>&#8220;budget forcing&#8221;</strong> as a concept extends beyond the s1 paper. Many providers are exploring giving users explicit control over the &#8220;reasoning budget&#8221; &#8211; akin to a slider for how many thoughts or how long the model should think. If a user is willing to pay more or wait longer for a highly reliable answer (say for a complex medical or legal question), they can choose a higher budget. If they just need a quick guess, they use a lower budget. This user-driven trade-off is likely to become standard in AI services (somewhat like image rendering quality vs. speed settings).</p><p>Another trade-off is <strong>complexity and reliability</strong>. More moving parts (like combining an LLM with a separate reward model and a search algorithm) means more things that can go wrong &#8211; e.g., the search might get stuck in a loop, or the reward model might be misaligned with true correctness, leading the system astray. Ensuring robust performance across all these new pipelines is an active engineering challenge. The benchmark by Parashar et al. (<a href="https://arxiv.org/abs/2502.12521#:~:text=existing%20inference,all%20reasoning%20and%20planning%20tasks"> Inference-Time Computations for LLM Reasoning and Planning: A Benchmark and Insights</a>) highlighted that each method has scenarios where it fails; an ideal system might dynamically choose between methods or combine them. We see early signs of this: some research combines multiple techniques (e.g., using &#8220;Wait&#8221; tokens <em>and</em> self-consistency voting together).</p><p><strong>Emerging trends</strong> include the aforementioned <em>thinking on demand</em>, where reasoning is optional. In the long term, we may not distinguish &#8220;reasoning LLMs&#8221; as a separate category &#8211; much like how instruction-tuning became ubiquitous, the expectation is that <em>all strong LLMs will have a reasoning ability and flexibly use it</em> (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=Overall%2C%20the%20trend%20of%20adding,forward%20for%20LLMs%20in%202025">The State of LLM Reasoning Models</a>). OpenAI&#8217;s CEO hinted that future models might automatically adapt their inference compute internally, rather than requiring users to pick a reasoning versus non-reasoning model . This points toward a future of <strong>dynamic inference</strong>: models that internally decide, token by token or question by question, how much thought to put in. Techniques like ITT and latent depth are steps in this direction, giving models a built-in way to allocate resources.</p><p>Another trend is <strong>integration with external tools and knowledge bases</strong> during inference (beyond the scope of this review). Some methods allow the model to call external calculators, search engines, or databases as part of its reasoning. This can be seen as another form of inference-time augmentation, orthogonal to the ones discussed, but often complementary (e.g., a model might do a chain-of-thought, realize it needs a factual lookup, call an API, then continue reasoning).</p><p>In terms of <em>theoretical advancements</em>, the field is maturing in understanding the <strong>scaling laws of inference</strong> akin to scaling laws of model size. The &#8220;1B vs 405B&#8221; study showed how performance scales with more compute at test-time in a non-linear way (<a href="https://arxiv.org/abs/2502.06703#:~:text=experiments%20on%20MATH,indicate%20that%20TTS%20is%20a"> Can 1B LLM Surpass 405B LLM? Rethinking Compute-Optimal Test-Time Scaling</a>). We&#8217;re likely to see more formal analysis of where the sweet spots are &#8211; how many samples or steps are worth it given a task&#8217;s entropy or difficulty. There&#8217;s also growing interest in <strong>profile-guided inference</strong>: profiling a model&#8217;s behavior (like where it&#8217;s uncertain or what types of mistakes it makes) to decide an inference strategy. For example, if a model is very unsure between two answers, one might invoke a deeper chain-of-thought or a comparison step to resolve that uncertainty (somewhat like S* does with generating extra tests (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=Stage%202%3A%20Selection">The State of LLM Reasoning Models</a>)).</p><p>In summary, inference-time compute scaling is a powerful lever now firmly in the practitioner&#8217;s toolbox. It enables smaller models and new models to <em>punch above their weight</em> by using clever algorithms at runtime. The trade-off is increased compute cost and system complexity, but techniques like Chain-of-Draft and dynamic depth are showing ways to keep those costs in check. Industry adoption confirms that the benefits often outweigh the costs, especially as hardware and software continue to optimize for these patterns. As research and practice continue to inform each other, we can expect reasoning-optimized LLMs to become more efficient, more autonomous in deciding how to reason, and ultimately standard in AI systems &#8211; fulfilling the promise that giving an AI more &#8220;time to think&#8221; makes it <em>smarter and safer</em>, just as it often does for humans.</p><p><strong>Sources:</strong></p><ul><li><p>Muennighoff et al., <em>&#8220;s1: Simple test-time scaling.&#8221;</em> arXiv preprint (2025) &#8211; Introduces &#8220;Wait&#8221; token budget forcing (<a href="https://arxiv.org/abs/2501.19393#:~:text=of%201%2C000%20questions%20paired%20with,Further%2C%20scaling"> s1: Simple test-time scaling</a>).</p></li><li><p>Li et al., <em>&#8220;Test-Time Preference Optimization: On-the-Fly Alignment via Iterative Textual Feedback.&#8221;</em> arXiv (2025) &#8211; Proposes TPO for inference alignment (<a href="https://arxiv.org/abs/2501.12895#:~:text=,improves%20alignment%20with%20human%20preferences"> Test-Time Preference Optimization: On-the-Fly Alignment via Iterative Textual Feedback</a>).</p></li><li><p>Wang et al., <em>&#8220;Thoughts Are All Over the Place: On the Underthinking of o1-Like LLMs.&#8221;</em> arXiv (2025) &#8211; Identifies underthinking and introduces TIP penalty (<a href="https://arxiv.org/abs/2501.18585#:~:text=,like%20models%2C%20revealing%20that"> Thoughts Are All Over the Place: On the Underthinking of o1-Like LLMs</a>).</p></li><li><p>Zaremba et al., <em>&#8220;Trading Inference-Time Compute for Adversarial Robustness.&#8221;</em> arXiv / OpenAI (2025) &#8211; Finds more inference steps improve robustness (<a href="https://arxiv.org/abs/2501.18841#:~:text=,Our%20results%20suggest%20that"> Trading Inference-Time Compute for Adversarial Robustness</a>).</p></li><li><p>Pan et al., <em>&#8220;CoAT: Chain-of-Associated-Thoughts Framework for Enhancing LLM Reasoning.&#8221;</em> arXiv (2025) &#8211; Combines MCTS with associative memory (<a href="https://arxiv.org/abs/2502.02390#:~:text=during%20thinking%2C%20we%20developed%20the,also%20adaptively%20incorporate%20evolving%20information"> CoAT: Chain-of-Associated-Thoughts Framework for Enhancing Large Language Models Reasoning</a>).</p></li><li><p>Yang et al., <em>&#8220;Step Back to Leap Forward: Self-Backtracking for Boosting Reasoning of LMs.&#8221;</em> arXiv (2025) &#8211; Self-backtracking strategy with ~40% performance gain (<a href="https://huggingface.co/papers/2502.04404#:~:text=ability%20to%20backtrack%20during%20both,more%20advanced%20and%20robust%20Reasoners">Paper page - Step Back to Leap Forward: Self-Backtracking for Boosting Reasoning of Language Models</a>).</p></li><li><p>Geiping et al., <em>&#8220;Scaling up Test-Time Compute with Latent Reasoning: A Recurrent Depth Approach.&#8221;</em> arXiv (2025) &#8211; Uses latent loop to improve a 3.5B model to 50B-equivalent performance (<a href="https://arxiv.org/abs/2502.05171#:~:text=,the%20resulting%20model%20can%20improve"> Scaling up Test-Time Compute with Latent Reasoning: A Recurrent Depth Approach</a>).</p></li><li><p>Liu et al., <em>&#8220;Can 1B LLM Surpass 405B LLM? Rethinking Compute-Optimal Test-Time Scaling.&#8221;</em> arXiv (2025) &#8211; Small models beat large ones with optimal TTS (<a href="https://arxiv.org/abs/2502.06703#:~:text=experiments%20on%20MATH,indicate%20that%20TTS%20is%20a"> Can 1B LLM Surpass 405B LLM? Rethinking Compute-Optimal Test-Time Scaling</a>).</p></li><li><p>Parashar et al., <em>&#8220;Inference-Time Computations for LLM Reasoning and Planning: A Benchmark and Insights.&#8221;</em> arXiv (2025) &#8211; Benchmarks trade-offs; no one method wins all (<a href="https://arxiv.org/abs/2502.12521#:~:text=improve%20reasoning%20and%20planning%2C%20focusing,all%20reasoning%20and%20planning%20tasks"> Inference-Time Computations for LLM Reasoning and Planning: A Benchmark and Insights</a>).</p></li><li><p>Chen et al., <em>&#8220;Inner Thinking Transformer: Leveraging Dynamic Depth Scaling to Foster Adaptive Internal Thinking.&#8221;</em> arXiv (2025) &#8211; Dynamic depth per token (ITT) nearly matches a model 3&#215; size (<a href="https://arxiv.org/abs/2502.13842#:~:text=standard%20Transformers,By%20enabling%20elastic"> Inner Thinking Transformer: Leveraging Dynamic Depth Scaling to Foster Adaptive Internal Thinking</a>).</p></li><li><p>Li et al., <em>&#8220;S</em>: Test Time Scaling for Code Generation.&#8221;* arXiv (2025) &#8211; Iterative code generation + testing; 3B model with S* beats GPT-4o-mini (<a href="https://arxiv.org/html/2502.14382v1#:~:text=We%20evaluate%20across%2012%20Large,AI%2FSkyThought">^&#8727;: Test Time Scaling for Code Generation</a>) .</p></li><li><p>Xu et al., <em>&#8220;Chain of Draft: Thinking Faster by Writing Less.&#8221;</em> arXiv (2025) &#8211; Achieves CoT-level accuracy with ~7.6% tokens (92% fewer) (<a href="https://arxiv.org/abs/2502.18600#:~:text=humans%20typically%20employ%20a%20more,available%20at%20this%20https%20URL"> Chain of Draft: Thinking Faster by Writing Less</a>).</p></li><li><p><strong>Sebastian Raschka,</strong> <em>&#8220;The State of LLM Reasoning Models (Part 1: Inference-Time Scaling)&#8221;</em> (2025) &#8211; Overview of these methods and industry trends (<a href="https://sebastianraschka.com/blog/2025/state-of-llm-reasoning-and-inference-scaling.html#:~:text=Inference,encourage%20more%20%E2%80%9Cthought%E2%80%9D%20during%20generation">The State of LLM Reasoning Models</a>) .</p></li><li><p><strong>IBM Research Blog,</strong> <em>&#8220;Reasoning in Granite 3.2 using inference scaling&#8221;</em> (2025) &#8211; Reports 20+ point boosts via inference scaling, 8B model exceeding GPT-4o (<a href="https://research.ibm.com/blog/inference-scaling-reasoning-ai-model#:~:text=Using%20inference%20scaling%2C%20we%20wanted,code%20and%20math%20reasoning%20tasks">Reasoning in Granite 3.2 using inference scaling - IBM Research</a>) .</p></li><li><p><strong>NVIDIA Blog,</strong> <em>&#8220;DeepSeek-R1 &#8211; a Perfect Example of Test-Time Scaling&#8221;</em> (2025) &#8211; Describes deploying a 671B MoE with high inference compute, and hardware (Blackwell) optimized for test-time scaling (<a href="https://blogs.nvidia.com/blog/deepseek-r1-nim-microservice/#:~:text=Getting%20every%20floating%20point%20operation,domain%20specifically%20optimized%20for%20inference">DeepSeek-R1 Now Live With NVIDIA NIM | NVIDIA Blog</a>).</p></li></ul>]]></content:encoded></item><item><title><![CDATA[Building and Refining AI Reasoning Models: A Literature Review]]></title><description><![CDATA[Browse all previously published AI Tutorials here.]]></description><link>https://www.rohan-paul.com/p/building-and-refining-ai-reasoning</link><guid isPermaLink="false">https://www.rohan-paul.com/p/building-and-refining-ai-reasoning</guid><pubDate>Mon, 16 Jun 2025 09:02:25 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!VGo0!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!VGo0!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!VGo0!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png 424w, https://substackcdn.com/image/fetch/$s_!VGo0!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png 848w, https://substackcdn.com/image/fetch/$s_!VGo0!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png 1272w, https://substackcdn.com/image/fetch/$s_!VGo0!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!VGo0!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png" width="1024" height="434" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:434,&quot;width&quot;:1024,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:743723,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.rohan-paul.com/i/166053073?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!VGo0!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png 424w, https://substackcdn.com/image/fetch/$s_!VGo0!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png 848w, https://substackcdn.com/image/fetch/$s_!VGo0!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png 1272w, https://substackcdn.com/image/fetch/$s_!VGo0!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8042e76c-fb99-433a-a48d-80479ee98f9d_1024x434.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong><a href="https://www.rohan-paul.com/s/ai-tutorial/archive?sort=new">Browse all previously published AI Tutorials here</a></strong>.</p><h2><strong>Table of Contents</strong></h2><ol><li><p>Definition of Reasoning Models</p></li><li><p>When to Use Reasoning Models</p></li><li><p>DeepSeek-R1: Training Pipeline and Reasoning Optimization</p></li><li><p>Four Key Methods to Build and Improve Reasoning Models</p><ul><li><p>Inference-Time Scaling (Test-Time Reasoning Enhancements)</p></li><li><p>Pure Reinforcement Learning (RL-Only Training)</p></li><li><p>Supervised Fine-Tuning + Reinforcement Learning (Hybrid RLHF Approaches)</p></li><li><p>Pure Supervised Fine-Tuning and Distillation</p></li></ul></li><li><p>Industry Applications of Reasoning Models</p></li><li><p>Budget Considerations for Building Reasoning Models</p></li></ol><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://x.com/rohanpaul_ai&quot;,&quot;text&quot;:&quot;Connect with me on X (Twitter)&quot;,&quot;action&quot;:null,&quot;class&quot;:&quot;button-wrapper&quot;}" data-component-name="ButtonCreateButton"><a class="button primary button-wrapper" href="https://x.com/rohanpaul_ai"><span>Connect with me on X (Twitter)</span></a></p><p>Understood. I will conduct a comprehensive literature review covering the most recent arXiv papers (2024-2025) on reasoning models, focusing on methods and strategies for building and refining these models. The analysis will be broad across various industries, covering both enterprise-scale and resource-constrained development environments.</p><p>I will also provide an in-depth examination of the DeepSeek training pipeline and DeepSeek R1, along with industry applications from official sources such as PyTorch, TensorFlow, and other frameworks. Expect inline citations for all sources.</p><p>I will notify you when the research is complete.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.rohan-paul.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">I write everyday for my readers on actionable AI. Subscribe and instantly get a 1300+ page Python book.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Definition of Reasoning Models</strong></h2><p><strong>Reasoning models</strong> in AI are advanced language models specifically trained to <strong>&#8220;think&#8221; through complex problems step-by-step before producing an answer</strong> (<a href="https://www.ignorance.ai/p/r1-is-reasoning-for-the-masses#:~:text=R1%20belongs%20to%20a%20new,mirrors%20human%20trains%20of%20thought">R1 is reasoning for the masses - by Charlie Guo</a>). Unlike standard large language models (LLMs) that often generate a response in one pass, reasoning models employ an <strong>internal chain-of-thought (CoT)</strong> &#8211; a series of intermediate reasoning steps &#8211; much like a human&#8217;s thought process . For example, OpenAI&#8217;s <em>o1</em> model family pioneered this approach by <strong>breaking down problems into multiple steps and refining their thinking before finalizing an answer</strong> . This means a reasoning LLM will silently work through sub-problems or hypotheses (which can sometimes be shown as a &#8220;thought process&#8221; if enabled) and possibly correct itself along the way . By performing deeper multi-step analysis, reasoning models can tackle tasks that require logic, planning, or multi-hop inference, rather than relying purely on surface-level pattern matching from training data . In essence, a reasoning model is a type of LLM &#8220;that can perform complex reasoning tasks,&#8221; distinguishing itself by its structured problem-solving approach (<a href="https://muckrack.com/alex-woodie/articles#:~:text=Journalist%20muckrack,article%3F%20This%20byline%3F">Articles by Alex Woodie's Profile | BigDATA Wire, IT Jungle Journalist</a>).</p><p><strong>Key characteristics</strong> of reasoning models include:</p><ul><li><p><strong>Step-by-step problem solving</strong>: They generate explicit or latent intermediate steps (a CoT) instead of jumping straight to an answer . This makes their solutions easier to verify, as they often explain themselves step-by-step .</p></li><li><p><strong>Self-correction and reflection</strong>: They can recognize when an intermediate step seems wrong and revise it (a capability not present in basic LLMs) . This iterative refinement leads to more reliable outcomes on complex tasks.</p></li><li><p><strong>Deeper reasoning beyond training data</strong>: By reasoning, they can combine learned knowledge with logical deduction. This helps them solve puzzles or questions in ways that <strong>go beyond memorized responses</strong>, addressing problems that stump &#8220;shallow&#8221; LLMs .</p></li></ul><p>In summary, reasoning models extend the power of LLMs by incorporating an internal thinking loop. This allows them to handle tasks requiring logical sequencing, long-term planning, or multi-step reasoning that ordinary generative models struggle with. As one commentator put it, <em>reasoning models &#8220;employ an internal reasoning process that mirrors human trains of thought&#8221; rather than blurting out an immediate answer</em> (<a href="https://www.ignorance.ai/p/r1-is-reasoning-for-the-masses#:~:text=R1%20belongs%20to%20a%20new,mirrors%20human%20trains%20of%20thought">R1 is reasoning for the masses - by Charlie Guo</a>).</p><h2><strong>When to Use Reasoning Models</strong></h2><p>Because of their ability to <strong>handle complex, multi-step reasoning</strong>, these models are essential in scenarios where straightforward question-answering or text generation is insufficient. You would turn to a reasoning model when a task requires planning, logical deduction, or <strong>chain-of-thought analysis</strong> to reach a correct solution (<a href="https://getstream.io/blog/reasoning-llms/#:~:text=LLMs%20have%20excelled%20in%20writing%2C,4o">Exploring Reasoning LLMs and Their Real-World Applications</a>) . Key scenarios include:</p><ul><li><p><strong>Complex Problem Solving</strong>: For <strong>mathematical proofs, multi-step math word problems, or scientific reasoning</strong>, reasoning LLMs excel by working through each step. For instance, OpenAI&#8217;s <em>o1</em> and other recent &#8220;reasoners&#8221; can solve complex math or logic puzzles that earlier models would get wrong without stepwise thinking . If a question involves reasoning through several layers of conditions (like a puzzle or an Olympiad geometry problem), a reasoning model is far more likely to reach a correct answer than a standard LLM.</p></li><li><p><strong>Long-form Logical Queries</strong>: In domains like <strong>law or analytical finance</strong>, a single question may require analyzing multiple facts or regulations in sequence. Reasoning models can break down a query (e.g., a legal question that needs applying several statutes) into sub-queries and deduce an answer in a logical progression. They are also useful for <strong>theorem proving or software verification</strong>, where formal logical steps are needed .</p></li><li><p><strong>Planning and Decision Support</strong>: Reasoning LLMs shine when used as planners or decision aids. Rather than just answering a question, they can <strong>plan a series of actions</strong>. For example, in an autonomous agent setting, a reasoning model can decide: &#8220;To accomplish task X, I should do step 1, then step 2, then step 3,&#8221; and so on. This is crucial in applications like robotics (for task planning), or scheduling and optimization problems, where <strong>decomposing a high-level goal into actionable steps</strong> is required (<a href="https://www.analyticsvidhya.com/blog/2024/12/large-action-models/#:~:text=LAMs%20are%20advanced%20AI%20systems%2C,aware%20solutions">Large Action Models (LAMs): Applications and Challenges</a>) . Regular LLMs lacking deep reasoning might skip such planning and produce incomplete solutions.</p></li><li><p><strong>Ambiguous or Novel Problems</strong>: If facing questions that aren&#8217;t straightforward or were never directly seen in training data, reasoning models attempt to <strong>generalize by reasoning</strong>. A non-reasoning model might just make a guess based on similarity to known data, whereas a reasoning model will try to logically figure it out. This makes them valuable for anything requiring on-the-fly reasoning, e.g. debugging code by considering why an error occurs and iterating through hypotheses, or handling complex customer queries that involve several related questions at once.</p></li></ul><p>In short, whenever a task involves <strong>multi-step thinking, intermediate decisions, or the need to verify and correct along the way</strong>, a reasoning-oriented model is the appropriate choice. They are less needed for simple tasks (like straightforward fact recall or single-sentence completions), where a standard LLM is often sufficient. But for <strong>puzzles, long-form reasoning, and critical decision making tasks</strong>, these models are essential to reach accurate and reliable outcomes (<a href="https://getstream.io/blog/reasoning-llms/#:~:text=LLMs%20have%20excelled%20in%20writing%2C,4o">Exploring Reasoning LLMs and Their Real-World Applications</a>). Indeed, benchmarks have shown that reasoning LLMs vastly outperform older models on complex reasoning challenges &#8211; confirming their necessity for those scenarios .</p><h2><strong>DeepSeek-R1: Training Pipeline and Reasoning Optimization</strong></h2><p><em>DeepSeek-R1</em> is a recent open-source reasoning model that provides a case study in how to train and optimize an LLM for improved reasoning capabilities (<a href="https://huggingface.co/deepseek-ai/DeepSeek-R1#:~:text=We%20introduce%20our%20first,o1%20across">deepseek-ai/DeepSeek-R1 &#183; Hugging Face</a>) . Developed by the company DeepSeek (a newcomer in 2023), R1 garnered attention for achieving reasoning performance on par with some of OpenAI&#8217;s models (like <em>o1</em>) while being fully open-source . This did not happen by accident &#8211; it was the result of a carefully designed training pipeline geared towards efficiency and reasoning.</p><p><strong>Multi-Stage Training Pipeline</strong>: DeepSeek-R1 was trained through a <em>four-stage pipeline</em> that alternated between supervised and reinforcement learning phases to progressively build the model&#8217;s reasoning skill . In summary, the stages were:</p><ol><li><p><strong>&#8220;Cold-Start&#8221; Supervised Fine-Tuning (SFT)</strong> &#8211; DeepSeek&#8217;s team first collected a few thousand high-quality reasoning demonstrations (chain-of-thought examples) and fine-tuned their base LLM (called DeepSeek-V3-Base) on this data (<a href="https://arxiv.org/html/2501.12948v1#:~:text=cold,1217">DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning</a>). This gave the model a seed of reasoning ability and improved output <em>readability</em>. Even a small amount of supervised training on step-by-step solutions helps the model avoid gibberish or chaotic outputs and establishes some basic reasoning patterns. The DeepSeek authors found this step crucial to address issues encountered when doing pure RL (described below), providing the model with a &#8220;common sense&#8221; starting point (<a href="https://huggingface.co/deepseek-ai/DeepSeek-R1#:~:text=learning%20%28RL%29%20without%20supervised%20fine,six%20dense%20models%20distilled%20from">deepseek-ai/DeepSeek-R1 &#183; Hugging Face</a>).</p></li><li><p><strong>Reinforcement Learning Stage 1 (Reasoning-Oriented RL)</strong> &#8211; After the initial SFT, they applied large-scale <strong>pure Reinforcement Learning</strong> on the model to push its reasoning performance much further . Using a custom RL algorithm (GRPO) and only reward signals for correct reasoning/task success, the model was encouraged to explore and generate <em>long chain-of-thoughts to solve complex problems</em>. The result of this stage was a model dubbed <strong>DeepSeek-R1-Zero</strong>, which demonstrated remarkable reasoning behaviors emerging from the RL training alone . Notably, R1-Zero learned to perform <strong>self-verification and reflection</strong> &#8211; for example, it could generate a solution and then internally check its work and correct mistakes without any supervised examples of that process . This was a breakthrough result: it <em>validated that pure RL (with no supervised data) can indeed cultivate reasoning capabilities in an LLM</em> . DeepSeek-R1-Zero&#8217;s reasoning skill soared on benchmarks (e.g., its accuracy on a medical exam dataset jumped from 15.6% to 71.0% after RL training, an enormous gain) . However, R1-Zero also suffered some side effects: without any supervised grounding, it sometimes produced <strong>endless repetitive text, mixed languages, or poorly readable answers</strong> . These issues likely arose because the model was chasing the reward (solving the problem) at the expense of fluency or adherence to instructions. Thus, while Stage 2 unlocked reasoning power, it needed refinement to be user-friendly.</p></li><li><p><strong>Supervised Fine-Tuning Stage 2 (Rejection Sampling &amp; Broader Alignment)</strong> &#8211; To refine the RL-trained model, DeepSeek next generated a new supervised dataset by leveraging R1-Zero itself. They used <em>rejection sampling</em>: having R1-Zero solve many prompts, then <strong>filtering for high-quality reasoning outputs</strong>, which were added to a training set . They also incorporated some additional supervised data from their earlier model (DeepSeek-V3) covering general abilities like writing, factual Q&amp;A, etc., to ensure the model retained a well-rounded skill set . The base model was then fine-tuned again on this mixture of data. This step effectively <strong>aligned the model with human preferences</strong> (via picking lucid, correct solutions from the RL model) and improved its general capabilities beyond pure reasoning. Fine-tuning on the RL model&#8217;s best outputs addressed the readability and repetition problems by explicitly training the model to produce solutions that were both correct <em>and</em> well-written .</p></li><li><p><strong>Reinforcement Learning Stage 2 (Final Tuning)</strong> &#8211; In the last stage, they performed another round of RL on the newly fine-tuned model, this time using a wide range of prompt types (&#8220;prompts from all scenarios&#8221;) . The idea was to <strong>fine-tune via RL across diverse tasks</strong> &#8211; not just math or logic puzzles, but also coding, knowledge questions, etc. &#8211; to ensure the reasoning improvements generalize to all types of queries. This final RL pass yielded the ultimate model called <strong>DeepSeek-R1</strong>, which achieved performance on par with OpenAI&#8217;s o1 model (specifically, matching an OpenAI-o1 model&#8217;s score on benchmarks in December 2024) . The multi-stage approach allowed DeepSeek-R1 to combine the strengths of both supervised learning and pure RL, resulting in a highly capable and balanced reasoning model.</p></li></ol><p><strong>Efficiency and Results</strong>: One notable aspect of DeepSeek&#8217;s pipeline is that it was relatively <strong>compute-efficient</strong> given the gains achieved. Rather than training a new giant model from scratch, they started from a pre-trained base and focused on <em>post-training techniques (SFT and RLHF)</em> which require &#8220;minimal computational resources compared to pre-training&#8221; . This approach of heavy post-training paid off &#8211; DeepSeek-R1&#8217;s reasoning performance on complex tasks (math, coding, scientific QA) is <em>comparable to closed-source state-of-the-art models</em> . For example, through RL and a bit of voting at inference, DeepSeek-R1-Zero was able to reach an 86.7% success rate on a challenging medical exam benchmark, matching OpenAI&#8217;s o1 model . The final DeepSeek-R1 further improved generality and matched an even newer OpenAI-o1 variant . All of this was achieved in a matter of months, demonstrating how an optimized training pipeline can yield <strong>frontier-level reasoning ability at a fraction of the traditional training cost</strong>. Moreover, DeepSeek open-sourced not only R1, but also <em>six distilled smaller models</em> derived from it . These distilled models (ranging from 1.5B to 70B parameters) retain much of R1&#8217;s reasoning skill, making it accessible to those with lower compute &#8211; a point we revisit under Budget Considerations.</p><p>In summary, DeepSeek-R1 illustrates how <strong>multi-stage training with alternating Supervised Fine-Tuning and Reinforcement Learning</strong> can be used to efficiently build a reasoning model. By first seeding the model with some supervised knowledge, then letting it improve itself via RL (self-discovery of reasoning), and finally aligning it with human-like outputs, R1 achieved a high level of reasoning performance. This case study will inform several of the methods discussed next, as it actually combined <em>all four</em> of the key strategies for refining reasoning models (inference-time techniques, pure RL, SFT + RL, and distillation) into one coherent pipeline.</p><h2><strong>Four Key Methods to Build and Improve Reasoning Models</strong></h2><p>Researchers and practitioners have explored multiple strategies to enhance the reasoning capabilities of AI models. The most prominent methods can be categorized into four groups: <strong>(1) Inference-Time Scaling techniques, (2) Pure Reinforcement Learning, (3) Supervised Fine-Tuning combined with Reinforcement Learning,</strong> and <strong>(4) Pure Supervised Fine-Tuning &amp; Knowledge Distillation</strong>. Each approach has its advantages and trade-offs. We review each method below, with recent research insights (2024&#8211;2025) illustrating how they contribute to building better reasoning models.</p><h3><strong>1. Inference-Time Scaling (Test-Time Reasoning Enhancements)</strong></h3><p>Inference-time scaling refers to improving a model&#8217;s reasoning performance <em>without changing the model&#8217;s parameters</em>, by giving it more &#8220;thinking time&#8221; or by using smarter decoding strategies at inference. OpenAI&#8217;s o1 series models introduced a simple but effective form of this: <strong>increasing the length of the Chain-of-Thought the model is allowed to produce</strong> (<a href="https://arxiv.org/html/2501.12948v1#:~:text=of%20reasoning%20capabilities%2C%20OpenAI%E2%80%99s%20o1%C2%A0,and%20search%20algorithms%20such%20as">DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning</a>). By prompting the model to generate <strong>longer, detailed reasoning chains</strong> before final answers, they achieved significant improvements on tasks like math, coding, and scientific Q&amp;A . In essence, rather than restricting the model to a brief answer, you let it <strong>think out loud extensively</strong>, which often leads to more accurate conclusions.</p><p>Another inference-time technique is <strong>self-consistency via multiple sampling</strong>. Instead of one shot, you sample the model&#8217;s answer multiple times (each with its own reasoning path) and then take a majority vote or best-consensus answer. This was shown to boost accuracy on reasoning tasks, as the ensemble of different reasoning paths tends to cancel out random errors . For instance, DeepSeek observed that after RL training, <strong>using a majority vote over several reasoning outputs raised accuracy from 71% to 86.7% on a medical exam task</strong>, closing the gap to the top-tier model . This approach, known as <em>Self-Consistency</em>, was originally proposed in 2022 and remains a powerful test-time method: the model basically &#8220;rethinks&#8221; the problem many times and the most consistent result is chosen as the final answer, reducing occasional reasoning mistakes.</p><p>Researchers have also explored more elaborate <strong>search-based inference</strong> methods. These include using <strong>Beam Search or Monte Carlo Tree Search (MCTS)</strong> over the space of possible reasoning chains (<a href="https://arxiv.org/html/2501.12948v1#:~:text=explored%20various%20approaches%2C%20including%20process,of%20these%20methods%20has%20achieved">DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning</a>). For example, one 2024 study guided LLM reasoning with an AlphaZero-like tree search, essentially treating the model as a game player that explores different move sequences (reasoning steps) and uses a value network to pick the best path . Another approach integrated a formal proof assistant&#8217;s feedback with MCTS to guide an LLM in solving math proofs . These search-based inference techniques can systematically explore multiple reasoning branches and backtrack when a line of thought appears unpromising. In complex domains like theorem proving or planning, such <strong>tree-of-thought</strong> methods have shown promise, though they come with higher computational cost and complexity at inference time. So far, none of these search-based methods alone has surpassed the performance of heavily-trained models like OpenAI&#8217;s o1 on general reasoning benchmarks , but they continue to be an active research area.</p><p>In summary, inference-time scaling methods <strong>do not modify the model&#8217;s weights</strong> &#8211; instead, they <strong>give the model more opportunities to reason during decoding</strong>. Whether by extending the allowed reasoning length, sampling multiple solutions and choosing the best, or systematically searching through thoughts, these techniques can significantly improve outcomes on reasoning tasks without additional training . They are especially useful as a quick way to boost performance of an existing model: if you have a decent base model, just letting it reason more thoroughly (e.g. &#8220;let&#8217;s think step by step&#8221;) and aggregating its answers can yield better accuracy. The trade-off is usually <strong>latency and compute at inference</strong> &#8211; more steps or multiple samples mean slower responses. Effective test-time scaling remains an open challenge, but it is a critical tool in the reasoning toolkit.</p><h3><strong>2. Pure Reinforcement Learning (RL-Only Training)</strong></h3><p>Pure reinforcement learning involves training a model to improve its reasoning by <strong>learning from trial and error, using a reward signal, without any supervised dataset of correct solutions</strong>. In this approach, the model starts from a pretrained base and is optimized via RL on a <strong>reward function that captures successful reasoning</strong> &#8211; for example, solving a puzzle, getting a question correct, or following logical constraints. The recent DeepSeek-R1-Zero is a landmark example demonstrating the potential of pure RL for reasoning: it was trained <em>entirely via reinforcement learning</em> (no supervised fine-tune first) and &#8220;numerous powerful and interesting reasoning behaviors <em>naturally emerged</em>&#8221; from this process (<a href="https://huggingface.co/deepseek-ai/DeepSeek-R1#:~:text=Post,the%20Base%20Model">deepseek-ai/DeepSeek-R1 &#183; Hugging Face</a>). During training, the model discovered strategies like checking its own answers and writing longer scratchpads to maximize its reward, effectively learning to reason better on its own .</p><p>The advantage of pure RL is that the model is not constrained by human-written examples &#8211; it can, in theory, <strong>innovate new reasoning strategies</strong> that humans didn&#8217;t directly teach it. For instance, in DeepSeek-R1-Zero, the model learned to do <em>self-verification</em> (explicitly verifying intermediate steps) purely because it helped achieve the reward of correct answers . Other researchers in 2024 have similarly reported that RL can induce self-correction behavior in language models. Kumar et al. (2024) describe training language models to <em>self-correct</em> via RL, letting the model iteratively propose and refine answers and rewarding it when it corrects mistakes (<a href="https://arxiv.org/html/2501.12948v1#:~:text=,12917%2C%202024">DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning</a>). Such approaches treat the reasoning process as a sequential decision-making problem: each step of reasoning influences the final reward, and the model is optimized to produce sequences that yield high reward (e.g., accurate final answers or high logical consistency).</p><p>However, pure RL comes with <strong>significant challenges</strong>. One issue is that, without any supervised guidance, the model might exploit the reward in unintended ways or produce unnatural outputs. As seen with R1-Zero, <em>quality issues like gibberish text, repetitive loops, or mixing languages can occur</em> (<a href="https://huggingface.co/deepseek-ai/DeepSeek-R1#:~:text=learning%20%28RL%29%20without%20supervised%20fine,six%20dense%20models%20distilled%20from">deepseek-ai/DeepSeek-R1 &#183; Hugging Face</a>) when the model tries every trick to maximize reward. The RL optimization might encourage correct reasoning but not penalize poor readability or irrelevant verbosity unless those are part of the reward. Another challenge is defining a good reward function for reasoning. If the only reward is &#8220;answer is correct at the end,&#8221; the model gets very sparse feedback, which makes training difficult. Researchers have addressed this by designing <strong>process-based rewards</strong> &#8211; e.g., giving partial credit for each correct intermediate step (a concept explored by Uesato et al. 2022 and Lightman et al. 2023) . Process supervision via RL can guide the model to reason correctly step-by-step, not just get the final answer, but it requires careful setup of what to reward at each step .</p><p>Despite hurdles, the pure RL approach has shown it can produce top-tier reasoning models. DeepSeek-R1-Zero achieved performance close to GPT-4-level on some benchmarks purely through RL optimization, which is a remarkable result (<a href="https://arxiv.org/html/2501.12948v1#:~:text=reasoning%20behaviors,0912">DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning</a>). This suggests a potential future where models could <em>learn to reason</em> with minimal human examples, simply by interacting with problems and receiving feedback. We are also seeing pure RL being used in specific domains: for instance, in code generation, an LLM can be trained via RL to pass unit tests, effectively learning to logically debug its code. In robotics (where an agent needs to reason about actions), RL on language models is being investigated to allow planning through trial-and-error in simulations. Pure RL thus offers a way to <strong>discover emergent reasoning skills</strong>, but in practice it is often paired with other methods to rein in its excesses. As we saw, DeepSeek ultimately combined RL with some supervised data to get the best of both worlds &#8211; which leads us to the next strategy.</p><h3><strong>3. Supervised Fine-Tuning + Reinforcement Learning (Hybrid RLHF Approaches)</strong></h3><p>Combining supervised fine-tuning (SFT) with reinforcement learning has become the <em>standard recipe</em> for building aligned and high-performing LLMs, popularized by techniques like <strong>Reinforcement Learning from Human Feedback (RLHF)</strong>. In the context of reasoning models, this hybrid approach means you first <strong>teach the model via examples</strong> (SFT), then <strong>refine it via feedback-driven optimization</strong> (RL). The supervised phase might involve feeding the model many step-by-step solutions or high-quality answers so it learns the basics of reasoning and fluency. The RL phase then further optimizes the model&#8217;s behavior according to a reward function, often to better align with correctness or human preferences.</p><p>OpenAI&#8217;s ChatGPT and InstructGPT are classic instances of SFT+RLHF: they first did supervised fine-tuning on demonstrations of ideal answers, and then applied RL using a reward model to align the outputs with what humans prefer (which includes aspects of correctness, helpfulness, etc.). For reasoning tasks, this two-stage approach helps ensure the model is both <strong>capable and aligned</strong>. The supervised step gives it knowledge of how to reason (since it learns from human solutions), and the RL step can push it to avoid errors and undesirable traits by leveraging feedback signals. Anthropic&#8217;s Claude model similarly uses a hybrid approach, where a supervised base is further tuned with a form of RL guided by a &#8220;Constitution&#8221; of principles (a variant of RLHF without direct human intervention in the loop). These processes have proven effective in practice &#8211; for example, models like GPT-4 that underwent extensive SFT and RLHF are among the top performers in both reasoning benchmarks and helpfulness alignment tests (<a href="https://getstream.io/blog/reasoning-llms/#:~:text=OpenAI%27s%20o1%20and%20o3%20models%2C,4o">Exploring Reasoning LLMs and Their Real-World Applications</a>).</p><p>The DeepSeek-R1 pipeline we discussed exemplifies the power of mixing SFT and RL. Initially, a bit of SFT on reasoning data fixed readability and gave the model a grounding (<a href="https://huggingface.co/deepseek-ai/DeepSeek-R1#:~:text=learning%20%28RL%29%20without%20supervised%20fine,six%20dense%20models%20distilled%20from">deepseek-ai/DeepSeek-R1 &#183; Hugging Face</a>), then RL greatly boosted raw reasoning skill , and finally another SFT (with filtered data) plus RL fine-tuned the model to be well-behaved and broadly skilled (<a href="https://arxiv.org/html/2501.12948v1#:~:text=cold,1217">DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning</a>). Such <strong>multi-turn alternating optimization</strong> is essentially SFT+RL on repeat. Each SFT phase can be seen as realigning the model to human-like distribution (so it doesn&#8217;t drift too far in its own direction), and each RL phase as pushing the frontier of capability under the guidance of a reward function.</p><p>One popular configuration of SFT+RL for reasoning models is: <strong>Supervised Fine-Tuning on chain-of-thought demonstrations, followed by RLHF with a reward model that values correct reasoning</strong>. Recent research suggests that if you have a way to automatically judge the correctness of an answer (e.g., a programmatic verifier for math problems, or human ratings), using that in RL can dramatically improve performance. For example, OpenAI&#8217;s <em>let&#8217;s verify step by step</em> approach (Lightman et al. 2023) used a verifier to give feedback on each step of reasoning in math, thereby refining the model&#8217;s reasoning via RL on those signals . Another example: a 2023 paper <em>Math-Shepherd</em> trained a <strong>reward model to judge the validity of each step in a math proof</strong>, and then did RL to encourage the LLM to generate only valid steps . These are instances of SFT+RL where SFT provides initial reasoning ability and RL then enforces correctness rigorously.</p><p>From an industry perspective, the SFT + RL approach is attractive because it leverages human expertise and preferences effectively. <strong>Supervised fine-tuning leverages existing data (or expert demonstrations)</strong>, and <strong>RLHF allows iterative improvement based on real feedback loops</strong>. Companies like OpenAI have leaned heavily on RLHF to align their models with user expectations. In the realm of open-source, techniques like <em>Reinforcement Learning from AI Feedback</em> (RLAIF) use AI critics instead of human annotators to similarly refine models after a supervised stage &#8211; again combining an initial SFT model with an RL phase for polishing. The key benefit over pure RL is that the supervised step often makes training more stable and sample-efficient (the model starts closer to a good solution), and the RL step can then focus on more nuanced improvements (like avoiding rare errors or tailoring to user preferences). Indeed, <strong>RLHF has been called the &#8220;secret sauce&#8221; behind ChatGPT and GPT-4</strong>&#8217;s success (<a href="https://github.com/AI4Finance-Foundation/FinGPT#:~:text=adaptation%2C%20leveraging%20the%20best%20available,source%20LLMs">GitHub - AI4Finance-Foundation/FinGPT: FinGPT: Open-Source Financial Large Language Models! Revolutionize We release the trained model on HuggingFace.</a>), underscoring how crucial this hybrid method is for state-of-the-art performance.</p><h3><strong>4. Pure Supervised Fine-Tuning and Distillation</strong></h3><p>The fourth strategy is to rely solely on supervised learning signals to build a reasoning model &#8211; that is, fine-tuning on curated datasets of prompts and solutions, and optionally using <strong>knowledge distillation</strong> from a stronger model to guide the training. This approach forgoes any direct reinforcement learning; instead, it tries to encode reasoning behavior through examples and mimicry.</p><p>A straightforward version is <strong>Supervised Fine-Tuning (SFT) on reasoning data</strong>: collect a large set of problems with correct step-by-step solutions (which could be human-written or generated by a capable model), and train the model to reproduce those solutions given the problems. Many open-source chat models and reasoning models have been built this way, because it&#8217;s easier to implement than RLHF and doesn&#8217;t require designing a reward function or having human feedback for each output. For instance, models like <em>Vicuna</em>, <em>Alpaca</em>, and others were trained by fine-tuning on datasets of question-answer pairs (some of which involve reasoning) that were distilled from larger models. In the reasoning domain, one notable technique is <em>self-instruct or self-generation</em>: use a powerful LLM (like GPT-4) to generate a large set of reasoning examples (questions with detailed CoT solutions), and then fine-tune a smaller model on that synthetic dataset. This is purely supervised (the smaller model just learns to imitate the teacher&#8217;s reasoning traces) and has been shown to impart surprising reasoning ability to the smaller model.</p><p><strong>Knowledge distillation</strong> takes this a step further by having the smaller &#8220;student&#8221; model not only imitate outputs, but effectively compress the knowledge of a larger &#8220;teacher&#8221; model. In 2024, multiple studies focused on distilling chain-of-thought reasoning from big models into smaller ones. <em>Feng et al. (2024)</em> describe CoT distillation as a powerful way to transfer reasoning skills &#8211; the student model is trained to mimic the <em>important steps</em> in the teacher&#8217;s reasoning, rather than every token equally (<a href="https://arxiv.org/abs/2405.16064#:~:text=%3E%20Abstract%3AChain,optimal%20outcomes.%20To"> Keypoint-based Progressive Chain-of-Thought Distillation for LLMs</a>). By identifying key reasoning milestones (or &#8220;keypoints&#8221;) in the teacher&#8217;s solutions and focusing the training on those, they achieved better learning of reasoning with a smaller model . Another work (Xu et al. 2024) similarly found that <em>carefully distilling the reasoning process</em> yields a student that approaches the teacher&#8217;s ability on reasoning tasks . In practice, this means you can take a very large reasoning model (say 70B or 180B parameters) and use its outputs to train a 7B or 13B model that still performs well on complex tasks &#8211; a hugely cost-effective outcome.</p><p>DeepSeek&#8217;s team also validated the effectiveness of pure SFT+distillation in their pipeline: they reported that <strong>distilling the reasoning patterns of a large model into a smaller model outperformed training that smaller model with RL from scratch</strong> (<a href="https://huggingface.co/deepseek-ai/DeepSeek-R1#:~:text=Distillation%3A%20Smaller%20Models%20Can%20Be,Powerful%20Too">deepseek-ai/DeepSeek-R1 &#183; Hugging Face</a>). They distilled DeepSeek-R1 (which is 37B active parameters in a larger MoE setup) into a 32B dense model and saw it beat a baseline where the 32B model had been directly RL-fine-tuned . This demonstrates that <strong>a well-trained teacher model can impart reasoning skills to a student more effectively than the student might learn on its own via RL</strong>. The open-source community has embraced this: as noted, DeepSeek released a whole suite of distilled models (1.5B up to 70B) that were purely fine-tuned on R1&#8217;s generated data . These distilled models achieve state-of-the-art results among models of comparable size , showing the viability of the pure supervised approach when it leverages a good teacher.</p><p>The pure SFT approach is especially appealing for resource-constrained developers or academics. <strong>It sidesteps the complexity of RL training and reward design</strong>, and instead uses offline data which can be curated once and reused. Many &#8220;open instruction-tuned&#8221; models are built this way by harvesting high-quality outputs from ChatGPT/GPT-4 (effectively treating GPT-4 as the reasoning expert to distill from). The drawback is that the model is limited by the quality and scope of the data. If your supervised dataset doesn&#8217;t cover certain kinds of reasoning or is too small, the model won&#8217;t learn to handle those cases. There&#8217;s also a risk of the model <em>overfitting to the style of the data</em> and not being as generally adaptable as an RL-trained model that has explored various possibilities. Nonetheless, given the success of projects like Dolly, Vicuna, and distilled DeepSeek models, it&#8217;s clear that <strong>with enough diverse and well-crafted examples, pure supervised fine-tuning can produce a strong reasoning model</strong>. It&#8217;s a simpler pipeline: just &#8220;train on lots of reasoning examples,&#8221; possibly augmented by <strong>distillation from a top-tier model to bootstrap the process</strong> (<a href="https://arxiv.org/abs/2405.16064#:~:text=LLMs%20arxiv.org%20%20Chain,to%20smaller%20student%20models">Keypoint-based Progressive Chain-of-Thought Distillation for LLMs</a>). As such, it remains a key strategy, often used in combination with or as a precursor to the other methods.</p><h2><strong>Industry Applications of Reasoning Models</strong></h2><p>Reasoning-oriented AI models are being applied across a wide range of industries to tackle tasks that demand complex decision-making and multi-step analysis. Below we highlight how such models are benefitting a few major sectors, with examples drawn from recent applications and official sources:</p><ul><li><p>Finance: In finance, reasoning LLMs assist with <strong>investment analysis, trading strategies, and financial advice</strong>. Models like BloombergGPT (a 50B-parameter finance-trained LLM) have shown strong ability in question answering and analysis of financial documents (<a href="https://github.com/AI4Finance-Foundation/FinGPT#:~:text=1%29,tuning">GitHub - AI4Finance-Foundation/FinGPT: FinGPT: Open-Source Financial Large Language Models! Revolutionize We release the trained model on HuggingFace.</a>). However, BloombergGPT&#8217;s training was extremely costly (an estimated $3M over 53 days) , which is why newer approaches like <em>FinGPT</em> focus on lightweight fine-tuning and reasoning to continuously adapt models to fast-changing financial data . FinGPT leverages open-source LLMs and techniques like RLHF to allow personalized financial assistants &#8211; for example, adjusting the model to a user&#8217;s risk preferences or portfolio context . Reasoning models in finance can interpret <strong>long financial reports, perform step-by-step risk assessment, or generate a chain-of-thought explaining a stock recommendation</strong>. Such transparency is crucial in finance. Companies are also exploring using these models for automated fraud detection and auditing, where the model must logically go through transactions and flag anomalies. Overall, the ability to <em>think through</em> a complex financial scenario (rather than just retrieve info) makes reasoning LLMs valuable for analysts and advisors.</p></li><li><p>Healthcare: The medical field is leveraging reasoning LLMs for <strong>diagnostic support, medical Q&amp;A, and summarizing patient interactions</strong>. Medical questions often require logical deduction &#8211; e.g., combining symptoms and test results to narrow down a diagnosis &#8211; which reasoning models can handle by parsing through each piece of evidence. For instance, Google&#8217;s Med-PaLM 2 (an LLM fine-tuned for medicine) has demonstrated expert-level reasoning on medical exam questions, including providing step-by-step justifications for its answers. In clinical settings, products like the <em>Nuance Dragon Ambient eXperience (DAX)</em> use AI (powered by models with advanced NLP capabilities) to <strong>automatically generate clinical notes from doctor-patient conversations</strong> ([</p></li></ul><pre><code><code>Ambient Clinical Intelligence: Generating Medical Reports with PyTorch | PyTorch
</code></code></pre><ul><li><p>](<a href="https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/#:~:text=This%20article%20will%20showcase%20how,the%20technologies%20that%20enable%20it">https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/#:~:text=This article will showcase how,the technologies that enable it</a>)). While much of that is summarization, a reasoning component helps ensure the notes logically reflect the conversation and medical context. Reasoning models are also being used to power <strong>medical chatbots that can triage patients</strong> by asking a series of questions (planning the interview dynamically based on previous answers). In healthcare, errors can be life-threatening, so the step-by-step verification that reasoning models provide is highly valued &#8211; e.g., an AI doctor assistant can explain its rationale for a treatment recommendation, allowing the human doctor to double-check each step. Early studies in 2025 indicate that such AI assistants, when using reasoning, can achieve more accurate and <strong>trustworthy diagnoses</strong> compared to simpler models, because they won&#8217;t as easily be fooled by superficial cues and can handle multi-factor conditions.</p></li><li><p><strong>Robotics and Automation</strong>: Robotics has embraced large language models as high-level planners, giving rise to the concept of <strong>Large Action Models (LAMs)</strong> that integrate reasoning, planning, and execution (<a href="https://www.analyticsvidhya.com/blog/2024/12/large-action-models/#:~:text=Artificial%20Intelligence%20%20has%20seen,incorporate%20reasoning%2C%20planning%2C%20and%20execution">Large Action Models (LAMs): Applications and Challenges</a>) . A robot operating in an unstructured environment (like a home or a factory floor) needs to <strong>make decisions step-by-step</strong>, often based on sensor inputs and goals. Embedding a reasoning LLM in the control loop allows the robot to plan actions in natural language (&#8220;First, check if the object is on the table. If not, look in the cupboard, then grasp it with the gripper...&#8221;) which the system can then execute. For example, <em>LightPlanner (2025)</em> uses a lightweight LLM to plan household tasks; it employs a hierarchical reasoning process to handle errors (if an action fails, it reasons about why and tries an alternative) (<a href="https://arxiv.org/html/2503.08508v1#:~:text=III">LightPlanner: Unleashing the Reasoning Capabilities of Lightweight Large Language Models in Task Planning</a>) . In robotics, reasoning models also facilitate <strong>human-robot interaction</strong> &#8211; the robot can understand complex instructions from a human by breaking them down. A user might say, &#8220;Fetch me the red book from the shelf in the study room after checking if it&#8217;s not under the table.&#8221; A reasoning-enabled robot can parse this, plan the navigation, the checking action, the fetching action in sequence, and even clarify if some part is ambiguous. Beyond physical robots, in process automation (RPA) and control systems, these models can serve as decision engines that <strong>simulate a human operator&#8217;s thought process</strong> for monitoring systems, diagnosing issues, and planning responses. The use of reasoning LLMs in robotics is still emerging, but early trials show that it greatly improves robustness &#8211; the robot can handle unexpected situations by reasoning through them, rather than being stuck when something falls outside of a predefined script .</p></li><li><p><strong>Other Sectors</strong>: Virtually any domain with complex workflows or decision trees can benefit from reasoning models. In education, they are used as intelligent tutors that can break down solutions step-by-step for students and adjust the teaching strategy if the student is confused (essentially reasoning about the student&#8217;s needs). In <strong>customer support</strong>, reasoning LLMs can operate as multi-turn assistants that figure out what a customer&#8217;s underlying issue is through dialog, instead of just answering FAQ-style; they keep track of context and deduce the best solution even if the question is vague. Multi-agent systems also use reasoning LLMs to enable more sophisticated interactions &#8211; for example, two agent bots can negotiate or collaborate on a task by exchanging reasoning (in natural language) about the task, which is far more flexible than passing fixed signals (<a href="https://getstream.io/blog/reasoning-llms/#:~:text=This%20article%20focuses%20on%20LLMs%27,and%20%2012%20apps">Exploring Reasoning LLMs and Their Real-World Applications</a>). In <strong>finance and law</strong>, as mentioned, their use is expanding &#8211; legal reasoning models can draft and analyze contracts by logically connecting clauses and identifying inconsistencies. <strong>Scientific research</strong> is another area: tools like ChatGPT have been augmented with reasoning modules to design experiments or analyze experimental results step-by-step, assisting scientists in hypothesis testing. The broad applicability across these sectors underscores that whenever complex logic or multi-step decision making is involved, reasoning AI models are becoming go-to solutions.</p></li></ul><h2><strong>Budget Considerations for Building Reasoning Models</strong></h2><p>Developing and deploying reasoning models comes with varying costs, and effective strategies can differ widely for startups, large enterprises, or resource-constrained teams. Here we outline cost-related considerations and strategies:</p><ul><li><p><strong>Training Costs &#8211; Large-Scale vs. Efficient Training</strong>: Training a cutting-edge LLM from scratch is enormously expensive &#8211; recent estimates put <strong>OpenAI&#8217;s GPT-4 training at ~$78 million, and Google&#8217;s Gemini Ultra at $191 million</strong> in compute (<a href="https://redmarble.ai/cost-of-fine-tuning-an-llm/#:~:text=Evaluating%20a%20low,open%20source%20LLM">The Cost of Fine Tuning an LLM - Red Marble</a>). Such efforts (and even smaller but still hefty ones like Databricks&#8217; 15B model at $10M) are beyond reach for most organizations . Large enterprises with deep pockets or special data (e.g., Bloomberg in finance) might invest in training a bespoke model, but even they face a cost-benefit question. The good news is that to get <em>reasoning</em> capabilities, one doesn&#8217;t necessarily need to train a new base model from scratch. As highlighted earlier, <strong>post-training fine-tuning (SFT, RLHF)</strong> can yield big reasoning gains at a fraction of the cost of pre-training (<a href="https://arxiv.org/html/2501.12948v1#:~:text=Recently%2C%20post,time%20scaling">DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning</a>). Startups and smaller labs usually opt to <strong>fine-tune existing open-source models</strong> (like Llama-2, Mistral, etc.) on domain-specific or reasoning data. This can often be done for a few hundred dollars in cloud compute, especially with models under 10B parameters. For instance, one report noted that fine-tuning a 7B model on a specialized dataset can cost on the order of $100 on cloud GPUs (<a href="https://news.ycombinator.com/item?id=39934480#:~:text=Ask%20HN%3A%20Most%20efficient%20way,100%20depending%20on%20your%20requirements">Ask HN: Most efficient way to fine-tune an LLM in 2024?</a>) &#8211; a trivial amount compared to training huge models from scratch. So, a cost-effective strategy is: <em>use a pre-trained base model (possibly one released by a big company) and focus budget on fine-tuning it for reasoning</em>. DeepSeek&#8217;s approach also exemplified this &#8211; they started with an existing base (DeepSeek V3) and only spent compute on the RL/SFT stages, which is far cheaper than creating a 37B MoE model from scratch.</p></li><li><p><strong>Open-Source Models and Community Data</strong>: Another budget-friendly strategy, especially for startups, is to leverage the rich ecosystem of open-source LLMs and publicly available instruction datasets. Models like <strong>Llama 2, Mistral, Falcon, etc., can be downloaded for free</strong>, and many have strong general capabilities. By fine-tuning or distilling these models on reasoning data (which could be collected from sources like Stack Exchange explanations, proofs, or via synthetic generation from GPT-4), one can obtain a competent reasoning model without proprietary access. The <em>Open-R1</em> project, for example, is a community effort to <strong>reconstruct DeepSeek-R1&#8217;s training pipeline and data</strong> openly (<a href="https://huggingface.co/blog/open-r1#:~:text=Face%20huggingface,boundaries%20of%20open%20reasoning%20models">Open-R1: a fully open reproduction of DeepSeek-R1 - Hugging Face</a>) &#8211; initiatives like this mean that the cutting-edge techniques are reproduced in accessible ways. Additionally, companies like Hugging Face host many fine-tuned reasoning models (some distilled from GPT-4) that one can use directly or as a starting point. This greatly lowers the entry barrier &#8211; instead of paying API fees or training costs, a startup can pick an open 13B model that has chain-of-thought ability and run it on a modest GPU. The trade-off might be some performance gap to the absolute state-of-art, but often this gap is small for practical use, as seen with DeepSeek&#8217;s own claim of reaching GPT-4 quality at <em>one-tenth the price</em> by leveraging open approaches (<a href="https://www.ignorance.ai/p/r1-is-reasoning-for-the-masses#:~:text=And%20R1%20isn%27t%20DeepSeek%E2%80%99s%20only,expertise%20in%20building%20frontier%20LLMs">R1 is reasoning for the masses - by Charlie Guo</a>).</p></li><li><p><strong>Operational Costs (Inference and Deployment)</strong>: Running a reasoning model in production has its own cost considerations. Reasoning models tend to use more tokens (due to the chain-of-thought) and possibly multiple inference passes (as with self-consistency or tool usage), meaning <strong>higher computational cost per query</strong>. Large enterprises can afford to deploy big models behind their services (e.g., using clusters of GPUs or specialized hardware), but startups might need to optimize. Techniques like <strong>model quantization</strong> (running models at 8-bit or 4-bit precision) can drastically cut memory and compute costs for inference, allowing even a 30B model to run on a single high-end GPU or a few CPU cores. There are also <strong>parameter-efficient serving</strong> strategies: for instance, using a smaller distilled model for most queries and only resorting to a larger model for particularly complex queries (cascaded deployment). Cloud providers offer on-demand GPU inference, so a startup could scale usage with demand rather than maintaining expensive hardware 24/7. Another route is using APIs of large models (OpenAI, etc.) for the hardest tasks and using an in-house model for easier tasks; however, API costs can add up and pose their own budget challenges if usage is high. The key is to balance model size and reasoning depth with the cost envelope. Often, a moderately-sized model (6B-13B parameters) with good training can handle a large fraction of tasks with reasoning if prompted well, at a vastly lower running cost than a 70B+ model.</p></li><li><p><strong>Choosing the Right Method for the Budget</strong>: Each training method discussed has different cost implications. <strong>Inference-time scaling</strong> is cheap from a development standpoint (no extra training), but it makes each inference more expensive (e.g., running 10 sampled solutions instead of 1). This might be fine for low-volume, high-stakes queries (like research analyses), but for high-throughput systems, one might prefer to invest more in training to make single-pass inference accurate. <strong>Pure RL training</strong> can be expensive in terms of the number of trial runs needed &#8211; it&#8217;s notoriously sample-inefficient, often requiring millions of queries through the model to get significant improvement. This translates to substantial GPU time. Thus, pure RL might be feasible only for well-funded teams or when using smaller models. <strong>SFT+RL (RLHF)</strong> pipelines also require human or AI feedback generation, which has a cost (either paying human annotators or the compute to run a judge model). OpenAI and others have spent many millions of dollars on RLHF data collection. Startups can mitigate this by using off-the-shelf reward models or by focusing RLHF on narrow domains (reducing the scope of feedback needed). <strong>Pure SFT</strong> is arguably the most budget-friendly to get started: if you have or can generate a dataset, you can fine-tune an open model in a matter of hours. Distillation adds some overhead (you need a teacher model to generate data, which if it&#8217;s an API like GPT-4, could incur usage costs). Some projects deliberately use <em>cheaper teacher models or automated heuristics</em> to generate reasoning data to avoid API fees.</p></li></ul><p>In conclusion, the path you take should align with your resource level:</p><ul><li><p>A <strong>startup or small lab</strong> should capitalize on open models, supervised fine-tuning with available data, and maybe light RLHF with open-source reward models. Keep models small-to-medium for manageable inference. Use cloud GPUs only as needed. The FinGPT example is apt: by using open data and models, they claim fine-tuning costs in the hundreds of dollars versus millions for training a new model (<a href="https://github.com/AI4Finance-Foundation/FinGPT#:~:text=1%29,tuning">GitHub - AI4Finance-Foundation/FinGPT: FinGPT: Open-Source Financial Large Language Models! Revolutionize We release the trained model on HuggingFace.</a>).</p></li><li><p>A <strong>large enterprise</strong> might train a custom reasoning model if the use-case demands (and justify it with proprietary data advantages). But even then, leveraging existing architectures and doing heavy post-training fine-tuning is usually more cost-effective than raw training. Enterprises also consider maintenance cost: a model like BloombergGPT might need retraining or frequent updates, which is expensive, so they are exploring continuous fine-tuning (which reasoning models handle well by incrementally learning new information) .</p></li><li><p>In <strong>resource-constrained environments</strong> (e.g., on-device AI or embedded systems), using distilled models or smaller &#8220;reasoning specialists&#8221; is key. One might distill a 70B model down to 7B and then quantize it so it can run on a mobile device or a single CPU &#8211; sacrificing some accuracy but achieving autonomy from cloud resources. The open research community&#8217;s focus on distillation (<a href="https://huggingface.co/deepseek-ai/DeepSeek-R1#:~:text=Distillation%3A%20Smaller%20Models%20Can%20Be,Powerful%20Too">deepseek-ai/DeepSeek-R1 &#183; Hugging Face</a>) and efficient fine-tuning is directly enabling this: we now have models like Llama-2 7B that, with the right fine-tuning, can perform complex reasoning surprisingly well, all while being deployable in low-resource settings.</p></li></ul><p>Ultimately, <strong>cost-effective reasoning AI is about leveraging what&#8217;s already available and tailoring it</strong> rather than reinventing the wheel. With the plethora of 2024&#8211;2025 research and open resources, even smaller players can build sophisticated reasoning models by smartly combining techniques &#8211; using public models, community data, and focusing compute on the critical fine-tuning steps. This democratization of reasoning models means we&#8217;ll continue to see broad adoption across industries without each player needing an enormous budget. The literature and industry trends agree: the gap between cutting-edge capability and accessible AI is closing, thanks in large part to these refined methods of building reasoning models (<a href="https://www.ignorance.ai/p/r1-is-reasoning-for-the-masses#:~:text=And%20R1%20isn%27t%20DeepSeek%E2%80%99s%20only,expertise%20in%20building%20frontier%20LLMs">R1 is reasoning for the masses - by Charlie Guo</a>) .</p><p><strong>Sources:</strong> Recent research papers and industry reports were referenced inline, including <em>DeepSeek-R1: Incentivizing Reasoning Capability in LLMs (2024/25)</em> (<a href="https://arxiv.org/html/2501.12948v1#:~:text=of%20reasoning%20capabilities%2C%20OpenAI%E2%80%99s%20o1%C2%A0,and%20search%20algorithms%20such%20as">DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning</a>), discussions of OpenAI&#8217;s and Anthropic&#8217;s models (<a href="https://getstream.io/blog/reasoning-llms/#:~:text=Large%20Language%20Models%20,LLMs%20that">Exploring Reasoning LLMs and Their Real-World Applications</a>), and insights from community projects like FinGPT (<a href="https://github.com/AI4Finance-Foundation/FinGPT#:~:text=1%29,tuning">GitHub - AI4Finance-Foundation/FinGPT: FinGPT: Open-Source Financial Large Language Models! Revolutionize We release the trained model on HuggingFace.</a>). Industry use cases were informed by official blogs and publications (e.g., PyTorch healthcare case study ([</p><pre><code><code>  Ambient Clinical Intelligence: Generating Medical Reports with PyTorch | PyTorch
</code></code></pre><p>](<a href="https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/#:~:text=This%20article%20will%20showcase%20how,the%20technologies%20that%20enable%20it">https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/#:~:text=This article will showcase how,the technologies that enable it</a>)), analytics on Large Action Models in robotics (<a href="https://www.analyticsvidhya.com/blog/2024/12/large-action-models/#:~:text=LAMs%20are%20advanced%20AI%20systems%2C,aware%20solutions">Large Action Models (LAMs): Applications and Challenges</a>)). These illustrate the state-of-the-art approaches and practical considerations as of 2024&#8211;2025 in building reasoning AI systems.</p>]]></content:encoded></item></channel></rss>