<?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 Neeraj Kumar on Medium]]></title>
        <description><![CDATA[Stories by Neeraj Kumar on Medium]]></description>
        <link>https://medium.com/@neerajku?source=rss-53044a832204------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CPXbQFlmPLpomM9_aLapxA.jpeg</url>
            <title>Stories by Neeraj Kumar on Medium</title>
            <link>https://medium.com/@neerajku?source=rss-53044a832204------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:01:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@neerajku/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[How the Workload–Router–Pool architecture turns adapter names into an intelligent routing signal]]></title>
            <link>https://neerajku.medium.com/how-the-workload-router-pool-architecture-turns-adapter-names-into-an-intelligent-routing-signal-f70bb72d7e81?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/f70bb72d7e81</guid>
            <category><![CDATA[small-language-model]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[vllm]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 13:35:51 GMT</pubDate>
            <atom:updated>2026-03-26T13:35:51.987Z</atom:updated>
            <content:encoded><![CDATA[<h3>The problem: one-size-fits-all serving for wildly different workloads</h3><p>You’ve got a Llama-3 70B on vLLM serving five LoRA adapters — SQL, code, chat, summarization, medical. You set max_loras=5 and deploy. It works: base model weights live on GPU once, each adapter adds a tiny low-rank correction, and continuous batching mixes requests from different adapters in the same batch.</p><p>But under the hood, everything gets treated identically:</p><ul><li>Your <strong>SQL adapter</strong> handles 500-token one-shots — done in 3 second.</li><li>Your <strong>code adapter</strong> runs 20-turn agent sessions that balloon to 64K tokens</li><li>Your <strong>medical adapter</strong> hallucinates on 12% of cardiology queries — nobody tracks it.</li><li>Your <strong>code-agent sessions</strong> lose their KV-cache every time a tool call pauses for 10 seconds</li><li>Your short SQL queries sit behind a 64K code-agent prefill in the same scheduling queue</li></ul><p>You’re running a hospital where the ER, cardiology, and dermatology share one waiting room with one triage nurse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMuHnOaNjpwnfKVYYW872A.png" /></figure><h3>The fix: the Workload–Router–Pool (WRP) architecture</h3><p>The vLLM Semantic Router project’s <a href="https://vllm-semantic-router.com/vision-paper/">WRP vision paper</a> says LLM inference has <strong>three coupled dimensions</strong> you must co-optimize:</p><ul><li><strong>W — Workload</strong>: <em>What</em> you’re serving — chat vs. agent, short vs. long context, prefill-heavy vs. decode-heavy</li><li><strong>R — Router</strong>: <em>How</em> each request is dispatched — safety gating, adapter selection, caching, compression, hallucination tracking</li><li><strong>P — Pool</strong>: <em>Where</em> inference runs — short-context GPUs vs. long-context GPUs, KV-cache topology</li></ul><p>The killer insight for multi-LoRA: <strong>the adapter name is a zero-latency workload signal</strong>. &quot;model&quot;: &quot;code-lora&quot; instantly tells the router this is a multi-turn, decode-heavy, long-context workload — no embedding classification needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agR02aLnHA2R4s-tQB6TMw.png" /></figure><h3>What the router adds (that doesn’t exist today)</h3><p>The semantic router sits between client and engine, making decisions in under 50ms:</p><ul><li><strong>Safety gating</strong> — block prompt injections before they touch the GPU (two-stage classifier: binary safe/unsafe → 9-category hazard classification)</li><li><strong>Semantic caching</strong> — return cached responses for equivalent queries without inference (domain-aware similarity thresholds per adapter)</li><li><strong>Per-adapter reputation</strong> — track hallucination rates per adapter per domain; route cardiology questions away from the medical adapter if it’s underperforming</li><li><strong>KV-cache retention hints</strong> — tell the engine “this code session will resume in ~15s, keep the cache warm” instead of letting LRU eviction destroy 40K tokens</li><li><strong>Compression</strong> — shrink borderline requests to fit cheaper short-context pools</li><li><strong>Feedback-driven re-routing</strong> — detect user dissatisfaction from their next message (98.8% accuracy) and upgrade to a stronger adapter</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gu5UJhRa0XCMXvMmEwMCpQ.png" /></figure><h3>What the pool split gives you</h3><p>Instead of one vLLM instance serving everything, split into pools matched to workload type:</p><ul><li><strong>Short-context pool</strong> (A10G) → SQL + chat adapters, 4K–8K context, high concurrency (256 sequences)</li><li><strong>Long-context pool</strong> (H100) → code + summarization adapters, 32K–64K context, disaggregated prefill/decode</li></ul><p>The numbers from the paper:</p><ul><li><strong>17–39% GPU cost reduction</strong> from two-pool routing vs. homogeneous fleet</li><li><strong>2.5× energy efficiency</strong> from routing topology (vs. 1.7× from upgrading GPU generation — and they multiply to ~4.25×)</li><li><strong>57× faster response</strong> with prefix-cache-aware scheduling in distributed deployments</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZk7GaEmTOo1CFXcAfOf3g.png" /></figure><p>References:<br>1. <a href="https://vllm-semantic-router.com/">https://vllm-semantic-router.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f70bb72d7e81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teacher–Student Skill Distillation]]></title>
            <link>https://neerajku.medium.com/teacher-student-skill-distillation-bae50171665d?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/bae50171665d</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[knowledge-distillation]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 09:22:00 GMT</pubDate>
            <atom:updated>2026-01-30T05:46:33.867Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turning Expensive AI Reasoning into a Reusable Asset</h3><p>Modern AI systems are powerful — but expensive. Large reasoning models deliver expert-level analysis, yet using them repeatedly for routine tasks is neither scalable nor economical.</p><p>This <strong>Teacher–Student Skill Distillation</strong> architecture converts costly expert reasoning into a reusable, portable asset using <strong>SKILL.md</strong> files. The result is a system that is cheaper, faster, auditable, and production-ready.</p><h3>The Core Idea: Distill Thinking, Not Weights</h3><p>Traditional knowledge distillation trains a smaller model to imitate the internal weights of a larger one. That approach is opaque, slow to adapt, and tightly coupled to a specific model.</p><p>Skill distillation takes a different path:</p><p>· The <strong>Teacher model</strong> performs deep reasoning once<br>· Its reasoning is compressed into a structured <strong>SKILL.md</strong> file<br>· The <strong>Student model</strong> executes tasks by strictly following this skill</p><p>The intelligence lives <strong>outside the model</strong>, not inside its weights.</p><h3>SKILL.md: The “USB Port” of Agent Intelligence</h3><p>A SKILL.md file is a portable, executable representation of expert knowledge.</p><p>Just like a USB drive works across machines, a well-written skill file can be consumed by: — CLI agents (e.g., Claude Code) — IDE copilots — LangGraph-based agents — Any instruction-following LLM</p><p>This makes expertise model-agnostic, version-controlled, and reusable.</p><h3>Cognitive Decoupling: Intelligence vs Execution</h3><p>This architecture separates what is traditionally tightly coupled:</p><p>· <strong>Reasoning</strong>: expensive, creative, rare<br>· <strong>Execution</strong>: cheap, repetitive, frequent<br>You pay for expert thinking once, then reuse it indefinitely.</p><h3>Flowchart: End-to-End Skill Distillation Architecture</h3><p>┌──────────────────────────────────────────┐<br> │ PHASE 1: SKILL GENERATION <br> │ (Strategic / One-Time Cost) <br> ├──────────────────────────────────────────┤<br> │ Teacher Model (Large / Expensive) <br> │ • Deep reasoning <br> │ • Regulatory interpretation <br> │ • Edge-case handling <br> │ │<br> │ Output: SKILL.md <br> │ • Objective <br> │ • Step-by-step SOP <br> │ • Negative constraints <br> │ • Failure rules <br> └──────────────────────────────────────────┘<br> │<br> ▼<br> ┌──────────────────────────────────────────┐<br> │ SKILL.md (Knowledge Asset) <br> │ • Portable <br> │ • Version-controlled <br> │ • Model-agnostic <br> └──────────────────────────────────────────┘<br> │<br> ▼<br> ┌──────────────────────────────────────────┐<br> │ PHASE 2: SKILL EXECUTION <br> │ (Operational / Repeated) <br> ├──────────────────────────────────────────┤<br> │ Student Model (Small / Cheap) <br> │ • Loads SKILL.md <br> │ • Follows rules exactly <br> │ • No inference, no guessing <br> │ <br> │ Output: Deterministic Results <br> └──────────────────────────────────────────┘</p><h3>Cost &amp; Performance Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gi3UUWIl55urhA75aBUBNg.png" /></figure><h3>Mental Model: Senior Partner → Junior Analyst</h3><p>Think of the system as a firm:</p><p>· The <strong>Senior Partner</strong> writes the playbook once<br>· The <strong>Junior Analysts</strong> execute it thousands of times<br>· The firm scales without rehiring senior staff</p><p>This mirrors how real organizations operate — and why this pattern scales.</p><h3>Why This Pattern Works in Production</h3><p>Skill distillation is especially effective for: — Financial analysis — Compliance checks — Risk assessment — Document extraction — Enterprise agent workflows</p><p>Anywhere correctness, repeatability, and cost control matter more than creative generation.</p><h3>Implementation Guide (Crisp)</h3><h4>A minimal, production-ready implementation can be achieved in five steps.</h4><h4>1. Setup</h4><p>Install the skill generation tool and configure access to a high-reasoning Teacher model.</p><blockquote>pip install upskill<br> export ANTHROPIC_API_KEY=sk-…</blockquote><h4>2. Generate the Skill (Teacher)</h4><p>Use the Teacher model once to convert expert reasoning into a reusable SOP.</p><blockquote>upskill generate “Act as a Senior Financial Analyst. Create a GAAP-compliant liquidity risk analysis guide for SEC 10-K filings.” \<br> — model opus</blockquote><blockquote><strong>Output:</strong> skills/&lt;skill-name&gt;/SKILL.md</blockquote><h4>3. Validate the Skill</h4><p>Review the generated SKILL.md to ensure it contains: — Clear objective — Step-by-step procedure — Explicit negative constraints — Defined failure behavior (N/A, not estimates)</p><h4>4. Execute with a Student Model</h4><p>At runtime, load the skill file into the system prompt of a small, fast model.</p><p>Execution pattern: 1. Load SKILL.md 2. Inject into system context 3. Provide input document or query 4. Execute instructions verbatim</p><h4>5. Scale</h4><p>Reuse the same skill across thousands of tasks: — Swap models freely — Keep logic fixed — Scale cost with execution, not reasoning</p><h3>Final Takeaway</h3><p><strong>SKILL.md turns intelligence into infrastructure.</strong></p><p>Instead of repeatedly paying for expensive reasoning, you: — Capture expertise once — Store it as a reusable artifact — Execute it cheaply, safely, and at scale</p><p>This shift — from <em>models as brains</em> to <em>skills as brains</em> — is what enables agentic AI systems to move from demos to production.</p><p>References:<br>1. We got Claude to teach open models how to write CUDA kernels! — <a href="https://huggingface.co/blog/upskill">https://huggingface.co/blog/upskill</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bae50171665d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Squeezing Effect in DPO Training]]></title>
            <link>https://neerajku.medium.com/the-squeezing-effect-in-dpo-training-ab21c3def54a?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab21c3def54a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[ai-alignment-and-safety]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 05:25:10 GMT</pubDate>
            <atom:updated>2025-12-19T05:25:10.341Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why gradients over-suppress rejected responses, stall chosen optimization, and redistribute probability mass</em></p><p>In vanilla Direct Preference Optimization (DPO), the objective optimizes a relative margin between a chosen (preferred) response and a rejected response. As training progresses, the rejected likelihood can be driven toward zero, which amplifies the effective gradient pressure on the rejected response and reduces the useful learning signal for improving the chosen response. When chosen and rejected responses share many tokens and patterns, suppressing the rejected response can also suppress shared-token probability in the chosen response. Because the model’s output distribution must remain normalized, probability mass may disperse into other completions not present in the preference pairs, increasing likelihood on unseen responses.</p><h4>1. Setup and Notation</h4><p>We train a policy model πθ(y | x) using preference pairs (x, yw, yl) where:</p><p>· <strong>x</strong>: prompt / input.</p><p>· <strong>yw</strong>: chosen (winner) response.</p><p>· <strong>yl</strong>: rejected (loser) response.</p><p>A fixed reference model πref(y | x) is used to anchor the optimization.</p><p>Token factorization for a completion y = (y1, …, yT):</p><p><em>log πθ(y | x) = Σt=1..T log πθ(yt | x, y&lt; t)</em></p><h4>2. Vanilla DPO Objective</h4><p>A commonly used DPO loss for one preference pair can be written as:</p><p><em>L_DPO(θ) = — log σ( β [ Δθ — Δref ] )</em></p><p>where σ(·) is the sigmoid, β &gt; 0 is an inverse-temperature parameter, and:</p><p><em>Δθ = log πθ(yw | x) — log πθ(yl | x)</em></p><p><em>Δref = log πref(yw | x) — log πref(yl | x)</em></p><p>Crucially, DPO optimizes the margin (difference) between chosen and rejected log-likelihoods rather than maximizing the chosen likelihood directly (as in supervised fine-tuning).</p><h4>3. Gradient Dynamics and the Origin of Asymmetry</h4><p>Define s = β(Δθ — Δref). Then L = -log σ(s) and dL/ds = -σ(-s).</p><h4>3.1 Gradients in Log-Likelihood Space</h4><p>Using Δθ = log π+ — log π-, with π+ = πθ(yw | x) and π- = πθ(yl | x):</p><p><em>∂L/∂ log π+ = -β σ(-s)</em></p><p><em>∂L/∂ log π- = +β σ(-s)</em></p><p>These gradients have equal magnitude and opposite sign in log space. However, the effective optimization pressure becomes highly asymmetric when expressed with respect to probabilities (or token probabilities).</p><h4>3.2 Gradients with Respect to Likelihoods (Squeezing)</h4><p>Because ∂ log π / ∂π = 1/π, we obtain:</p><p><em>∂L/∂ π+ = (∂L/∂ log π+) · (1/π+) = -β σ(-s) / π+</em></p><p><em>∂L/∂ π- = (∂L/∂ log π-) · (1/π-) = +β σ(-s) / π-</em></p><p>Taking the ratio of magnitudes:</p><p><em>|∂L/∂π-| / |∂L/∂π+| = π+ / π-</em></p><p>As training succeeds, typically π+ increases and π- decreases. The ratio π+/π- therefore grows, meaning the effective gradient pressure on π- can become much larger than on π+. This drives a rapid decline of rejected-response likelihood and shifts training focus toward suppressing rejected responses.</p><h4>4. Why the Chosen Likelihood Can Also Decrease</h4><h4>4.1 Sigmoid Saturation Reduces Useful Signal for π+</h4><p>As the margin grows, s becomes large and σ(-s) approaches 0. Then ∂L/∂ log π+ approaches 0, so DPO provides little additional signal to further increase the chosen likelihood. In practice, once the model already strongly prefers the chosen response over the rejected response, DPO can lose its ability to meaningfully steer improvements in the chosen response direction.</p><h4>4.2 Shared Tokens and Patterns Cause Collateral Suppression</h4><p>Chosen and rejected responses often share many tokens, phrases, or structural patterns (for example, a common prefix or shared reasoning steps). Since sequence likelihood is a sum over token log-probabilities, suppressing the rejected sequence can also reduce probabilities of shared tokens, which can inadvertently reduce the chosen sequence likelihood as well.</p><h4>4.3 Normalization Forces Probability Mass to Redistribute</h4><p>For any prompt x, the model must satisfy Σy πθ(y | x) = 1. If training decreases likelihood on both the chosen and rejected responses (for instance, due to shared-token suppression), the removed probability mass must go somewhere else in the space of completions. As a result, likelihood may disperse into other unseen responses outside the preference dataset, increasing the probability of completions that were not directly constrained by the preference pairs.</p><h4>5. Practical Consequences in Training</h4><p>· Both chosen and rejected sequence likelihoods can decrease over the DPO phase (a phenomenon reported in multiple works and highlighted by the paper).</p><p>· Probability mass tends to concentrate into argmax-like continuations (greedy-decoding trajectories) rather than spreading across diverse high-quality alternatives.</p><p>· Because y+ and y− often share many tokens/patterns, suppressing y− can inadvertently suppress shared token probabilities, dragging down y+ as well.</p><p>· Due to normalization (probabilities sum to 1), if probability is removed from both y+ and y−, it must reappear in other completions — often ‘unseen’ responses outside the preference pairs.</p><h4>6. Approaches that reduce the squeezing effect</h4><h4>6.1 Control the strength of negative updates</h4><p>Common stabilizers align with the paper’s mechanism (‘avoid big negative gradients in valleys’):</p><p>· Use smaller learning rates for DPO (a typical practical choice that unintentionally mitigates harmful squeezing).</p><p>· Schedule or adapt the DPO temperature β (e.g., a Flex-DPO-style idea) so π− does not collapse to ~0 too quickly.</p><p>· Mix DPO with an SFT term on y+ (Total loss = DPO + λ * SFT) to preserve absolute-likelihood pressure on chosen responses.</p><p>· Use KL regularization or PPO-style constraints to avoid pushing probability too aggressively away from a reference policy, especially in low-probability regions.</p><h4>6.2 DPO + SFT: Augment with a Supervised Loss</h4><p>Add an SFT term on the chosen response to anchor absolute likelihood:</p><p><em>L_total = L_DPO + λ · L_SFT, where L_SFT = — log πθ(yw | x)</em></p><p>This stabilizes training by explicitly rewarding the chosen response in absolute terms, counteracting likelihood collapse and helping preserve fluency and calibration.</p><h4>6.3 Prefer on-policy / online preference variants</h4><p>Because squeezing is most harmful when negative gradients are applied in low-probability (‘valley’) regions, on-policy sampling can help by keeping training samples in higher-probability regions under the current model. The paper points to on-policy DPO/IPO and online algorithms such as SPIN, SPPO, and SLiC as relevant variants.</p><h4>References:</h4><ol><li>LEARNING DYNAMICS OF LLM FINETUNING — <a href="https://arxiv.org/pdf/2407.10490">https://arxiv.org/pdf/2407.10490</a></li><li>3D-Properties: Identifying Challenges in DPO and Charting a Path Forward — <a href="https://arxiv.org/html/2406.07327v2">https://arxiv.org/html/2406.07327v2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab21c3def54a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GEPA: Reflective Prompt Evolution — How LLMs Can Learn Without Reinforcement Learning]]></title>
            <link>https://neerajku.medium.com/gepa-reflective-prompt-evolution-how-llms-can-learn-without-reinforcement-learning-eb215539aa5e?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb215539aa5e</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 04:57:40 GMT</pubDate>
            <atom:updated>2025-11-03T04:59:21.818Z</atom:updated>
            <content:encoded><![CDATA[<h3>GEPA: Reflective Prompt Evolution — How LLMs Can Learn Without Reinforcement Learning</h3><h3>Section 1: The Problem: Why Reinforcement Learning Isn’t Always Enough</h3><p><em>Large Language Models (LLMs) are increasingly used as </em><strong><em>multi-step agents</em></strong><em> — reasoning, calling tools, or collaborating with other modules to solve complex tasks.<br> To adapt them for specific goals, researchers often turn to </em><strong><em>reinforcement learning (RL)</em></strong><em> algorithms like </em><strong><em>Group Relative Policy Optimization (GRPO)</em></strong><em>.</em></p><p>But there’s a catch.</p><p>RL methods rely on <strong>sparse scalar rewards</strong> — a single number at the end of each trial. To find good strategies, they often need <strong>tens of thousands of rollouts</strong>, each requiring expensive inference, API calls, or tool execution.</p><p>This makes them <strong>sample-inefficient</strong> and <strong>hard to scale</strong> for real-world systems where:</p><ul><li>Each evaluation costs money or compute.</li><li>Rollouts are slow</li><li>And the reward signal is too weak to teach nuanced behavior.</li></ul><h3>The Insight: Language Itself Is a Learning Medium</h3><p><em>Unlike most RL agents, </em><strong><em>LLMs already think and express themselves in natural language</em></strong><em>.<br> Their reasoning traces, tool calls, and outputs form a </em><strong><em>textual trajectory</em></strong><em> that is readable and interpretable.</em></p><p><em>What if instead of giving the model a numerical reward, we asked it to </em><strong><em>reflect in words</em></strong><em> on what went wrong — and then </em><strong><em>rewrite its own instructions</em></strong><em> accordingly?</em></p><p><em>That’s exactly the intuition behind </em><strong><em>GEPA</em></strong><em> — short for </em><strong><em>Genetic-Pareto Reflective Prompt Evolution</em></strong><em>.</em></p><h3>Section 2 — The GEPA Architecture (Section 3 of the Paper)</h3><h3>GEPA: Reflective Prompt Evolution</h3><p><strong>GEPA (Genetic-Pareto)</strong> combines:</p><ol><li><strong>Reflective prompt updates</strong> — the LLM analyzes its failures in natural language and rewrites its prompts accordingly.</li><li><strong>Genetic evolution</strong> — it treats each prompt configuration as a “candidate” and evolves them through mutation and crossover (inheritance of good traits).</li><li><strong>Pareto frontier selection</strong> — instead of always choosing the single “best” candidate, it maintains a <strong>diverse pool of top performers</strong> across tasks to avoid local optima.</li></ol><h3>Example: Multi-Hop QA System</h3><p>Imagine a system that answers questions like:</p><blockquote><strong><em>Q:</em></strong><em> “Which city is the capital of the country where the Eiffel Tower is located?”</em></blockquote><p>To answer this, the system needs to reason across <strong>two hops</strong>:</p><ol><li><strong>Hop 1:</strong> Identify the country → “France.”</li><li><strong>Hop 2:</strong> Retrieve the capital city of France → “Paris.”</li></ol><p>Each hop is handled by an <strong>LLM module</strong> with its own <strong>prompt</strong> (set of instructions).<br> The full system (Φ) chains them together:</p><pre>M1: QueryWriter1   → generate first-hop search query<br>M2: Retriever      → fetch supporting docs<br>M3: QueryWriter2   → generate second-hop query<br>M4: AnswerSynthesizer → compose final answer</pre><h3>Step 1: Initialization (Genetic Optimization Loop)</h3><p>GEPA starts with a <strong>seed version</strong> of all prompts, for example:</p><pre>M3 Seed Prompt:<br>&quot;Given the fields question and summary 1, produce a search query.&quot;</pre><p>This initial version is simple but vague — it doesn’t know how to reason about multi-hop dependencies.</p><p>So GEPA begins its optimization loop.</p><h3>Step 2: Run Rollouts &amp; Collect Feedback</h3><p>GEPA runs the system on a small set of training examples (a minibatch).<br> For one example:</p><blockquote><em>Q: Which city hosted the Summer Olympics right before Rio de Janeiro?”</em></blockquote><ul><li><strong>Hop 1 result:</strong> Retrieves “London hosted the 2012 Olympics.”</li><li><strong>Hop 2 result:</strong> Wrong — it retrieves irrelevant info like “Olympics in Brazil.”</li></ul><p>The evaluator gives:</p><ul><li><strong>Numeric score:</strong> 0 (wrong)</li><li><strong>Feedback text:</strong></li><li>“The second-hop query repeated the original question instead of focusing on the <em>previous result (‘London 2012’)</em>.”</li></ul><h3>Step 3: Reflective Prompt Mutation</h3><p>Now GEPA uses this <em>textual feedback</em> as a diagnostic signal.<br> It asks an LLM to reflectively rewrite M3’s prompt.</p><p>🧠 GEPA’s inner prompt to the optimizer looks like:</p><blockquote><em>“You saw that the query failed because it didn’t focus on the new entity (‘London’).<br> Rewrite the instruction to encourage reasoning over previous summary context.”</em></blockquote><p>The <strong>LLM updates the module prompt</strong> to:</p><pre>Step 3: Reflective Prompt Mutation<br><br>Now GEPA uses this textual feedback as a diagnostic signal.<br>It asks an LLM to reflectively rewrite M3’s prompt.<br><br>🧠 GEPA’s inner prompt to the optimizer looks like:<br><br>“You saw that the query failed because it didn’t focus on the new entity (‘London’).<br>Rewrite the instruction to encourage reasoning over previous summary context.”</pre><p>This version now <strong>teaches the model how to reason across hops</strong>.</p><p>This is a <strong>reflective prompt mutation</strong> — the LLM learns from its own language feedback instead of numeric gradients.</p><h3>Step 4: Evaluate and Add to Pool</h3><p>GEPA now runs this updated candidate system on the validation examples:</p><ul><li>The new version correctly retrieves “London” → “UK” → “capital: London.”</li><li>The score improves.</li></ul><p>So GEPA <strong>keeps this candidate</strong> in its pool (P).<br> If multiple modules were updated in other runs, each new combination becomes another “child” candidate.</p><p>Each candidate stores its <strong>ancestry</strong> — who it mutated from.</p><h3>Step 5: Pareto-Based Candidate Selection</h3><p>Suppose there are now 5–10 candidates in the pool:</p><ul><li>Some perform best on reasoning-heavy questions.</li><li>Others perform better on retrieval-heavy ones.</li></ul><p>Instead of picking <em>just one best model</em>, GEPA:</p><ol><li>Looks at each task instance in the training set.</li><li>Identifies which candidates performed <em>best on each example</em></li><li>Keeps <strong>all those Pareto-optimal candidates</strong> — they form the <em>Pareto frontier</em>.</li></ol><p>Then it randomly selects the next candidate to evolve, giving higher chances to those that have “won” across multiple examples.</p><p>This ensures <strong>diversity</strong> — it doesn’t overfit one strategy.</p><h3>Step 6: Repeat Evolution</h3><p>GEPA repeats this loop:</p><ol><li>Select a promising candidate from the Pareto front.</li><li>Choose another module (maybe M1 this time).</li><li>Mutate its prompt reflectively.</li><li>Add the improved version back.</li></ol><p>Over time, the prompt set evolves like a <strong>genetic tree</strong>, where each generation learns new rules:</p><pre>Base → adds “use second-hop reasoning”<br>        ↓<br>        → adds “avoid repeating question”<br>             ↓<br>             → adds “use complementary entities”</pre><h3>Step 7: Final Output</h3><p>After many iterations (but far fewer rollouts than RL), GEPA converges on the <strong>best candidate system .</strong></p><h3>Results:</h3><p>Across four benchmarks — <strong>HotpotQA, IFBench, PUPA, and HoVer</strong> — GEPA:</p><ul><li><strong>Outperforms GRPO by ~10–20%</strong> on average.</li><li>Uses <strong>up to 35× fewer rollouts</strong>.</li><li>Also beats the leading prompt optimizer <strong>MIPROv2</strong> by over <strong>10%</strong> on two LLMs (Qwen3–8B and GPT-4.1-mini).</li></ul><p>References:</p><ol><li><a href="https://www.rajapatnaik.com/blog/2025/10/23/langgraph-dspy-gepa-researcher">https://www.rajapatnaik.com/blog/2025/10/23/langgraph-dspy-gepa-researcher</a></li><li>GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning — <a href="https://arxiv.org/abs/2507.19457">https://arxiv.org/abs/2507.19457</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb215539aa5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KTO: Model Alignment as Prospect Theoretic Optimization]]></title>
            <link>https://neerajku.medium.com/kto-model-alignment-as-prospect-theoretic-optimization-4ba48f211377?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ba48f211377</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rlhf]]></category>
            <category><![CDATA[llm-alignment]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Sat, 31 May 2025 03:42:30 GMT</pubDate>
            <atom:updated>2025-05-31T03:47:51.096Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>Prospect Theory</em></h3><p><em>Kahneman and Tversky’s Prospect Theory describes how people actually make<br>decisions under risk, as opposed to how they should according to classical economics.</em></p><p><em>It introduces a value function v(x) that:<br>• Is defined relative to a reference point (e.g., current wealth).<br>• Is concave over gains.<br>• Is convex over losses.<br>• Is steeper for losses than for gains ⇒ loss aversion.</em></p><p><strong><em>Concave for Gains<br></em></strong><em>For gains (i.e., x &gt; xo):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDpgYBGjxFKPvq-ppxRnPw.png" /></figure><p><em>A curve that increases but flattens out — concave. As you gain more, the<br>incremental value you feel decreases.</em></p><p><em>Example: When you gain 1,000, it feels exciting and rewarding. But if you<br>gain another 1,000 right after that, the total amount is now 2,000 — yet the<br>second 1,000 doesn’t feel as thrilling as the first. This is due to diminishing<br>marginal utility.</em></p><p><strong><em>Convex for Losses</em></strong><em><br>For losses (i.e., x &lt; x0):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PFra0Zyv28fX_kJpjrgSYQ.png" /></figure><p><em>A curve that drops fast and steep — convex. As you lose more, the incremental<br>pain may start to feel less bad (but it starts very steep).</em></p><p><em>Example: Losing 1,000 hurts a lot. Losing another 1,000 (2,000 total) hurts<br>more, but less than double the initial pain.</em></p><p><em>The reference point (xo) is the baseline to which all rewards are compared.<br>In KTO, it’s the expected reward over the reference distributions. For example,<br>in DPO, it’s often the reward of the dispreferred response.</em></p><p><em>KTO Framework for Aligning LLMs</em></p><p><em>The KTO (Kahneman-Tversky Optimization) framework introduces HALO<br> — Human-Aware Loss Objective.</em></p><ul><li><em>HALO is a general class of loss functions that incorporates cognitive modeling<br>of human preferences, derived from Prospect Theory.<br>• Most existing methods (like DPO, PPO) require pairwise preference data,<br>where for a given prompt x, one preferred output yw is ranked above<br>another yl.<br>• HALO proposes a value-based formulation, where we compare a response<br>to a reference point, inspired by how humans perceive gains and<br>losses in Prospect Theory.<br>• This eliminates the need for pairwise comparisons.</em></li></ul><p><strong><em>HALO Loss Function</em></strong></p><p><em>From the HALO framework, a loss function requires:<br>1. A reward function r(x, y): Often defined using the policy’s log-likelihood<br>ratio:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*UWn2qRpfWCFCQMXkBIYvLA.png" /></figure><p><em>2. A reference distribution Q: Usually an expectation over responses<br>(e.g., batch mean):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*mznP6EL2iYKZmhIfTwawqA.png" /></figure><p><strong><em>HALO Loss Form (as Implemented in KTO):</em></strong><em><br>Given all ingredients, the general HALO loss is:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9fdldethqRcDqY5rNsF2w.png" /></figure><p><em>Where:</em></p><ul><li><em>ax,y ∈ {+1,−1}: Indicates whether y is a preferred or dispreferred response.<br>• v(°§): which is concave in gains, convex in losses, per Prospect Theory.<br></em><strong><em>Sigmoid is used in KTO as v() function.</em></strong><em><br>• r(x, y): Reward.<br>• .r(x): Reference reward.<br>• CD: Constant (e.g., dataset-dependent).</em></li></ul><p><strong><em>How Concave and Convex Behavior Emerges</em></strong></p><p><strong><em>For desirable outputs: z0 = r_bar(x)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*e5DG9ExeJEwV50pgzxUM3A.png" /></figure><ul><li><em>If r(x, y) &gt; z0, then v(x, y) is in the </em><strong><em>upper part of the sigmoid</em></strong><em>, i.e.,<br>concave.<br>• This reflects diminishing sensitivity to gains.<br>• This is aligned with Prospect Theory: large gains provide less incremental<br>value.</em></li></ul><p><strong><em>For undesirable outputs:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*PBbCrI8bxRu80vJbL0yKag.png" /></figure><p><em>• If r(x, y) &lt; z0, we apply </em><strong><em>sigmoid to a negative input.</em></strong><em><br>• The lower part of the sigmoid is convex.<br>• This reflects loss aversion — people are very sensitive to losses initially.</em></p><p><em>Here, z0 is the reference distribution — often the batch mean or an expectation<br>over a set of baseline outputs.</em></p><p><strong><em>HALO as a Generalization of DPO</em></strong></p><p><em>“HALO is a cognitive-theoretic generalization of DPO.”</em></p><p><em>This means that the HALO framework (Human-Aware Loss Objective)<br>is a more general, cognitively inspired formulation in which DPO (Direct<br>Preference Optimization) is just one special case.</em></p><p><strong><em>What is DPO?</em></strong><em><br>DPO optimizes LLMs using preference data.<br>Given a preference pair (x, yw, yl), where yw is preferred over yl, DPO minimizes:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVCAVqhppEWtvDdihGduWw.png" /></figure><p><em>This is effectively a binary classifier over pairwise preferences.</em></p><p><strong><em>Assumptions of DPO<br></em></strong><em>• Requires pairwise comparison.<br>• Ignores human cognitive biases (e.g., risk aversion, reference dependence).</em></p><p><strong><em>Why HALO Generalizes DPO</em></strong><em><br>DPO becomes a special case of HALO when:<br>• ax,y = +1 for preferred y, and −1 for dispreferred.<br>• v(z) = log(exp(z)/1+exp(z)) — logistic-style value function.<br>• The reference point E[r(x, y′)] is implicitly embedded as yl.</em></p><p><strong><em>DPO is a special case of HALO where:</em></strong></p><ul><li><em>data is pairwise</em></li><li><em>value function v is logistic</em></li><li><em>reference point = the dispreferred response</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ba48f211377" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MemGPT- Extending LLM Context Through OS-Inspired Virtual Memory and Hierarchical Storage]]></title>
            <link>https://neerajku.medium.com/memgpt-extending-llm-context-through-os-inspired-virtual-memory-and-hierarchical-storage-c5cc96f9818a?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5cc96f9818a</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 05:22:51 GMT</pubDate>
            <atom:updated>2024-11-09T07:21:33.521Z</atom:updated>
            <content:encoded><![CDATA[<h3>Extending LLM Context Through OS-Inspired Virtual Memory and Hierarchical Storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ck7gid2UkHk7YuJLeix5mw.png" /></figure><p>MemGPT manages different types of memory resources, similar to how an operating system (OS) handles virtual and physical memory, along with storage on disk.</p><h4>OS Memory Management</h4><ul><li><strong>Virtual Memory</strong>: In a traditional OS, virtual memory is an abstraction layer that allows programs to use more memory than what’s physically available by swapping data to and from disk. It provides each program with an isolated memory space, improving efficiency and multitasking.</li><li><strong>Physical Memory</strong>: Physical memory (RAM) is where data is stored temporarily for quick access. In OS memory management, physical memory handles active tasks and data.</li><li><strong>Disk</strong>: When physical memory is full, data can be transferred to disk storage, a more permanent but slower storage solution. The OS manages this transfer to ensure that high-priority tasks remain in physical memory while less active data is offloaded.</li></ul><p>In an OS, the <strong>operating system</strong> coordinates between virtual memory, physical memory, and disk, deciding what data stays in RAM, what goes to disk, and when to swap it back.</p><h4>MemGPT- M<strong>emory Management</strong></h4><ul><li><strong>Memory Sources</strong> that contain different types of information.</li><li><strong>Context Memory</strong>, Similar to physical memory in an OS, MemGPT’s context memory aggregates data from multiple sources (conversation, entities, tasks, RAG) that is immediately relevant to the current interaction. This allows MemGPT to access pertinent information without needing to retrieve from deeper storage every time.</li><li>An <strong>LLM acting as the OS</strong>, the language model functions as an “operating system,” coordinating between memory sources, managing retrieval and storage, and autonomously deciding what to keep in context memory. Just as an OS decides what data stays in RAM or gets moved to disk, MemGPT decides which parts of memory (e.g., recent conversation history, task states) should remain in its active context for quick access.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivFWi8f2-_FQKuwxR_Cd2w.png" /></figure><h3><strong>Architecture:</strong></h3><p>1. <strong>Main Context (LLM Finite Context Window)</strong>: This is the main, limited context area accessible to the LLM. It consists of three segments:</p><p>— <strong>System Instructions</strong>: These static, read-only instructions guide the LLM on handling memory, specifying tasks, and usage guidelines for MemGPT functions. These instructions help the LLM to decide when and how to manage context.</p><p>— <strong>Working Context</strong>: This read-write section holds critical information, like key facts about the user or the agent’s persona, stored in unstructured text. It can be updated by the LLM through function calls.</p><p>— <strong>FIFO Queue</strong>: A rolling queue that stores recent messages, interactions, and system messages (e.g., memory alerts). As the queue reaches capacity, older messages are replaced with a recursive summary, allowing the LLM to retain a high-level overview.</p><p>2.<strong> Queue Manager</strong>: This component manages the FIFO queue and recall storage, handling message overflow and organizing which information is retained within context.</p><p>— When a new message arrives, it’s appended to the FIFO queue and saved to recall storage. If the queue exceeds a certain length, the queue manager initiates a memory pressure warning, prompting the LLM to store relevant information in working context or external storage.</p><p>— If the queue surpasses the maximum token count, it flushes older messages, generating a recursive summary that compresses past interactions into a more concise representation.</p><p>3. <strong>Recall Storage</strong>: This is an out-of-context storage system that holds data outside the LLM’s context window. The LLM can retrieve this data by explicitly calling functions. It serves as an intermediate memory tier, storing a larger set of historical interactions that can be referenced when needed.</p><p>4. <strong>Archival Storage</strong>: This component is a long-term memory, where more distant or seldom-used information is stored. Unlike recall storage, archival storage is intended for less frequently accessed data, but it can still be searched and brought back into the context if relevant.</p><p>5. <strong>Function Executor</strong>: This interprets the LLM’s output, allowing MemGPT to manage its memory based on function calls embedded within the generated text. These functions help transfer data between main and external contexts, enabling MemGPT to handle complex, multi-step memory retrievals.</p><p>— The LLM uses functions to save, edit, or retrieve memory, which the function executor manages based on the system’s current state. These functions are self-directed and allow MemGPT to move data independently to optimize context space.</p><p>6. <strong>Control Flow and Function Chaining</strong>: Control flow in MemGPT allows the system to manage sequences of tasks by chaining function calls. If the LLM requires multiple memory operations, it can flag certain outputs for immediate follow-up processing, which allows for multi-step reasoning or iterative data retrievals without interrupting the user experience.</p><h3>Queue Manager</h3><p>The Queue Manager in MemGPT plays a central role in managing the limited memory resources of the main context (LLM’s context window). It efficiently organizes incoming messages and system alerts, optimizes memory usage by deciding what information to retain or evict, and allows MemGPT to handle long, complex conversations without overloading the finite context window. Here’s an in-depth explanation of each function within the Queue Manager:</p><p>1. <strong>Message Management:<br> </strong><br> — <strong>Appending New Messages</strong>: When a new message (from either the user or the system) arrives, the Queue Manager appends it to the end of the FIFO queue. This queue acts as a temporary storage that retains the most recent interactions and allows the LLM to generate relevant responses by referencing recent conversation history.</p><p>— <strong>LLM Inference Trigger</strong>: After appending a new message, the Queue Manager triggers the LLM inference by sending the current state of the prompt tokens (combined system instructions, working context, and FIFO queue) to the LLM. The LLM then generates a response based on this full prompt context.</p><p>— <strong>Storing LLM Output</strong>: Once the LLM generates its response (completion tokens), the Queue Manager saves this response alongside the incoming message in Recall Storage (external memory).</p><p>2. <strong>Handling Context Overflow and Eviction Policy </strong><br> The Queue Manager operates with a set of thresholds that guide how it handles memory pressure due to limited context space:<br> <br> — <strong>Warning Token Count</strong>: When the number of prompt tokens in the FIFO queue approaches a critical level (e.g., 70% of the total context window capacity), the Queue Manager inserts a memory pressure warning. This alert signals the LLM to prioritize saving essential information to either the Working Context (within the main context) or to Archival Storage (a longer-term memory outside the main context) before the FIFO queue overflows.</p><p>— <strong>Flush Token Count</strong>: Once the queue reaches the Flush Token Count (e.g., 100% of context capacity), the Queue Manager automatically “flushes” the queue to free up space. It evicts the oldest messages (typically around 50% of the context window) and replaces them with a recursive summary.</p><p>— <strong>Recursive Summary Creation</strong>: The Queue Manager combines information from the evicted messages with the previous recursive summary, creating a new, updated summary that captures essential information. This summary compresses the conversation history, preserving critical points while freeing up space for new messages.</p><p>3. <strong>Function Call Management for Recall and Archival Storage </strong><br> When relevant information needs to be accessed from storage:</p><p>— <strong>Recall Retrieval</strong>: If the LLM calls a function to retrieve historical messages stored in Recall Storage, the Queue Manager pulls the required messages and appends them to the FIFO queue. This allows the LLM to reference previous conversations or details that might be relevant for the current task.</p><p>— <strong>Data Transfer to Archival Storage</strong>: During memory pressure warnings, the Queue Manager also facilitates the movement of less immediately relevant information to Archival Storage. This enables MemGPT to store information that doesn’t need to remain in the active context but should still be accessible if recalled later.</p><p>4. <strong>Managing Recency and Relevance of Messages</strong><br> To ensure that the context remains up-to-date with the most relevant data, the Queue Manager employs strategies that favor:</p><p>— <strong>Recent Interactions</strong>: The FIFO queue inherently prioritizes recent messages by removing older ones first.</p><p>— <strong>Recursive Summarization</strong>: This keeps track of important past events without requiring full retention of every message, striking a balance between recency and historical reference.</p><p>References:</p><ol><li>MemGPT: Towards LLMs as Operating Systems — <a href="https://arxiv.org/pdf/2310.08560">https://arxiv.org/pdf/2310.08560</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5cc96f9818a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Service for Agentic Applications]]></title>
            <link>https://neerajku.medium.com/memory-service-for-agentic-applications-299741621abf?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/299741621abf</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 17:30:03 GMT</pubDate>
            <atom:updated>2024-10-24T17:30:03.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RrlwELL7kgyuERhoNfK7w.png" /></figure><p>Language models are stateless: they do not persist information across calls. In contrast, language agents may store and maintain information internally for multi-step interaction with the world. language agents explicitly organize information (mainly textural, but other modalities also allowed) into multiple memory modules, each containing a different form of information. These include <strong>short-term working memory and several long-term memories: episodic, semantic, and procedural.</strong></p><ol><li><strong>Working Memory: </strong>Maintain active and readily available information for the current decision cycle. This includes perceptual inputs, active knowledge, and core information from previous cycles.</li></ol><p><strong>When to Implement:</strong></p><p>When the agent needs to hold temporary information that is actively being used for decision-making processes.</p><p>For Intermediate Reasoning: When generating intermediate steps or reasoning paths that need to be referenced within the same decision cycle.</p><p>As a Central Hub: To connect and synchronize interactions between the LLM, long-term memories, and grounding interfaces.</p><p><strong>2. Episodic Memory: s</strong>tore experiences from earlier decision cycles, such as training input-output pairs, history event flows, and game trajectories.</p><p><strong>When to Implement:</strong></p><p>For Learning from Experience: When the agent needs to learn from past experiences and use this information to inform future decisions.</p><p>During Planning Stages: To retrieve relevant episodes into working memory to support reasoning and decision-making.</p><p>As Historical Records: To maintain a history of the agent’s interactions and decisions over time.</p><p><strong>3. Semantic Memory:</strong> Store the agent’s knowledge about the world and itself. This includes structured and unstructured information that can be retrieved to support reasoning and decision-making.</p><p><strong>When to Implement:</strong></p><p>For Knowledge Retrieval: When the agent needs to retrieve factual information or knowledge to support its reasoning processes.</p><p>To Build World Knowledge: When the agent needs to incrementally learn and store new knowledge obtained from LLM reasoning or external sources.</p><p>As a Knowledge Base: To provide a rich source of information that the agent can reference during its operations.</p><p><strong>4. Procedural Memory:</strong> Contain implicit knowledge stored in the LLM weights and explicit knowledge written in the agent’s code. This includes procedures for actions and decision-making.</p><p><strong>When to Implement:</strong></p><p>For Action Implementation:* When the agent needs to perform specific actions such as reasoning, retrieval, grounding, and learning.</p><p>For Decision-Making: To define the procedures and logic for how the agent makes decisions.</p><p>To Bootstrap the Agent: Procedural memory must be initialized with proper code from the start to ensure the agent can function correctly.</p><p><strong>Scenario:</strong></p><p>Imagine a virtual assistant named “PythonBot” designed to help users learn about Python programming. PythonBot uses a sophisticated memory system to provide accurate and contextually relevant responses.</p><p><strong>Memory Initialization</strong></p><ol><li><strong>Semantic Memory:</strong><br>Store general knowledge about Python programming.<br>Example Content: “Python is a high-level programming language known for its readability and versatility. It is used for web development, data analysis, artificial intelligence, scientific computing, and more.</li><li><strong>Procedural Memory:</strong><br> Define the procedures and actions the bot can perform, such as retrieving information, reasoning, and making decisions.<br><strong>Example Procedures:</strong><br>a. Action Procedure: Retrieve information about Python concepts.<br>b. Decision Procedure: Determine the best response based on user queries and available knowledge.</li></ol><p><strong>User Interaction Flow<br></strong>Step 1: User Sends a Message<br>User Message: “Tell me about Python.”</p><p><strong>Working Memory:</strong><br>Update: Store the user message as the current input.<br>Content: {“user_message”: “Tell me about Python”}</p><p><strong>Episodic Memory:</strong><br>Retrieve: Check if there are any past interactions related to Python.<br>Result: No relevant past interactions found (initial interaction).</p><p><strong>Semantic Memory:</strong><br>Retrieve: Fetch general knowledge about Python.<br>Result: “Python is a high-level programming language known for its readability and versatility.”</p><p><strong>Procedural Memory:</strong><br>Execute: Use the decision procedure to generate a response based on the user message and retrieved knowledge.</p><p>Result: “Python is a high-level programming language known for its readability and versatility. It is used for web development, data analysis, artificial intelligence, scientific computing, and more.”</p><p><strong>Update Working Memory:</strong></p><p>Content: {“user_message”: “Tell me about Python”, “llm_response”: “Python is a high-level programming language known for its readability and versatility. It is used for web development, data analysis, artificial intelligence, scientific computing, and more.”}</p><p><strong>Update Episodic Memory:</strong></p><p>Content: [{“user_message”: “Tell me about Python”, “llm_response”: “Python is a high-level programming language known for its readability and versatility. It is used for web development, data analysis, artificial intelligence, scientific computing, and more.”}]</p><p>Response to User: “Python is a high-level programming language known for its readability and versatility. It is used for web development, data analysis, artificial intelligence, scientific computing, and more.”</p><p>Step 2: User Sends a Follow-Up Message<br>User Message: “What can I use Python for?”</p><p><strong>Working Memory:</strong><br>Update: Store the new user message.<br>Content: {“user_message”: “What can I use Python for?”}</p><p><strong>Episodic Memory:</strong><br>Retrieve: Check past interactions related to Python usage.<br>Result: Retrieve the previous interaction about Python.</p><p><strong>Semantic Memory:</strong><br>Retrieve: Fetch additional knowledge about Python applications.<br>Result: “Python is used for web development, data analysis, artificial intelligence, scientific computing, automation, and more.”</p><p><strong>Procedural Memory:</strong><br>Execute: Use the decision procedure to generate a response combining past interactions and additional knowledge.</p><p>Result: “In addition to what I mentioned earlier, Python is used for web development, data analysis, artificial intelligence, scientific computing, automation, and more.”</p><p><strong>Update Working Memory:</strong></p><p>Content: {“user_message”: “What can I use Python for?”, “llm_response”: “In addition to what I mentioned earlier, Python is used for web development, data analysis, artificial intelligence, scientific computing, automation, and more.”}</p><p><strong>Update Episodic Memory:</strong></p><p>Content: [{“user_message”: “Tell me about Python”, “llm_response”: “Python is a high-level programming language known for its readability and versatility. It is used for web development, data analysis, artificial intelligence, scientific computing, and more.”}, {“user_message”: “What can I use Python for?”, “llm_response”: “In addition to what I mentioned earlier, Python is used for web development, data analysis, artificial intelligence, scientific computing, automation, and more.”}]</p><p>Response to User: “In addition to what I mentioned earlier, Python is used for web development, data analysis, artificial intelligence, scientific computing, automation, and more.”</p><p><strong>Summary</strong></p><p>In this example, <strong>PythonBot</strong> uses:</p><p><strong>Working Memory:</strong> To store current user inputs and intermediate results.<br><strong>Episodic Memory:</strong> To keep track of past interactions and use them to inform future responses.<br><strong>Semantic Memory:</strong> To store and retrieve factual information about Python.<br>Procedural Memory: To define how to process user inputs, retrieve relevant information, and generate coherent responses.</p><p>This approach ensures that PythonBot can provide accurate, contextually relevant, and coherent responses by leveraging the different types of memory effectively. It demonstrates how a language agent can simulate understanding and continuity in a conversation, making the interaction more meaningful and helpful for the user.</p><p>Reference:<br>1. Cognitive Architectures for Language Agents — <a href="https://arxiv.org/pdf/2309.02427">https://arxiv.org/pdf/2309.02427</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=299741621abf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ColPali and PLAID- Part 2]]></title>
            <link>https://neerajku.medium.com/colpali-and-plaid-part-2-a316ccee2052?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/a316ccee2052</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 13:54:37 GMT</pubDate>
            <atom:updated>2024-09-20T13:54:37.831Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>PLAID architecture :</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*955bJFH0ZYiktJKqQ4KC0w.png" /></figure><h4><strong>Improvement over ColBERTv2 in terms of latency.</strong></h4><p>Latency is split into several stages: query encoding, candidate generation, index lookups (which involve retrieving compressed vector representations for candidate passages), residual decompression, and scoring (i.e., final MaxSim computations).</p><p>In the case of vanilla ColBERTv2, the primary bottlenecks are the index lookups and residual decompression processes. <strong>Index lookups</strong> are resource-intensive because they require significant memory bandwidth. Each vector is encoded with a 4-bit centroid ID and 32-byte residuals, and since each passage can contain many vectors, retrieving data for potentially up to 65,536 (²¹⁶) candidate passages becomes costly. Furthermore, vanilla ColBERTv2 must dynamically construct padded tensors to accommodate passages of varying lengths, which adds to the complexity.</p><p><strong>Residual decompression</strong> is another time-consuming task, as it involves several computationally expensive operations such as unpacking bits and summing large values.</p><p>While ColBERTv2 reduces space usage by employing centroids, PLAID demonstrates that centroids can also accelerate search without sacrificing quality by acting as proxies for passage embeddings. This approach allows the model to skip low-scoring passages, avoiding the need to retrieve or decompress their residuals.</p><p>Although this adds a small overhead in the candidate generation stage, it leads to substantial time savings in later stages. The hypothesis is that retrieval based solely on centroids can identify high-scoring passages that would have been retrieved by the full ColBERTv2 method.</p><p><strong>PLAID inference pipeline</strong>, comprising several consecutive stages for retrieval, filtering, and ranking.</p><ul><li>The <strong>first stage</strong> generates an initial candidate set in <strong>candidate generation step</strong> by calculating relevance scores for each centroid in relation to the query embeddings.</li><li>In the <strong>intermediate stages</strong>, PLAID employs innovative techniques like <strong>centroid interaction</strong> and <strong>centroid pruning</strong> to efficiently filter candidate passages.</li><li>Finally, PLAID ranks(<strong>scoring</strong>)the remaining candidates using fully reconstructed passage embeddings.</li></ul><h4><strong>Candidate Generation Step:</strong></h4><p>1. Query Embedding Matrix (Q): This is a matrix representing the query in a high-dimensional vector space.</p><p>2. List of Centroid Vectors : These are pre-computed vectors that represent clusters of token embeddings, created using k-means clustering.</p><p>3. Token-level Query-Centroid Relevance Scores (S_c,q) : These scores indicate how relevant each centroid is to each token in the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mT9cVR-QjB0w0whbw4nbVA.png" /></figure><p>A passage is considered “close” to a centroid if one or more of its tokens were assigned to that centroid during the k-means clustering process.</p><p>Inverted List Structure:<br>Stores an inverted list mapping centroids to unique passage IDs. This is more space-efficient because there are fewer passages than embeddings.</p><h4><strong>Centroid Interaction:</strong></h4><p>Equation 2 that 𝑆𝑐,𝑞 contains the relevance scores for each centroid in relation to the query tokens. Let 𝐼 represent the list of centroid indices associated with each token in the candidate set. Additionally, let 𝑆𝑐,𝑞[𝑖] represent the 𝑖-th row of 𝑆𝑐,𝑞. Using this, PLAID constructs the approximate centroid-based scores, denoted as 𝐷˜.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*0gW2zx2QwUxOSUJ8g29Plg.png" /></figure><p>Then to rank the candidate passages using 𝐷˜ , PLAID computes the MaxSim scores 𝑆𝐷˜ as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*vrRoPuVwob47RWBfO4sUdw.png" /></figure><h4>Example</h4><p>1. <strong>Query</strong>: “Best Italian restaurants NYC”<br>2. <strong>Query Embedding Matrix </strong>( Q ) (4 tokens, 6 dimensions):</p><p>Q = [0.1 &amp; 0.2 &amp; 0.3 &amp; 0.4 &amp; 0.5 &amp; 0.6 \\<br>0.2 &amp; 0.3 &amp; 0.4 &amp; 0.5 &amp; 0.6 &amp; 0.7 \\<br>0.3 &amp; 0.4 &amp; 0.5 &amp; 0.6 &amp; 0.7 &amp; 0.8 \\<br>0.4 &amp; 0.5 &amp; 0.6 &amp; 0.7 &amp; 0.8 &amp; 0.9<br>]</p><p><strong>3. Centroid Vectors ( C ) </strong>(5 centroids, 6 dimensions)<strong>:</strong><br>C = [<br>0.1 &amp; 0.2 &amp; 0.1 &amp; 0.2 &amp; 0.1 &amp; 0.2 \\<br>0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 \\<br>0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6 \\<br>0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 \\<br>0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0<br>]</p><p><strong>4. Passage Tokens and Centroid Assignments:</strong></p><p>- Passage 1: [0.1, 0.2, 0.1, 0.2, 0.1, 0.2] (C1), [0.5, 0.6, 0.5, 0.6, 0.5, 0.6] (C3)<br>- Passage 2: [0.9, 1.0, 0.9, 1.0, 0.9, 1.0] (C5), [0.3, 0.4, 0.3, 0.4, 0.3, 0.4] (C2)<br>- Passage 3: [0.7, 0.8, 0.7, 0.8, 0.7, 0.8] (C4), [0.1, 0.2, 0.1, 0.2, 0.1, 0.2] (C1)<br>- Passage 4: [0.3, 0.4, 0.3, 0.4, 0.3, 0.4] (C2), [0.7, 0.8, 0.7, 0.8, 0.7, 0.8] (C4)<br>- Passage 5: [0.5, 0.6, 0.5, 0.6, 0.5, 0.6] (C3), [0.9, 1.0, 0.9, 1.0, 0.9, 1.0] (C5)<br>- Passage 6: [0.7, 0.8, 0.7, 0.8, 0.7, 0.8] (C4), [0.5, 0.6, 0.5, 0.6, 0.5, 0.6] (C3)</p><p><strong>Step-by-Step Process</strong></p><p>1.<strong> Compute Relevance Scores </strong>(\(S_{c,q}\))<br>Calculate the relevance scores between the query tokens and the centroids:</p><p>S_{c,q} = C \cdot Q^T</p><p>S_{c,q} = [<br>0.42 &amp; 0.54 &amp; 0.66 &amp; 0.78 \\<br>0.96 &amp; 1.26 &amp; 1.56 &amp; 1.86 \\<br>1.50 &amp; 1.98 &amp; 2.46 &amp; 2.94 \\<br>2.04 &amp; 2.70 &amp; 3.36 &amp; 4.02 \\<br>2.58 &amp; 3.42 &amp; 4.26 &amp; 5.10<br>]</p><p>2. <strong>Identify Top-(t) Centroids</strong>:<br>Suppose \(t = 2\) (top-2 centroids):</p><p>- For the first query token (“Best”):<br>- Relevance scores: [0.42, 0.96, 1.50, 2.04, 2.58]<br>- Top-2 centroids: \(C_5, C_4\)</p><p>- For the second query token (“Italian”):<br>- Relevance scores: [0.54, 1.26, 1.98, 2.70, 3.42]<br>- Top-2 centroids: \(C_5, C_4\)</p><p>- For the third query token (“restaurants”):<br>- Relevance scores: [0.66, 1.56, 2.46, 3.36, 4.26]<br>- Top-2 centroids: \(C_5, C_4\)</p><ul><li>For the fourth query token (“NYC”):<br>- Relevance scores: [0.78, 1.86, 2.94, 4.02, 5.10]<br>- Top-2 centroids: \(C_5, C_4\)</li></ul><p><strong>3. Map Centroids to Passages</strong></p><p>Identify passages that have tokens assigned to the top-2 centroids (\(C_4\) and \(C_5\)):<br>- Passage 1: [C1, C3] (not selected)<br>- Passage 2: [C5, C2] (selected)<br>- Passage 3: [C4, C1] (selected)<br>- Passage 4: [C2, C4] (selected)<br>- Passage 5: [C3, C5] (selected)<br>- Passage 6: [C4, C3] (selected)</p><p><strong>4. Construct Centroid-based Approximate Scores </strong>(\(\tilde{D}\))</p><p>For selected passages, use the relevance scores of the top-2 centroids:</p><p>S_{c,q} = [<br>0.42 &amp; 0.54 &amp; 0.66 &amp; 0.78 \\<br>0.96 &amp; 1.26 &amp; 1.56 &amp; 1.86 \\<br>1.50 &amp; 1.98 &amp; 2.46 &amp; 2.94 \\<br>2.04 &amp; 2.70 &amp; 3.36 &amp; 4.02 \\<br>2.58 &amp; 3.42 &amp; 4.26 &amp; 5.10<br>]</p><p>For each passage, we consider the relevance scores of the centroids assigned to its tokens. Let’s denote these relevance scores as \(\tilde{D}\):</p><p>- Passage 2 (Centroids \(C_5, C_2\)):<br>\tilde{D}_2 = [<br>2.58 &amp; 3.42 &amp; 4.26 &amp; 5.10 \\<br>0.96 &amp; 1.26 &amp; 1.56 &amp; 1.86<br>]</p><p>- Passage 3 (Centroids \(C_4, C_1\)):<br>\tilde{D}_3 = [<br>2.04 &amp; 2.70 &amp; 3.36 &amp; 4.02 \\<br>0.42 &amp; 0.54 &amp; 0.66 &amp; 0.78<br>]</p><p>- Passage 4 (Centroids \(C_2, C_4\)):<br>\tilde{D}_4 = [<br>0.96 &amp; 1.26 &amp; 1.56 &amp; 1.86 \\<br>2.04 &amp; 2.70 &amp; 3.36 &amp; 4.02<br>]</p><p>- Passage 5 (Centroids \(C_3, C_5\)):<br>\tilde{D}_5 = [<br>1.50 &amp; 1.98 &amp; 2.46 &amp; 2.94 \\<br>2.58 &amp; 3.42 &amp; 4.26 &amp; 5.10<br>]</p><p>- Passage 6 (Centroids \(C_4, C_3\)):<br>\tilde{D}_6 = [<br>2.04 &amp; 2.70 &amp; 3.36 &amp; 4.02 \\<br>1.50 &amp; 1.98 &amp; 2.46 &amp; 2.94<br>]</p><p><strong>5. Compute MaxSim Scores</strong></p><p>To compute the MaxSim scores for each passage, we use the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*Snb_y7KMgiEc9lX5--Qc6Q.png" /></figure><p>Let’s compute this for each passage:</p><ul><li>Passage 2:<br>S_{\tilde{D}_2} = \max(2.58, 0.96) + \max(3.42, 1.26) + \max(4.26, 1.56) + \max(5.10, 1.86) = 2.58 + 3.42 + 4.26 + 5.10 = 15.36</li><li>Passage 3:<br>S_{\tilde{D}_3} = \max(2.04, 0.42) + \max(2.70, 0.54) + \max(3.36, 0.66) + \max(4.02, 0.78) = 2.04 + 2.70 + 3.36 + 4.02 = 12.12</li><li>Passage 4:<br>S_{\tilde{D}_4} = \max(0.96, 2.04) + \max(1.26, 2.70) + \max(1.56, 3.36) + \max(1.86, 4.02) = 2.04 + 2.70 + 3.36 + 4.02 = 12.12</li><li>Passage 5:<br>S_{\tilde{D}_5} = \max(1.50, 2.58) + \max(1.98, 3.42) + \max(2.46, 4.26) + \max(2.94, 5.10) = 2.58 + 3.42 + 4.26 + 5.10 = 15.36</li><li>Passage 6:<br>S_{\tilde{D}_6} = \max(2.04, 1.50) + \max(2.70, 1.98) + \max(3.36, 2.46) + \max(4.02, 2.94) = 2.04 + 2.70 + 3.36 + 4.02 = 12.12</li></ul><p><strong>6. Rank the Passages</strong></p><p>Rank the candidate passages based on the computed scores:<br>1. Passage 2: \(S_{\tilde{D}_2} = 15.36\)<br>2. Passage 5: \(S_{\tilde{D}_5} = 15.36\)<br>3. Passage 3: \(S_{\tilde{D}_3} = 12.12\)<br>4. Passage 4: \(S_{\tilde{D}_4} = 12.12\)<br>5. Passage 6: \(S_{\tilde{D}_6} = 12.12\)</p><h4><strong>Centroid Pruning:</strong></h4><p>PLAID filters out tokens whose associated centroids do not meet a certain threshold, for relevance. In this filtering phase, only tokens whose highest centroid score exceeds the threshold t_cs are considered. Mathematically, the condition for a centroid iii to be included is that the maximum score across all query tokens (S) must be greater than or equal to the threshold. This helps to reduce the computational load by focusing only on the most relevant centroids and eliminating unnecessary computations for low-scoring centroids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*WyHUbklMgBRBpp_xQHr5qw.png" /></figure><h4><strong>Scoring:</strong></h4><p>After generating an initial set of candidate passages, PLAID reconstructs the original embeddings for these passages using <strong>residual decompression</strong>. This step restores the full passage embeddings from the compressed format used during retrieval.</p><p>Once the embeddings are reconstructed, PLAID applies the <strong>MaxSim</strong> operation to rank the candidates based on their similarity to the query. Here, the term <strong>MaxSim</strong> refers to the method used to compute the similarity scores between the query and the candidate passages. The decompressed embedding vectors for the final candidate set are denoted by D.</p><p>Finally, the scores for each query-passage pair are calculated based on Equation 1. This ensures that the final ranking is based on fully reconstructed passage representations, allowing for a high-quality retrieval of relevant passages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*F7OS7cqUdX0QJCinvokFrA.png" /></figure><h4><strong>Latency :</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNaA61r99gvMnWVLrAXIcA.png" /></figure><h3>References:</h3><ol><li>ColPali: Efficient Document Retrieval with Vision Language Models</li><li>PLAID: An Efficient Engine for Late Interaction Retrieval</li><li>ColBERTv2: Effective and Efficient Retrieval via Lightweight Late Interaction</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a316ccee2052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ColPali and PLAID- Part 1]]></title>
            <link>https://neerajku.medium.com/colpali-and-plaid-part-1-45caec3b14d1?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/45caec3b14d1</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 13:45:50 GMT</pubDate>
            <atom:updated>2024-09-20T13:55:18.334Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>ColPali:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JbjxO7UFvvxuEFzEwSbRZw.png" /></figure><h4><strong>Context:</strong></h4><p>To enhance the query-answering capabilities of large language models (LLMs), it is often more effective to first search for relevant information online or within external document collections, such as PDFs, before generating a grounded response using <strong>Retrieval-Augmented Generation (RAG)</strong>. In practice, setting up efficient retrieval pipelines for PDF documents is essential for performance but can be quite complex. The process involves running Optical Character Recognition (OCR) on scanned PDFs, followed by using Document Layout Detection models to segment pages into different sections like paragraphs, figures, and titles. Once segmented, the structure and reading order of the page are reconstructed. Additionally, resource-intensive specialized models can optionally be applied to generate natural language captions for figures, images, and tables. A coherent chunking strategy is then used to split or merge text passages appropriately. Finally, a powerful neural embedding model, such as BGE M3, maps the text chunks into a semantically meaningful vector space, and the vector index is stored for future retrieval tasks.</p><h3><strong>Architecture:</strong></h3><p>The core idea is to utilize the alignment between text and image token embeddings learned during multi-modal fine-tuning. In this regard, we present ColPali, an extension of PaliGemma-3B, designed to generate multi-vector representations of text and images in the style of ColBERT.</p><p>During runtime , a user query is embedded by the language model, to obtain token embeddings. We are able to run a ColBERT-style “<a href="https://arxiv.org/abs/2004.12832">late interaction</a>” (LI) operation to efficiently match query tokens to document patches</p><p><strong>Late Interaction :</strong></p><p>This mechanism is used in retrieval models like ColBERT for comparing a query q and a document d in a common embedding space .</p><p>This operator compares the embeddings by summing the maximum similarity between each query vector Eq(i)E_q^{(i)}Eq(i)​ and the document vectors Ed(j)E_d^{(j)}Ed(j)​. In this case, similarity is measured using the <strong>dot product</strong> ⟨Eq(i)∣Ed(j)⟩⟨E_q^{(i)} | E_d^{(j)}⟩⟨Eq(i)​∣Ed(j)​⟩, which captures how closely aligned the vectors are in the embedding space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*-UXYJRqMaXFKRxJmZARmeA.png" /></figure><p>This calculates the <strong>maximum dot product</strong> for each query vector Eq(i)E_q^{(i)}Eq(i)​ with all document vectors Ed(1:Nd)E_d^{(1:N_d)}Ed(1:Nd​)​, and then sums these maximum values. The idea is to find the most relevant parts of the document for each query vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvAq_ryHsLyu2XS8U-3_dg.png" /></figure><h4><strong>Issue with ColPali especially the late interaction process:</strong></h4><ol><li>Space (Compression)- uses dense vector representations, typically 128-dimensional or higher, for each token. These vectors are stored with high precision (e.g., 16-bit or 32-bit floating-point values).For large document collections, this results in substantial storage requirements. For instance, a single document with hundreds of tokens can require kilobytes of storage just for the embeddings. The overall footprint becomes massive when dealing with millions of documents, making it impractical for many real-world applications.</li><li>Latency- During retrieval, LI requires computing pairwise similarities between query and document token embeddings. This is computationally expensive, especially for long documents and queries. The exhaustive computation of these similarities can lead to high latency, making real-time retrieval challenging. Each query token needs to be compared with all document tokens, leading to a quadratic growth in the number of comparisons as the length of queries and documents increases. This complexity translates into longer response times, which is particularly problematic for applications requiring low-latency responses, such as interactive search engines.</li></ol><p><strong>PLAID</strong> is designed to address the space and latency issues inherent in ColPali.</p><ol><li>Space (Compression) —<br><strong>Centroid-based Encoding and Residual Quantization </strong>— PLAID uses a centroid-based encoding approach, similar to the residual representation in ColBERTv2.<br><strong>Efficient Vector Compression </strong>— By quantizing the residuals into lower precision (e.g., 1 or 2 bits per dimension), PLAID further compresses the embeddings.</li><li>Latency — Centroid based candidate paragraph retreival helps in reduding the time.</li></ol><p>Before going to PLAID, we should revisit the <strong>ColBERTV2</strong> residual compression method.</p><h3><strong>ColBERTV2:</strong></h3><p>ColBERTv2, a retriever that couples an <strong>aggressive residual compression</strong> mechanism to improve the quality and space footprint of late interaction and is built on top of ColBERT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asdC1wWnR043L5vOfR_wwA.png" /></figure><h4><strong>Compression Strategy:</strong></h4><p><strong>Step 1: Clustering</strong></p><ul><li>*Centroids (C ):<br>- A set of centroids is precomputed. Each centroid represents a cluster of vectors in the embedding space.<br>- For example, let’s assume we have 4 centroids: ( C = {C_1, C_2, C_3, C_4}).</li></ul><p><strong>Step 2: Encoding Vectors</strong><br>Each vector ( v ) is assigned to its closest centroid ( C_t).<br>- For example, suppose we have a vector ( v = [0.9, 0.8]), and it is closest to centroid ( C_2 = [0.85, 0.75] ).</p><p>-The residual ( r ) is computed as ( r = v — C_t ).<br>- For our example: ( r = [0.9, 0.8] — [0.85, 0.75] = [0.05, 0.05] ).</p><p><strong>Quantization of Residual:</strong><br>- The residual ( r ) is quantized into a lower precision representation.<br>- In ColBERTv2, each dimension of ( r ) is quantised into one or two bits (( b = 1) or ( b = 2 )).<br>- For simplicity, let’s assume ( b = 2 ). Each component of ( r ) can be quantised into one of four possible values.</p><p><strong>Step 3: Storage<br></strong><br>- The centroid index ( t ) is stored, which requires (ceil(log C) ) bits.<br>- The quantised residual (r) is stored, which requires (bn) bits, where \( n \) is the dimensionality of the vector.</p><p>- For ( n = 128 ), ( b = 2 ), and ( |C| = 2^{32} ):<br>- Centroid index requires ( 32 ) bits (or 4 bytes).<br>- Quantised residual requires ( 128*2 = 256 ) bits (or 32 bytes).</p><h3><strong>Comparison:</strong></h3><p>- Traditional ColBERT uses 256-byte vector encodings at 16-bit precision.<br>- ColBERTv2 uses 20 or 36 bytes per vector, significantly reducing storage costs.</p><h3><strong>Total Storage:</strong></h3><p>- Centroid index: 4 bytes.<br>- Quantized residual: 32 bytes.<br>- Total: 36 bytes per vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnYGqTThbHgXH91PXrvClA.png" /></figure><h3><strong>Centroid Calculation and residual Generation:</strong></h3><p>Steps for Generating Centroids and Residuals<br>1. Passage Embedding Collection: Collect the embeddings of all tokens in the passages.</p><p>2. Clustering: Apply k-means clustering to group the token embeddings into clusters (centroids).</p><p>3. Centroid Calculation: Calculate the centroid for each cluster.</p><p>4. Residual Calculation: Compute the residuals for each token embedding relative to its assigned centroid.</p><p>5. Residual Encoding: Encode the residuals using 1-bit precision.</p><p>Let’s assume we have the following passage embeddings (each embedding has 6 dimensions):</p><p><strong>1. Passage Embeddings:</strong></p><p>- Passage 1: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6], [0.2, 0.3, 0.4, 0.5, 0.6, 0.7]<br>- Passage 2: [0.9, 1.0, 0.9, 1.0, 0.9, 1.0], [0.3, 0.4, 0.3, 0.4, 0.3, 0.4]<br>- Passage 3: [0.7, 0.8, 0.7, 0.8, 0.7, 0.8], [0.1, 0.2, 0.1, 0.2, 0.1, 0.2]<br>- Passage 4: [0.3, 0.4, 0.3, 0.4, 0.3, 0.4], [0.7, 0.8, 0.7, 0.8, 0.7, 0.8]<br>- Passage 5: [0.5, 0.6, 0.5, 0.6, 0.5, 0.6], [0.9, 1.0, 0.9, 1.0, 0.9, 1.0]<br>- Passage 6: [0.7, 0.8, 0.7, 0.8, 0.7, 0.8], [0.5, 0.6, 0.5, 0.6, 0.5, 0.6]</p><p><strong>1. Passage Embedding Collection</strong></p><p>Collect all token embeddings from the passages into a single matrix \( E \):</p><p>E = [<br>0.1 &amp; 0.2 &amp; 0.3 &amp; 0.4 &amp; 0.5 &amp; 0.6 \\<br>0.2 &amp; 0.3 &amp; 0.4 &amp; 0.5 &amp; 0.6 &amp; 0.7 \\<br>0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0 \\<br>0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 \\<br>0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 \\<br>0.1 &amp; 0.2 &amp; 0.1 &amp; 0.2 &amp; 0.1 &amp; 0.2 \\<br>0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 \\<br>0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 \\<br>0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6 \\<br>0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0 \\<br>0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 \\<br>0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6<br>]</p><p><strong>2. Clustering</strong></p><p>Apply <strong>k-means clustering</strong> to the embeddings. Suppose we use \(k = 5\) clusters (centroids). The clustering algorithm assigns each token embedding to one of the 5 centroids.</p><p>Assume the clustering result is as follows (each row indicates the index of the assigned centroid):</p><p><strong>Cluster Assignments </strong>=[<br>1 \\<br>1 \\<br>2 \\<br>3 \\<br>4 \\<br>1 \\<br>3 \\<br>4 \\<br>5 \\<br>2 \\<br>4 \\</p><p>]</p><p><strong>3. Centroid Calculation</strong></p><p>Calculate the centroid for each cluster. Each centroid is the mean of all embeddings assigned to that cluster.</p><p><strong>Centroid 1 (C1):</strong></p><p>C1 = 0.33[<br>0.1 &amp; 0.2 &amp; 0.3 &amp; 0.4 &amp; 0.5 &amp; 0.6 \\<br>0.2 &amp; 0.3 &amp; 0.4 &amp; 0.5 &amp; 0.6 &amp; 0.7 \\<br>0.1 &amp; 0.2 &amp; 0.1 &amp; 0.2 &amp; 0.1 &amp; 0.2<br>]</p><p>=[0.133 &amp; 0.233 &amp; 0.266 &amp; 0.366 &amp; 0.4 &amp; 0.5]</p><p><strong>Centroid 2 (C2):</strong><br>C2 = 0.5[<br>0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0 \\<br>0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0<br>]</p><p>= [0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0 &amp; 0.9 &amp; 1.0]</p><p><strong>Centroid 3 (C3):</strong><br>C3 = 0.5[<br>0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 \\<br>0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4<br>= 0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4 &amp; 0.3 &amp; 0.4</p><p><strong>-Centroid 4 (C4):</strong><br>C4 = 0.33[<br>0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 \\<br>0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 \\<br>0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8<br>=[0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8 &amp; 0.7 &amp; 0.8]</p><p><strong>Centroid 5 (C5):<br></strong>C5 = 0.5[<br>0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6 \\<br>0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6<br>]</p><p>= [0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6 &amp; 0.5 &amp; 0.6]</p><p><strong>4. Residual Calculation</strong></p><p>Compute the residuals for each token embedding relative to its assigned centroid. The residual is the difference between the token embedding and its centroid.</p><p>For example,<br>for the first token embedding [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] assigned to (C1):</p><p>[0.133 &amp; 0.233 &amp; 0.266 &amp; 0.366 &amp; 0.4 &amp; 0.5]<br>[-0.033 &amp; -0.033 &amp; 0.034 &amp; 0.034 &amp; 0.1 &amp; 0.1]</p><p><strong>5. Residual Encoding</strong></p><p>Encode the residuals using 1-bit precision. With 1-bit precision, we can represent the residual as either -1 or 1 (or any two states). For simplicity, let’s assume that we encode the residual as follows:</p><p>- If the residual is negative, encode it as -1.<br> If the residual is positive, encode it as 1.<br> For the residual [-0.033, -0.033, 0.034, 0.034, 0.1, 0.1] — [-1 &amp; -1 &amp; 1 &amp; 1 &amp; 1 &amp; 1]</p><h3><strong>Part 2 —</strong></h3><h3><strong>https://neerajku.medium.com/colpali-and-plaid-part-2-a316ccee2052</strong></h3><h3>References:</h3><ol><li>ColPali: Efficient Document Retrieval with Vision Language Models</li><li>PLAID: An Efficient Engine for Late Interaction Retrieval</li><li>ColBERTv2: Effective and Efficient Retrieval via Lightweight Late Interaction</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45caec3b14d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logsumexp trick and Flash attention- Part 2]]></title>
            <link>https://neerajku.medium.com/logsumexp-trick-and-flash-attention-part-2-9e2d55cf1610?source=rss-53044a832204------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2d55cf1610</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[softmax]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llmops]]></category>
            <dc:creator><![CDATA[Neeraj Kumar]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 14:38:52 GMT</pubDate>
            <atom:updated>2024-09-05T14:48:47.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBnTlRTVPvCieh1nJFZ7dw.png" /></figure><p>GPU memory hierarchy consists of various types of memory that differ in size and speed, where smaller memory is faster. For instance, the A100 GPU features 40–80GB of high-bandwidth memory (HBM) with a bandwidth of 1.5–2.0TB/s, alongside 192KB of on-chip SRAM per each of its 108 streaming multiprocessors, with an estimated bandwidth of around 19TB/s . Although the on-chip SRAM is significantly faster than HBM, it is much smaller in capacity.</p><p>GPUs have a massive number of threads to execute an operation (called a kernel). Each kernel loads inputs from HBM to registers and SRAM, computes, then writes outputs to HBM.</p><h4>Flash Attention objective:</h4><p>Attention algorithms are made IO-aware, meaning they are designed to efficiently manage reads and writes across different memory tiers, such as fast on-chip GPU SRAM and the relatively slower high-bandwidth memory (HBM) . On modern GPUs, computation speed has surpassed memory speed , leading to memory access bottlenecks in most Transformer operations. FlashAttention, a new algorithm, reduces memory accesses while computing exact attention. The primary objective is to minimize the need to read and write the attention matrix to and from HBM.</p><h4>Standard approach:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQO7PG98HJT0fnNGJfFI2Q.png" /></figure><p>Load Q and K:<br>Load the query matrix ( Q ) and the key matrix ( K ) from HBM.<br>Compute the scores matrix ( S = QK^T ) and write ( S ) back to HBM.<br>Compute P:<br>Read the scores matrix ( S ) from HBM.<br>Apply the softmax function to ( S ), resulting in the probabilities matrix ( P ).<br>Write ( P ) back to HBM.<br>Load P and V:<br>Load the probabilities matrix ( P ) and the value matrix ( V ) from HBM.<br>Compute the output matrix ( O = PV ) and write ( O ) back to HBM.</p><h4>Limitation:</h4><p>High Memory Usage: Storing large intermediate matrices ( S ) and ( P ) in HBM.</p><p>Numerical Stability: Potential for numerical instability when exponentiating large or small values in the softmax operation.</p><p>Performance Bottlenecks: Multiple reads and writes to and from HBM, leading to slower performance due to memory access latency.</p><h4>Flash Attention Approach</h4><p>The key idea is to divide the inputs Q, K, and V into blocks, load them from slower HBM into faster SRAM, and then compute the attention output for each block. ttention is computed in blocks. Since Softmax couples the columns of K, we break down the large Softmax operation using scaling. To ensure numerical stability, logsumexp trcik has been used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYt0M5Hp4_YxypdS9_Anpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sr9pBf_Jb_1xIGOsqXgDIw.png" /></figure><h4>Flash Attention Algorithm:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYh91DvpQipdXYSx_zGWSg.png" /></figure><p>Input Matrices:<br>Q (Query): Shape (N * d)<br>K^T (Key Transposed): Shape (d * N)<br>V (Value): Shape (N * d)</p><p>Copy Block to SRAM:<br>Small blocks of the matrices are copied to the fast SRAM from HBM. This is done to leverage the high bandwidth and low latency of SRAM for computations.</p><p>Compute Block on SRAM:</p><p>The attention scores (QK^T) are computed in SRAM. This involves matrix multiplication, which benefits from the high-speed access of SRAM.<br>The softmax operation is applied, resulting in the matrix (sm(QK^T)).</p><p>Inner and Outer Loops:</p><p>Outer Loop: Iterates over blocks of the Key and Value matrices, copying them to SRAM and performing computations.</p><p>Inner Loop: Iterates over blocks of the Query matrix, copying them to SRAM for block-wise computation.</p><p>Output to HBM:</p><p>The resulting matrix (sm(QK^T)V) is computed block-by-block in SRAM and then written back to HBM.</p><p>Example</p><p>Sequence length ( N = 4 )<br>Head dimension ( d = 2 )<br>SRAM size ( M = 8 )<br>Block sizes ( B_c = 2 ), ( B_r = 2 )</p><p>Q = [[1, 0],<br>[0, 1],<br>[1, 1],<br>[0, 0]]</p><p>K = [[1, 0],<br>[1, 1],<br>[0, 1],<br>[1, -1]]</p><p>V = [[1, 2],<br>[2, 3],<br>[3, 4],<br>[4, 5]]</p><p>Execution Steps</p><ol><li>Set Block Sizes:<br>( B_c = 2 ), ( B_r = 2 )</li><li>Initialization:<br>Initialize ( O = [[0, 0], [0, 0], [0, 0], [0, 0]] )<br>Initialize ( \ell = [0, 0, 0, 0] )<br>Initialize ( m = [-inf, -inf, -inf, -inf] )</li><li>Divide Matrices into Blocks:<br>Divide ( Q ) into two blocks ( Q_1 ) and ( Q_2 ):<br>Q_1 = [[1, 0], [0, 1]]<br>Q_2 = [[1, 1], [0, 0]]<br>Divide ( K ), ( V ), and ( O ) into two blocks each:<br>K_1 = [[1, 0], [1, 1]]<br>K_2 = [[0, 1], [1, -1]]<br>V_1 = [[1, 2], [2, 3]]<br>V_2 = [[3, 4], [4, 5]]<br>O_1 = [[0, 0], [0, 0]]<br>O_2 = [[0, 0], [0, 0]]</li><li>Outer Loop:<br>For ( j = 1 ):<br>Load ( K_1 ) and ( V_1 ) into on-chip SRAM.</li></ol><p>Inner Loop:<br>For ( i = 1 ):<br>Load ( Q_1 ), ( O_1 ), ( ell_1 ), and ( m_1 ) into on-chip SRAM.<br>Compute ( S_{11} = Q_1 K_1^T ):<br>S_{11} = [[1, 1], [0, 1]]<br>Compute ( m_{11} ) and ( P_{11} ):<br>m_{11} = [1, 1]<br>P_{11} = exp([[0, 0], [-1, 0]])<br>Update ( m_1 ) and ( ell_1 ):<br>m_1 = [1, 1]<br>ell_1 = [1, 1]<br>Compute the new output block ( O_1 ) and write it back to HBM:<br>O_1 = [[1, 2], [2, 3]]</p><ol><li>Continue for Next Block:</li></ol><p>Repeat similar steps for remaining blocks ( j = 2 ) and ( i = 2 ).</p><p>References:<br>1. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — <a href="https://arxiv.org/pdf/2205.14135">https://arxiv.org/pdf/2205.14135</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2d55cf1610" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>