<?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 Gaurav Jain on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Jain on Medium]]></description>
        <link>https://medium.com/@gj979986?source=rss-561251cc6836------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6UPso8QQImjiDrPlLQfXRQ.jpeg</url>
            <title>Stories by Gaurav Jain on Medium</title>
            <link>https://medium.com/@gj979986?source=rss-561251cc6836------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:53:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gj979986/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[Gunicorn and Uvicorn — What They Actually Are and When You Need Both]]></title>
            <link>https://medium.com/@gj979986/gunicorn-and-uvicorn-what-they-actually-are-and-when-you-need-both-127a1d1fcc5a?source=rss-561251cc6836------2</link>
            <guid isPermaLink="false">https://medium.com/p/127a1d1fcc5a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Gaurav Jain]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 03:28:26 GMT</pubDate>
            <atom:updated>2026-09-30T03:28:26.937Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7LuBOAVL94AXLHBH_ANgA.png" /></figure><p><em>While building a full-stack FastAPI app — streaming AI responses, WebSockets, multi-minute workflows — I kept using the startup command below without really knowing what it did. Curiosity got the best of me, so I went down the rabbit hole to learn how it actually works. These are my working notes; hope they help someone in the community.</em></p><h3>The Command in Question</h3><p>If you have deployed a FastAPI app to any managed hosting platform, you have probably seen something like this:</p><pre>gunicorn main:app -w 4 -k uvicorn_worker.UvicornWorker --timeout 300 --bind 0.0.0.0:8000</pre><p>Two names. One command. They do very different things.</p><blockquote><strong><em>Version note (2026):</em></strong><em> older examples use “-k uvicorn.workers.UvicornWorker”. That module is deprecated — install “uvicorn-worker” and use “uvicorn_worker.UvicornWorker”. Also worth knowing: Gunicorn 24+ ships a native ASGI worker ( — worker-class asgi), and Uvicorn’s own — workers mode now supervises and restarts its children. Gunicorn + Uvicorn is still the most common pairing, but it is no longer the only option.</em></blockquote><h3>First Principles — WSGI vs ASGI</h3><p>Before touching either tool, you need to understand the interface contract they both implement, because that is where the whole story begins.</p><p><strong>WSGI — The Synchronous Contract (2003)</strong></p><p>WSGI (Web Server Gateway Interface — PEP 333 in 2003, updated for Python 3 as PEP 3333 in 2010) is a synchronous request/response protocol. The entire contract is roughly:</p><pre>def application(environ: dict, start_response: callable) -&gt; list[bytes]:<br>    start_response(&#39;200 OK&#39;, [(&#39;Content-Type&#39;, &#39;text/plain&#39;)])<br>    return [b&#39;Hello World&#39;]</pre><p>One request in. One response out. The function blocks until it returns.</p><p>This works well for Django, Flask and traditional web apps. But it has limits:</p><ul><li><strong>No native WebSockets:</strong> WebSocket is a persistent connection, not a request/response</li><li><strong>Limited streaming:</strong> you can return an iterable, but there is no async streaming or bidirectional event flow</li><li><strong>No async concurrency:</strong> a sync worker waiting on a database query sits idle. You scale with more processes or threads.</li></ul><p><strong>ASGI — The Async Contract</strong></p><p>ASGI (Asynchronous Server Gateway Interface) came out of the Django Channels project as the spiritual successor to WSGI. The core idea: replace the synchronous function with an async coroutine, and replace the single request/response cycle with a generic event stream.</p><pre>async def application(scope: dict, receive: callable, send: callable) -&gt; None:<br>    if scope[&#39;type&#39;] == &#39;http&#39;:<br>        await send({&#39;type&#39;: &#39;http.response.start&#39;, &#39;status&#39;: 200,<br>                    &#39;headers&#39;: [(b&#39;content-type&#39;, b&#39;text/plain&#39;)]})<br>        await send({&#39;type&#39;: &#39;http.response.body&#39;, &#39;body&#39;: b&#39;Hello World&#39;})<br>    elif scope[&#39;type&#39;] == &#39;websocket&#39;:<br>        # handle WebSocket events<br>        ...<br>    elif scope[&#39;type&#39;] == &#39;lifespan&#39;:<br>        # startup / shutdown hooks<br>        ...</pre><p>The scope tells you the connection type. receive lets you await incoming events. send lets you push events back. One interface covers HTTP, WebSockets, streaming responses (including Server-Sent Events) and lifespan hooks. Which HTTP versions you actually get depends on the server.</p><p>FastAPI is an ASGI framework. Every async def route you write lives inside this model.</p><h3>Uvicorn — The ASGI Server</h3><p>Uvicorn is a fast ASGI server created by Tom Christie (of Django REST Framework and HTTPX) and now maintained by Marcelo Trylesinski.</p><p>When installed with uvicorn[standard], it uses <strong>uvloop</strong> — a Cython binding over <strong>libuv</strong>, the same C library behind Node.js’s event loop — and httptools for parsing. Without those extras it falls back to the standard asyncio loop and h11.</p><p><strong>What Uvicorn does</strong></p><ul><li>Listens on a TCP socket</li><li>Parses HTTP/1.1 requests and WebSocket upgrade handshakes (HTTP/2 is experimental and off by default since 0.53, via — http zttp — http2)</li><li>Translates incoming bytes into ASGI scope / receive / send events</li><li>Runs your FastAPI app as an ASGI callable</li><li>Handles connection lifecycles, keep-alive and stream framing</li></ul><p><strong>What Uvicorn is not</strong></p><p>A plain uvicorn main:app is one process with one event loop — no supervision, no worker recycling. uvicorn — workers N adds a basic process manager that restarts dead or stuck children and supports graceful restarts on SIGHUP. That is enough for many setups. Gunicorn is still the more mature process manager — richer configuration, server hooks, and a long production track record.</p><h3>Gunicorn — The Process Manager</h3><p>Gunicorn (Green Unicorn) has been a standard Python process manager since 2010. It uses the pre-fork worker model:</p><pre>Gunicorn master process (the &quot;Arbiter&quot;)<br>│   owns the listening socket, handles signals, monitors and restarts workers<br>│<br>├── Worker 1 (child process)<br>├── Worker 2 (child process)<br>├── Worker 3 (child process)<br>└── Worker 4 (child process)</pre><p>Workers accept connections and handle requests. If a worker crashes or stops sending its heartbeat, the master kills it and forks a new one.</p><p><strong>The UvicornWorker bridge</strong></p><p>Gunicorn has a pluggable worker class. -k uvicorn_worker.UvicornWorker tells it: “instead of a synchronous WSGI worker, run a Uvicorn event loop in each worker process.”</p><pre>Gunicorn master (supervision, signals, restarts)<br>├── UvicornWorker → event loop (concurrency within this process)<br>├── UvicornWorker → event loop<br>├── UvicornWorker → event loop<br>└── UvicornWorker → event loop</pre><p><strong>Gunicorn provides:</strong> process supervision, crash recovery, graceful restarts, signal handling, and worker recycling via — max-requests / — max-requests-jitter (useful for containing memory leaks — hard memory limits come from the OS, container or platform).</p><p><strong>Uvicorn provides:</strong> async I/O, WebSockets and streaming within each worker.</p><h3>Concurrency Within a Single Worker</h3><p>This is the piece most people miss. A single UvicornWorker is not limited to one request at a time. Its event loop can hold many concurrent connections — hundreds or more for I/O-bound work, limited by memory, file descriptors and your downstream services.</p><p>Imagine 30 users, each holding a WebSocket and waiting on a multi-minute AI workflow. One worker can hold all 30:</p><pre>UvicornWorker (one process, one event loop)<br>│<br>├── user_1 WS /ws        → awaiting AI service response (8 min so far)<br>├── user_2 WS /ws        → awaiting AI service response (3 min so far)<br>├── user_3 WS /ws        → just connected, sending workflow_started<br>├── user_4 POST /upload  → awaiting vector store indexing<br>└── user_5 GET /health   → returns immediately</pre><p>The key word is <strong>awaiting</strong>. When user_1 hits await client.responses.create(…), its coroutine is suspended and the loop moves on to the others. When the response arrives, the loop resumes user_1 where it left off. Waiting on the network costs nothing.</p><p><strong>Where it breaks: blocking calls</strong></p><pre>@app.post(&quot;/upload&quot;)<br>async def upload():<br>    time.sleep(5)           # WRONG: blocks the event loop<br>    await asyncio.sleep(5)  # RIGHT: yields to the loop</pre><p>time.sleep() inside an async def freezes the whole loop — all 30 connections on that worker stall. The same goes for any synchronous call: a sync SDK, requests.get(), file I/O, heavy parsing.</p><p>Prefer async libraries (httpx.AsyncClient, async DB drivers). When you can’t, offload:</p><pre>import asyncio<br>from starlette.concurrency import run_in_threadpool<br>result = await asyncio.to_thread(my_sync_function, arg1, arg2)<br># or the Starlette/FastAPI equivalent:<br>result = await run_in_threadpool(my_sync_function, arg1, arg2)</pre><blockquote><em>FastAPI already does this in one case: routes and dependencies declared with plain def (not async def) run in a thread pool automatically. The trap is blocking code </em>inside<em> async def.</em></blockquote><p><strong>What the thread pool actually does</strong></p><pre>async route (on the event loop)<br>   │<br>   │  await asyncio.to_thread(sync_func)<br>   ▼<br>sync_func submitted to ThreadPoolExecutor ──► worker thread runs sync_func<br>   │                                                │<br>   │  route coroutine suspends                      │  blocks only this thread<br>   ▼                                                │<br>event loop keeps serving other requests             │<br>   │                                                ▼<br>   │◄─────────── result posted back to the loop ────┘<br>   ▼<br>route resumes after the await → response sent</pre><p>Two caveats:</p><ul><li><strong>The pool is finite.</strong> asyncio.to_thread uses the loop’s default pool of min(32, cpu_count + 4) threads; Starlette’s pool (used by def routes and run_in_threadpool) is capped at 40 by AnyIO. If every request offloads long blocking work, jobs queue. The loop stays responsive, but requests still wait.</li><li><strong>Threads don’t give CPU parallelism for pure-Python work.</strong> They are the right tool for blocking <em>I/O</em>. For CPU-heavy work, read on.</li></ul><h3>When Async Is Not Enough — The GIL and CPU-Bound Work</h3><p>This is the part that trips up most people who understand asyncio but have not thought carefully about the GIL.</p><p><strong>The GIL in a sentence</strong></p><p>Standard CPython has a Global Interpreter Lock: only one thread runs Python bytecode at a time, even on a multi-core machine. (Python 3.13+ offers an optional free-threaded build without it, but most production stacks still run the standard build.)</p><p>For I/O-bound work this barely matters — while a coroutine is awaiting the network, no Python code is running for it. For CPU-bound work it matters a lot. If JSON cleanup, XML manipulation or regex processing runs inline in an async def, the event loop cannot schedule anything else until it finishes.</p><p>Moving it to a thread keeps the loop responsive, but the GIL still stops it running in parallel with other Python code in that process.</p><p><strong>Concurrency vs Parallelism</strong></p><ul><li><strong>Concurrency</strong> — many tasks making progress by taking turns. asyncio gives you this: one worker juggling 30 WebSockets.</li><li><strong>Parallelism</strong> — tasks running at the same time on different cores. — workers 4 gives you this: four processes, each with its own interpreter and GIL, scheduled across cores by the OS.</li></ul><pre>One process, 3 threads (CPU work):<br>  core 1: [T1][T2][T3][T1][T2][T3]...   ← taking turns on one GIL<br><br>Four worker processes:<br>  core 1: [W1 ─────────────]<br>  core 2: [W2 ─────────────]            ← truly simultaneous<br>  core 3: [W3 ─────────────]<br>  core 4: [W4 ─────────────]</pre><p>(Simplified: the OS may move threads between cores, but only one holds the GIL at a time.)</p><p>One UvicornWorker is highly concurrent but not parallel. Four are both.</p><p><strong>How this shows up in a real AI agent backend</strong></p><p>A typical multi-agent AI workflow mixes both:</p><pre>prefetch context               → I/O  (parallel calls to storage / internal APIs via httpx)<br>LLM call per agent             → I/O  (30–60s waiting for the model API)<br>parse agent output             → CPU  (JSON parsing, regex extraction)<br>fill a document template       → CPU  (XML tree manipulation, e.g. lxml)<br>build and upload the document  → CPU  (zip/XML assembly) + I/O (upload to storage)</pre><p>The I/O dominates wall-clock time, and the event loop handles it for free. The CPU bursts are the problem: tens to a few hundred milliseconds of parsing and XML work per agent output. Some native libraries release the GIL for parts of their work, but the Python-level glue around them does not.</p><p>With one worker, every CPU burst stalls everyone else on that loop:</p><pre>t=0ms    User A: XML template fill runs inline on the event loop (200ms)<br>t=0ms    User B: LLM response has arrived, but can&#39;t be processed yet<br>t=0ms    User C: wants to parse JSON, also waiting<br>t=200ms  User A done → loop resumes B and C</pre><p>With four workers, each process handles its own users’ bursts in parallel. That is the real reason multiple workers matter for AI backends: <strong>not just more connections, but isolating one user’s CPU bursts from everyone else.</strong></p><h3>30 Concurrent Users — A Worked Example</h3><p>Take a backend serving 30 concurrent users, each running a multi-agent workflow like the one above. The numbers below are illustrative — use them to follow the reasoning, not as capacity figures. Measure your own workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIFRjlcDVEqoS55DPWVEpw.png" /></figure><p>On a 4-vCPU instance with 4–5 workers, each worker holds 6–8 users. At any moment almost all of them are suspended at an await, so the loop is mostly idle. A CPU burst now affects ~7 users on that worker instead of all 30.</p><p>It can still stall briefly if several users on the same worker hit their CPU phase at once — a 200–500ms delay before the next agent starts, but no errors. The real fix is to move heavy CPU work off the event loop (asyncio.to_thread for GIL-releasing libraries, a process pool or background job for pure-Python work) rather than sprinkling asyncio.sleep() between steps.</p><p><strong>Memory:</strong> each worker is a full Python process. With a typical AI-backend import chain (FastAPI, an LLM SDK, lxml, httpx, OpenTelemetry) expect roughly 200–300 MB per worker, so five workers plus active workflow state land around 1–1.5 GB — comfortable on a 16 GB instance. For workloads like this, CPU usually runs out long before memory does.</p><pre># 4 vCPU, 16 GB — a reasonable starting point for ~30 concurrent users<br>gunicorn main:app \<br>  -w 5 \<br>  -k uvicorn_worker.UvicornWorker \<br>  --timeout 600 \<br>  --graceful-timeout 120 \<br>  --bind 0.0.0.0:8000</pre><h3>How Many Workers ?</h3><p>For <strong>sync WSGI workers</strong>, the Gunicorn docs suggest starting around (2 × cores) + 1: while one worker blocks on I/O, another can use the CPU.</p><p>For <strong>async workers</strong>, each process already overlaps I/O on its event loop, so you need fewer. A practical starting point is <strong>cores to cores + 1</strong>, then benchmark:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbW1bQlqcyNA0O89t-s0hQ.png" /></figure><p>Go higher only if the workload is overwhelmingly I/O-bound and CPU and memory stay healthy. Every extra worker is another full Python process — and another separate copy of any in-memory state (see the next section).</p><p><strong>The timeout flag</strong></p><p>— timeout is <strong>not</strong> a per-request timeout. Gunicorn kills a worker that has been <em>silent</em> — not sending its heartbeat — for that many seconds (default 30). The Gunicorn docs are explicit: for non-sync workers it “is not tied to the length of time required to handle a single request.”</p><p>With UvicornWorker, a 10-minute await on an LLM call does not trip it as long as the event loop stays alive. What trips it is <strong>blocking the loop</strong> — CPU work or a sync call running inline long enough that the heartbeat can’t be sent. If workers are being killed at exactly the timeout, look for blocking code before raising the number.</p><p>— timeout 0 disables the check entirely. Only do that if you have other protection: application-level timeouts, health checks and monitoring.</p><h3>The Stateful Process Problem</h3><p>This one is easy to miss when you are focused on getting the app running — and it produces one of the hardest classes of bugs to diagnose: intermittent failures that never reproduce in development.</p><p>Each Gunicorn worker is a <strong>separate OS process with its own memory space</strong>. There is no shared memory between workers. Any Python module-level variable — a cache, a registry, a connection pool, a session store — exists independently in each worker.</p><pre>Worker 1 memory:<br>  _session_store = {&quot;conv_AAA&quot;: {&quot;email&quot;: &quot;alice@example.com&quot;, &quot;agent&quot;: &quot;reviewer&quot;}}<br>Worker 2 memory:<br>  _session_store = {}   ← Alice does not exist here<br>Worker 3 memory:<br>  _session_store = {}<br>Worker 4 memory:<br>  _session_store = {}</pre><p><strong>The probability of failure</strong></p><p>With N workers and requests spread evenly across them, any follow-up request — one that depends on state written by a previous request — has a N−1/<em>N</em> probability of landing on a worker that has never seen that session.</p><p>With 4 workers: <strong>75% failure rate</strong> on any stateful multi-step interaction.</p><pre>Step 1: POST /threads → Worker 1 → session_store[&quot;conv_AAA&quot;] = {...}  ✓<br>Step 2: POST /upload  → Worker 2 → session_store.get(&quot;conv_AAA&quot;)      ✗  (75% chance)<br>Step 3: POST /upload  → Worker 3 → session_store.get(&quot;conv_AAA&quot;)      ✗  (still 75%)<br>Step 4: POST /upload  → Worker 1 → session_store.get(&quot;conv_AAA&quot;)      ✓  (got lucky)</pre><p>This is why the failure appears to “work after a few retries” — the user is simply waiting for the lottery to land on the right worker. (Real traffic isn’t perfectly even — keep-alive connections and proxies skew it — but the core problem holds.)</p><p><strong>Why this is invisible until production</strong></p><p>In development you run one Uvicorn process, so everything works. In production under light load, a user’s follow-up requests may happen to land on the same worker (for example, by reusing a keep-alive connection). Under real concurrent load the failure rate climbs towards N−1/<em>N</em>​.</p><p><strong>The symptom is intermittent and load-dependent</strong>, which makes it easy to misdiagnose as a network, API or upload problem.</p><p><strong>WebSocket affinity — a partial solution only</strong></p><p>A WebSocket is a persistent TCP connection. Once the upgrade handshake completes, that socket stays with one worker for its lifetime, so every message on it sees the same in-process state. (The same holds across instances: a proxied WebSocket stays on one backend for the life of the connection.)</p><p><strong>But WebSocket affinity only protects the hot path — the persistent connection itself.</strong> Two failure modes remain:</p><p><strong>1. The setup path is still HTTP.</strong> Any REST calls that create or mutate session state alongside the WebSocket can still land on any worker. If POST /api/threads lands on Worker A and the WebSocket upgrade lands on Worker B, the WebSocket worker has never seen the session. The very first configuration message fails silently.</p><pre>POST /api/threads  → Worker A → session_store.set(&quot;conv_AAA&quot;, {...})<br>WS connect         → Worker B → session_store.get(&quot;conv_AAA&quot;) → None<br>                                 instructions = None, agent = None<br>                                 agent runs with no configuration</pre><p><strong>2. Reconnect breaks affinity.</strong> When a client disconnects and reconnects — tab refresh, network drop, mobile screen lock — the new WebSocket upgrade is again load-balanced. The new connection lands on a random worker. Any in-memory session state from the previous worker is permanently gone.</p><p>The correct mental model:</p><blockquote><em>A WebSocket connection gives you process-level affinity for the duration of that connection only. It does not protect concurrent HTTP calls, and it does not survive reconnects. A purely WebSocket-based app is safer than a purely REST-based stateful app, but neither is safe without externalised state.</em></blockquote><p><strong>The three fixes</strong></p><p><strong>1. Externalise state (correct, permanent fix)</strong></p><p>Move all session data to a store that every worker can reach: Redis, a relational database, Azure Table Storage, DynamoDB. The in-process dict becomes a thin facade over the external store. All workers read and write the same data. Any worker can serve any request.</p><pre># Before — in-memory dict, breaks with N &gt; 1 workers<br>class SessionStore:<br>    def __init__(self):<br>        self._store = {}          # lives only in this process<br># After - Redis-backed, works across any number of workers<br>class SessionStore:<br>    def __init__(self):<br>        self._r = Redis(...)      # shared external store<br>    def set(self, thread_id: str, data: dict) -&gt; None:<br>        self._r.hset(thread_id, mapping=data)<br>    def get(self, thread_id):<br>        return self._r.hgetall(thread_id) or None</pre><p>The public interface (set, get, delete) stays identical. Every caller — HTTP handlers, WebSocket handlers, background tasks — requires zero changes.</p><p><strong>2. Sticky routing (fragile workaround, not a fix)</strong></p><p>Configure the load balancer to pin a client to one <em>instance</em>: ARR affinity on Azure App Service, ip_hash in Nginx, consistent hashing in HAProxy.</p><p>Two problems. First, it does nothing for the worker problem — the load balancer sees the instance, not the Gunicorn workers inside it, so requests still spread across workers. Second, even across instances it is fragile: a restart or scale-in loses every session pinned to that instance, and load becomes uneven.</p><p>Sticky routing is useful for keeping a live connection in place — not a substitute for externalised state.</p><p><strong>3. Make the service genuinely stateless</strong></p><p>Move session identity into signed tokens carried by the client (JWT, signed cookies). The server derives session context from the token on every request — no server-side store needed. This is ideal for pure REST APIs but impractical for server-side workflows that accumulate substantial state (uploaded documents, multi-step agent progress, etc.).</p><p><strong>The mitigations in practice</strong></p><p>For a stateful real-time backend (WebSocket + REST), the correct pattern:</p><pre>On thread create    → write session to external store (Redis / Azure Table)<br>On WebSocket open   → read session from external store → load into coroutine-local dict<br>On any state change → write delta back to external store<br>On reconnect        → read session from external store → resume seamlessly<br>On session end      → delete from external store</pre><p>The coroutine-local dict is a performance cache (no I/O on every message). The external store is the source of truth (survives any worker boundary).</p><p>Any stateful per-user data that needs to survive across workers, reconnects, or deployments must live in external storage, not Python dictionaries.</p><h3>Scaling Up vs Scaling Out</h3><p><strong>Vertical (scale up)</strong> — a bigger instance with more cores and more workers. Simpler: one App Service plan, no cross-instance routing. But the workers on that machine still don’t share memory, so the stateful-process problem above applies in full.</p><p><strong>Horizontal (scale out)</strong> — several identical instances behind a load balancer:</p><pre>Load Balancer<br>├── Instance A: Gunicorn -w 3<br>├── Instance B: Gunicorn -w 3<br>└── Instance C: Gunicorn -w 3</pre><p>This needs externalised state, WebSocket support at the load balancer (plus state that survives reconnects), shared config and secrets, and health-check endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIRxbjpHZnx5ez2S1hkdCw.png" /></figure><p>For a pilot or internal AI agent backend: <strong>start vertical, but externalise session state from day one.</strong> Then scaling out is a configuration change, not a rewrite.</p><h3>Putting It Together — A Real Configuration</h3><p>A startup command for a 1-vCPU App Service running a streaming AI agent backend:</p><pre>gunicorn main:app \<br>  -w 2 \<br>  -k uvicorn_worker.UvicornWorker \<br>  --timeout 600 \<br>  --graceful-timeout 120 \<br>  --keep-alive 65 \<br>  --max-requests 1000 \<br>  --max-requests-jitter 100 \<br>  --bind 0.0.0.0:8000 \<br>  --access-logfile - \<br>  --error-logfile - \<br>  --log-level info</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ro1-AopyeaAbEmRa9ih9vQ.png" /></figure><p><strong>Containers (Docker / Kubernetes)</strong></p><p>When an orchestrator already handles restarts, replication and health checks, the FastAPI docs recommend one Uvicorn process per container:</p><pre>uvicorn main:app --host 0.0.0.0 --port 8000</pre><p>Gunicorn adds the most value where the platform gives you one VM or container per instance and expects you to manage workers inside it — App Service, plain VMs, a traditional VPS.</p><p><strong>Other settings worth knowing</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_TQbYlE4bCtVdKaQVD4Hg.png" /></figure><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIv3Ffr9Yh0vtaHk2lpKqA.png" /></figure><p>The mental model: <strong>Uvicorn is the engine, Gunicorn is the fleet manager.</strong> Each Gunicorn worker runs its own engine. Inside each engine, await gives you concurrency for free; across engines, the OS gives you parallelism.</p><p>Start with cores to cores + 1 workers and benchmark. Keep blocking and CPU-heavy code off the event loop. And externalise session state before you add a second worker — not after users start seeing intermittent failures.</p><p>Hope this is useful to someone. Happy to discuss in the comments if anything is off.</p><p><em>Versions checked: Uvicorn 0.54, uvicorn-worker 0.4, Gunicorn 26.2, FastAPI 0.142, Python 3.14 — September 2026.</em></p><p><em>References:</em></p><ul><li><a href="https://uvicorn.dev/deployment/"><em>Uvicorn — Deployment</em></a></li><li><a href="https://uvicorn.dev/settings/"><em>Uvicorn — Settings</em></a></li><li><a href="https://github.com/Kludex/uvicorn-worker"><em>uvicorn-worker package</em></a></li><li><a href="https://gunicorn.org/design/"><em>Gunicorn — Design</em></a></li><li><a href="https://gunicorn.org/reference/settings/"><em>Gunicorn — Settings</em></a></li><li><a href="https://gunicorn.org/asgi/"><em>Gunicorn — ASGI worker</em></a></li><li><a href="https://fastapi.tiangolo.com/deployment/server-workers/"><em>FastAPI — Server workers</em></a></li><li><a href="https://fastapi.tiangolo.com/async/"><em>FastAPI — Concurrency and async/await</em></a></li><li><a href="https://asgi.readthedocs.io/en/latest/"><em>ASGI specification</em></a></li><li><a href="https://peps.python.org/pep-3333/"><em>PEP 3333 — WSGI</em></a></li><li><a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread"><em>Python — asyncio.to_thread</em></a></li><li><a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor"><em>Python — ThreadPoolExecutor</em></a></li><li><a href="https://anyio.readthedocs.io/en/stable/threads.html"><em>AnyIO — Working with threads</em></a></li><li><a href="https://learn.microsoft.com/en-us/azure/app-service/configure-language-python"><em>Azure App Service — Configure Python apps</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=127a1d1fcc5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Indexing Algorithms in RAG — What Each One Actually Costs]]></title>
            <link>https://medium.com/@gj979986/vector-indexing-algorithms-in-rag-what-each-one-actually-costs-00d016ff3e43?source=rss-561251cc6836------2</link>
            <guid isPermaLink="false">https://medium.com/p/00d016ff3e43</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Gaurav Jain]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 13:58:32 GMT</pubDate>
            <atom:updated>2026-09-07T02:02:49.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIdrvRKbZ65_UAAZbJ6AwA.png" /></figure><p><em>Detailed Working notes on Flat, IVF, HNSW, PQ/OPQ, quantization and hybrid search — what each one does, what it costs, and where it breaks.</em></p><p>While doing my regular explorations and readings around RAG and vector search, I put together these notes as a reference on different indexing approaches, including Flat, IVF, HNSW, PQ/OPQ, quantization, and hybrid search. The goal is to briefly explain what each index family does, the tradeoffs in memory and compute. If you want to skip the full write-up, detailed references for all index families are included at the end for deeper reading. Hope the community finds this helpful. Enjoy, and happy upskilling!</p><h3>The 30-Second RAG Context</h3><p>RAG (Retrieval-Augmented Generation) grounds an LLM’s answer in external documents rather than relying solely on what it learned during training. The pipeline is straightforward: chunk your documents, embed each chunk into a dense vector, index those vectors, then at query time embed the question and search the index for the most relevant chunks — which get passed to the LLM as context.</p><p>The index governs that retrieval step. It determines how fast the system responds, how much of the relevant material it finds, and how much memory the whole thing consumes. Retrieval also sets a ceiling on the rest of the pipeline: if the index returns the wrong chunks, the model cannot recover information it never received.</p><p><strong>The core problem.</strong> Vector search means finding the k stored vectors most similar to a query vector — nearest neighbor search. Checking every single vector in a large corpus is too slow for real-time use. So, production systems use <strong>Approximate Nearest Neighbor (ANN)</strong> search: trade a small, controlled accuracy loss for orders-of-magnitude speed gains. All the algorithms in this article are different answers to that tradeoff.</p><h3>Index Family Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ci8IY_f_zqfGWKPoLLkDMg.png" /></figure><h3>Vectors, Embeddings, and Why Clustering Matters</h3><h4>Vectors and Embeddings — Same Thing?</h4><p>In RAG conversations, yes. Technically: a <strong>vector</strong> is just a list of numbers — coordinates in high-dimensional space. An <strong>embedding</strong> is a vector produced by a trained model (BERT, OpenAI text-embedding-3, etc.) such that semantic meaning maps to geometric proximity. As Meilisearch’s documentation puts it, semantically similar items are placed closer together in the embedding space than dissimilar ones. So, all embeddings are vectors, but not all vectors are embeddings. In a RAG pipeline the stored vectors are embeddings — every chunk of text becomes a point in a space where proximity means relevance.</p><h4>What is Clustering?</h4><p>Clustering groups data points by similarity without labels. The RAG-relevant family is <strong>K-Means</strong>: iteratively find K centroids minimizing total squared distance to assigned points, producing Voronoi cells — the geometric structure IVF directly exploits. K-Means++ initialization spreads seeds proportionally to squared distance from existing centroids, giving a log-K approximation guarantee over vanilla random seeding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNGrWr__DRZE210AfM-ndQ.png" /></figure><h4>Why Vectors Need Clustering</h4><p>At scale, brute-force distance computation is impractical. 5 million 768-dimensional float32 vectors require ~15 GB of storage, and a single query touches all 5M × 768 ≈ 3.84 billion vector components — several times that in actual floating-point operations.</p><p>The deeper problem is the <strong>Curse of Dimensionality</strong>. As dimensions increase, distances between all pairs of points converge toward the same value — the contrast between “near” and “far” degrades. Milvus’s documentation describes this as making it hard to distinguish nearest neighbors from random points. Zilliz frames the implication directly: it forces indexing techniques to prioritize efficiency and approximation over exactness, since traditional spatial partitions become too numerous and overlapping to prune effectively.</p><p>The saving grace: embedding models impose semantic structure on the space. Similar documents genuinely cluster together. Clustering algorithms expose that structure so that at query time, instead of checking all N vectors, the system checks only the relevant neighborhood — typically one to two orders of magnitude fewer comparisons, at a recall cost you control.</p><p><strong>The boundary problem.</strong> Hard cluster assignments mean a document near the edge of two clusters lives in only one inverted list. A query landing near that same boundary may miss it. This single tension explains the design of every ANN algorithm below — each is a different engineering answer to: <em>how do we handle boundary cases gracefully?</em></p><blockquote><strong><em>Why classical spatial trees don’t apply.</em></strong><em> KD-Trees and Ball Trees prune branches using bounding boxes or hyperspheres. That pruning collapses above ~20 dimensions (the </em><a href="https://scikit-learn.org/stable/modules/neighbors.html"><em>scikit-learn Nearest Neighbours guide</em></a><em> gives this rough threshold) — distance contrast degrades, almost every branch gets visited anyway. Embeddings live at 768–3,072 dimensions.</em></blockquote><h3>FLAT — Brute Force Exact Search</h3><p><strong>What you get.</strong> 100% recall — Flat is the ground truth that every ANN algorithm is benchmarked against. FAISS documents IndexFlatL2 (Euclidean distance) and IndexFlatIP (inner product) as exhaustive search with 4d bytes per vector.</p><p><strong>The BLAS trick.</strong> FAISS isn’t just a naive loop. The squared distance between two vectors equals the squared norm of the first, plus the squared norm of the second, minus twice their inner product. Expanding it that way turns the expensive part into a matrix multiplication, which FAISS routes through BLAS Level 3 routines that exploit AVX2/AVX-512 SIMD. GPU implementations (GpuIndexFlatL2) are also available for high-throughput batch workloads.</p><p><strong>One important caveat.</strong> IndexFlatIP returns cosine similarity only for L2-normalised vectors. FAISS explicitly notes that cosine similarity requires normalization beforehand. Using it on un-normalized vectors conflates direction with magnitude — a silent correctness bug.</p><p><strong>When to use.</strong> Flat is practical for small-to-mid collections, offline batch workloads, and as a GPU-accelerated reranked over a smaller ANN candidate set. There is no single universal size cutoff — the crossover depends on hardware, dimensionality, and query volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPy8gLDuYAMRbZflaC6eSA.png" /></figure><h3>IVF — Inverted File Index</h3><p><a href="https://www.velodb.io/glossary/inverted-file-index-in-vector-similarity-search">IVF</a> is the production workhorse for large corpora. Rather than scanning every vector, it first narrows the search to a few relevant partitions and then scans only those exhaustively. As the <a href="https://github.com/facebookresearch/faiss/wiki/Faiss-indexes">FAISS indexes guide</a> describes partition the feature space into nlist Voronoi cells using K-Means, assign each vector to an inverted list, and at query time probe only the nprobe nearest cells. Note that the within-cell scan is exact only for IVF-Flat; with IVF-PQ the stored codes are compressed, so even a fully probed list gives approximate distances.</p><h4>How It Works</h4><ol><li><strong>Build:</strong> Train K-Means on a corpus sample → nlist centroids. Assign each vector to its nearest centroid. Store vectors (or compressed codes) in per-centroid inverted lists.</li><li><strong>Query:</strong> Find the nprobe centroids nearest the query. Search only those lists. Return the best candidates found.</li><li><strong>Residual encoding.</strong> IVFPQ encodes the <em>residual</em> — the vector minus its cell’s centroid — rather than the raw vector. The residual captures local variation within the cell rather than global position: smaller magnitude, lower quantization error.</li></ol><h4>The Two Knobs That Matter</h4><ol><li><strong>nlist</strong> — number of clusters. <a href="https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index">FAISS’s guideline</a> is 4√N to 16√N for datasets below 1M, moving to fixed large values (65,536 / 262,144 / 1,048,576) as the corpus grows into the 1M–1B range. More clusters = finer partitions, faster queries, slower training. FAISS also recommends between 30× and 256× nlist training vectors — under-training the quantizer is a common and silent cause of poor recall.</li><li><strong>nprobe</strong> — clusters probed per query. The primary recall/speed lever. nprobe=1 is fastest but misses boundary vectors. nprobe=nlist recovers brute-force recall. Note: nprobe / nlist is only an approximation of the fraction of the database searched, because list lengths are unequal.</li></ol><h4>Training Requirement</h4><p>IVF must be trained on a representative corpus sample before vectors can be added. If the document distribution shifts — new topic domains added — recall degrades silently without any error. Periodic retraining is required. This is operational overhead that graph-based methods like HNSW avoid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdl4JzlUws53ziWfmrt6jQ.png" /></figure><h3>HNSW — Hierarchical Navigable Small World</h3><p>HNSW is the most widely deployed ANN index in production RAG systems. It is graph-based, requires no training, supports dynamic inserts, and separates long-range navigation from local refinement across a hierarchy of layers.</p><h4>The Core Idea</h4><p>Each vector is a node. Edges connect approximate nearest neighbors. Search is a greedy walk: start at the top, hop toward the query at each layer, descend when no closer node is reachable, repeat until layer 0. At layer 0, run a beam search of width efSearch to collect the final candidates.</p><p>The hierarchy is the key innovation over its predecessor NSW. The <a href="https://arxiv.org/abs/1603.09320">original paper by Malkov and Yashunin</a> reports that starting the search at the upper layer and exploiting scale separation “allows a logarithmic complexity scaling.” Treat this as an empirical expectation rather than a guaranteed worst-case bound, especially for high-dimensional embedding data; measurements on your own dataset are more reliable than the asymptotic framing.</p><p>Each vector is assigned a maximum layer at insert time, drawn from an exponentially decaying distribution: take the negative natural log of a uniform random number between 0 and 1, multiply by a normalization factor (1 divided by the natural log of M), and round down.</p><p>Most vectors land at layer 0 only. Approximately 1 in M reach layer 1, 1 in M² reach layer 2, and so on — producing a structure that is sparse at the top and dense at the bottom. The top layers act as a coarse express lane that covers long distances in few hops; layer 0 holds every vector and does the fine-grained work.</p><h4>Neighbour Selection</h4><p>The <a href="https://arxiv.org/abs/1603.09320">HNSW paper</a> describes two strategies:</p><ol><li><strong>Simple</strong> — connect to the M closest candidates. Fast, works well on uniform data.</li><li><strong>Heuristic (production default)</strong> — prefer neighbors that reach <em>diverse</em> regions. If a candidate is closer to an already-selected neighbor than to the query, deprioritize it in favor of a farther candidate that extends connectivity into a new region. Improves recall on clustered data.</li></ol><p>At layer 0, each node can hold up to 2M connections — double the upper-layer limit — to support the dense local search needed for final refinement (<a href="https://arxiv.org/abs/1603.09320">source</a>).</p><p><strong>Memory.</strong> For capacity planning, <a href="https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index">FAISS gives</a> (d × 4) + (M × 2 × 4) bytes per vector for IndexHNSWFlat. This is a practical estimate for that implementation, not a universal exact formula for every HNSW library; allocation details and graph structure vary. At d = 768 and M = 16 that is roughly 3,200 bytes per vector, or about 32 GB at 10M vectors. All FAISS indexes are held in RAM; SSD-resident graph indexes exist but are a different family (see DiskANN below).</p><p><strong>Why it handles boundaries better than IVF.</strong> A vector near the border of two semantic clusters will have edges into both regions. Graph traversal follows those edges regardless of where a Voronoi line would have been drawn — structural advantage over hard cell assignment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rZx9OcZTVJxNYEdcqeIcA.png" /></figure><h3>PQ and OPQ — Product Quantization &amp; Optimized Product Quantization</h3><p>PQ is a compression and approximate-distance scheme. It is most often combined with IVF as IVFPQ, but <a href="https://github.com/facebookresearch/faiss/wiki/Faiss-indexes">FAISS also exposes IndexPQ</a> for standalone exhaustive PQ search. The two roles are distinct.</p><h4>The Problem It Solves</h4><p>A single flat codebook is not a practical alternative at these code lengths: matching the expressiveness of a 64-bit code with plain K-Means would require 2⁶⁴ centroids, which is impossible to store, train, or search. <a href="https://doi.org/10.1109/TPAMI.2010.57">PQ</a> sidesteps this by splitting each vector into M sub-vectors and learning one small codebook per sub-space. With K centroids per sub-space, the sub-codebooks combine into K-to-the-power-M effective reconstructions at a fraction of the storage cost.</p><h4>Compression in Plain Terms</h4><p>Split a 768-d vector into 8 blocks of 96 dimensions each. For each block, train a 256-centroid codebook (K-Means). Encode each block as the index of its nearest centroid — 1 byte. The full vector becomes 8 bytes instead of 3,072 bytes. For the full mathematical treatment, see <a href="https://doi.org/10.1109/TPAMI.2010.57">Jégou, Douze &amp; Schmid (2011)</a>. For an accessible walkthrough, <a href="https://mccormickml.com/2017/10/22/product-quantizer-tutorial-part-2/">McCormick’s tutorial</a> is excellent.</p><h4>OPQ — Optimized Product Quantization</h4><p>Standard PQ slices at fixed boundaries. If embedding dimensions are correlated across block boundaries, quantization error is unnecessarily high. <a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2013/11/pami13opq.pdf">OPQ (Ge et al., 2013)</a> learns a rotation matrix R that re-aligns the vector space before encoding, distributing variance more evenly across sub-spaces. The pipeline becomes: rotate the vector by R, then PQ-encode the rotated result.</p><p>R is constrained to be orthogonal — its transpose times itself gives the identity matrix — which means the rotation preserves all pairwise distances. Only the basis changes. R is trained via alternating optimisation: fix R and retrain the codebooks, then fix the codebooks and solve for R (a Procrustes problem with a closed-form SVD solution). The <a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2013/11/pami13opq.pdf">paper</a> shows improved recall at fixed compression ratio versus standard PQ; the magnitude depends on dataset geometry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNHu4IiHxwp-0s9Yiu4OQQ.png" /></figure><h3>Scalar and Binary Quantisation</h3><p>PQ compresses by replacing whole groups of dimensions with codebook IDs. There is a simpler alternative that has become more common recently: keep all d dimensions, but store each one in fewer bits.</p><h4>Scalar Quantisation (SQ)</h4><p>Map each float32 component onto a smaller integer range. <a href="https://github.com/facebookresearch/faiss/wiki/Faiss-indexes">FAISS’s IndexScalarQuantizer</a> stores 8-bit codes at d bytes per vector, with 6-bit and 4-bit variants also implemented; an fp16 variant costs 2d bytes. At d = 768 that is 768 bytes instead of 3,072 — a 4× reduction, no codebook to train, and none of PQ’s divisibility constraints. It is the simplest method described here and often the first one worth trying.</p><h4>Binary Quantisation and RaBitQ</h4><p>The aggressive end of the spectrum: one bit per dimension. Distance computations collapse into bitwise operations, which modern CPUs execute extremely fast. Naive binarisation — just taking the sign of each component — loses too much signal. <a href="https://arxiv.org/abs/2405.12497"><strong>RaBitQ</strong> (Gao &amp; Long, SIGMOD 2024)</a> quantises a D-dimensional vector into a D-bit string while providing a sharp theoretical error bound, something the authors note PQ and its variants lack and which matters because those methods “are observed to fail disastrously on some real-world datasets.”</p><p><a href="https://github.com/facebookresearch/faiss/wiki/Faiss-indexes">FAISS now ships it</a>: 1 bit per dimension plus a small overhead, at (d / 8) + 8 bytes per vector, with multi-bit variants (RaBitQ2 through RaBitQ9) and a FastScan variant for higher throughput. It requires a random rotation preprocessing step for good accuracy. At d = 768 that is <strong>104 bytes per vector against 3,072</strong> — roughly 30× smaller. A 10M-vector corpus drops from about 31 GB to about 1 GB.</p><p><strong>Where this leaves PQ.</strong> PQ and OPQ remain the reference methods and are deeply embedded in IVF pipelines. But if you are choosing today and memory is the binding constraint, benchmark scalar and binary quantisation first — they are simpler to operate, and on the <a href="https://arxiv.org/abs/2405.12497">RaBitQ paper’s own evaluation</a> they beat PQ on the accuracy-efficiency trade-off by a clear margin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WS-5rlyIA2mpYxKT8crpbw.png" /></figure><h3>Hybrid Search — Dense + Sparse + Rerank</h3><p>Dense vector search captures semantic similarity. Sparse lexical search captures exact term matching. Neither alone is sufficient in production. The modern pattern — documented across Weaviate, Qdrant, Elasticsearch, and Pinecone — is a retrieval <em>stack</em>: dense + sparse retrieval fused together, then optionally reranked.</p><h4>Why Dense-Only Falls Short</h4><p>Embedding models generalise across synonyms and paraphrases — a strength for conceptual questions, a structural weakness for exact identifier queries. A search for a specific product code, license plate, or medical ID may semantically retrieve related documents while missing the exact record. BM25 handles this through direct term matching; dense retrieval has no equivalent.</p><h4>BM25</h4><p>BM25 is a classical term-frequency scoring function. It rewards documents where query terms appear frequently (with saturation — repeated terms don’t dominate indefinitely) and penalises long documents. Rare terms are weighted higher via IDF. For the full formula, see Robertson and Zaragoza (2009) or the <a href="https://en.wikipedia.org/wiki/Okapi_BM25">Wikipedia BM25 article</a>. The fundamental limitation: “car”, “automobile”, “vehicle” are unrelated tokens — zero semantic generalisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjzBp42DeNVSIgDG6chS3w.png" /></figure><h4>SPLADE — Learned Sparse Retrieval</h4><p><a href="https://arxiv.org/abs/2109.10086">SPLADE (Formal et al., 2021)</a> modernises the sparse side using a masked language model to produce sparse vocabulary-level vectors with implicit query expansion. A document about “cars” gets non-zero weight for “vehicle”, “automobile”, etc. The result preserves exact term matching and inverted-index efficiency while bridging the synonym gap BM25 cannot. The SPLADE v2 paper shows strong performance on retrieval benchmarks including BEIR.</p><h4>Fusion Strategies</h4><p><strong>Weighted combination</strong> — score the document as alpha × BM25 plus (1 minus alpha) × cosine similarity. Simple, but requires score normalisation since BM25 and cosine scores live on different scales. <a href="https://weaviate.io/developers/weaviate/search/hybrid">Weaviate exposes this</a> via an alpha parameter.</p><p><strong>Reciprocal Rank Fusion (RRF)</strong> — rank-based and scale-agnostic. For each document, take its rank in each result list it appears in, add a constant k to that rank, and take the reciprocal. Sum those reciprocals across all lists. Documents ranked highly in several lists accumulate the most score, and because only ranks are used, the raw scores never need normalising.</p><p>The constant k is conventionally 60, which comes from <a href="https://dl.acm.org/doi/10.1145/1571941.1572114">Cormack, Clarke &amp; Buettcher (2009)</a>, who found it worked well without tuning. It is a robust default, not an optimum for your data — a sensible starting point before adding a reranker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_V76NOzWZEIc4P6_j8ChBQ.png" /></figure><h4>Reranking</h4><p>Once fusion produces a top-n candidate set (typically 20–100 documents), a reranker rescores with a stronger relevance model:</p><p><strong>Cross-encoder</strong> — encodes the (query, document) pair jointly through a transformer, allowing full token-level interaction. Far more expressive than bi-encoder cosine similarity. Too slow to run over a full corpus; fast enough over 50–100 candidates.</p><p><a href="https://arxiv.org/abs/2004.12832"><strong>ColBERT</strong></a> — a late-interaction architecture (Khattab &amp; Zaharia, 2020) that encodes query and document independently into token-level representations, then scores via MaxSim: for each query token, find its highest-scoring match among the document’s token vectors, then sum those maxima across all query tokens.</p><p>Each query token matches its best document token. Document representations are precomputed offline — enabling scalable retrieval, not just reranking. ColBERT is architecturally distinct from RRF or weighted fusion: it is a late-interaction neural retrieval method, not a list-combination strategy (<a href="https://arxiv.org/abs/2004.12832">source</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Mrffc6tXpb7ynk89zKFHw.png" /></figure><h4>Metadata Filtering</h4><p>Many business constraints — access control, price range, geography, availability — cannot be expressed as embedding geometry. The important design point is that filtering must be applied <em>during</em> ANN traversal rather than as a post-processing step over an unfiltered top-k; otherwise recall collapses under highly selective filters, because the candidates the index returns may contain almost nothing that survives the filter. <a href="https://qdrant.tech/documentation/concepts/filtering/">Qdrant addresses this</a> with payload indexes and filter-aware graph traversal, and native filtered ANN is also available in Weaviate and Milvus. Create payload indexes on the fields you actually filter on — an unindexed payload field forces a full scan.</p><h3>From Theory to Azure AI Search</h3><p>A note before this section: I’m currently building on top of exactly these concepts in a personal project — manually driving RAG on Azure AI Search rather than letting an agent-attached tool or Azure Foundry manage it. The reason is control. Managed tools abstract away which index is queried, what fields are selected, and whether semantic reranking actually fired. By owning the retrieval layer yourself, you get observability, graceful fallback, dynamic field discovery, and real source URLs you can surface to users — none of which come through the managed abstraction. What follows is what that looks like in practice.</p><p>Azure AI Search implements the production hybrid stack from natively — HNSW for vectors, BM25 for keywords, RRF fusion (k = 60), and a <a href="https://learn.microsoft.com/en-us/azure/search/semantic-search-overview">deep-learning semantic ranker</a> that applies secondary ranking to the top 50 candidates. The Decision Guide’s “quality critical” path, out of the box. <strong>Dynamic introspection.</strong> Rather than hardcoding field names, inspect the index schema at runtime to discover which vector field, content fields, and semantic config exist — making the retriever work across any index shape:</p><pre>def _inspect_index(index_name, credential):<br>    index = SearchIndexClient(endpoint, credential).get_index(index_name)<br>    scalar_fields, vector_field = set(), None<br>    for f in index.fields:<br>        if str(f.type) in {&quot;Collection(Edm.Single)&quot;, &quot;Collection(Edm.Double)&quot;}:<br>            vector_field = vector_field or f.name<br>        else:<br>            scalar_fields.add(f.name)<br>    sem = getattr(index, &quot;semantic_search&quot;, None)<br>    configs = getattr(sem, &quot;configurations&quot;, None) if sem else None<br>    return scalar_fields, vector_field, configs[0].name if configs else None</pre><p><strong>Graceful fallback.</strong> Semantic reranking costs more per query and may not be configured on every index. This simplified example first attempts semantic hybrid search, then falls back to hybrid search without semantic ranking:</p><pre>def retrieve(index_name, query, top=5):<br>    _, vector_field, semantic_config = _inspect_index(index_name, credential)<br>    vq = [VectorizedQuery(embed(query), k_nearest_neighbors=top*2,<br>                          fields=vector_field)] if vector_field else []<br>    kwargs = dict(search_text=query, vector_queries=vq or None, top=top)<br>    if semantic_config:<br>        try:<br>            return client.search(**kwargs, query_type=QueryType.SEMANTIC,<br>                                 semantic_configuration_name=semantic_config)<br>        except Exception:<br>            pass<br>    return client.search(**kwargs)</pre><p><strong>Non-blocking concurrency.</strong> The SDK is synchronous. In an async backend, offload to the thread pool — each call creates its own SearchClient with no shared state between sessions:</p><pre>results = await asyncio.to_thread(retrieve, index_name, query)</pre><h3>Other Index Families Worth Knowing</h3><p>A note on scope: these families are new territory for me too — I encountered them while researching this piece and haven’t worked with them hands-on yet. I’m including them here as signposts for my own future learning and for anyone who wants to go deeper. The references below are the right starting point for each.</p><ul><li><strong>DiskANN / Vamana</strong> — <a href="https://proceedings.neurips.cc/paper/2019/hash/09853c7fb1d3f8ee67a61b6bf4a7f8e6-Abstract.html">graph-based ANN for SSD-resident corpora</a>, with competitive recall at billion scale. Reach for this when your corpus won’t fit in RAM but you still want graph-quality recall.</li><li><strong>ScaNN</strong> — <a href="https://arxiv.org/abs/1908.10396">anisotropic vector quantisation from Google</a> that accounts for directional compression asymmetry. Worth benchmarking if you’re on Google infrastructure or maximising inner-product recall.</li><li><strong>GPU ANN</strong> — FAISS ships GpuIndexIVFPQ and GpuIndexFlatL2 for GPU-accelerated search (<a href="https://arxiv.org/abs/1702.08734">Johnson, Douze &amp; Jégou, 2019</a>). A natural fit for high-throughput batch workloads where GPU memory covers the index.</li><li><strong>Matryoshka embeddings (MRL)</strong> — <a href="https://arxiv.org/abs/2205.13147">leading dimensions are independently useful</a>; a 1,536-d vector truncates cleanly to 256-d. The cheapest memory win available — composes with every compression method in §6.</li></ul><h3>Summary</h3><p>There is no best vector index. The choice follows from corpus size, memory budget, update pattern, and filtering requirements. The rest is measurement. Points worth restating:</p><ul><li>Flat is not only a baseline for small datasets. It is the ground truth required to compute recall, so it stays in the workflow permanently.</li><li>Constraints determine the index more often than benchmarks do. In the worked example, the update pattern and the permission filtering settled the choice, not latency.</li><li>Binary quantisation is the largest single memory lever available, and oversample-and-rescore recovers most of the accuracy it costs.</li><li>HNSW’s logarithmic complexity is reported empirically in the original paper, not proven as a worst-case bound. Several widely repeated figures shift slightly when checked against the source.</li></ul><p>This blog was written using my prior knowledge, supplemented by insights gained through generative AI tools for deep research, fact-checking, and improvements in tone and grammar. Thanks</p><h3>References</h3><h4>Clustering</h4><ol><li>Wikipedia. <em>K-Means Clustering</em>. <a href="https://en.wikipedia.org/wiki/K-means_clustering">https://en.wikipedia.org/wiki/K-means_clustering</a></li><li>Brenndoerfer, M. (2025). <em>K-Means Clustering: Complete Guide</em>. <a href="https://mbrenndoerfer.com/writing/kmeans-clustering-complete-guide">https://mbrenndoerfer.com/writing/kmeans-clustering-complete-guide</a></li><li>Upadhyay, A. (2025). <em>K-Means Clustering Explained: Geometric Intuition, Assumptions, Limitations, and Variations</em>. <a href="https://www.aryanupadhyay.com/post/k-means-clustering-explained-geometric-intuition-assumptions-limitations-and-variations">https://www.aryanupadhyay.com/post/k-means-clustering-explained-geometric-intuition-assumptions-limitations-and-variations</a></li><li>Analytics Vidhya. <em>K-Means Clustering Algorithm</em>. <a href="https://www.analyticsvidhya.com/blog/2019/08/comprehensive-guide-k-means-clustering/">https://www.analyticsvidhya.com/blog/2019/08/comprehensive-guide-k-means-clustering/</a></li><li>Pinecone. <em>Introduction to K-Means Clustering</em> (covers K-Means++ initialisation). <a href="https://www.pinecone.io/learn/k-means-clustering/">https://www.pinecone.io/learn/k-means-clustering/</a></li><li>Tate, A. (2023). <em>When To Choose Density-Based Methods</em> (compares k-means, hierarchical clustering, and DBSCAN). Hex. <a href="https://hex.tech/blog/comparing-density-based-methods/">https://hex.tech/blog/comparing-density-based-methods/</a></li></ol><h4>Curse of Dimensionality</h4><ol><li>Milvus. <em>Curse of Dimensionality and Vector Search</em>. <a href="https://milvus.io/ai-quick-reference/what-is-the-curse-of-dimensionality-and-how-does-it-affect-vector-search">https://milvus.io/ai-quick-reference/what-is-the-curse-of-dimensionality-and-how-does-it-affect-vector-search</a></li><li>Govindaraj, P. (2025). <em>Clustering in High-Dimensional Space</em>. Medium. <a href="https://medium.com/@govindarajpriyanthan/clustering-in-high-dimensional-space-building-and-evaluating-a-custom-k-means-algorithm-49802d63a6fc">https://medium.com/@govindarajpriyanthan/clustering-in-high-dimensional-space-building-and-evaluating-a-custom-k-means-algorithm-49802d63a6fc</a></li><li>Zilliz. <em>How Does the Curse of Dimensionality Influence Vector Search Indexing?</em> <a href="https://zilliz.com/ai-faq/how-does-the-concept-of-the-curse-of-dimensionality-influence-the-design-of-indexing-techniques-for-vector-search">https://zilliz.com/ai-faq/how-does-the-concept-of-the-curse-of-dimensionality-influence-the-design-of-indexing-techniques-for-vector-search</a></li><li>Lakshman, V., Munyampirwa, B., Shun, J., &amp; Coleman, B. (2025). <em>Breaking the Curse of Dimensionality: On the Stability of Modern Vector Retrieval</em>. arXiv:2512.12458. <a href="https://arxiv.org/abs/2512.12458">https://arxiv.org/abs/2512.12458</a></li></ol><h4>HNSW</h4><ol><li>Malkov, Y. &amp; Yashunin, D. (2016, rev. 2018). <em>Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs</em>. arXiv:1603.09320; published in IEEE TPAMI (2020). <strong>Primary source.</strong> <a href="https://arxiv.org/abs/1603.09320">https://arxiv.org/abs/1603.09320</a></li><li>Pinecone. <em>HNSW</em>. <a href="https://www.pinecone.io/learn/series/faiss/hnsw/">https://www.pinecone.io/learn/series/faiss/hnsw/</a></li><li>Zilliz. <em>Understanding HNSW</em>. <a href="https://zilliz.com/learn/hierarchical-navigable-small-worlds-HNSW">https://zilliz.com/learn/hierarchical-navigable-small-worlds-HNSW</a></li><li>Meilisearch. (2025). <em>What Are Vector Embeddings?</em> <a href="https://www.meilisearch.com/blog/what-are-vector-embeddings">https://www.meilisearch.com/blog/what-are-vector-embeddings</a></li><li>Fu, C. (2024). <em>A Visual Guide to HNSW</em>. <a href="https://cfu288.com/blog/2024-05_visual-guide-to-hnsw/">https://cfu288.com/blog/2024-05_visual-guide-to-hnsw/</a></li></ol><h4>IVF, PQ, OPQ &amp; FAISS</h4><ol><li>Ge, T. et al. (2013). <em>Optimized Product Quantization</em>. Microsoft Research. <strong>Primary source.</strong> <a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2013/11/pami13opq.pdf">https://www.microsoft.com/en-us/research/wp-content/uploads/2013/11/pami13opq.pdf</a></li><li>Jégou, H., Douze, M., &amp; Schmid, C. (2011). <em>Product Quantization for Nearest Neighbor Search</em>. IEEE TPAMI. <strong>Primary source.</strong> DOI: 10.1109/TPAMI.2010.57</li><li>Facebook Research. <em>Faiss Indexes Wiki</em> and <em>Guidelines to Choose an Index</em>. <strong>Primary source for memory formulas and parameter guidance.</strong> <a href="https://github.com/facebookresearch/faiss/wiki/Faiss-indexes">https://github.com/facebookresearch/faiss/wiki/Faiss-indexes</a></li><li>McCormick, C. (2017). <em>Product Quantizers for k-NN Tutorial</em>. <a href="https://mccormickml.com/2017/10/22/product-quantizer-tutorial-part-2/">https://mccormickml.com/2017/10/22/product-quantizer-tutorial-part-2/</a></li><li>Towards Data Science. <em>Product Quantization for Similarity Search</em>. <a href="https://towardsdatascience.com/product-quantization-for-similarity-search-2f1f67c5fddd/">https://towardsdatascience.com/product-quantization-for-similarity-search-2f1f67c5fddd/</a></li><li>IVF. <a href="https://www.velodb.io/glossary/inverted-file-index-in-vector-similarity-search">https://www.velodb.io/glossary/inverted-file-index-in-vector-similarity-search</a></li></ol><h4>KD-Tree &amp; Ball Tree</h4><ol><li>scikit-learn. <em>Nearest Neighbours User Guide</em>. <strong>Primary source for algorithm=’auto’ behaviour.</strong> <a href="https://scikit-learn.org/stable/modules/neighbors.html">https://scikit-learn.org/stable/modules/neighbors.html</a></li></ol><h4>Hybrid Search, SPLADE, ColBERT &amp; Reranking</h4><ol><li>Formal, T. et al. (2021). <em>SPLADE v2: Sparse Lexical and Expansion Model</em>. arXiv:2109.10086. <strong>Primary source.</strong> <a href="https://arxiv.org/abs/2109.10086">https://arxiv.org/abs/2109.10086</a></li><li>Khattab, O. &amp; Zaharia, M. (2020). <em>ColBERT: Efficient and Effective Passage Search</em>. arXiv:2004.12832. <strong>Primary source.</strong> <a href="https://arxiv.org/abs/2004.12832">https://arxiv.org/abs/2004.12832</a></li><li>Weaviate. <em>Hybrid Search Documentation</em>. <a href="https://weaviate.io/developers/weaviate/search/hybrid">https://weaviate.io/developers/weaviate/search/hybrid</a></li><li>Qdrant. <em>Payload Filtering Documentation</em>. <a href="https://qdrant.tech/documentation/concepts/filtering/">https://qdrant.tech/documentation/concepts/filtering/</a></li><li>Bronckers, P. <em>Better RAG Accuracy with Hybrid BM25 + Dense</em>. Medium. <a href="https://medium.com/@pbronck/better-rag-accuracy-with-hybrid-bm25-dense-vector-search-ea99d48cba93">https://medium.com/@pbronck/better-rag-accuracy-with-hybrid-bm25-dense-vector-search-ea99d48cba93</a></li><li>Superlinked. <em>Optimizing RAG with Hybrid Search &amp; Reranking</em>. <a href="https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking">https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking</a></li></ol><h4>Modern Index Families</h4><ol><li>Jayaram Subramanya, S. et al. (2019). <em>DiskANN: Fast Accurate Billion-point Nearest Neighbor Search on a Single Node</em>. NeurIPS. <a href="https://proceedings.neurips.cc/paper/2019/hash/09853c7fb1d3f8ee67a61b6bf4a7f8e6-Abstract.html">https://proceedings.neurips.cc/paper/2019/hash/09853c7fb1d3f8ee67a61b6bf4a7f8e6-Abstract.html</a></li><li>Guo, R. et al. (2020). <em>Accelerating Large-Scale Inference with Anisotropic Vector Quantization (ScaNN)</em>. ICML. <a href="https://arxiv.org/abs/1908.10396">https://arxiv.org/abs/1908.10396</a></li></ol><h4>General RAG &amp; Benchmarking</h4><ol><li>ANN-Benchmarks. <a href="https://ann-benchmarks.com/">https://ann-benchmarks.com</a></li><li>Charan, M. (2025). <em>Vector Index Types for RAG: In-Depth Analysis</em>. Medium. <a href="https://medium.com/@mohitcharan04/vector-index-types-for-rag-in-depth-analysis-29e28c189394">https://medium.com/@mohitcharan04/vector-index-types-for-rag-in-depth-analysis-29e28c189394</a></li><li>Liu, D. &amp; Yu, Y. (2025). <em>SPI: Query-Depth-Adaptive Indexing for Streaming RAG in Vector Databases</em>. arXiv:2511.16681. <a href="https://arxiv.org/abs/2511.16681">https://arxiv.org/abs/2511.16681</a></li><li>Scaling Vector Search: Flat vs HNSW vs HNSW+PQ. <a href="https://datashot.substack.com/p/scaling-vector-search-flat-vs-hnsw">https://datashot.substack.com/p/scaling-vector-search-flat-vs-hnsw</a></li></ol><h4>Quantisation &amp; Embedding Compression</h4><ol><li>Gao, J. &amp; Long, C. (2024). <em>RaBitQ: Quantizing High-Dimensional Vectors with a Theoretical Error Bound for Approximate Nearest Neighbor Search</em>. SIGMOD 2024. arXiv:2405.12497. <strong>Primary source.</strong> <a href="https://arxiv.org/abs/2405.12497">https://arxiv.org/abs/2405.12497</a></li><li>Kusupati, A. et al. (2022, rev. 2024). <em>Matryoshka Representation Learning</em>. NeurIPS 2022. arXiv:2205.13147. <strong>Primary source.</strong> <a href="https://arxiv.org/abs/2205.13147">https://arxiv.org/abs/2205.13147</a></li><li>Cormack, G., Clarke, C., &amp; Buettcher, S. (2009). <em>Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods</em>. SIGIR. <strong>Primary source for RRF and the k = 60 constant.</strong> <a href="https://dl.acm.org/doi/10.1145/1571941.1572114">https://dl.acm.org/doi/10.1145/1571941.1572114</a></li><li>Johnson, J., Douze, M., &amp; Jégou, H. (2019). <em>Billion-scale similarity search with GPUs</em>. IEEE Transactions on Big Data. <a href="https://arxiv.org/abs/1702.08734">https://arxiv.org/abs/1702.08734</a></li></ol><p>#RAG #VectorSearch #LLM #AIEngineering #MachineLearning #VectorDatabase #GenerativeAI #MLEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00d016ff3e43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resource Share: KL Divergence in LLMs]]></title>
            <link>https://medium.com/@gj979986/resource-share-kl-divergence-in-llms-6179a67766bb?source=rss-561251cc6836------2</link>
            <guid isPermaLink="false">https://medium.com/p/6179a67766bb</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Gaurav Jain]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 05:47:14 GMT</pubDate>
            <atom:updated>2026-07-09T05:48:13.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*VkTeuvV4qELoUpWLlAxj5g.jpeg" /></figure><p>I Came across this article by Kuriko Iwai on KL divergence in the context of LLM fine-tuning and thought it was worth sharing with the community. This article covers KL divergence specifically in the context of LLM fine-tuning. Well worth the read if you are working on RLHF pipelines, SFT, or just want to understand why this term keeps appearing in training objectives.</p><p>Link: <a href="https://kuriko-iwai.com/research/kullback-leibler-divergence-for-llms">https://kuriko-iwai.com/research/kullback-leibler-divergence-for-llms</a></p><p>Here is a breakdown of what the article covers, for those who want the gist before opening it.</p><h3>The Problem It Solves: Policy Collapse</h3><p>When you fine-tune a language model on a narrow task without any constraint, the model will over-optimize. It learns the task, and in doing so, collapses its output distribution to near-deterministic confidence — assigning 99.8% probability to a single output and effectively killing all other possibilities. The model has forgotten the broader distribution it started from. This is policy collapse, and it is not an edge case. It can happen when optimization is left unconstrained. KL divergence is one of the primary regularization techniques used to mitigate it.</p><h3>Quick Probability Primer — Needed for This</h3><h3>Probability Distributions</h3><p>A probability distribution describes how likely different outcomes are. Two types matter here.</p><p>For discrete outputs — like sentiment labels (positive, negative, neutral) or token IDs in a vocabulary — each outcome gets a probability via a <strong>Probability Mass Function (PMF)</strong>. P(x) gives the exact probability assigned to outcome x. The probabilities must be non-negative and must sum to exactly 1 across all outcomes. Nothing leaks, nothing is missing.</p><p>For continuous outcomes, we use a <strong>Probability Density Function (PDF)</strong>. A single point x has probability zero. What matters is the integral over a range: to ask “what is the probability that x falls between a and b?” you integrate the PDF over [a, b].</p><p>The distinction matters because KL divergence has different forms for each: a sum for discrete distributions, an integral for continuous ones. Both compute the same conceptual thing — the expected log-ratio between two distributions — just over different mathematical domains.</p><p>Interactive visual reference: <a href="https://seeing-theory.brown.edu/probability-distributions/index.html">Seeing Theory — Brown University</a>. The animated PMF and PDF sections make the difference immediately intuitive.</p><p>Formal definitions: <a href="https://en.wikipedia.org/wiki/Probability_mass_function">Probability Mass Function — Wikipedia</a>, <a href="https://en.wikipedia.org/wiki/Probability_density_function">Probability Density Function — Wikipedia</a>.</p><h3>Expected Value</h3><p>The expected value E[f(x)] is the probability-weighted average of some function f(x) over all outcomes:</p><pre>E[f(x)] = Σ P(x) · f(x)     (discrete)<br>E[f(x)] = ∫ p(x) · f(x) dx  (continuous)</pre><p>Outcomes that are more likely under P contribute more to the average. Outcomes that are rare contribute less. This is not just a statistical formality — KL divergence is itself an expected value. When you see the KL formula, you are looking at E_P[log(P(x)/Q(x))]: the expectation of the log-ratio, taken under distribution P. Every part of KL divergence flows from this.</p><h3>Shannon Entropy</h3><p>Entropy is what KL divergence builds on. Shannon entropy H(P) measures the average uncertainty — or information content — in a distribution:</p><pre>H(P) = − Σ P(x) · log P(x)</pre><p>A uniform distribution over many outcomes has high entropy — everything is equally uncertain. A distribution collapsed onto one outcome has zero entropy — there is nothing to be surprised by. The log base determines the unit: base 2 gives bits, natural log gives nats. The choice does not change the concept.</p><p>Entropy is the theoretical minimum description length for events drawn from P. It is the baseline against which KL divergence measures the excess cost of using the wrong distribution.</p><p>Best resource for this: <a href="https://colah.github.io/posts/2015-09-Visual-Information/">Visual Information Theory — Chris Olah</a>. Builds from entropy through cross-entropy to KL divergence with clean visual intuition and no hand-waving.</p><p>Primary source: <a href="https://people.math.harvard.edu/~ctm/home/text/others/shannon/entropy/entropy.pdf">A Mathematical Theory of Communication — Shannon, 1948 (PDF)</a>. Formal reference: <a href="https://en.wikipedia.org/wiki/Entropy_(information_theory)">Entropy (information theory) — Wikipedia</a>.</p><h3>Cross-Entropy</h3><p>Cross-entropy H(P, Q) measures the average number of bits needed to encode events drawn from P using a code optimized for Q:</p><pre>H(P, Q) = − Σ P(x) · log Q(x)</pre><p>When Q is a perfect model of P, cross-entropy equals entropy — no excess cost. When Q is a poor model, cross-entropy is higher. The gap between them is exactly KL divergence:</p><pre>D_KL(P ‖ Q) = H(P, Q) − H(P)</pre><p>KL divergence is the excess encoding cost that comes from using the wrong distribution. This also explains why minimizing cross-entropy loss in classification is equivalent to minimizing KL divergence — the entropy term H(P) is fixed during training, so minimizing H(P, Q) and minimizing D_KL(P ‖ Q) are the same operation. Standard classification training is already implicit KL minimization.</p><p>Reference: <a href="https://en.wikipedia.org/wiki/Cross-entropy">Cross-entropy — Wikipedia</a>.</p><h3>The Log-Ratio</h3><p>The term log(P(x)/Q(x)) is the core quantity inside KL divergence. It asks: how surprised would Q be by events that P considers likely?</p><ul><li>If P(x) = Q(x): log(1) = 0. No surprise. Q has this exactly right.</li><li>If P(x) &gt;&gt; Q(x): the ratio is large, the log is large, the penalty is large. Q is underestimating a likely event.</li><li>If Q(x) = 0 and P(x) &gt; 0: the ratio goes to infinity. Q is completely blind to an event P considers possible. The penalty is infinite.</li></ul><p>That last case is why KL divergence has no upper bound — and why policy collapse is so damaging. The collapsed model assigns zero probability to outputs the reference model considered possible, and the KL penalty reflects that catastrophically.</p><h3>What KL Divergence Is</h3><p>KL divergence measures the information lost when an approximating distribution Q is used to model a true distribution P. Discrete form:</p><pre>D_KL(P ‖ Q) = Σ P(x) · log( P(x) / Q(x) )</pre><p>For continuous distributions, the sum becomes an integral over x. In both cases, you are computing the expectation of the log-ratio, weighted by P.</p><p>Four properties define its behavior:</p><p><strong>Always non-negative.</strong> D_KL(P ‖ Q) ∈ [0, +∞). This follows from Jensen’s inequality applied to the convex function −log(x). Reference: <a href="https://en.wikipedia.org/wiki/Jensen%27s_inequality">Jensen’s Inequality — Wikipedia</a>.</p><p><strong>Zero if and only if P = Q.</strong> When P(x) = Q(x) everywhere, log(P(x)/Q(x)) = log(1) = 0. Total divergence collapses to zero.</p><p><strong>No upper bound.</strong> If Q(x) = 0 for any x where P(x) &gt; 0, the log term goes to infinity. There is no soft penalty for blind spots.</p><p><strong>Asymmetric.</strong> D(P ‖ Q) ≠ D(Q ‖ P). KL divergence is not a distance metric in the formal sense — it violates both symmetry and the triangle inequality. This asymmetry is a structural property that creates two meaningfully different modes of regularization.</p><p>Comprehensive reference: <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">Kullback-Leibler Divergence — Wikipedia</a>.</p><h3>Forward vs. Reverse KL — The Asymmetry That Matters</h3><p><strong>Forward KL: D(P ‖ Q)</strong></p><p>Weighted by P. Minimizing this forces Q to cover all regions where P has mass. Result: Q spreads across all modes of P, even at the cost of being diffuse and uncertain. This is often described as mode-covering behavior.</p><p><strong>Reverse KL: D(Q ‖ P)</strong></p><p>Weighted by Q. The penalty fires when Q places mass where P has very little. Result: Q latches onto one mode and commits to it sharply. This is called <strong>mode-seeking</strong> behavior.</p><p>Concrete case: if P is bimodal — two valid output classes — forward KL makes Q hedge across both. Reverse KL makes Q pick one and collapse onto it with confidence.</p><p>These are not interchangeable. They produce structurally different distributions, and the choice has real consequences in fine-tuning pipelines. Reference: <a href="http://blog.evjang.com/2016/08/variational-bayes.html">Eric Jang — A Beginner’s Guide to Variational Methods</a>.</p><h3>In SFT and RLHF Objectives</h3><p><strong>SFT Regularization</strong></p><p>When fine-tuning on a narrow task, the model drifts from the base model’s general distribution. Adding a KL penalty constrains that drift:</p><pre>L = L_Task + β · D_KL(Q ‖ P)</pre><p>Where Q is the fine-tuned model, P is the reference model, and β controls penalty strength. High β: KL dominates, general knowledge is preserved. Low β: task loss dominates, the model adapts freely but risks collapse.</p><p><strong>RLHF Regularization</strong></p><p>In RLHF, the model maximizes a reward signal derived from human preferences. Without a constraint, it exploits the reward function — finding degenerate high-reward outputs that no longer resemble coherent language. The objective:</p><pre>L(θ) = L_Reward − β · D_KL(π_θ ‖ π_ref)</pre><p>You are maximizing reward while subtracting a penalty for diverging from the reference SFT model. The KL term functions as a trust region — limiting how aggressively each update can move. This is in the training objective of InstructGPT and has become a standard component of many modern RLHF implementations. The lineage of RLHF for language models traces through: <a href="https://arxiv.org/abs/1909.08593">Fine-Tuning Language Models from Human Preferences — Ziegler et al., 2019 — arXiv:1909.08593</a> and <a href="https://arxiv.org/abs/2009.01325">Learning to Summarize with Human Feedback — Stiennon et al., 2020 — arXiv:2009.01325</a>.</p><p><strong>DPO — Implicit KL Without an RL Loop</strong></p><p>Direct Preference Optimization (Rafailov et al., 2023) reformulates the same objective. It derives a closed-form supervised loss directly from the optimal policy under the KL-constrained RLHF problem, eliminating the need for an explicit reward model or a PPO training loop. The KL regularization is mathematically preserved — it is embedded inside the loss function rather than computed as a separate penalty at runtime. DPO has become a widely used alternative for preference alignment because it is simpler to implement and more stable to train. Reference: <a href="https://arxiv.org/abs/2305.18290">Direct Preference Optimization — Rafailov et al., 2023 — arXiv:2305.18290</a>.</p><h3>The Experiment</h3><p>The article fine-tunes BERT on 3-label sentiment classification under three conditions: pure SFT, SFT + forward KL, SFT + reverse KL — each tested across β ∈ {0.1, 0.3, 0.5, 0.7, 0.9}.</p><p><strong>Pure SFT</strong>: Positive receives 99.8% probability. The other two labels are functionally dead. Classic policy collapse.</p><p><strong>Forward KL</strong>: Distribution smooths out. Positive confidence drops, other labels receive meaningful mass. Output stays closer to the reference distribution.</p><p><strong>Reverse KL</strong>: Also prevents collapse, but produces a sharper distribution than forward KL. Positive stays higher, other labels receive less mass. Consistent with mode-seeking behavior.</p><p>Loss curves confirm the tradeoff: low β → lower task loss, more deviation from reference. High β → higher task loss, stronger regularization. The β coefficient is the explicit dial between stability and specialization.</p><h3>Where This Sits in the Broader Picture</h3><p>KL divergence belongs to two overlapping mathematical families. It is a special case of <strong>Csiszár f-divergence</strong> — forward KL uses f(x) = −log(x), reverse KL uses f(x) = x log(x). It is also a <strong>Bregman divergence</strong>, with forward KL using negative entropy as the generator function.</p><p>It appears in variational inference as the gap between an approximating distribution Q and the true posterior P in the ELBO (Evidence Lower Bound) — the foundation of VAEs: <a href="https://arxiv.org/abs/1312.6114">Auto-Encoding Variational Bayes — Kingma &amp; Welling, 2013 — arXiv:1312.6114</a>. And minimizing forward KL with a fixed target P is mathematically equivalent to minimizing cross-entropy loss. Most practitioners are already working with this concept without calling it that.</p><p>As a Bregman divergence, KL has additional geometric properties that connect it to exponential families and mirror descent: <a href="https://en.wikipedia.org/wiki/Bregman_divergence">Bregman Divergence — Wikipedia</a>.</p><h3>References</h3><ul><li>Original article: <a href="https://kuriko-iwai.com/research/kullback-leibler-divergence-for-llms">KL Divergence in LLMs — Kuriko Iwai</a></li><li>Probability distributions (visual, interactive): <a href="https://seeing-theory.brown.edu/probability-distributions/index.html">Seeing Theory — Brown University</a></li><li>Entropy, cross-entropy, KL divergence (visual): <a href="https://colah.github.io/posts/2015-09-Visual-Information/">Visual Information Theory — Chris Olah</a></li><li>InstructGPT paper — RLHF with KL penalty: <a href="https://arxiv.org/abs/2203.02155">Ouyang et al., 2022 — arXiv:2203.02155</a></li><li>KL divergence in variational inference: <a href="https://arxiv.org/abs/1601.00670">Blei et al. — arXiv:1601.00670</a></li><li>Jensen’s inequality (non-negativity proof): <a href="https://en.wikipedia.org/wiki/Jensen%27s_inequality">Wikipedia — Jensen’s Inequality</a></li><li>Forward vs. reverse KL behavior: <a href="http://blog.evjang.com/2016/08/variational-bayes.html">Eric Jang — A Beginner’s Guide to Variational Methods</a></li><li>Csiszár f-divergence: <a href="https://en.wikipedia.org/wiki/F-divergence">Wikipedia — f-divergence</a></li><li>KL divergence (comprehensive): <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">Wikipedia — Kullback-Leibler Divergence</a></li><li>Bregman divergence: <a href="https://en.wikipedia.org/wiki/Bregman_divergence">Wikipedia — Bregman Divergence</a></li><li>Probability mass function: <a href="https://en.wikipedia.org/wiki/Probability_mass_function">Wikipedia — PMF</a></li><li>Probability density function: <a href="https://en.wikipedia.org/wiki/Probability_density_function">Wikipedia — PDF</a></li><li>Entropy (information theory): <a href="https://en.wikipedia.org/wiki/Entropy_(information_theory)">Wikipedia — Entropy</a></li><li>Cross-entropy: <a href="https://en.wikipedia.org/wiki/Cross-entropy">Wikipedia — Cross-entropy</a></li><li>Shannon’s original paper: <a href="https://people.math.harvard.edu/~ctm/home/text/others/shannon/entropy/entropy.pdf">A Mathematical Theory of Communication — Shannon, 1948 (PDF)</a></li><li>Original RLHF for NLP: <a href="https://arxiv.org/abs/1909.08593">Fine-Tuning Language Models from Human Preferences — Ziegler et al., 2019 — arXiv:1909.08593</a></li><li>Learning to summarize with RLHF: <a href="https://arxiv.org/abs/2009.01325">Learning to Summarize with Human Feedback — Stiennon et al., 2020 — arXiv:2009.01325</a></li><li>Direct Preference Optimization (DPO): <a href="https://arxiv.org/abs/2305.18290">Rafailov et al., 2023 — arXiv:2305.18290</a></li><li>Auto-Encoding Variational Bayes (VAE): <a href="https://arxiv.org/abs/1312.6114">Kingma &amp; Welling, 2013 — arXiv:1312.6114</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6179a67766bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Module Objects Are Cached Per Process — and Why That Matters for AI Backends]]></title>
            <link>https://medium.com/@gj979986/python-module-objects-are-cached-per-process-and-why-that-matters-for-ai-backends-c5bb68139d47?source=rss-561251cc6836------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5bb68139d47</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gaurav Jain]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 14:09:16 GMT</pubDate>
            <atom:updated>2026-07-08T00:36:16.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LH19XtjfHW2MPH1J_fsvMA.png" /></figure><p><em>A lesson from building a multi-user agentic AI system on Azure AI Foundry.</em></p><blockquote><strong><em>What I learned</em></strong><em> — While building a FastAPI + Azure AI Foundry backend, I ran into a subtle state-management bug that only showed up under concurrent users. Tracing it back led me down the rabbit hole of how Python’s import system actually works, how Gunicorn worker processes isolate memory, and what still needs external storage when you scale out. Writing this down in case it saves someone else the debugging time.</em></blockquote><h3>The Starting Point — PoC / Single-User Setup</h3><p>When building a proof of concept or a single-user system, the simplest approach is to define a module-level class instance — a global object that holds all the state your application needs. It is clean, easy to reason about, and works perfectly in development:</p><pre># services/ux_agent.py<br>class GeneralUserFacingUXAgent:<br>    def __init__(self):<br>        self.synthesizerOutput = None   # evaluation result<br>        self.chatSearchIndex = None     # Azure AI Search index<br>        self.session = None             # Foundry conversation thread<br><br>generalUserFacingUXAgent = GeneralUserFacingUXAgent()  # module-level instance</pre><p>This pattern is common and reasonable during early development. Any file in the codebase can import and use the same object:</p><pre>from services.ux_agent import generalUserFacingUXAgent<br>generalUserFacingUXAgent.synthesizerOutput = &quot;User&#39;s evaluation report&quot;</pre><p>The behaviour that makes this work — and also the behaviour that eventually bites you when you scale to multiple users — is how Python’s import system caches module objects.</p><p>The core issue, stated plainly: <strong>a Gunicorn worker is a single Python process, and all requests it handles run inside that same process.</strong> That means every concurrent user hitting the same worker shares the same module-level objects — the same dict, the same class instance, the same state.</p><h3>What Actually Happens When You import</h3><p>On a normal first import, Python creates and initialises the module object, stores it in a built-in dictionary called sys.modules, and subsequent imports of the same module name reuse that cached object. From the <a href="https://docs.python.org/3/reference/import.html#the-module-cache">Python documentation</a>:</p><blockquote>“The first place checked during import search is sys.modules. This mapping serves as a cache of all modules that have been previously imported.&quot;</blockquote><p>Precisely: the cache key is the <strong>fully qualified module name</strong> within a given interpreter/process. Importing the same file under two different names can produce two separate module objects. For typical FastAPI backends this edge case rarely appears intentionally, but it can happen through path or import misconfiguration.</p><p>The sequence on a normal first import:</p><ol><li>Python reads and executes ux_agent.py top-to-bottom</li><li>The resulting module object — including all variables and class instances defined at module level — is stored in sys.modules[&quot;services.ux_agent&quot;]</li><li>Every subsequent import of the same module name <strong>returns the cached object</strong> — the file is never re-executed</li></ol><pre># router_a.py<br>from services.ux_agent import generalUserFacingUXAgent<br># Python executes ux_agent.py, caches in sys.modules<br># router_b.py<br>from services.ux_agent import generalUserFacingUXAgent<br># Python returns sys.modules[&quot;services.ux_agent&quot;] - same object, no re-execution</pre><p>Any module-level variable or instance is therefore <strong>shared across every request handled by that process</strong>. That object defined at the bottom of the file? Truly process-global.</p><h3>Gunicorn, Workers, and Memory Isolation</h3><p>When deploying a FastAPI app with Gunicorn as the process manager:</p><pre>Gunicorn master (PID 100)  ← arbiter / pre-fork manager<br>    ├── Worker 1 (PID 101) — its own sys.modules cache<br>    ├── Worker 2 (PID 102) — its own sys.modules cache<br>    └── Worker 3 (PID 103) — its own sys.modules cache</pre><p>Gunicorn uses a <strong>pre-fork model</strong>: the master process (arbiter) spawns worker processes, each of which handles requests independently with fully isolated memory. Module-level state is scoped to each worker process — it is not shared across workers. Practically:</p><ul><li>3 workers = 3 independent module-level states</li><li>State written in Worker 1 is invisible to Worker 2</li><li>WebSocket continuity across reconnects, worker restarts, or routing changes requires either connection affinity/sticky routing or externally stored state.</li></ul><p><strong>On </strong><strong>--preload</strong>: Gunicorn&#39;s --preload option loads application code before forking workers. The OS may share memory pages via copy-on-write after the fork, which can reduce initial memory usage. However, once a worker mutates a Python object, that mutation is private to that worker — --preload does not create a shared cross-worker mutable store.</p><p><strong>On threaded workers</strong>: If you use --worker-class gthread, Gunicorn creates a thread pool inside each worker process. Threads inside the same worker share that worker&#39;s module-level state. Use asyncio.Lock when concurrency is within a single event loop; use threading.Lock or another thread-safe structure when multiple OS threads can mutate the same registry.</p><h3>@lru_cache — Function-Level Memoisation</h3><p>functools.lru_cache is a decorator that memoises function return values. From the <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache">official docs</a>:</p><blockquote>“Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.”</blockquote><p>A practical example: caching a Microsoft Graph API call that resolves SharePoint site and drive IDs — values that never change within a deployment:</p><pre>from functools import lru_cache<br>@lru_cache(maxsize=1)<br>def _resolve_site_and_drive() -&gt; tuple[str, str]:<br>    # HTTP call to Graph API - expensive, result is static<br>    site_id = ...<br>    drive_id = ...<br>    return site_id, drive_id</pre><p>maxsize=1 works here because the function takes no arguments — there is exactly one cache key. For a function that takes arguments, maxsize=1 would cache only the most recent argument combination, not &quot;one global result&quot;.</p><p>Key properties:</p><ul><li><strong>Scope</strong>: per-process, per-function — same lifetime as the module itself</li><li><strong>Eviction</strong>: LRU when maxsize is reached; maxsize=None for unbounded</li><li><strong>Clearable</strong>: call _resolve_site_and_drive.cache_clear() to invalidate</li><li><strong>Thread safety</strong>: the cache data structure remains coherent across threads, but lru_cache is not a &quot;single-flight&quot; mechanism — if two threads both call a cold function before the first result is cached, both may execute it. For exactly-once initialisation, add an explicit lock.</li><li><strong>Avoid for</strong>: user/session state, functions with side effects, or functions that must return different values over time</li></ul><h3>Scaling to Multiple Users: Per-User Registry</h3><p>When a system moves beyond single-user, module-level state needs to be keyed per user rather than shared globally. One approach: a registry dict at module level, keyed by a stable identifier.</p><pre>import time<br>_agent_registry: dict[str, &quot;GeneralUserFacingUXAgent&quot;] = {}<br>_last_active:    dict[str, float]                       = {}<br>TTL_SECONDS = 3600  # 1 hour idle → cleanup<br>def get_ux_agent(user_id: str) -&gt; &quot;GeneralUserFacingUXAgent&quot;:<br>    _last_active[user_id] = time.time()<br>    if user_id not in _agent_registry:<br>        _agent_registry[user_id] = GeneralUserFacingUXAgent()<br>    return _agent_registry[user_id]<br>async def release_ux_agent(user_id: str) -&gt; None:<br>    # Remove from registry before cleanup so new lookups don&#39;t receive<br>    # an agent that is being torn down.<br>    # In production, guard registry mutation with a lock if concurrent<br>    # lookup/release is possible.<br>    agent = _agent_registry.pop(user_id, None)<br>    _last_active.pop(user_id, None)<br>    if agent:<br>        await agent.cleanup()<br>async def evict_idle_agents() -&gt; None:<br>    now = time.time()<br>    # Collect expired keys first - do not mutate dict while iterating<br>    expired = [uid for uid, ts in _last_active.items() if now - ts &gt; TTL_SECONDS]<br>    for uid in expired:<br>        await release_ux_agent(uid)</pre><p><strong>On the choice of key</strong>: the examples above use user_id. In practice this could be email for simplicity, but in enterprise systems email can change due to renames or domain migrations. An immutable identity claim such as Azure AD object ID / user OID is a safer production key.</p><blockquote><em>The example above keeps the code intentionally small. Production code should also guard </em><em>get_ux_agent, </em><em>release_ux_agent, and eviction with the same lifecycle lock if concurrent access is possible.</em></blockquote><p><strong>Important scope caveat</strong>: this registry is <strong>per worker process</strong>, not deployment-wide. With multiple Gunicorn workers, the same user can end up with a different in-memory agent depending on which worker handles their request. For reliable multi-user continuity across workers, durable state (Foundry thread/session IDs, workflow outputs, search index preferences) should be stored externally — e.g. Azure Table Storage, Cosmos DB, or Redis — and used to re-hydrate the in-memory runtime object on lookup. Short-lived runtime objects (WebSocket handle, current in-flight task) remain in memory and are recreated on reconnect.</p><p>The same principle applies above Gunicorn too: each container, App Service instance, or Kubernetes pod has its own process memory.</p><h3>Layer 2 — Horizontal Scaling and Durable State</h3><p>The per-user registry solves <strong>cross-user contamination within a single worker</strong>. That is Layer 1, and it covers the most common real-world scenario: a PoC, an internal tool, or an early-stage backend running on one instance.</p><p>Layer 2 is a separate, harder problem: <strong>what happens when the same user reconnects to a different worker, or the worker restarts?</strong></p><pre>Layer 1 (what the registry solves):<br>  User A and User B on the SAME worker<br>  → per-user dict keeps their state isolated <br><br>Layer 2 (what external storage solves):<br>  User A reconnects after Worker 1 restarts → lands on Worker 2<br>  → new worker has no entry for User A in its registry<br>  → conversation context, session ID, search index - all gone </pre><p>Layer 2 does not invalidate Layer 1. Both need to be solved to scale properly. The good news is they are solved at different points in the system.</p><h3>The Foundry architecture can partially help here</h3><p>For AI backends using service-side Azure AI Foundry threads/sessions, there is a useful state boundary: the durable conversation identifier can live outside your Python process.</p><p>If a worker restarts, the local Python object pointing to that conversation is gone. But if you persisted the service-side session/thread ID, a new worker can recreate the lightweight runtime object and reattach to the existing conversation. The recovery path becomes:</p><pre># On reconnect, re-hydrate the agent from stored session ID<br>agent = get_ux_agent(user_id)<br>if not agent.agentClient:<br>    await initialize_ux_agent(agent)<br>stored_session_id = await fetch_session_id_from_db(user_id)<br>if stored_session_id:<br>    agent.session = restore_session(stored_session_id)</pre><p>The important design rule: <strong>do not rely on the Python object itself as the source of truth</strong>. Persist the durable identifier, then rebuild the runtime handle when needed.</p><h3>Practical recommendation</h3><p>For a production multi-worker or containerised deployment, store these three things externally per user:</p><ol><li><strong>Foundry conversation/session ID</strong> — so it can be re-attached on any worker</li><li><strong>Workflow run ID + report URLs</strong> — so the user can see their results after reconnect</li><li><strong>Search index reference/preference</strong> (chatSearchIndex) — small metadata that can be persisted and validated on reconnect</li></ol><p>Everything else — client objects, credential/token handles, in-flight task handles, streaming buffers — is ephemeral and should be recreated. The per-user registry remains the right in-process pattern; it just becomes a cache backed by durable storage rather than the source of truth.</p><p><strong>The key insight</strong>: module-level state is not application-global — it is <strong>process-global</strong>. In a single-user PoC, that is elegant. In a multi-user backend, it can leak state between users within the same worker, and diverge or disappear across workers. Use module-level globals only for process-local caches or registries whose limitations are intentional. Store durable, cross-worker user and session state externally.</p><p><em>Note: This is based on real implementation lessons from building a production AI backend. AI assistance was used only for polishing structure and wording.</em></p><p><em>If you’re building Python AI backends with FastAPI, Gunicorn, WebSockets, or agent sessions — this is one of those small runtime details that can quietly become a production state-management bug. Would love corrections, counter-examples, or your own patterns for handling this.</em></p><h3>References</h3><ul><li><a href="https://docs.python.org/3/reference/import.html#the-module-cache">Python Import System — The Module Cache (</a><a href="https://docs.python.org/3/reference/import.html#the-module-cache">sys.modules)</a> — Official Python language reference</li><li><a href="https://docs.python.org/3/library/functools.html#functools.lru_cache">functools.lru_cache — Python Standard Library</a> — Official docs including thread-safety notes</li><li><a href="https://gunicorn.org/design/">Gunicorn Design — Server Model</a> — Pre-fork worker model, arbiter/worker architecture</li><li><a href="https://docs.gunicorn.org/en/stable/settings.html#preload-app">Gunicorn Settings — </a><a href="https://docs.gunicorn.org/en/stable/settings.html#preload-app">preload_app / </a><a href="https://docs.gunicorn.org/en/stable/settings.html#preload-app">--preload</a> — Loads application code before worker processes are forked; copy-on-write can share pages until mutation</li><li><a href="https://fastapi.tiangolo.com/async/">FastAPI — Async / Concurrency</a> — How FastAPI handles async workers and event loops</li><li><a href="https://docs.python.org/3/library/asyncio-sync.html#asyncio.Lock">asyncio.Lock — Python Standard Library</a> — Async-safe mutual exclusion within a single event loop</li><li><a href="https://docs.python.org/3/library/threading.html#threading.Lock">threading.Lock — Python Standard Library</a> — Thread-safe mutual exclusion for OS-level threads</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5bb68139d47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Did You Know a Word Document is Just XML ? Here’s How You Can Auto-Fill Templates from Responses]]></title>
            <link>https://medium.com/@gj979986/did-you-know-a-word-document-is-just-xml-heres-how-you-can-auto-fill-templates-from-responses-518eaee38535?source=rss-561251cc6836------2</link>
            <guid isPermaLink="false">https://medium.com/p/518eaee38535</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gaurav Jain]]></dc:creator>
            <pubDate>Wed, 27 May 2026 08:56:26 GMT</pubDate>
            <atom:updated>2026-07-08T00:35:10.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mxsar4dlGSKfQ2yDQIvScA.png" /></figure><h3>Did You Know a Word Document Is Just XML? Here’s How You Can Auto-Fill Templates Using AI Agent Responses | Random Explorations</h3><p>Hey everyone 👋 here’s a concept worth knowing if you’re building anything that touches document generation with AI.</p><h3>Word Documents Are ZIP Files Full of XML</h3><p>A .docx file is not a binary blob. Rename one to .zip, open it, and you&#39;ll find a folder structure. The actual document content lives in word/document.xml. Every paragraph, every table cell, every run of bold text — it&#39;s all XML.</p><pre>mydoc.docx (ZIP)  <br>├── word/  <br>│    ├── document.xml   ← the document body  <br>│    ├── styles.xml     ← fonts, heading styles  <br>│    └── numbering.xml  ← bullet/list definitions  <br>└── [Content_Types].xml</pre><p>For Example - The XML Content of One of the Word files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*2qP4Y0C55D76uKxWS08HtA.png" /></figure><p>This means you can manipulate a Word document entirely in code, no Word installation needed, by unzipping it, editing the XML, and rezipping. Libraries like Python’s lxml make this straightforward.</p><h3>The XML Tag Hierarchy</h3><p>Everything in document.xml follows a strict parent-child hierarchy using the w: namespace (OOXML — Office Open XML standard):</p><pre>w:body                 ← document root  <br>└── w:tbl              ← table  <br>      └── w:tr         ← table row  <br>           └── w:tc    ← table cell  <br>                └── w:p  ← paragraph  <br>                     └── w:r  ← run (a styled span of text)  <br>                          └── w:t  ← the actual text</pre><p>Understanding this tree is everything. When you want to insert a new row, you find the parent w:tbl, locate the right w:tr child, and insert sibling w:tr elements. When you want to change text, you find the w:t element and set its .text property. The parent-child relationship dictates where things appear in the rendered document.</p><h3>Content Controls — Named Placeholders in Word</h3><p>Word has a built-in feature called <strong>Structured Document Tags (SDTs)</strong> — named fields you can drop into any .docx template. In XML they look like this:</p><pre>&lt;w:sdt&gt;  <br>&lt;w:sdtPr&gt;  <br>&lt;w:tag w:val=&quot;ProblemStatement&quot;/&gt;   ← the field name  <br>&lt;/w:sdtPr&gt;  <br>&lt;w:sdtContent&gt;  <br>&lt;w:p&gt;&lt;w:r&gt;&lt;w:t&gt;placeholder&lt;/w:t&gt;&lt;/w:r&gt;&lt;/w:p&gt;  <br>&lt;/w:sdtContent&gt;  <br>&lt;/w:sdt&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*svucD_KzE3CZhz_iV0d21Q.png" /></figure><p>The w:tag is the machine-readable name. The w:sdtContent is what Word renders. A template author creates these in Word&#39;s Developer tab. Your code then matches w:tag values against any data source — an AI agent&#39;s JSON response, a database, a form — and writes values into w:sdtContent.</p><p><strong>This gives you a clean contract</strong>: the template owner manages layout and branding; the data source (AI or otherwise) manages content. Neither needs to know about the other.</p><p><strong>Extracting Content Controls from a Word Template</strong>: Before you can fill a template, you may want to list all its placeholders (content controls). Here’s a Python Based Sample Code to scan a .docx (given Content Controls are added) and extract all SDT field names:</p><pre>from typing import Dict<br>import zipfile<br>from lxml import etree<br>from lxml.etree import QName<br><br>def extract_content_controls_from_docx(file_path) -&gt; Dict[str, str]:<br>    content_controls = []<br>    found_any = False<br>    try:<br>        with zipfile.ZipFile(file_path, &#39;r&#39;) as docx:<br>            for part in docx.namelist():<br>                if not (part.startswith(&#39;word/&#39;) and part.endswith(&#39;.xml&#39;)):<br>                    continue<br>                xml_content = docx.read(part)<br>                tree = etree.XML(xml_content)<br>                sdt_elements = tree.xpath(&quot;//*[local-name() = &#39;sdt&#39;]&quot;)<br>                if sdt_elements:<br>                    found_any = True<br>                for sdt in sdt_elements:<br>                    field_name = None<br>                    sdtPr = None<br>                    for child in sdt:<br>                        if QName(child).localname == &#39;sdtPr&#39;:<br>                            sdtPr = child<br>                            break<br>                    if sdtPr is not None:<br>                        for node in sdtPr:<br>                            local = QName(node).localname<br>                            if local in (&#39;tag&#39;, &#39;alias&#39;):<br>                                for a_k, a_v in node.attrib.items():<br>                                    if a_k.endswith(&#39;}val&#39;) or a_k == &#39;val&#39; or a_k.endswith(&#39;:val&#39;):<br>                                        field_name = a_v<br>                                        break<br>                            if local == &#39;dataBinding&#39; and field_name is None:<br>                                for a_k, a_v in node.attrib.items():<br>                                    if a_k.lower().endswith(&#39;xpath&#39;):<br>                                        xpath = a_v<br>                                        candidate = xpath.split(&#39;/&#39;)[-1]<br>                                        field_name = candidate.strip().strip(&#39;[]&#39;)<br>                                        break<br>                    if not field_name:<br>                        tag_nodes = sdt.xpath(&#39;.//*[local-name() = &quot;tag&quot;]&#39;)<br>                        alias_nodes = sdt.xpath(&#39;.//*[local-name() = &quot;alias&quot;]&#39;)<br>                        if tag_nodes:<br>                            for a_k, a_v in tag_nodes[0].attrib.items():<br>                                if a_k.endswith(&#39;}val&#39;) or a_k == &#39;val&#39; or a_k.endswith(&#39;:val&#39;):<br>                                    field_name = a_v<br>                                    break<br>                        elif alias_nodes:<br>                            for a_k, a_v in alias_nodes[0].attrib.items():<br>                                if a_k.endswith(&#39;}val&#39;) or a_k == &#39;val&#39; or a_k.endswith(&#39;:val&#39;):<br>                                    field_name = a_v<br>                                    break<br>                    if field_name:<br>                        content_controls.append({&quot;field&quot;: field_name})<br>    except zipfile.BadZipFile:<br>        raise<br>    if not found_any:<br>        print(&quot;[content_control_extractor] WARNING: No &lt;sdt&gt; content controls found in any XML part!&quot;)<br>    output_template = {item[&#39;field&#39;]: &quot;&quot; for item in content_controls}<br>    return output_template<br>__all__ = [&quot;extract_content_controls_from_docx&quot;]</pre><h3>Mapping an AI Agent Response to a Template</h3><p>When an agent produces structured output like:</p><pre>{  <br>  &quot;ProblemStatement&quot;: &quot;Teams rely on spreadsheets and lack programme-level tooling.&quot;,  <br>  &quot;ProposedSolution&quot;: &quot;An AI-native PMO platform integrated into the existing workflow.&quot;,  <br>  &quot;Owner&quot;: &quot;Products PDT&quot;  <br>}</pre><p>The fill process is:</p><ol><li>Unzip the .docx</li><li>Parse document.xml with an XML library</li><li>Walk every w:sdt element, read its w:tag value</li><li>Normalize both the tag name and the JSON key (lowercase, trim spaces) for tolerant matching</li><li>Write the matched value into the first w:t node inside w:sdtContent</li><li>Reserialize the XML, rezip the file</li></ol><p>Three fields become three filled controls in a polished, branded Word document — no copy-paste, no manual formatting.</p><p><strong>Automating Word Template Filling with Python</strong>: Once you understand that a Word document is just XML inside a ZIP, you can automate template filling with code. Here’s a Sample Code using Python’s zipfile and lxml libraries:</p><pre>import zipfile<br>from lxml import etree<br>def fill_content_controls(docx_path, json_data):<br>    # Open the .docx file as a zip archive<br>    with zipfile.ZipFile(docx_path, &#39;r&#39;) as docx:<br>        xml = docx.read(&#39;word/document.xml&#39;)<br>        tree = etree.fromstring(xml)<br>        ns = {&#39;w&#39;: &#39;http://schemas.openxmlformats.org/wordprocessingml/2006/main&#39;}<br>        # Find all Structured Document Tags (SDTs)<br>        for sdt in tree.findall(&#39;.//w:sdt&#39;, namespaces=ns):<br>            tag_elem = sdt.find(&#39;.//w:tag&#39;, namespaces=ns)<br>            if tag_elem is not None:<br>                tag = tag_elem.get(&#39;{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val&#39;).strip().lower()<br>                # Match JSON keys to SDT tags<br>                if tag in json_data:<br>                    text_elem = sdt.find(&#39;.//w:t&#39;, namespaces=ns)<br>                    if text_elem is not None:<br>                        text_elem.text = json_data[tag]<br>        # Serialize XML back to bytes<br>        new_xml = etree.tostring(tree, xml_declaration=True, encoding=&#39;UTF-8&#39;)<br>    # Write the updated XML back into a new .docx file<br>    with zipfile.ZipFile(&#39;FilledDocument.docx&#39;, &#39;w&#39;) as new_docx:<br>        for item in docx.namelist():<br>            if item == &#39;word/document.xml&#39;:<br>                new_docx.writestr(item, new_xml)<br>            else:<br>                new_docx.writestr(item, docx.read(item))<br># Example usage:<br>agent_response = {<br>    &quot;problemstatement&quot;: &quot;Teams rely on spreadsheets and lack programme-level tooling.&quot;,<br>    &quot;proposedsolution&quot;: &quot;An AI-native PMO platform integrated into the existing workflow.&quot;,<br>    &quot;owner&quot;: &quot;Products PDT&quot;<br>}<br>fill_content_controls(&#39;Template.docx&#39;, agent_response)</pre><h3>Dynamic Table Rows — The Interesting Problem</h3><p>Static fields are straightforward. The real challenge is tabular data. An agent might return parallel arrays:</p><pre>{  <br>  &quot;Header.Criteria&quot;: [&quot;Problem statement&quot;, &quot;Why now&quot;, &quot;Strategic fit&quot;],  <br>  &quot;Header.Score&quot;:    [&quot;3/5&quot;, &quot;4/5&quot;, &quot;5/5&quot;],  <br>  &quot;Header.Rationale&quot;: [&quot;Credible pain point&quot;, &quot;Newly formed team&quot;, &quot;Explicit alignment&quot;]  <br>}</pre><p>The template has <strong>one template row</strong> with three cells. You need <strong>three rows</strong> in the output.</p><p>The algorithm:</p><pre>1. Find all SDTs whose tag starts with &quot;Header.&quot; → these are column definitions  <br>2. Group them by their parent w:tr (table row) — that&#39;s the template row  <br>3. Deep-copy that w:tr N times (once per array element)  <br>   └── deep copy is critical: lxml elements are mutable; a shallow copy would  <br>       make all rows share the same XML nodes in memory  <br>4. For each clone i: fill each SDT with column[i]  <br>5. Remove the original template row from w:tbl  <br>6. Insert the N filled clones at the same position</pre><p>The parent tag chain matters here: w:sdt → w:tc → w:tr → w:tbl. Walking up to w:tr tells you which row is the template. Walking up to w:tbl tells you where to insert siblings.</p><h3>Dynamic Bullet Points — Non-Tabular Arrays</h3><p>For array values that aren’t table columns — risk lists, acceptance criteria, sub-items — the approach is different. Instead of rows, you create N paragraphs:</p><pre>1. Find the w:p containing the SDT  <br>2. Capture its w:pPr (paragraph properties: bullet style, indentation, numbering)  <br>   and w:rPr (run properties: font, bold, size) → these are the formatting nodes  <br>3. Deep-copy those property nodes into N new w:p elements  <br>4. Set each new paragraph&#39;s w:t text to items[i]  <br>5. Replace the original paragraph with the N new ones at the same position in w:body or w:tc</pre><p>Because w:pPr is copied, every generated paragraph inherits the template&#39;s bullet numbering and indentation automatically — no manual styling required.</p><h3>The Full Pattern in One Picture</h3><pre>Agent JSON response  <br>       │  <br>       ▼  normalize keys  <br>  key → value map  <br>       │  <br>       ├─ &quot;Header.*&quot; + list  ──►  clone w:tr × N  ──►  fill columns  ──►  insert rows  <br>       │  <br>       ├─ other key  + list  ──►  clone w:p × N   ──►  fill text     ──►  insert paragraphs  <br>       │  <br>       └─ other key  + scalar ──►  set w:t.text directly  <br>       │  <br>       ▼  <br>  reserialize XML → rezip → publish</pre><p>The template stays untouched as a prototype. The output is a structurally complete, correctly formatted Word document built entirely from the agent’s response.</p><p>This pattern works with any data source — not just AI. Any system that can emit JSON can drive a Word template this way. The Word file is just XML, and XML is just a tree you can manipulate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=518eaee38535" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Streaming Applications — async for vs for, Implicit Await, and the Hidden Cost of a…]]></title>
            <link>https://medium.com/@gj979986/real-time-streaming-applications-async-for-vs-for-implicit-await-and-the-hidden-cost-of-a-83d8cde0f1ae?source=rss-561251cc6836------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d8cde0f1ae</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gaurav Jain]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 05:55:47 GMT</pubDate>
            <atom:updated>2026-07-08T00:40:27.954Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*uRY-0Vta5FOpA5Ar.jpg" /></figure><h3>Real-Time Streaming Applications — async for vs for, Implicit Await, and the Hidden Cost of a Synchronous Iterator</h3><p>While building a real-time AI response streaming application using FastAPI WebSockets and an OpenAI-compatible client, I came across a subtle but impactful observation. The streaming worked perfectly with the old SDK — chunks appeared one by one on the UI in a smooth typewriter effect. After migrating to the new OpenAI client, the backend was clearly streaming — console logs confirmed every chunk arriving — but the frontend would show nothing, then suddenly render the entire response at once.</p><p>The fix turned out to be a single line:</p><pre>await asyncio.sleep(0.05)</pre><p>Understanding why that one line matters requires going deep into how Python’s event loop, coroutines, and iterators actually work together.</p><h4>The Event Loop is Cooperative, Not Parallel</h4><p>Python’s asyncio is built on a <strong>single-threaded cooperative concurrency model</strong>. There is no true parallelism. Every coroutine runs on one thread, and they take turns using the CPU. The only way a coroutine yields control back to the event loop — allowing other coroutines, I/O callbacks, and network flushes to run — is through an await expression.</p><p>If a coroutine never awaits, it holds the event loop hostage for its entire duration. This is the foundational principle that explains everything that follows.</p><h4>Coroutines and What await Actually Means</h4><p>A coroutine in Python is a function defined with async def. It does not run immediately when called — it returns a coroutine object. It only executes when the event loop drives it via await.</p><p>When a coroutine hits an await expression, it:</p><ol><li>Suspends itself</li><li>Hands control back to the event loop</li><li>Says: <em>“I’m waiting for this. Go do other work. Resume me when it’s ready.”</em></li></ol><p>This suspension is the <strong>yield point</strong>. It is the moment the event loop gets a free tick to:</p><ul><li>Flush pending I/O</li><li>Check for new network data</li><li>Fire registered callbacks</li><li>Push buffered WebSocket frames down to the OS TCP stack</li></ul><p><strong>Without a yield point, the event loop cannot do any of that.</strong></p><h4>async for — The Implicit Await</h4><p>The async for statement is syntactic sugar over a specific protocol. When you write:</p><pre>async for event in stream:<br>    await websocket.send_json({&quot;type&quot;: &quot;chat_chunk&quot;, &quot;chunk&quot;: event.delta})</pre><p>Python internally:</p><ol><li>Calls stream.__aiter__() once to get the async iterator</li><li>Calls <strong>await stream.__anext__()</strong> on every single iteration</li></ol><p>That await is <strong>implicit</strong> — not written by the developer, but absolutely present at the bytecode level.</p><p>What does await __anext__() actually wait for? In a streaming HTTP response from an LLM, it waits for the next Server-Sent Event token to arrive from the network. The LLM generates tokens sequentially with measurable latency between them — sometimes 5ms, sometimes 20ms. <strong>During that wait, the event loop is free.</strong></p><p>The flow per chunk looks like this:</p><pre>Receive token from LLM stream<br>  → await websocket.send_json()<br>      → schedules write to transport buffer<br>      → yields event loop<br>  → Event loop tick:<br>      → flushes WebSocket buffer<br>      → frame hits OS TCP stack<br>      → browser receives frame<br>      → onmessage fires → Angular processes chunk → DOM updates<br>  → await __anext__()<br>      → suspends, waits for next token over the network<br>  → Next token arrives, loop resumes</pre><p>Every chunk gets its own event loop tick, its own TCP flush, its own browser frame. The network latency between LLM tokens was acting as a <strong>natural, built-in pacing mechanism</strong> that nobody explicitly designed for — it just happened because async for carries an implicit await.</p><h4>for — The Synchronous Iterator, No Yield</h4><p>When the new OpenAI client was introduced, it switched from an async iterator to a <strong>synchronous one</strong> for its streaming response object. The loop became:</p><pre>for event in response:   # synchronous __next__(), no await<br>    await websocket.send_json({&quot;type&quot;: &quot;chat_chunk&quot;, &quot;chunk&quot;: event.delta})</pre><p>Python now calls response.__iter__() and response.__next__() — both fully synchronous, no await anywhere. The OpenAI client internally buffers the SSE stream. By the time __next__() is called, a token is already sitting in an <strong>in-memory buffer</strong> and returns instantly.</p><p>The loop spins like this:</p><pre>__next__() → token in buffer → return instantly (no yield)<br>await send_json() → schedules write... but does NOT flush yet<br>__next__() → another token in buffer → return instantly (no yield)<br>await send_json() → schedules another write...<br>__next__() → ...<br>[ all 60 tokens processed before the event loop gets a single free tick ]</pre><p>The await on send_json does give the event loop a brief opportunity in theory, but Starlette&#39;s WebSocket transport batches writes and only flushes when it gets a full uninterrupted tick. Because __next__() returns so fast and there are no real suspension points between iterations, <strong>the entire loop completes before the event loop processes a single I/O flush.</strong></p><p>The result:</p><ul><li>All 60 chunks get scheduled as writes</li><li>Loop ends</li><li>Event loop finally gets its tick</li><li>Everything flushes at once in one or a few TCP packets</li><li>Browser receives all frames nearly simultaneously</li><li>All 60 onmessage events fire in a single JS microtask queue drain</li><li>Zone.js batches change detection</li><li><strong>One render. Full text appears instantly.</strong></li></ul><h4>System Design View — Where the Batching Happens</h4><p>It helps to visualize the full stack and where the batching occurs:</p><pre>LLM (token stream)<br>      ↓<br>Python OpenAI client (SSE parser, sync buffer)<br>      ↓<br>FastAPI coroutine (for loop, no yield between iterations)<br>      ↓<br>Starlette WebSocket transport (write buffer — not flushed yet)<br>      ↓  ← all 60 frames pile up here until event loop ticks<br>OS TCP stack (sends as 1–2 packets)<br>      ↓<br>Browser (receives all frames in ~same tick)<br>      ↓<br>JavaScript onmessage (fires 60 times in one microtask drain)<br>      ↓<br>Angular Zone.js (batches change detection)<br>      ↓<br>DOM (one repaint, full text appears)</pre><p>With async for, the LLM&#39;s network latency naturally breaks the loop into individual event loop ticks and each stage gets a chance to flush independently. With for, every stage above the OS TCP stack batches together.</p><h3>Why await asyncio.sleep(0.05) Fixes It</h3><p>asyncio.sleep(0.05) is a coroutine that yields control to the event loop immediately without actually waiting for any time to pass. Adding it after each send:</p><pre>for event in response:<br>    if event.type == &quot;response.output_text.delta&quot;:<br>        await websocket.send_json({&quot;type&quot;: &quot;chat_chunk&quot;, &quot;chunk&quot;: event.delta})<br>        await asyncio.sleep(0.05)  # explicit yield point</pre><p>Now every iteration has a <strong>guaranteed yield point</strong>. After each chunk is scheduled, the event loop gets a free tick:</p><pre>send chunk 1<br>  → await sleep(0) → suspend coroutine<br>      → Event loop tick:<br>          → flush WebSocket buffer<br>          → TCP frame ships to client<br>          → browser receives it, onmessage fires, DOM updates<br>      → resume coroutine<br>send chunk 2<br>  → await sleep(0.05) → ...</pre><p>This is the exact same behavior that async for was providing for free via its implicit await __anext__(). The explicit sleep(0) is <strong>manually replicating what the async iterator&#39;s network wait was doing naturally.</strong></p><h4>Why 0.05 Seconds Is the Sweet Spot</h4><p>sleep(0) yields for one event loop tick — typically 0.1ms to 1ms depending on system load. On fast hardware or when the LLM generates tokens rapidly, the browser can still receive 2–3 chunks before its rendering pipeline completes a frame.</p><p>At 60fps, a browser repaints every <strong>~16ms</strong>. For streaming to feel like streaming visually, each chunk needs to land in a <strong>different animation frame</strong>.</p><p>Sleep ValueChunk IntervalBehaviorsleep(0)~0.1–1msUsually smooth, may micro-batch on fast hardwaresleep(0.05)~50msSmooth, guaranteed per-frame renderingsleep(0.1)~100msPerceptibly slow, breaks real-time illusion</p><p><strong>50ms is above the 16ms frame budget</strong>, which guarantees every chunk lands in a different animation frame — fast enough to feel live and responsive, slow enough to ensure the browser never batches two chunks into the same paint cycle.</p><h4>The Deeper Lesson</h4><p>The implicit await in async for is not just syntactic convenience — it is a <strong>behavioral contract</strong>. It says: <em>between every item I yield, I will suspend and let the event loop breathe.</em> Synchronous iterators carry no such contract. When you switch from one to the other in an async context, you are silently removing yield points that downstream systems — in this case, the browser&#39;s rendering pipeline — were depending on.</p><p>In any system where you are pumping data through an async pipeline to a real-time UI, <strong>the pacing of yield points is as important as the correctness of the data itself.</strong> A correct response rendered all at once is functionally fine but experientially broken. The user does not see streaming — they see a loading spinner followed by a wall of text.</p><blockquote><em>Real-time streaming is not just about sending data fast. It is about sending data with the right cadence, and in Python asyncio, cadence is controlled by where you place your </em><em>await</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d8cde0f1ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do We Know If an LLM Is Actually Giving Good Answers? Meet ROUGE]]></title>
            <link>https://medium.com/@gj979986/how-do-we-know-if-an-llm-is-actually-giving-good-answers-meet-rouge-310ca634edb3?source=rss-561251cc6836------2</link>
            <guid isPermaLink="false">https://medium.com/p/310ca634edb3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Gaurav Jain]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 02:01:55 GMT</pubDate>
            <atom:updated>2026-07-08T00:38:58.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*NMexqEGkqS5fFlKzAKb5pA.png" /></figure><p>You’ve built an LLM-powered system. It summarizes documents, answers questions, extracts key points. It <strong>seems</strong> to work. But how do you <strong>prove</strong> it works systematically, repeatably, and at scale? When you ask an AI to summarize a document or answer a complex question, how do you <strong>measure</strong> how good that answer really is?</p><p>Traditional ML metrics like accuracy or F1 score don’t cut it for text generation. If a model outputs “I prefer coffee to tea” and the expected answer is “I like coffee over tea”, a machine can’t easily tell these are equivalent. Or, If your ground truth is <em>“The patient was diagnosed with hypertension”</em> and your model outputs <em>“The doctor found the patient has high blood pressure”, </em>accuracy gives you a zero. Same meaning, zero credit.</p><p>This is where <strong>ROUGE</strong> comes in.</p><p><strong>What is ROUGE?</strong></p><p>ROUGE: which stands for <strong>Recall-Oriented Understudy for Gisting Evaluation,</strong> is a widely adopted metric for evaluating the quality of text generated by NLP systems, particularly in tasks like text summarization, paraphrase generation, and machine translation.</p><p>Unlike BLEU, which focuses on precision, ROUGE primarily emphasizes <strong>recall: </strong>measuring how much of the reference text is captured in the generated output. <a href="https://doc.superannotate.com/docs/guide-bleu-rouge">SuperAnnotate Docs</a></p><p>ROUGE metrics range between 0 and 1, with higher scores indicating greater similarity between the automatically produced text and the reference. <a href="https://en.wikipedia.org/wiki/ROUGE_(metric)">Wikipedia</a></p><p><strong>The Math, Properly Explained</strong></p><p>Every ROUGE variant is built on three quantities:</p><p><strong>Recall</strong> — how much of the reference does my output cover?</p><pre>Recall =   matching n-grams (Reference ∩ Hypothesis)<br>          ─────────────────────────────────────────────<br>           n-grams in Reference</pre><p><strong>Precision</strong> — how much of my output is actually in the reference?</p><pre>Precision =   matching n-grams (Reference ∩ Hypothesis)<br>             ─────────────────────────────────────────────<br>              n-grams in Hypothesis</pre><p><strong>F1</strong> — the harmonic mean of both, used in practice to prevent gaming either side:</p><pre>F1 = 2 × Precision × Recall<br>     ────────────────────────<br>       Precision + Recall</pre><pre>Why F1 and not just Recall? Pure recall can be gamed: a model that copies <br>the entire reference scores 1.0 on recall. F1 penalises that by also <br>requiring precision.</pre><p><strong>ROUGE Variants: What Each One Measures</strong></p><p><strong>ROUGE-N (N-gram Overlap — the parent family)</strong></p><p>ROUGE-N is the general formula that underpins ROUGE-1 and ROUGE-2. The “N” refers to the size of the n-gram used for comparison — you choose N, and the metric measures how many consecutive sequences of N words overlap between the hypothesis and the reference.</p><ul><li>N=1 → ROUGE-1 (unigrams)</li><li>N=2 → ROUGE-2 (bigrams)</li><li>N=3 → ROUGE-3 (trigrams, rarely used in practice)</li></ul><p>As N increases, the metric becomes increasingly strict — trigram matches require three consecutive words to align exactly. In practice, ROUGE-1 and ROUGE-2 are the most commonly reported because beyond N=2, scores drop so sharply they become hard to interpret meaningfully.</p><p><strong>ROUGE-1 (Unigrams):</strong></p><p>Measures overlap at the single-word level. It asks: how many individual words in the reference text also appear in the generated text?</p><pre>Reference: &quot;The weather is cold outside.&quot;<br>LLM Output: &quot;The weather is cold.&quot;<br>Matching unigrams: &quot;The&quot;, &quot;weather&quot;, &quot;is&quot;, &quot;cold&quot; → high ROUGE-1 score.</pre><p><strong>ROUGE-2 (Bigrams):</strong></p><p>Unlike ROUGE-1, ROUGE-2 looks at pairs of consecutive words (bigrams). For example, bigrams of <em>The weather is cold outside</em> would be: (the, weather), (weather, is), (is, cold), (cold, outside). More bigram matches = a higher score, meaning the model preserved more of the phrasing structure. <a href="https://medium.com/@MUmarAmanat/llm-evaluation-with-rouge-0ebf6cf2aed4)">Medium <em>(LLM Eval With ROUGE)</em></a></p><p><strong>ROUGE-L (Longest Common Subsequence)</strong></p><p>ROUGE-L considers the longest common subsequence (LCS) of words between the reference and generated text, even if they aren’t consecutive, as long as they remain in the same order. This is useful for capturing structural similarity beyond just word counting. <a href="https://www.traceloop.com/blog/evaluating-model-performance-with-the-rouge-metric-a-comprehensive-guide">Traceloop <em>(evaluating model performance with rouge)</em></a></p><p><strong>ROUGE-S (Skip-gram</strong>)</p><p>ROUGE-S is a skip-gram concurrence metric, it considers n-grams that appear in the reference text and allows the words to be separated by one or more words in the model output, but they must still appear in the correct order. <a href="https://www.traceloop.com/blog/evaluating-model-performance-with-the-rouge-metric-a-comprehensive-guide">Traceloop</a></p><p><strong>Example</strong></p><p>Let’s manually compute ROUGE-1, ROUGE-2, and ROUGE-L on the same pair:</p><pre>Reference: The quick brown fox jumps over the lazy dog today.<br>Hypothesis: A quick brown fox leaps over a lazy dog quickly.</pre><p><strong>ROUGE-1</strong></p><ul><li>Reference unigrams (10): The, quick, brown, fox, jumps, over, the, lazy, dog, today</li><li>Hypothesis unigrams (10): A, quick, brown, fox, leaps, over, a, lazy, dog, quickly</li><li>Matches (6): quick, brown, fox, over, lazy, dog</li><li>Recall = 6/10 = 0.60 | Precision = 6/10 = 0.60 | F1 = 0.60</li></ul><p><strong>ROUGE-2</strong></p><ul><li>Reference bigrams (9): (the,quick), (quick,brown), (brown,fox), (fox,jumps)…</li><li>Hypothesis bigrams (9): (a,quick), (quick,brown), (brown,fox), (fox,leaps)…</li><li>Matches (3): (quick,brown), (brown,fox), (lazy,dog)</li><li>Recall = 3/9 = 0.33 | Precision = 3/9 = 0.33 | F1 = 0.33</li></ul><p><strong>ROUGE-L</strong></p><ul><li>LCS: “quick brown fox … over … lazy dog” → length 6</li><li>Recall = 6/10 = 0.60 | Precision = 6/10 = 0.60 | F1 = 0.60</li></ul><pre>Key insight: ROUGE-2 dropped sharply (0.33) vs ROUGE-1 and ROUGE-L (0.60). <br>A big gap between ROUGE-1 and ROUGE-2 signals the model captures the <br>right vocabulary but not the right phrasing structure.</pre><p><strong>How Is the Score Calculated?</strong></p><p>The core calculation involves comparing recall for n-grams, how much of the reference n-grams are captured in the generated output. There are also variations that calculate <strong>precision</strong> (how much of the generated text matches the reference) and the <strong>F1 score</strong>, which is the harmonic mean of precision and recall, providing a balanced evaluation. <a href="https://www.analyticsvidhya.com/blog/2025/03/llm-evaluation-metrics/">Analytics Vidhya</a></p><p><strong>Practical Example</strong></p><p>Reference Text: <em>“The quick brown fox jumps over the lazy dog.”</em></p><p>Generated Text: <em>“A fast brown fox jumps over the lazy dog.”</em></p><p>Even though “quick” and “fast” are synonyms, ROUGE would not count them as a match — it relies on exact word overlap, not semantic similarity. This is an important limitation to keep in mind. <a href="https://www.analyticsvidhya.com/blog/2025/03/llm-evaluation-metrics/)">Analytics Vidhya</a></p><p><strong>Where ROUGE Shines</strong></p><p>ROUGE is very helpful in jobs like summarization, where recall — capturing all of the relevant information from the reference text, is more crucial than precision. ROUGE gives priority to capturing all of the pertinent information from the reference text, in contrast to BLEU, which is precision-focused. <a href="https://www.analyticsvidhya.com/blog/2025/03/rouge/">Analytics Vidhya</a></p><p>Common use cases</p><ul><li>Text summarization</li><li>Document Q&amp;A evaluation</li><li>RAG pipeline output validation</li><li>Fine-tuning LLMs for summarization tasks</li></ul><p><strong>Where ROUGE Has Limits</strong></p><p>ROUGE considers syntactic rather than semantic matches — it does not take into account words that have the same meaning. It also requires a reference evaluation, which means it cannot be used for automatic evaluation of generated outputs without a human-written ground truth. <a href="https://www.traceloop.com/blog/evaluating-model-performance-with-the-rouge-metric-a-comprehensive-guide">Traceloop</a> | <a href="https://www.analyticsvidhya.com/blog/2025/03/rouge/">Analytics Vidhya</a></p><p><strong>Additional gaps:</strong></p><ul><li>It does not verify whether generated content is factually accurate.</li><li>It does not capture sentence coherence or readability.</li><li>Higher recall can inflate scores without truly improving quality — there is a bias toward longer texts.</li></ul><p><strong>ROUGE vs. Other Metrics</strong></p><ul><li><strong>ROUGE</strong> — Recall‑based (n‑gram overlap); best for summarization and Q&amp;A</li><li><strong>BLEU</strong> — Precision‑based (n‑gram overlap); best for machine translation</li><li><strong>BERTScore</strong> — Semantic similarity using embeddings; best for nuanced text quality</li><li><strong>METEOR</strong> — Precision + recall with synonym matching; best for translation and paraphrasing</li></ul><p>ROUGE does not fully capture semantic meaning, so complementary measures like BERTScore and METEOR are often required alongside it. <a href="https://www.analyticsvidhya.com/blog/2025/03/rouge/">Analytics Vidhya</a></p><p><strong>Quick Code Snippet (Python / HuggingFace)</strong></p><pre>import evaluate<br>rouge = evaluate.load(&quot;rouge&quot;)<br>predictions = [&quot;The weather is cold today.&quot;]<br>references = [&quot;The weather is very cold outside today.&quot;]<br>results = rouge.compute(predictions=predictions, references=references)<br>print(results)<br># {&#39;rouge1&#39;: 0.727, &#39;rouge2&#39;: 0.545, &#39;rougeL&#39;: 0.727, &#39;rougeLsum&#39;: 0.727}</pre><p>Hugging Face’s <strong>evaluate </strong>library is a simple and easy-to-use tool for evaluating LLMs with ROUGE. <a href="https://medium.com/@MUmarAmanat/llm-evaluation-with-rouge-0ebf6cf2aed4">Medium</a></p><p><strong>Bottom Line</strong></p><p>ROUGE is a fast, language-agnostic, and widely adopted baseline for evaluating LLM outputs — especially in summarization and retrieval tasks. Calculating ROUGE is computationally inexpensive and can be used with any input language. But it’s a starting point, not the finish line. For production-grade LLM evaluation, combine ROUGE with semantic metrics like BERTScore and task-specific evaluators. <a href="https://www.traceloop.com/blog/evaluating-model-performance-with-the-rouge-metric-a-comprehensive-guide">Traceloop</a></p><p>Use it confidently for summarization and retrieval evaluation. Combine it with BERTScore for semantic coverage and LLM-as-a-judge for qualitative depth. No single metric tells the whole story — the skill is knowing which metric to trust for which dimension of quality.</p><p>ROUGE is like a GPS for language models, useful for navigation, but unable to truly understand the journey</p><p>#LLM #GenerativeAI #NLP #ROUGE #AIEvaluation #MachineLearning #DataScience #LLMOps #AIEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=310ca634edb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python BytesIO — .getvalue() vs .getbuffer()]]></title>
            <link>https://medium.com/@gj979986/python-bytesio-getvalue-vs-getbuffer-aca9367bbdfc?source=rss-561251cc6836------2</link>
            <guid isPermaLink="false">https://medium.com/p/aca9367bbdfc</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Gaurav Jain]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 10:43:29 GMT</pubDate>
            <atom:updated>2026-07-08T00:37:33.537Z</atom:updated>
            <content:encoded><![CDATA[<p>While building full stack applications and agentic workflows, I kept running into the same decision point around in-memory file handling. Thought a community reference blog would be useful.</p><p><strong>What is BytesIO ?</strong></p><p>io.BytesIO is an in-memory binary stream — essentially a file that lives in RAM instead of on disk. Internally it wraps a byte array and maintains a position pointer (like a cursor). You use it when you want to read or write bytes without touching the filesystem, common in file processing pipelines, API integrations, and anywhere you pass binary data between services.</p><p>The two functions</p><p><strong>.getvalue()</strong></p><ul><li>Returns a <strong>new bytes object</strong> — a full copy of the buffer contents regardless of current position</li><li>Memory cost: file size × 2 (original buffer + copy)</li><li>Safe to pass around independently; immutable; works even after buffer is closed</li><li>Internally calls memcpy on the underlying bytearray</li></ul><p><strong>.getbuffer()</strong></p><ul><li>Returns a <strong>memoryview</strong> — a zero-copy reference into the buffer’s internal memory</li><li>No extra allocation; efficient for large files</li><li>The BytesIO is <strong>locked</strong> (no writes or resizes allowed) while the memoryview is alive</li><li>Release it with del mv when done, otherwise the lock persists and can silently leak memory in long-running processes</li><li>Accepts the Python buffer protocol — works directly with <em>f.write()</em>, <em>socket.send()</em>, <em>hashlib.update()</em> without an intermediate copy</li></ul><p><strong>Example: Reading a file from SharePoint via Graph API</strong></p><p>Authentication uses an SPN (service principal) via ClientSecretCredential. The token is passed as a Bearer header to Microsoft Graph. Graph may return a <strong><em>@microsoft.graph.downloadUrl</em></strong> — a pre-authenticated temporary URL that doesn’t require the Authorization header on the download request.</p><pre>import io, os, asyncio<br>import httpx<br>from azure.identity import ClientSecretCredential<br><br>GRAPH_BASE = &quot;https://graph.microsoft.com/v1.0&quot;<br>def get_token() -&gt; str:<br>    cred = ClientSecretCredential(<br>        tenant_id=os.environ[&quot;SHAREPOINT_TENANT_ID&quot;],<br>        client_id=os.environ[&quot;SHAREPOINT_CLIENT_ID&quot;],<br>        client_secret=os.environ[&quot;SHAREPOINT_CLIENT_SECRET&quot;],<br>    )<br>    return cred.get_token(&quot;https://graph.microsoft.com/.default&quot;).token<br>async def fetch_latest_file() -&gt; tuple[str, io.BytesIO]:<br>    token = get_token()<br>    folder = os.environ.get(&quot;SHAREPOINT_DEST_FOLDER&quot;, &quot;&quot;).strip(&quot;/&quot;)<br>    async with httpx.AsyncClient() as client:<br>        # resolve shorthand site id (hostname:/sites/Name) to opaque GUID<br>        r = await client.get(f&quot;{GRAPH_BASE}/sites/{os.environ[&#39;SHAREPOINT_SITE_ID&#39;]}&quot;, headers={&quot;Authorization&quot;: f&quot;Bearer {token}&quot;})<br>        r.raise_for_status()<br>        site_id = r.json()[&quot;id&quot;]<br>        # list folder children, pick most recently modified<br>        r = await client.get(f&quot;{GRAPH_BASE}/sites/{site_id}/drive/root:/{folder}:/children&quot;, headers={&quot;Authorization&quot;: f&quot;Bearer {token}&quot;})<br>        r.raise_for_status()<br>        latest = max(r.json()[&quot;value&quot;], key=lambda x: x.get(&quot;lastModifiedDateTime&quot;) or &quot;&quot;)<br>        # prefer pre-authenticated downloadUrl, fallback to content endpoint with token<br>        url = latest.get(&quot;@microsoft.graph.downloadUrl&quot;) or \<br>              f&quot;{GRAPH_BASE}/sites/{site_id}/drive/items/{latest[&#39;id&#39;]}/content&quot;<br>        r = await client.get(url, timeout=120)<br>        r.raise_for_status()<br>        return latest[&quot;name&quot;], io.BytesIO(r.content)</pre><p>Now using the buffer:</p><pre>name, buf = asyncio.run(fetch_latest_file())<br># .getvalue() - allocates a full copy as immutable bytes<br>data: bytes = buf.getvalue()<br># .getbuffer() - zero-copy memoryview, no extra allocation<br>mv = buf.getbuffer()<br>with open(name, &quot;wb&quot;) as f:<br>    f.write(mv)              # f.write() accepts buffer protocol directly<br>del mv                       # release the lock so BytesIO can be GC&#39;d or rewritten<br># streaming in chunks - avoids holding the full file in memory at once<br>buf.seek(0)<br>while chunk := buf.read(8192):<br>    pass  # push chunk to upstream API, blob storage, or upload session</pre><p><strong>Under the hood: Why it matters at concurrency</strong></p><p>BytesIO internally uses a byte array. Both <em>.getvalue()</em> and <em>.getbuffer()</em> expose the same underlying data — the difference is whether Python allocates a new object or shares memory via the buffer protocol.</p><p>At high concurrency (e.g., 20 concurrent users each downloading a 50 MB file), holding a full BytesIO per request means 1 GB of peak memory just from the buffers. .getbuffer() avoids the copy but still holds the full file. The real fix at scale is to not accumulate the whole file at all — stream the HTTP response in chunks directly to disk or Azure Blob:</p><pre># stream Graph response directly — BytesIO never created<br>async with client.stream(&quot;GET&quot;, download_url) as resp:<br>    resp.raise_for_status()<br>    with open(name, &quot;wb&quot;) as f:<br>        async for chunk in resp.aiter_bytes(8192):<br>            f.write(chunk)</pre><p>This keeps memory per request near zero regardless of file size, and is the right pattern for production pipelines.</p><p><strong>Rule of thumb </strong>(from my experience so far)</p><ol><li>If Use case is around small file which could be passed around safely then go with <em>.getvalue()</em></li><li>If Use case is around large files or uploads, then go with <em>.getbuffer()</em> + <em>del mv</em></li><li>If Use case is around High concurrency / large files then Stream chunks directly, skip BytesIO</li><li>If Use case around Hashing without copy then you could try <em>hashlib.sha256(buf.getbuffer()).hexdigest()</em></li></ol><p><a href="https://engage.cloud.microsoft/main/search?search=%23Python&amp;type=threads">#Python</a> <a href="https://engage.cloud.microsoft/main/search?search=%23Azure&amp;type=threads">#Azure</a> <a href="https://engage.cloud.microsoft/main/search?search=%23SharePoint&amp;type=threads">#SharePoint</a> <a href="https://engage.cloud.microsoft/main/search?search=%23MicrosoftGraph&amp;type=threads">#MicrosoftGraph</a> <a href="https://engage.cloud.microsoft/main/search?search=%23AgenticAI&amp;type=threads">#AgenticAI</a> <a href="https://engage.cloud.microsoft/main/search?search=%23BackendEngineering&amp;type=threads">#BackendEngineering</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aca9367bbdfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>