<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kapil Kumar on Medium]]></title>
        <description><![CDATA[Stories by Kapil Kumar on Medium]]></description>
        <link>https://medium.com/@kakumar1611?source=rss-22c5fee82d67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*geX2tQwwMDDKmlX3</url>
            <title>Stories by Kapil Kumar on Medium</title>
            <link>https://medium.com/@kakumar1611?source=rss-22c5fee82d67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:40:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kakumar1611/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Quest for Efficient Attention: A Journey from KV Cache to Radix Attention]]></title>
            <link>https://medium.com/@kakumar1611/the-quest-for-efficient-attention-a-journey-from-kv-cache-to-radix-attention-ea39b5bacca7?source=rss-22c5fee82d67------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea39b5bacca7</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[inference]]></category>
            <dc:creator><![CDATA[Kapil Kumar]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 17:04:59 GMT</pubDate>
            <atom:updated>2026-03-06T17:11:56.875Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Quest for Efficient Attention: A Journey from KV Cache to Radix Attention</strong></p><p><em>*How the ML community turned the O(n²) monster into a manageable beast*</em></p><p><strong>Prologue: The Attention Bottleneck</strong></p><p>It’s 2017. “Attention Is All You Need” has just been published, and the world is about to change. Transformers are elegant, parallelizable, and devastatingly effective.</p><h3><strong>Attention is expensive</strong></h3><p>Not just computationally expensive. Memory expensive. Quadratically expensive. For every token you add to your sequence, the attention matrix grows in both dimensions. A 2,048-token sequence needs to store 4 million attention scores. A 32,768-token sequence? Over a billion.</p><p>Attention Memory: O(n²)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*RHe1ElvygH3lRXrKQpkCQg.png" /></figure><blockquote>This is the story of how we fought back.</blockquote><h3><strong>Chapter 1: The Dawn of KV Caching</strong></h3><h4><strong>The Wasteful Ways of Autoregressive Generation</strong></h4><p>In the beginning, there was waste. Tremendous, horrifying waste.</p><p>When GPT-2 generated text, it would compute attention from scratch for every single token. Generate token 1? Compute attention. Generate token 2? Compute attention for <em>*both*</em> tokens. Token 100? Compute attention for all 100 tokens, even though tokens 1–99 haven’t changed.</p><p>Without KV Cache — Generating “The cat sat on the mat”</p><p>Step 1: Process “The” → 1 token</p><p>Step 2: Process “The cat” → 2 tokens</p><p>Step 3: Process “The cat sat” → 3 tokens</p><p>Step 4: Process “The cat sat on” → 4 tokens</p><p>Step 5: Process “The cat sat on the” → 5 tokens</p><p>Step 6: Process “The cat sat on the mat” → 6 tokens</p><p>Total: 1 + 2 + 3 + 4 + 5 + 6 = 21 token computations</p><p>For N tokens: N(N+1)/2 = O(N²) 🔥</p><p>This was madness. The Keys and Values for “The” don’t change just because we added “cat” to the sequence. Why recompute them?</p><p><strong>The Solution: Remember What You’ve Seen</strong></p><p>The insight was simple but powerful: <strong>**cache the K and V projections**</strong>.</p><p>With KV Cache:</p><p>Step 1: Compute K₁,V₁ for “The” → Store in cache</p><p>Step 2: Compute K₂,V₂ for “cat” → Append to cache, attend using [K₁,K₂]</p><p>Step 3: Compute K₃,V₃ for “sat” → Append to cache, attend using [K₁,K₂,K₃]</p><p>Total: 6 token computations (1 per step)</p><p>Complexity: O(N) 🎉</p><p>We went from O(N²) to O(N). The catch? We now had to store all those K and V tensors.</p><p># KV Cache structure</p><p>cache_size = 2 × num_layers × num_heads × seq_length × head_dim × bytes_per_element</p><p># For a 7B model (32 layers, 32 heads, head_dim=128, FP16):</p><p># At 2K context: 2 × 32 × 32 × 2048 × 128 × 2 = 1 GB</p><p># At 8K context: 2 × 32 × 32 × 8192 × 128 × 2 = 4 GB</p><p># At 32K context: 2 × 32 × 32 × 32768 × 128 × 2 = 16 GB</p><p>KV caching was our first victory. But it came with a price: memory. And as models grew larger and contexts grew longer, that price became steep.</p><h3><strong>Chapter 2: The Compression Crusade — MQA and GQA</strong></h3><h4><strong>The Memory Crisis</strong></h4><p>By 2022, the situation was getting dire. LLMs were scaling to 175B parameters. Context windows were growing from 2K to 8K to 32K. And the KV cache was eating GPUs alive.</p><p>LLMs were scaling to 175B parameters. Context windows were growing from 2K to 8K to 32K. And the KV cache was eating GPUs alive.</p><p>Consider serving a 70B model with 8K context:</p><ul><li>KV cache per request: ~4 GB</li><li>GPU memory: 80 GB (A100)</li><li>Usable for KV cache: ~40 GB</li><li><strong>**Maximum concurrent users: ~10**</strong></li></ul><p>Ten users. For a $10,000 GPU. Something had to give.</p><p><strong>Multi-Query Attention: A Radical Proposal</strong></p><p>Noam Shazeer had an idea in 2019 that was almost too simple: <strong>**what if all attention heads shared the same Keys and Values?**</strong></p><p>Standard Multi-Head Attention (MHA):</p><ul><li>32 Query heads</li><li>32 Key heads ← Each head has its own K</li><li>32 Value heads ← Each head has its own V</li></ul><p>Multi-Query Attention (MQA):</p><ul><li>32 Query heads</li><li>1 Key head ← All Q heads share one K</li><li>1 Value head ← All Q heads share one V</li></ul><p>The KV cache shrunk by 32×. One. Thirtieth. Of the memory.</p><p>KV Cache Comparison (70B model, 8K context):</p><ul><li>MHA: 4 GB per request</li><li>MQA: 125 MB per request ← 32× smaller!</li></ul><p>But there was a catch. Quality suffered. About 1–2% degradation on benchmarks. For some applications, that was acceptable. For others, it wasn’t.</p><p><strong>Grouped-Query Attention: The Goldilocks Solution</strong></p><p>In 2023, the Llama 2 team found the middle ground: <strong>**Grouped-Query Attention (GQA)**</strong>.</p><p>Instead of all heads sharing one KV pair (MQA) or each head having its own (MHA), groups of heads would share KV pairs.</p><p>GQA Configuration (Llama 2 70B):</p><ul><li>64 Query heads</li><li>8 Key heads ← 8 groups, 8 Q heads per group</li><li>8 Value heads</li></ul><p>KV cache: 8× smaller than MHA, only ~0.5% quality loss</p><p>This was the sweet spot. GQA became the standard overnight. Llama 2, Mistral, Qwen, Gemma — everyone adopted it.</p><p>We had won the memory war. But a new enemy was emerging.</p><h3><strong>Chapter 3: FlashAttention — Rewriting the Rules of Compute</strong></h3><h4><strong>The Hidden Bottleneck</strong></h4><p>While we were busy shrinking the KV cache, researchers at Stanford noticed something strange. Attention wasn’t slow because of computation. It was slow because of <strong>**memory bandwidth**</strong>.</p><p>GPUs in 2022 could perform 312 TFLOP/s of computation (A100). But they could only move 2 TB/s of data. The attention matrix was being written to memory, then read back for softmax, then written again, then read for the final multiplication.</p><p>Standard Attention Memory Traffic:</p><p>1. Compute S = Q @ K.T → Write S to HBM (slow)</p><p>2. Read S from HBM</p><p>3. Compute P = softmax(S) → Write P to HBM (slow)</p><p>4. Read P from HBM</p><p>5. Compute O = P @ V → Write O to HBM</p><p>For 8K sequence: Moving ~500MB back and forth, multiple times</p><p>The attention scores weren’t being <em>*computed*</em> slowly — they were being <em>*moved*</em> slowly.</p><p><strong>The Flash of Insight</strong></p><p>Tri Dao and his collaborators asked a beautiful question: <strong>**what if we never materialized the full attention matrix?**</strong></p><p>The key insight was that softmax could be computed <em>*incrementally*</em>. You didn’t need to see all the scores at once. You could process them in blocks, keeping a running maximum and sum, and correct as you went.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*fZLKOvZXL7wzCu4Ox6QvIw.png" /></figure><p>Memory: O(N) instead of O(N²)!</p><p>The algorithm was intricate. It involved tracking running statistics, rescaling partial results, and careful numerical precision. But the result was magical:</p><p>FlashAttention didn’t just make attention faster. It made previously impossible sequence lengths possible. The O(N²) memory wall had been shattered.</p><p><strong>FlashAttention-2 and 3: Refinements</strong></p><p>The community wasn’t done. FlashAttention-2 (2023) improved parallelism across sequence length, squeezing out another 2× speedup.</p><p>FlashAttention-3 (2024) leveraged H100-specific features — FP8 tensor cores, asynchronous memory operations, warp specialization — for yet another 1.5–2× improvement.</p><p>Attention had gone from the bottleneck to just another operation.</p><h3><strong>Chapter 4: Paged Attention — The Memory Allocation Revolution</strong></h3><h4><strong>The Fragmentation Problem</strong></h4><p>By late 2022, a new problem had emerged. Not compute. Not bandwidth. <strong>**Memory fragmentation**</strong>.</p><p>The KV cache had a dirty secret: it was pre-allocated. When a request came in, you had to reserve memory for the <em>*maximum possible*</em> sequence length, even if the actual response was much shorter.</p><p>The Pre-allocation Problem:</p><p>Request comes in: “What is 2+2?”</p><ul><li>Reserve KV cache for max_length=8192 tokens</li><li>Actual response: “4” (1 token)</li><li>Wasted memory: 8191 tokens worth</li></ul><p>With 100 concurrent requests:</p><ul><li>Allocated: 100 × 8192 tokens = 819,200 tokens</li><li>Actually used: Maybe 50,000 tokens</li><li>Efficiency: 6% 😱</li></ul><p>We were throwing away 94% of our memory. Worse, the pre-allocation meant we couldn’t even start new requests — the memory was “reserved” even though it wasn’t being used.</p><p><strong>vLLM and the Paged Revolution</strong></p><p>The vLLM team (UC Berkeley, 2023) borrowed an idea from operating systems: <strong>**virtual memory with paging**</strong>.</p><p>Instead of one contiguous block per sequence, the KV cache would be split into fixed-size pages (typically 16–256 tokens). Pages would be allocated on demand, only when actually needed.</p><p>Paged KV Cache:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LyyvnX3EeVsdF-XelLrktQ.png" /></figure><p>The page table tracked which physical pages belonged to which sequence. Pages could be allocated, freed, and even <em>*shared*</em> between requests with common prefixes.</p><p>Page Sharing (System Prompt):</p><p>All requests share: “You are a helpful assistant…”</p><ul><li>Traditional: Copy system prompt KV to every request</li><li>Paged: All requests point to same physical pages</li></ul><p>100 requests with 500-token system prompt:</p><ul><li>Traditional: 100 × 500 = 50,000 tokens</li><li>Paged: 500 tokens (shared) + unique parts</li><li>Savings: ~99× for the common prefix!</li></ul><p>Paged Attention increased serving throughput by 2–4× through better memory utilization. It was the difference between serving 10 users and serving 40 on the same hardware.</p><p><strong>Continuous Batching: The Final Piece</strong></p><p>Paged Attention enabled another crucial optimization: <strong>**continuous batching**</strong>.</p><p>Previously, you had to wait for all requests in a batch to finish before starting new ones (static batching). With paging, requests could join and leave dynamically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*aTzPusznoDRXmNE2PDXhwQ.png" /></figure><p>No more waiting. No more wasted cycles. The GPU stayed busy.</p><h3><strong>Chapter 5: Radix Attention — The Prefix Tree Revelation</strong></h3><h4><strong>The Redundancy We Missed</strong></h4><p>Even with paging, something nagged at the researchers at SGLang (UC Berkeley, 2024). They looked at production traffic patterns and saw massive redundancy:</p><p>Real-World Request Patterns:</p><p>Request 1: “You are a helpful assistant. User: What is Python?”</p><p>Request 2: “You are a helpful assistant. User: Explain recursion”</p><p>Request 3: “You are a helpful assistant. User: What is Python?”</p><p>Request 4: “You are a helpful assistant. Admin: Reset context”</p><p>Common prefix: “You are a helpful assistant. “</p><p>Requests 1 &amp; 3: Identical!</p><p>System prompts were repeated millions of times. Multi-turn conversations shared history. Even similar questions often had common prefixes.</p><p><strong>The Radix Tree Solution</strong></p><p>SGLang introduced <strong>**Radix Attention**</strong>: organize the KV cache as a radix tree (prefix tree), where common prefixes are stored once and shared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*Q4BTQVnHLPrIM4KDCAm80g.png" /></figure><p>When a new request comes in, the system traverses the tree, reusing cached KV values for any matching prefix. Only the novel suffix needs computation.</p><p><strong>The LRU Eviction Dance</strong></p><p>Trees grow. Memory doesn’t. Radix Attention needed smart eviction.</p><p>The solution was reference counting plus LRU (Least Recently Used). Each node tracks how many active requests use it. When a request finishes, reference counts decrement. Nodes with zero references become eviction candidates, prioritized by last access time.</p><p><strong>Epilogue: The State of the Art</strong></p><p>We’ve come far from the wasteful days of 2017. Let’s recap the journey:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*3TaPatgf6LPBQtiFf_qyyQ.png" /></figure><p>Each layer built on the last. KV caching made autoregressive generation practical. GQA made long contexts affordable. FlashAttention made them fast. Paged attention made serving efficient. Radix attention made prefix sharing automatic.</p><p><strong>### What’s Next?</strong></p><p>The journey isn’t over:</p><p>- <strong>**Speculative Decoding**</strong>: Use small models to draft tokens, large models to verify</p><p>- <strong>**Ring Attention**</strong>: Distribute attention computation across a ring of devices for million-token contexts</p><p>- <strong>**Linear Attention**</strong>: Approximate attention with O(N) complexity (Mamba, RWKV)</p><p>- <strong>**Sparse Attention**</strong>: Only attend to relevant tokens (BigBird, Longformer patterns)</p><p>- <strong>**Quantized KV Cache**</strong>: Store K,V in INT4/INT8 for 2–4× more context</p><p>The O(N²) monster isn’t slain — it’s just been tamed. For now.</p><p><em>The attention mechanism was supposed to be the heart of transformers. It almost became their Achilles’ heel. Instead, it became the most optimized piece of code in modern AI. And the optimization continues.*</em></p><p>**Written with assistance of claude.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea39b5bacca7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMs for Recsys and Search — Part 1: Semantic Ids and Evolving architectures]]></title>
            <link>https://medium.com/@kakumar1611/llms-for-recsys-and-search-part-1-semantic-ids-and-evolving-architectures-2651bc5c47c6?source=rss-22c5fee82d67------2</link>
            <guid isPermaLink="false">https://medium.com/p/2651bc5c47c6</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[semantics]]></category>
            <dc:creator><![CDATA[Kapil Kumar]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 13:32:06 GMT</pubDate>
            <atom:updated>2025-06-30T18:47:15.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rethinking Recommendation &amp; Search in LLM Era— Part 1: Semantic Ids and Generative Retrieval</h3><p>Large Language Models (LLMs) and multimodal AI are fundamentally transforming recommendation and search systems, shifting from traditional ID-based memorization to deep semantic understanding. This change is crucial for overcoming challenges like “cold-start” (new items/users) and “long-tail” (less popular content) problems, enabling unprecedented personalization and discovery.</p><p>Key advancements include:</p><ul><li><strong>Semantic Ids and Generative Retrieval:</strong> Systems leverage “Semantic IDs” (e.g., YouTube, RecGPT, RPG) and generative retrieval models (e.g., TIGER, OneRec, LIGER) for richer content representation and direct recommendations, moving beyond traditional ID-based approaches.</li><li><strong>Leveraging LLMs for Sequential Recommendations and Personalised Explanations:</strong> Generative LLMs (e.g., Google CALRec, GLOSS) provide direct recommendations and personalized explanations, enhancing transparency and user trust.</li><li><strong>Multimodal and Cross-Modal Integration:</strong> Multimodal embeddings (e.g., Kuaishou M3CSR) offer richer content understanding, while cross-modal alignment techniques (e.g., Huawei FLIP, beeFormer) bridge the strengths of ID-based models and LLMs.</li><li><strong>Data Augmentation and Quality:</strong> LLMs actively augment, generate, and enhance data quality, addressing scarcity by creating high-quality labels (e.g., Indeed), synthetic queries (e.g., Spotify, Amazon Music), and serving as scalable evaluation judges.</li><li><strong>Agentic Systems:</strong> LLM-empowered agents are emerging for search and recommendation, enabling autonomous decision-making, multi-step reasoning, and dynamic interaction with environments.</li><li><strong>Operational Scaling:</strong> Training paradigms adapt LLM best practices, including scaling laws (e.g., Netflix), knowledge distillation (e.g., YouTube, Google), and parameter-efficient fine-tuning (e.g., Alibaba MLORA) for performance and cost-effectiveness.</li><li><strong>Unified Discovery:</strong> Search and recommendation functionalities converge into unified architectures (e.g., Netflix UniCoRn, Spotify GenSAR), often with natural language interfaces (e.g., LinkedIn 360Brew), to streamline development and enhance user experience.</li></ul><h3>Introduction</h3><p>Recommendation systems (RecSys) and search engines are critical components of modern digital platforms, guiding users through vast amounts of information to discover relevant content. For decades, these systems relied primarily on ID-based approaches and collaborative filtering, which analyze extensive historical user interaction data such as clicks, purchases, and views to predict future preferences. While highly effective for popular items and users with rich interaction histories, these conventional methods frequently encountered significant limitations. A notable challenge was the “cold-start” problem, where insufficient or no historical interaction data is available for new users or items, making accurate recommendations difficult. Similarly, “long-tail” items, which are less popular and have sparse interaction data, also posed significant challenges. Conventional search systems, predominantly operating on keyword matching, often struggled to capture the nuanced intent embedded within natural language queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*kvkhRe0glNSeiSRWxg3HYg.png" /></figure><p>A profound transformation is now underway, driven by the rapid advancements in Large Language Models (LLMs) and multimodal AI. This shift fundamentally reshapes how recommendation and search systems function, moving beyond simple pattern recognition to encompass deep semantic understanding, sophisticated data generation, and the unification of previously disparate functionalities. LLMs, with their remarkable ability to comprehend, interpret, and generate complex language, are evolving from standalone text generators into integral components of intricate recommendation and search pipelines. This evolution is synergistically complemented by multimodal AI, which empowers systems to process and understand diverse data types — including images, audio, and video — thereby providing a more holistic and contextually rich view of content and user intent.</p><p>This technological progression represents a fundamental reorientation of recommendation systems, moving from an implicit understanding of user preferences to an explicit one. Traditional collaborative filtering models infer user preferences indirectly from behavioral signals, excelling at “memorizing” past user-item interactions, such as “users who engaged with X also engaged with Y”. This reliance on historical data, however, creates significant cold-start challenges for new or infrequently interacted items, as there is no interaction history to leverage. LLMs and multimodal AI overcome this by directly processing and understanding the intrinsic properties of items — their textual descriptions, visual characteristics, or audio features — and discerning the precise intent behind natural language user queries. This capability allows a system to recommend a new item based on its inherent semantic properties, even without prior user interactions. This transition fundamentally redefines the core problem from merely identifying patterns in interaction data to semantically understanding content and user intent, leading to more robust solutions for cold-start scenarios and enabling more transparent, human-understandable recommendations.</p><p>The inherent tension between a system’s ability to “memorize” specific past interactions (where ID-based systems excel) and its capacity to “generalize” to new, unseen content or users (where LLMs excel through semantic understanding) has been a persistent challenge. The emergence of LLMs directly addresses this fundamental weakness of previous systems. This suggests that a truly robust system will need to leverage both strengths, leading to hybrid architectures that can effectively recall known interactions while generalising to new or sparse data. This foundational understanding underpins many of the architectural solutions and advancements discussed in subsequent sections, where combined approaches are often preferred over wholesale replacements.</p><p>Furthermore, the ability of LLMs to generate synthetic data for cold-start scenarios signifies a paradigm shift in data acquisition and model training for new content. Historically, addressing cold-start was primarily a challenge of data scarcity, where new items remained invisible to collaborative filtering until sufficient user interactions accumulated. This often meant a “passive waiting game” for new content to gain traction. With the advent of LLMs, this paradigm has shifted dramatically. LLMs can now actively generate rich representations or synthetic data for new content and users. For instance, they can create synthetic user queries, elaborate item descriptions, or even discrete “semantic IDs” for new content. This capability effectively “fills in” missing data or constructs a rich, semantically meaningful initial representation from the moment a new item is introduced. This transforms cold-start from a passive waiting game into an active opportunity, significantly accelerating the onboarding of new content and users into the recommendation ecosystem.</p><h3>Semantic Ids and Generative Retrieval</h3><p>The integration of LLMs and multimodal AI is fundamentally reshaping the architectural design of recommendation and search systems. This evolution marks a pivotal shift from traditional ID-based approaches towards deep semantic understanding, which is crucial for overcoming the inherent limitations of conventional systems, particularly in handling cold-start and long-tail items.</p><h3>Semantic IDs and Discrete Item Representations</h3><p>Traditional recommendation models widely employ randomly-hashed item identifiers (IDs). While these IDs are effective for memorization and efficient lookup in large-scale systems, they inherently struggle with generalization, especially for new (cold-start) and less popular (long-tail) items where data sparsity prevents the system from learning meaningful relationships. YouTube has pioneered an innovative solution by introducing Semantic IDs (SIDs), which are compact, discrete item representations derived directly from content features. This approach is implemented through a two-stage framework: a transformer-based video encoder first generates dense content embeddings, which are then compressed into discrete SIDs using a Residual Quantization Variational AutoEncoder (RQ-VAE).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*f2QoxCuqekhFvUjvtbOQTw.png" /><figcaption><a href="https://arxiv.org/pdf/2306.08121v2">BETTER GENERALIZATION WITH SEMANTIC IDS</a></figcaption></figure><p>The design of SIDs captures hierarchical relationships and underlying concepts within items, providing a semantically rich representation. Utilizing these compact SIDs to represent user histories significantly enhances efficiency in large-scale systems. Empirical evaluations on YouTube’s dataset demonstrate that SIDs can effectively replace direct video IDs, leading to improved generalization capabilities for new and long-tail item distributions without compromising overall model quality. The SentencePiece Model (SPM) tokenization method was found to be particularly effective in adapting SIDs within ranking models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*U5Ibw8liJ1bbtWWavyK8Hg.png" /><figcaption><a href="https://arxiv.org/pdf/2306.08121v2">BETTER GENERALIZATION WITH SEMANTIC IDS</a></figcaption></figure><p><strong>RPG</strong>: Further advancements in semantic ID-based models involve tokenizing each item into multiple discrete tokens, <strong>which collectively enhance performance, scalability, and memory efficiency</strong>. For example, RPG, a recent framework, proposes generating unordered, long semantic IDs, capable of scaling up to 64 tokens per item. This parallel prediction of all tokens yields an average of 12.6% improvement in NDCG@10 over generative baselines, alongside enhanced inference efficiency. Extending this concept, Mixture-of-Codes introduces the construction of multiple independent codebooks for LLM representation during the indexing stage. When utilized with a fusion module in the recommendation phase, this approach demonstrates superior discriminability and dimension robustness, leading to improved scalability in recommendations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*brJrfmfydNc2pnvlbHgbvw.png" /><figcaption><a href="https://arxiv.org/pdf/2506.05781">Generating Long Semantic IDs in Parallel for Recommendation</a></figcaption></figure><p><strong>RPG performs quantisation by adopting Optimized Product Quantization (OPQ) to represent items</strong></p><p>The underlying principle of Product Quantisation (PQ), which OPQ is based on, involves:</p><p>Splitting and Clustering: A collection of d-dimensional vectors is first split into <em>m</em> smaller collections of sub-vectors. Each of these sub-vector collections then undergoes clustering (e.g., using k-means), where each original sub-vector is replaced by the centroid of its assigned cluster68.</p><p>Compression through Unique Sub-vectors: Instead of storing the entire matrix of sub-vectors, only these unique sub-vectors (centroids) are stored in a separate tensor.</p><p>Encoding with Sub-Item IDs: To compress the approximate embedding matrix, only the IDs of these sub-vectors (sub-ids or codes) need to be stored for each item. For each item, <em>m</em> integer codes are stored, each capable of taking one of <em>b</em> possible values, allowing for the encoding of up to b^m different vectors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*ZFyAbSpsycJ40klK_US8DA.png" /><figcaption><a href="https://arxiv.org/pdf/2312.06165">RecJPQ</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*JTr7x5TGDby8QpvsfJBFqg.png" /></figure><h3>Unified End-to-End Generative Recommendation Systems</h3><p>These systems aim to combine semantic understanding (often via implicit or explicit semantic ID generation) and the recommendation task (retrieval and/or ranking) into a single, integrated generative framework.</p><ul><li><strong>The Generative Leap: TIGER:</strong> Building directly on the semantic ID foundation, TIGER (Transformer Index for Generative Recommenders) represented the first major evolution toward generative retrieval. TIGER transformed the recommendation paradigm from retrieve-and-rank to pure generative retrieval by training Transformer models to autoregressively predict the Semantic IDs of items users would interact with next. The critical advancement was moving from using semantic IDs merely as better representations in traditional ranking models to treating them as the core output of a generative process. This approach demonstrated superior performance on cold-start recommendations and enhanced diversity compared to traditional methods. TIGER established that semantic IDs could serve as both the representation and the target for recommendation models. However, TIGER’s approach still relied on sequential generation with beam search, which introduced computational bottlenecks that would later be addressed by subsequent innovations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*jeGwBiRm5yB5KLrx65B9VA.png" /><figcaption><a href="https://papers.neurips.cc/paper_files/paper/2023/file/20dcab0f14046a5c6b02b61da9f13229-Paper-Conference.pdf">TIGER</a></figcaption></figure><ul><li><strong>The Industrial Solution: OneRec:</strong> OneRec represents the practical industrial deployment of generative recommendation principles at massive scale. Unlike TIGER’s focus on academic benchmarks, OneRec was designed as the first end-to-end generative model that significantly surpasses current complex and well-designed recommender systems in real-world scenarios. OneRec introduced several key innovations over TIGER: an encoder-decoder structure with sparse Mixture-of-Experts (MoE) to scale model capacity without proportional computational increases, a session-wise generation approach instead of traditional next-item prediction, and an Iterative Preference Alignment module combined with Direct Preference Optimization (DPO). This work demonstrated that the semantic ID paradigm established by the ranking paper and extended by TIGER could be successfully deployed at industrial scale with significant business impact.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*iXc9z_o6FrP1dJxxXqbPxg.png" /><figcaption><a href="https://arxiv.org/pdf/2502.18965">ONE REC</a></figcaption></figure><ul><li><strong>The Hybrid Approach: LIGER:</strong> LIGER (Leveraging dense retrieval for Generative Retrieval) emerged as a response to observed limitations in pure generative retrieval approaches. While generative retrieval showed promise for large-scale applications, it struggled with cold-start items on smaller datasets compared to dense retrieval methods. LIGER’s innovation was creating a hybrid model that combines the computational efficiency of generative retrieval with the robust performance of dense retrieval. The system uses generative retrieval to produce an initial candidate set, then applies dense retrieval techniques for final ranking. This approach maintains the storage advantages of semantic IDs while addressing the cold-start limitations that pure generative approaches faced. LIGER represents a mature understanding that different retrieval paradigms have complementary strengths, and the optimal solution often involves combining them rather than choosing one over the other.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*nuof0il_HkXcfo30TrKO6Q.png" /><figcaption><a href="https://arxiv.org/pdf/2411.18814">LIGER</a></figcaption></figure><ul><li><strong>The Foundation Model: RecGPT:</strong> RecGPT represents the most ambitious evolution of the semantic ID paradigm, addressing the fundamental barrier of cross-domain generalization. Unlike previous approaches that focused on single-domain optimization, RecGPT was designed as a foundation model capable of zero-shot generalization across different recommendation domains. RecGPT’s key innovations include unified item tokenization with Finite Scalar Quantization (FSQ) that transforms heterogeneous textual descriptions into standardized discrete tokens, eliminating domain barriers. The system features hybrid bidirectional-causal attention and an efficient catalog-aware beam search decoder with Trie-based prefix constraints. This work represents the culmination of the semantic ID evolution, showing how the basic principles established in the original ranking paper could be extended to create truly generalizable recommendation systems.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*HOJ88eadJkTzITijOr7BKQ.png" /><figcaption><a href="https://arxiv.org/pdf/2404.08675">REC-GPT</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*YTWWxdPMvnIkBOcFs1WNZQ.png" /></figure><p>The shift towards semantic ID-based recommendation systems introduces distinct challenges across the lifecycle of these identifiers, from their initial generation to their effective utilisation within complex recommendation models.</p><p><strong>Challenges in Semantic ID Generation:</strong></p><ul><li><strong>Capturing Rich Semantics and Hierarchical Relationships:</strong> Condensing complex, high-dimensional raw content (e.g., video, text) into compact, discrete IDs while retaining rich semantic meaning and hierarchical relationships (e.g., a video’s topic, genre, and specific actions) is a significant hurdle. Solutions include YouTube’s Semantic IDs (SIDs) using a transformer-based video encoder and RQ-VAE to capture hierarchical relationships and underlying concepts. RecGPT derives item representations exclusively from textual features using Finite Scalar Quantization (FSQ) to create a domain-invariant vocabulary that bridges diverse contexts. RPG generates unordered, long semantic IDs (up to 64 tokens) using optimized product quantization to increase expressiveness.</li><li><strong>Balancing Generalization vs. Memorization:</strong> Directly replacing traditional item IDs (which excel at memorizing specific interactions) with purely semantic embeddings can sometimes degrade performance, as ranking models heavily rely on memorization from ID-based embedding tables. Solutions like YouTube’s SIDs are explicitly designed to balance generalization (for new/long-tail items) and memorization (via their compact, discrete nature), suggesting that hybrid approaches are often superior to purely semantic ones.</li><li><strong>Efficiency and Expressiveness:</strong> Generative models often suffer from inefficient inference (e.g., beam search, multiple forward passes), which restricts the practical length of semantic IDs (e.g., to just 4 tokens), thereby limiting their expressiveness. RPG addresses this by proposing parallel prediction of all semantic ID tokens in a single step using a multi-token prediction (MTP) objective. This allows for the creation of longer semantic IDs (up to 64 tokens) and significantly improves inference efficiency, making runtime memory and time complexities independent of the number of candidate items.</li></ul><p><strong>Challenges in Using Semantic IDs within Recommendation Models:</strong></p><ul><li><strong>Integration into Existing Ranking Models:</strong> Adapting discrete semantic IDs for use in large-scale ranking models that were traditionally built for random item IDs requires specific techniques. YouTube found that the SentencePiece Model (SPM) tokenization method was particularly effective in adapting SIDs within their ranking models, outperforming N-gram approaches.</li><li><strong>Cold-Start for Generative Retrieval:</strong> While generative retrieval (predicting item IDs/tokens) offers efficiency, it can struggle with new, “cold-start” items that lack sufficient historical data to learn their semantic IDs effectively. LIGER proposes a hybrid model that integrates dense retrieval techniques into the generative framework to combine the efficiency of generative retrieval with the cold-start handling benefits of dense retrieval. RecGPT tackles this by deriving item representations exclusively from textual features and using a “domain-invariant tokenization mechanism,” enabling genuine zero-shot generalization for new items.</li><li><strong>Inefficient Inference for Generative Semantic ID Models:</strong> Generative models that predict semantic IDs token-by-token often suffer from inefficient inference due to reliance on resource-intensive beam search and multiple forward passes through the neural sequence model. RPG directly addresses this by enabling parallel prediction of all tokens in a semantic ID. During inference, it constructs a graph connecting similar SIDs and guides decoding to avoid invalid IDs, significantly improving efficiency.</li></ul><p>References:</p><ol><li><a href="https://arxiv.org/pdf/2306.08121v2">BETTER GENERALIZATION WITH SEMANTIC IDS</a></li><li><a href="https://arxiv.org/pdf/2506.05781">Generating Long Semantic IDs in Parallel for Recommendation</a></li><li><a href="https://papers.neurips.cc/paper_files/paper/2023/file/20dcab0f14046a5c6b02b61da9f13229-Paper-Conference.pdf">TIGER</a></li><li><a href="https://arxiv.org/pdf/2411.18814">LIGER</a></li><li><a href="https://arxiv.org/pdf/2502.18965">ONE REC</a></li><li><a href="https://arxiv.org/pdf/2404.08675">REC-GPT</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2651bc5c47c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Illustrated Guide to Cross-Encoders: From Deep to Shallow]]></title>
            <link>https://medium.com/@kakumar1611/the-illustrated-guide-to-cross-encoders-from-deep-to-shallow-2a23a8630016?source=rss-22c5fee82d67------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a23a8630016</guid>
            <category><![CDATA[reranker]]></category>
            <category><![CDATA[cross-encoder]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[reranking]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Kapil Kumar]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 09:38:27 GMT</pubDate>
            <atom:updated>2024-12-18T14:16:06.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*dI16cW2oboK_wzqU.gif" /></figure><p>This blog explores <strong>cross-encoders</strong>, their functionality, strengths, and trade-offs in modern information retrieval systems like <strong>Retrieval Augmented Generation (RAG)</strong>. You’ll learn:</p><ol><li><strong>How Cross-Encoders Work</strong>:They process query-document pairs together using transformers to compute relevance scores. Attention mechanisms reveal how tokens interact across sequences for semantic understanding.</li><li><strong>Implementation Insights</strong>: Examples, visualisations, and tips for integrating cross-encoders effectively. How to address limitations with fine-tuning and architecture choices.</li><li><strong>Strengths and Limitations</strong>:Why cross encoders excel at nuanced relevance detection but struggle with surface-level term matching or computational efficiency.</li><li><strong>Deep vs. Shallow Architectures</strong>: Trade-offs between precision, latency, and scalability. When to choose deep vs. shallow models based on real-world constraints.</li></ol><p>By the end, you’ll understand how cross-encoders enhance retrieval systems and how to optimise their use for your specific needs.</p><h3>Introduction</h3><p>A cross-encoder is a neural architecture that processes query-document pairs together to compute relevance scores. Unlike traditional embedding models (Bi Encoders) that process queries and documents separately, cross-encoders enable direct interaction between tokens from both sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OCjPc5JY6gGRqN0ffX_ndA.png" /></figure><p>In RAG applications, cross-encoders are typically deployed as rerankers in a two-stage retrieval process. First, a fast vector search(Bi-encoder) retrieves a broader set of potentially relevant documents. Then, the cross-encoder carefully examines these candidates to identify the truly most relevant ones for the LLM to use. This hybrid approach combines the best of both worlds — the speed of vector search with the precision of cross-encoder analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a23EIThb2EI1_RXuayy_Sg.png" /><figcaption>ref : <a href="https://www.pinecone.io/learn/series/rag/rerankers/">https://www.pinecone.io/learn/series/rag/rerankers/</a></figcaption></figure><p><strong>Key Features of Cross Encoder</strong></p><ol><li><strong>Deep Semantic Understanding</strong>: Cross-encoders capture nuanced relationships between queries and documents</li><li><strong>Contextual Analysis</strong>: Token interactions across sequences enable better relevance detection</li><li><strong>High Precision</strong>: Superior accuracy in understanding complex relationships</li></ol><p>While cross-encoders are computationally more intensive than simple embedding models, their superior accuracy in understanding relevance makes them invaluable for applications where precision matters. From improving search results to filtering the right context for LLMs, cross-encoders have become an essential tool in the modern information retrieval toolkit.</p><p>In this article, we’ll dive deep into how cross-encoders work, examine their strengths and limitations, and explore practical strategies for integrating them effectively into RAG systems.</p><h3>How Cross-Encoder Work ?</h3><p>The key to cross-encoders’ effectiveness is how they process query and document tokens together in a single sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1RzWtniGNXA7chUibXadw.png" /></figure><p>Let’s break down the process:</p><p><strong>Input Formation</strong></p><ul><li>Query and document are concatenated: [CLS] query [SEP] document [SEP]</li><li>Special tokens ([CLS], [SEP]) help model understand sequence structure</li><li>Query and document tokens can directly attend to each other</li></ul><p><strong>Attention Mechanisms</strong></p><ul><li>Each token can attend to every other token</li><li>Strong attention between matching terms (e.g., “neural” → “neural”)</li><li>Contextual attention between related terms (e.g., “networks” → “patterns”)</li><li>[CLS] token aggregates cross-sequence interactions</li></ul><p><strong>Key Patterns</strong></p><ul><li><strong>Term Matching</strong>: Direct attention between identical terms</li><li><strong>Semantic Matching</strong>: Attention between related concepts</li><li><strong>Cross-Sequence Understanding</strong>: Query terms attend to relevant document sections</li></ul><p><strong>Layer Progression</strong></p><ul><li>First layer: Mostly lexical matching</li><li>Later layers: More semantic and contextual matching</li><li>Final layers: Task-specific relevance patterns</li></ul><h3>Lets Visualise this</h3><p>We can use a popular cross encoder model, cross-encoder/ms-marco-TinyBERT-L-2-v2, pretrained on ms-macro dataset.</p><pre>Model: cross-encoder/ms-marco-MiniLM-L-2-v2<br>Number of transformer layers: 2<br>Number of attention heads per layer: 12<br>Hidden size: 384</pre><p>Visualiser Code Link : <a href="https://github.com/kapilduhoon/CrossEncoderViz/tree/main">https://github.com/kapilduhoon/CrossEncoderViz/tree/main</a></p><h3><strong>Relevant/Positive Example</strong></h3><p><strong>Query</strong>: how do neural networks learn patterns</p><p><strong>Document</strong> : neural networks learn by adjusting connection weights through backpropagation, gradually minimizing prediction errors during training.</p><pre>Cross-Encoder Relevance Score (Query X Document) : 6.6836</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIEtqwgq-_PVVOKXqHL3aw.png" /><figcaption>Layer Visualisation for +ve Example</figcaption></figure><p>Cross encoder gives a much lower score for another example which is expected as thats not really relevant</p><h3><strong>Irrelevant/Negative Example</strong></h3><p><strong>Query</strong>: how do neural networks learn patterns</p><p><strong>Document</strong> : Today, the weather pattern predicted by AI is sunny with a high of 75 degrees fahrenheit and light winds from the northwest</p><pre>Cross-Encoder Relevance Score: -11.2903</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yl6_wcBSdMdQz_ni1ybXyQ.png" /><figcaption>-ve example: Query: how do neural networks learn patterns<br>Document: Today, the weather pattern predicted by AI is sunny with a high of 75 degrees fahrenheit and light winds from the northwest</figcaption></figure><h3>Let us analyse the contrasting outcomes between the positive and negative examples:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xk2PkFoVTdx_s-q2cq8drA.png" /></figure><p><strong>Key Differences:</strong><br>Attention Strength:<br>- Positive example shows consistently higher attention scores<br>- Negative example has weak, scattered attention</p><p>Semantic Relevance:<br>- Positive example builds meaningful technical connections<br>- Negative example fails to establish relevant relationships</p><p>Layer Progression:<br>- Positive example shows increasing understanding across layers<br>- Negative example maintains low relevance across all layers</p><p>The cross-encoder effectively distinguishes between relevant and irrelevant content through both its attention patterns and final relevance scores.</p><h3>Caveats Of Using Cross Encoders blindly.</h3><p>As we see below, The score for the first document is higher for the second one, which was not really expected, Second example is much more relevant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMQgML00qY0jbQ0PC08MUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PE9JIsnKTS_uwY9lmPVGig.png" /><figcaption>Query: how do neural networks learn patterns<br>Document: Today, Neural networks learn complex patterns <br>but lets get back to our topic of how neuron predicts<br>Cross-Encoder Relevance Score: 7.1277</figcaption></figure><p>As we anlayse outputs from various layers for example 1, we observe</p><ol><li>Strong exact matches in early layers (superficial matching)</li><li>Consistent attention scores throughout layers</li><li>The model is heavily weighting the direct term matches (“neural networks learn patterns” appears almost verbatim)</li></ol><p><strong>This illustrates a key limitation:</strong> the cross-encoder is placing too much emphasis on surface-level term matching rather than understanding the deeper semantic relevance or quality of the explanation. The model seems to prefer documents that mirror the query terms exactly, even if they don’t provide a proper explanation of the concept.</p><p><strong>Potential Reasons</strong>:</p><ul><li><strong>Training data bias</strong>: The model might have seen more examples of simple term matching during training</li><li><strong>Length and complexity</strong>: The more detailed technical explanation might be penalised due to its complexity</li><li><strong>Position bias</strong>: The model might be giving more weight to early matches in the document , lets see the example below, where we change the order of words and suddenly the score drops.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elKbb4x_hNACGyRFjZAdqA.png" /><figcaption>here we get much lower score if we change positions</figcaption></figure><h3>Solutions</h3><ol><li>If using a pre-trained model, understand on which dataset it is trained on, does it fit your use case.</li><li>Potentially retrain or fine-tune the model a model on your dataset, with LLMs this has become much easier.</li></ol><h3>Another practical consideration for speed-up: Deep vs Shallow Architecture</h3><p>Cross-encoders face a fundamental trade-off between processing power and performance. With a fixed latency budget (say 25ms), you can either:<br>1. Process fewer documents with a deep model<br>2. Process more documents with a shallow model</p><p>The key difference between traditional cross-encoders and shallow ones lies in their architecture. Let’s look at them side by side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zox0bP_p06aHH_Xwps2w5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJDPTh6xtXZrUPNItXHZSQ.png" /><figcaption>Ref: <a href="https://arxiv.org/pdf/2403.20222v1">https://arxiv.org/pdf/2403.20222v1</a></figcaption></figure><p><strong>Speed vs Depth Trade-off</strong><br> — Deep models: More accurate per document but process fewer documents<br> — Shallow models: Less accurate per document but process many more documents<br> — In low-latency settings, the ability to examine more candidates wins</p><p><strong>Resource Efficiency</strong><br> — 17MB model size vs 1.2GB<br> — Works well on CPU (only 3% performance drop vs GPU)<br> — Lower memory and energy requirements</p><p>The surprising finding is that in real-world scenarios with strict latency requirements, the shallow model’s ability to process more candidates actually leads to better overall performance.</p><h3>Conclusion</h3><p>Cross-encoders excel at semantic matching by processing query-document pairs together, but require careful optimization. Here’s your practical implementation checklist:</p><p><strong><em>Optimizing Compute Costs</em></strong><br>- Leverage shallow architectures (2–4 layers)/ distillation for efficient processing<br>- Implement as a reranker, processing only top 50–100 candidates<br>- Maximize efficiency through ONNX runtime, model quantization</p><p><strong><em>Handling Relevance Challenges</em></strong><br>- Build and validate on domain-specific datasets<br>- Use attention visualization tools to understand model behavior<br>- Test extensively with varying document lengths and structures<br>- Test for position bias and if model is doing exact term matching.<br>- Regularly evaluate edge cases and failure modes</p><p><strong><em>Production Integration Tips</em></strong><br>- Implement smart caching for frequent queries<br>- Set appropriate timeouts (suggest 100–200ms)<br>- Build robust fallback mechanisms<br>- Track key metrics: Relevance score distribution, Latency (p95/p99), Cache hit rates, Error rates and types</p><p>Start simple, measure thoroughly, and optimize based on your specific use case needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a23a8630016" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Query Expansion Using LLMs]]></title>
            <link>https://medium.com/@kakumar1611/query-expansion-using-llms-a82547a2759a?source=rss-22c5fee82d67------2</link>
            <guid isPermaLink="false">https://medium.com/p/a82547a2759a</guid>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[query-understanding]]></category>
            <category><![CDATA[query-expansion]]></category>
            <dc:creator><![CDATA[Kapil Kumar]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 16:35:43 GMT</pubDate>
            <atom:updated>2024-11-19T16:46:57.644Z</atom:updated>
            <content:encoded><![CDATA[<p>Query expansion is a widely used technique that enhances search system recall by augmenting the original query with additional terms, enabling the retrieval of relevant documents even when they share no exact word matches with the initial query. While traditional methods have served us well, Large Language Models (LLMs) are now taking query expansion to exciting new heights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKm768WL_W5__nICWA687w.png" /><figcaption>Query Expansion</figcaption></figure><h3>The Evolution of Query Expansion</h3><p>Before diving into LLMs, let’s understand how query expansion has evolved. Traditional approaches started with simple dictionary lookups (think WordNet) and graduated to more sophisticated methods like:</p><ul><li><strong>Lexical Knowledge Bases</strong>: While reliable, they required constant manual updates to stay relevant. Some Search Systems may already have entities/keywords indexed those can be reused.</li><li><strong>Pseudo-Relevance Feedback (PRF)</strong>: This clever technique looks at top search results to find related terms. It’s like asking “If these results are good, what words do they have in common?”. This becomes powerful when query is short, Although it assumes returned results are relevant.</li><li><strong>Document Expansion</strong>: Instead of expanding queries, this method enriches documents themselves during indexing — like adding metadata to your library before anyone searches.</li><li><strong>Word Embeddings</strong>: Neural models like BERT brought us closer to understanding context, treating words not as mere strings but as complex concepts in a semantic space.</li></ul><p>LLMs Language Models (LLMs) have seen a growing interest in the Information Retrieval (IR) community in recent years. They exhibit several properties, including the ability to answer questions and generate text, that make them powerful tools.</p><ol><li><strong><em>Few Shot Prompting Using LLMs </em></strong>: In paper <a href="https://arxiv.org/pdf/2303.07678">Query2doc</a> authors recommend generating pseudo-documents by few-shot prompting LLMs and concatenates them with the original query to form a new query.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Cwi6SsAAXpBdLyZ9KL5fBg.png" /><figcaption>Query2Doc</figcaption></figure><p>3. <strong><em>Chain of Thought Prompting + Pseudo-Relevance Feedback :</em></strong> <a href="https://arxiv.org/pdf/2305.03653">Query Expansion by Prompting Large Language Models</a> , They compare various LLM based approaches and conclude that the best performance is obtained by CoT (and the corresponding PRF-enhanced prompt CoT/PRF). This particular prompt instructs the model to generate a verbose explanation by breaking its answer down into steps. We hypothesize that this verbosity may lead to many potential keywords that are useful for query expansion. Finally, we find that adding PRF documents to the prompt helps significantly in top-heavy ranking metrics like MRR@10 and NDCG@10 across models and prompts. A possible explanation for this is that LLMs are effective in distilling the PRF documents, which may already contain relevant passages, by attending over the most promising keywords and using them in the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*yVsNlGAZekyfz45SGr6lbA.png" /><figcaption>Query Expansion Chain of though Prompting</figcaption></figure><h3>Best Practices for the Real World</h3><p>While LLMs offer exciting possibilities, success lies in smart implementation:</p><ol><li><strong>Hybrid Approaches Win</strong>: Combine LLMs with traditional methods for robust results.</li><li><strong>Context Matters</strong>: Short queries need different handling than long ones. LLMs excel at understanding context but need appropriate prompting.</li><li><strong>Performance Optimisation</strong>: Cache common expansions.</li><li><strong>Domain Adaptation</strong>: Fine-tune LLMs for specific domains when possible. A medical search engine needs different expansions than a fashion retailer.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a82547a2759a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>