<?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 Vishesh S. on Medium]]></title>
        <description><![CDATA[Stories by Vishesh S. on Medium]]></description>
        <link>https://medium.com/@shahvishesh313?source=rss-5ef31430f4e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x4_xnS98pUoTkeFwmc69Vw.jpeg</url>
            <title>Stories by Vishesh S. on Medium</title>
            <link>https://medium.com/@shahvishesh313?source=rss-5ef31430f4e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 20:04:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shahvishesh313/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Retrieve Anything. Fast.]]></title>
            <link>https://pub.towardsai.net/how-to-retrieve-anything-fast-ee4c1b5c4497?source=rss-5ef31430f4e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee4c1b5c4497</guid>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai-architecture]]></category>
            <category><![CDATA[generative-ai-in-finance]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <dc:creator><![CDATA[Vishesh S.]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 23:01:01 GMT</pubDate>
            <atom:updated>2026-06-06T23:01:01.015Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Production Architecture for Financial Document Search at Scale</h4><p><strong>Assumptions going in:</strong> You know what RAG is. You know its failure modes — context window pollution, semantic gap, retrieval drift, stale embeddings. You’ve hit the wall where naive vector search works in a demo and breaks in production. This article is about what comes after that wall, specifically in the context of the financial industry, where the data is messier, the stakes are higher, and the retrieval requirements are more demanding than most other domains.</p><h3>The Problem Space: Financial Data Is Not Clean Text</h3><p>A financial services company — asset manager, bank, insurance firm, fintech — has a corpus that looks roughly like this:</p><ul><li><strong>PDF-heavy:</strong> 10-K/10-Q/8-K filings, audit reports, research notes, policy documents, contracts, compliance manuals</li><li><strong>Spreadsheets:</strong> Excel models, CSV exports, account statements, reconciliation sheets</li><li><strong>Presentations:</strong> PowerPoint earnings decks, investor briefings with charts, embedded commentary</li><li><strong>Receipts and invoices:</strong> Scanned PDFs, sometimes photographed, sometimes multi-page with stamps, handwriting, and low DPI</li><li><strong>Unstructured text:</strong> Email threads, analyst notes, internal memos in DOCX or plain text</li></ul><p>The challenge isn’t just retrieval. It’s everything upstream of retrieval. A scanned invoice that gets fed through a naive pypdf extractor becomes corrupted text — table rows collapse into comma-separated garbage, column headers merge with values, and multi-line fields lose their structure. If that&#39;s what you&#39;re embedding, your vector index is poisoned before a single query is run.</p><p>So the architecture has two distinct problems, and they need to be solved independently:</p><ol><li><strong>Ingestion quality</strong> — parsing, extracting structure, and chunking in a way that preserves semantic integrity</li><li><strong>Retrieval speed and accuracy</strong> — finding the right chunk fast, with provenance, at scale</li></ol><p>This article covers both, in order, because you cannot have a fast and accurate retrieval system if your index contains garbage.</p><h3>Part 1: Ingestion — Parse Before You Index</h3><h3>The Parser Decision</h3><p>Most teams default to pypdf or PDFMiner. Both are fine for clean, text-native PDFs with linear reading order. They both fail badly on:</p><ul><li>Multi-column layouts</li><li>Tables with merged cells or missing borders</li><li>Scanned/image-based PDFs with any OCR requirement</li><li>PDFs with embedded charts where the caption is spatially separated from the figure</li></ul><p>For a financial corpus, these failure cases are not edge cases. They are the norm.</p><p><strong>Docling</strong> (IBM Research, now Linux Foundation, MIT license) is the current open-source ceiling for document parsing in RAG pipelines. It uses computer vision models to understand page layout before doing text extraction — it identifies element types (title, paragraph, table, figure, list, caption) and their spatial relationships, then reconstructs reading order and structure. The output is a DoclingDocument object — a Pydantic model that keeps text, tables, images, headings, and layout metadata together rather than flattening everything into a text blob.</p><p>Critically, it does not treat a table as text. A table is extracted as a structured object with row/column relationships intact.</p><pre>from docling.document_converter import DocumentConverter</pre><pre>converter = DocumentConverter()<br>result = converter.convert(&quot;q3_earnings_report.pdf&quot;)</pre><pre>doc = result.document<br># Tables come out as structured objects, not linearized text<br>for table in doc.tables:<br>    df = table.export_to_dataframe()  # pandas DataFrame, structure preserved<br>    print(df)</pre><pre># Export full doc to markdown for text chunks<br>markdown_text = doc.export_to_markdown()</pre><p>IBM also released <strong>Granite-Docling</strong> (January 2026) — a 258M parameter VLM that does the full parse in one shot, including OCR within identified elements and linking captions to their figures. It’s worth evaluating for environments where running Docling’s ensemble pipeline (multiple models) is too slow for batch ingestion.</p><p>For scanned receipts and invoices with low quality or non-standard layouts, the preprocessing step matters: de-skewing, contrast enhancement, and resolution normalization before any parser sees the image. Confidence scoring on extracted fields is essential — you want corrupted extractions flagged for human review rather than silently poisoning your index.</p><h3>The Chunking Decision</h3><p>This is where most production systems make mistakes that are invisible until retrieval fails.</p><p>The wrong approach: fixed-size token chunking applied uniformly across all document types.</p><p>Fixed-size chunking at 256 or 512 tokens is fine for homogeneous prose. Financial documents are not homogeneous. The same PDF can have:</p><ul><li>Dense narrative text (risk factor disclosures) where 512-token chunks work well</li><li>Financial tables (income statement, balance sheet) where table rows need to be kept together with their headers</li><li>Charts with captions that need to be stored paired together</li><li>Section headers that provide critical context for the paragraphs below them</li></ul><p><strong>What the research says:</strong> A 2025 NVIDIA study on financial document retrieval (using FinanceBench as the evaluation corpus) found that factoid queries perform best with 256–512 token chunks, while complex analytical queries benefit from page-level or 1024-token chunks. This isn’t a reason to pick one — it’s a reason to implement per-document-type chunking strategies.</p><p><strong>The practical approach:</strong></p><pre>Document type → Chunking strategy</pre><pre>SEC filings (10-K, 10-Q)     → Section-level (split on headings), ~512-1024 tokens<br>                                Tables chunked separately as structured objects<br>                                Table header repeated in every table chunk</pre><pre>Earnings presentations (PPT) → Slide-level chunks<br>                                Each slide = one chunk, title + body + any chart caption</pre><pre>Receipts / invoices          → Whole-document chunk (receipts are usually short)<br>                                Key fields extracted as metadata: vendor, date, amount, currency</pre><pre>Spreadsheets (Excel/CSV)     → Row-group chunking for tabular data<br>                                Schema stored as metadata per chunk<br>                                Numeric columns normalized to strings with units preserved</pre><pre>Contracts (DOCX)             → Clause-level chunking<br>                                Clause header + clause body kept together<br>                                Cross-references stored as metadata links</pre><pre>Research notes (free text)   → Semantic chunking (sentence transformer-based)<br>                                ~256-512 tokens, 20% overlap</pre><p>For tables specifically: don’t flatten them to text. Store the structured representation (Markdown table or JSON object) as the chunk content. A table embedded in a 10-K that shows quarterly revenue should be retrievable by “Q3 revenue” even if those words don’t appear verbatim in the table — which means the table’s semantic embedding needs to capture its content, not garbled linearized text.</p><p>One effective approach: generate a natural language summary of each table using a small LLM (or Granite-Docling’s built-in captioning), store the summary as the chunk text for embedding, and keep the raw structured table as a reference artifact that gets returned to the LLM at generation time.</p><pre># Table handling pattern<br>table_summary = llm.generate(<br>    f&quot;Summarize this financial table in 2-3 sentences:\n{table.export_to_markdown()}&quot;<br>)</pre><pre>chunk = {<br>    &quot;chunk_id&quot;: f&quot;{doc_id}_table_{idx}&quot;,<br>    &quot;content&quot;: table_summary,          # What gets embedded for retrieval<br>    &quot;raw_content&quot;: table.export_to_markdown(),  # What gets sent to LLM<br>    &quot;metadata&quot;: {<br>        &quot;doc_type&quot;: &quot;10-K&quot;,<br>        &quot;element_type&quot;: &quot;table&quot;,<br>        &quot;page&quot;: table.page_no,<br>        &quot;section&quot;: parent_section_heading,<br>        &quot;source_file&quot;: filename,<br>        &quot;date&quot;: doc_date,<br>        &quot;company&quot;: company_name,<br>        &quot;fiscal_period&quot;: fiscal_period<br>    }<br>}</pre><p>The metadata schema is not optional. It’s the foundation for pre-filtering, which is covered in Part 2.</p><h3>Part 2: Retrieval Architecture</h3><p>With a correctly parsed and structured index, the retrieval problem becomes solvable. The architecture choices below are ordered by impact on latency and accuracy.</p><h3>Layer 1: Hybrid Search (Dense + Sparse) — Non-Negotiable</h3><p>Pure vector search has a known failure mode: it’s good at semantic similarity but bad at exact term matching. In financial retrieval, exact terms matter enormously. “IFRS 17,” “Basel III Pillar 2,” “Q3 FY2024,” “Article 23(1)(a)” — these are not paraphraseable. If your query contains a specific regulatory reference and the exact document mentioning it ranks 15th because it has lower semantic similarity to the query embedding than 14 other documents, your retrieval has failed.</p><p>The fix is hybrid search: run dense vector search and sparse BM25 in parallel, then fuse results using Reciprocal Rank Fusion (RRF).</p><p><strong>RRF formula:</strong></p><pre>RRF_score(d) = Σ 1 / (k + rank_i(d))</pre><p>Where k is a smoothing constant (typically 60) and rank_i(d) is the document&#39;s rank in each result list. RRF is preferred over weighted linear combination because it doesn&#39;t require calibrating scores between two differently-scaled systems.</p><p>Empirically (from the SIGIR 2025 LiveRAG Challenge), hybrid retrieval achieves the highest recall at depth — specifically at R@50 and beyond, which matters because you’re feeding a reranker downstream, not taking the raw top-5.</p><p>A 2026 benchmark (aimultiple.com, April 2026) measured hybrid search (BM25 + dense) against dense-only retrieval and found MRR improved from 0.410 to 0.486 — an 18.5% improvement in the likelihood that the best answer appears in the top position.</p><p>For financial queries, a 2025 paper evaluating RAG on SEC filings (arXiv:2511.18177) confirmed this: vector-based agentic RAG with hybrid search and metadata filtering achieved a 68% win rate over hierarchical node-based systems that don’t use embeddings at all.</p><p><strong>Implementation with Qdrant (supports native hybrid search):</strong></p><pre>from qdrant_client import QdrantClient<br>from qdrant_client.models import SparseVector, NamedSparseVector, NamedVector</pre><pre>client = QdrantClient(host=&quot;localhost&quot;, port=6333)</pre><pre># At query time: run hybrid search<br>results = client.query_points(<br>    collection_name=&quot;financial_docs&quot;,<br>    prefetch=[<br>        # Dense retrieval leg<br>        models.Prefetch(<br>            query=dense_query_vector,  # from your embedding model<br>            using=&quot;dense&quot;,<br>            limit=50<br>        ),<br>        # Sparse retrieval leg (BM25 / SPLADE)<br>        models.Prefetch(<br>            query=models.SparseVector(indices=sparse_indices, values=sparse_values),<br>            using=&quot;sparse&quot;,<br>            limit=50<br>        ),<br>    ],<br>    # RRF fusion<br>    query=models.FusionQuery(fusion=models.Fusion.RRF),<br>    limit=50  # Top 50 for the reranker<br>)</pre><p>Elasticsearch (with ELSER for sparse) and Weaviate (native hybrid) are alternatives. Qdrant’s RRF implementation in a single query call is cleaner operationally.</p><h3>Layer 2: Metadata Pre-Filtering — Reduce the Search Space Before ANN</h3><p>Pre-filtering applies metadata constraints before the ANN search executes. This narrows the candidate vector pool, which reduces both latency and noise. The key is that pre-filtering only works if your metadata is indexed and queryable efficiently.</p><p>For financial data, the natural pre-filters are:</p><pre># Example: Find Q3 2024 revenue figures for TechCorp from their 10-K filing<br>filters = {<br>    &quot;must&quot;: [<br>        {&quot;key&quot;: &quot;company&quot;, &quot;match&quot;: {&quot;value&quot;: &quot;TechCorp&quot;}},<br>        {&quot;key&quot;: &quot;fiscal_period&quot;, &quot;match&quot;: {&quot;value&quot;: &quot;Q3_2024&quot;}},<br>        {&quot;key&quot;: &quot;doc_type&quot;, &quot;match&quot;: {&quot;any&quot;: [&quot;10-K&quot;, &quot;10-Q&quot;]}}<br>    ],<br>    &quot;should&quot;: [<br>        {&quot;key&quot;: &quot;element_type&quot;, &quot;match&quot;: {&quot;value&quot;: &quot;table&quot;}}<br>    ]<br>}</pre><p>The tradeoff: pre-filtering reduces the candidate pool, which can hurt recall if filters are too aggressive or if your metadata schema is inconsistent. The failure mode is when a highly relevant chunk is excluded because of a metadata mismatch — e.g., a table stored with fiscal_period: &quot;2024-Q3&quot; instead of &quot;Q3_2024&quot;. Normalize your metadata schema at ingestion time, not at query time.</p><p>Post-filtering (retrieve top-k from full index, then filter by metadata) avoids this but is more expensive and can leave you with fewer than k results after filtering. The practical compromise: pre-filter on high-cardinality, reliable metadata (document type, company, date range), and leave the rest to the reranker.</p><h3>Layer 3: Vector Index Selection — HNSW at This Scale</h3><p>For a financial firm with tens of millions of document chunks (a reasonable number when you’re processing decades of filings, contracts, and research), the indexing choice matters.</p><p><strong>HNSW</strong> is the right default for datasets under roughly 100M vectors where you can afford the memory. It operates in O(log n) query time, handles high-dimensional vectors better than IVF (which relies on good cluster structure that high-dimensional data often lacks), and tolerates data distribution drift — relevant for a financial corpus where new document types get added regularly.</p><p>Benchmarks show HNSW delivering sub-10ms latency on millions of vectors with 95%+ recall at ef_search values tuned for your workload. Going from 0.80 to 0.95 recall increases HNSW latency by roughly 31% — a generally acceptable tradeoff.</p><p><strong>When to deviate:</strong></p><ul><li><strong>100M+ vectors:</strong> HNSW keeps the full graph in RAM. At 100M 1536-dim vectors (float32), that’s ~600GB. IVF-PQ with product quantization compresses this to ~75–150GB at 4–8x compression while maintaining 95%+ recall. Use IVF-PQ at billion scale.</li><li><strong>Tiered data:</strong> Hot data (current quarter filings, recent news) stays in HNSW in memory for fast access. Cold data (archived historical filings) moves to IVF-PQ or DiskANN (SSD-backed).</li></ul><pre>Dataset size     Recommended index<br>&lt; 1M vectors     HNSW (ef=200, M=16)<br>1M - 100M        HNSW (ef=128-256, M=16-32), tune ef_search per latency budget<br>100M - 1B        IVF-PQ or DiskANN<br>&gt; 1B             Distributed Milvus or Qdrant cluster with IVF-PQ shards</pre><h3>Layer 4: Cross-Encoder Reranking — The Accuracy Multiplier</h3><p>After hybrid search returns top-50 candidates (not top-5 — always retrieve more than you need), a cross-encoder reranker scores each query-chunk pair. Unlike bi-encoders that produce independent embeddings, a cross-encoder sees the full concatenated query + chunk text and scores their relevance jointly. This is significantly more accurate at the cost of compute.</p><p>From the financial domain specifically (arXiv:2511.18177): cross-encoder reranking achieves a 59% absolute improvement in MRR@5 at optimal parameters on SEC filing retrieval. That’s not a marginal improvement — it’s the difference between a system that sometimes finds the right document and one that reliably does.</p><p>The latency cost is real: on CPU, scoring 50 candidates with ms-marco-MiniLM-L6-v2 takes 100-300ms depending on chunk length. On a single GPU, under 50ms. This is the right tradeoff for financial queries where correctness matters more than shaving 200ms.</p><p><strong>Options in 2026:</strong></p><p>Reranker ELO (Agentset, Feb 2026) Latency Cost Notes Zerank-2 1638 ~200ms API, pay-per-use Current accuracy leader Cohere Rerank v4.0 Pro 1629 ~600ms API, pay-per-use 32K context window, strong on finance BGE-reranker-v2-m3–50–100ms GPU Free (self-host) Apache 2.0, multilingual, no data leaves your infra ms-marco-MiniLM-L6-v2–100–300ms CPU Free (self-host) Lightest option, good baseline</p><p>For a financial firm with data residency or air-gap requirements, BGE-reranker-v2-m3 self-hosted on a single GPU is the right choice. For external-facing products where accuracy ceiling matters most, Zerank-2 or Cohere Rerank v4 Pro.</p><pre>from sentence_transformers import CrossEncoder</pre><pre>reranker = CrossEncoder(&quot;BAAI/bge-reranker-v2-m3&quot;)</pre><pre># Input: top-50 from hybrid search<br>candidates = [(query, chunk[&quot;content&quot;]) for chunk in hybrid_results[:50]]<br>scores = reranker.predict(candidates)</pre><pre># Re-sort by reranker score<br>reranked = sorted(zip(hybrid_results, scores), key=lambda x: x[1], reverse=True)<br>top_k = [item[0] for item in reranked[:5]]  # Top-5 for LLM context</pre><h3>Layer 5: Semantic Caching — The Cheapest Query Is One That Doesn’t Run</h3><p>In financial workflows, query patterns repeat. “What is the revenue for Q3 2024?” and “Show me Q3 FY24 revenues” are semantically identical. Running the full pipeline — hybrid search, reranker, LLM generation — for both is wasteful.</p><p>Semantic caching works by embedding incoming queries and checking cosine similarity against a cache of past queries. If similarity exceeds a threshold (typically 0.90–0.95 for financial queries where precision matters), return the cached response.</p><p>Measured results from production pipelines (Catchpoint benchmarks, 2025–2026): retrieval time drops from ~6500ms to ~1900ms on cache hits, with exact matches returning in 53ms. Redis LangCache reports up to 73% cost reduction in high-repetition workloads. For financial dashboards or portals where the same 20% of questions make up 80% of volume, this is significant.</p><p><strong>Threshold tuning for finance:</strong> Financial queries are precise. “What is Q3 revenue?” and “What is Q3 profit?” are semantically close but not equivalent. Set your similarity threshold at 0.92–0.95 and measure false hit rates on a validation set before deploying.</p><pre>import redis<br>import numpy as np<br>from sentence_transformers import SentenceTransformer</pre><pre>encoder = SentenceTransformer(&quot;BAAI/bge-small-en-v1.5&quot;)<br>cache_client = redis.Redis(host=&quot;localhost&quot;, port=6379)</pre><pre>def get_cached_response(query: str, threshold: float = 0.93):<br>    query_emb = encoder.encode(query)</pre><pre>    # Check cache (Redis with vector search, or Qdrant collection)<br>    cached_queries = cache_client.lrange(&quot;query_cache&quot;, 0, -1)<br>    for entry in cached_queries:<br>        cached = json.loads(entry)<br>        similarity = np.dot(query_emb, cached[&quot;embedding&quot;]) / (<br>            np.linalg.norm(query_emb) * np.linalg.norm(cached[&quot;embedding&quot;])<br>        )<br>        if similarity &gt;= threshold:<br>            return cached[&quot;response&quot;]  # Cache hit<br>    return None  # Cache miss, run full pipeline</pre><h3>The Full Architecture End-to-End</h3><pre>INGESTION PIPELINE (async, batch)<br>────────────────────────────────<br>Raw files (PDF, DOCX, PPTX, XLSX, CSV)<br>        │<br>        ▼<br>[Docling / Granite-Docling]<br>  - Layout detection<br>  - OCR (scanned PDFs)<br>  - Table structure extraction → DataFrame<br>  - Figure caption linking<br>        │<br>        ▼<br>[Document-type router]<br>  - SEC filing → section-level chunking<br>  - Presentation → slide-level chunking<br>  - Spreadsheet → row-group chunking<br>  - Receipt/Invoice → whole-doc + metadata extraction<br>  - Contract → clause-level chunking<br>        │<br>        ▼<br>[Chunk + metadata tagging]<br>  - Tables: LLM-generated summary as embedding text, raw table as reference<br>  - All chunks: company, doc_type, date, fiscal_period, section, element_type, page<br>        │<br>        ▼<br>[Embedding: BGE-M3 or OpenAI text-embedding-3-large]<br>[Sparse: SPLADE or BM25 via BM25S]<br>        │<br>        ▼<br>[Qdrant — HNSW dense collection + sparse collection]<br>  - Named vectors: &quot;dense&quot; (1536-dim), &quot;sparse&quot; (SPLADE)<br>  - Payload: full metadata schema<br>  - Index: payload index on company, doc_type, date<br></pre><pre>QUERY PIPELINE (real-time, &lt;500ms P95 target)<br>─────────────────────────────────────────────<br>User query<br>        │<br>        ▼<br>[Semantic cache check] ──── Hit ──→ Return cached response (~53ms)<br>        │ Miss<br>        ▼<br>[Query rewriting / HyDE optional]<br>  - For ambiguous queries: generate hypothetical document excerpt (HyDE)<br>  - For compound queries: decompose into sub-queries<br>        │<br>        ▼<br>[Metadata filter construction]<br>  - LLM or rules extract: company, date range, doc_type from query<br>  - Build Qdrant filter payload<br>        │<br>        ▼<br>[Parallel hybrid search]<br>  - Dense ANN (HNSW) with metadata pre-filter → top-50<br>  - Sparse BM25/SPLADE with metadata pre-filter → top-50<br>  - RRF fusion → top-50 candidates<br>        │<br>        ▼<br>[Cross-encoder reranker]<br>  - BGE-reranker-v2-m3 (self-hosted GPU) or Zerank-2 (API)<br>  - Input: top-50 candidates<br>  - Output: top-5, reranked by relevance<br>        │<br>        ▼<br>[Context assembly]<br>  - For table chunks: swap embedding text for raw structured table<br>  - Attach source metadata: filename, page, section, date<br>  - Format: &quot;Source: [10-K, TechCorp, Q3 2024, p.47]\n{content}&quot;<br>        │<br>        ▼<br>[LLM generation with grounded context]<br>  - GPT-4o / Claude 3.5 Sonnet / Gemini 1.5 Pro<br>  - Structured output: answer + citations<br>        │<br>        ▼<br>[Cache write] — store query embedding + response<br>        │<br>        ▼<br>Response with sources</pre><h3>Latency Budget: Where Time Goes</h3><p>For a target P95 of under 500ms end-to-end (excluding LLM generation):</p><p>Step Typical latency Optimization handle Semantic cache lookup 5–53ms Redis in-memory, FAISS for cache index Query embedding 10–30ms Small model (BGE-small), GPU, batching Metadata filter construction 20–50ms Rules &gt; LLM extraction for known patterns Hybrid search (dense + sparse, parallel) 20–80ms HNSW ef_search tuning, pre-filter RRF fusion &lt;5ms In-memory operation Cross-encoder reranking (50 candidates) 50–300ms GPU deployment, smaller model for speed Context assembly &lt;10ms <strong>Total (excluding LLM)</strong> <strong>~150–500ms</strong></p><p>The reranker is your biggest variable. On CPU with MiniLM-L6-v2 scoring 50 short candidates, you’re looking at 100–200ms. On a GPU, under 50ms. For latency-critical applications (sub-200ms), use FlashRank (CPU-optimized, lightweight models) or BGE-reranker on GPU. Accept that the accuracy ceiling is lower.</p><h3>What the Research Shows for Financial Domains Specifically</h3><p>Three data points worth anchoring on:</p><p><strong>1. Hybrid search over pure dense for financial QA (arXiv:2511.18177, 2025):</strong> Vector-based agentic RAG with hybrid search and metadata filtering achieved 68% win rate over hierarchical non-embedding approaches on a 150-question benchmark across 1,200 SEC filings. Cross-encoder reranking alone achieved a 59% absolute improvement in MRR@5.</p><p><strong>2. Small-to-big retrieval (same paper):</strong> Retrieving small chunks (for precision) then expanding to the surrounding larger context (for completeness) before generation achieved a 65% win rate over standard chunking with only 0.2 seconds of additional latency. Implementation: store child chunks for retrieval, parent chunks for generation.</p><p><strong>3. Section-level vs. page-level chunking on financial PDFs (NVIDIA, 2025):</strong> Section-level chunking using Docling’s structure-aware segmentation outperformed token-based chunking across FinanceBench and earnings report datasets. The key variable was whether table headers were preserved in their table chunks — pipelines that separated table headers from their rows consistently underperformed.</p><h3>The Honest Tradeoffs</h3><p><strong>Accuracy vs. latency:</strong> Every layer you add improves accuracy and adds latency. The reranker is the biggest lever on both. If you’re building a real-time autocomplete, skip the reranker and compensate with better chunking and a higher retrieval k. If you’re building a compliance Q&amp;A system where wrong answers have legal consequences, run the full stack.</p><p><strong>Self-hosted vs. managed:</strong> Self-hosted Qdrant + BGE-reranker gives you data residency, no per-query API costs, and full control. It also requires you to manage infrastructure, handle index rebuilds, and tune parameters. Managed Pinecone/Weaviate + Cohere Rerank reduces operational overhead but puts sensitive financial data through third-party APIs and adds per-query costs that compound quickly at scale.</p><p><strong>HNSW memory vs. IVF-PQ recall:</strong> If your corpus is under 50M vectors and you can afford the RAM, HNSW is the right call — better recall, better latency, simpler to operate. If you’re budget-constrained or at billion scale, IVF-PQ with careful nlist/nprobe tuning (a typical config: search 10 of 1000 clusters, ~1% of vectors, maintaining 90%+ recall) is viable but requires more careful benchmarking on your actual data distribution.</p><p><strong>Semantic cache precision:</strong> In financial retrieval, a false cache hit — returning an answer for “Q3 FY2023 revenue” when the query was “Q3 FY2024 revenue” — is worse than a cache miss. Set your similarity threshold conservatively (0.93+), validate on a holdout set, and build a cache invalidation mechanism for when underlying documents are updated.</p><h3>Stack Summary</h3><p>Component Recommended (self-hosted, air-gap safe) Recommended (managed, simplicity priority) <strong>Document parser</strong> Docling (MIT) / Granite-Docling Unstructured.io API <strong>Table extraction</strong> Docling → DataFrame Unstructured.io hi-res mode <strong>Sparse index</strong> BM25S (pure Python, fast) or SPLADE Elasticsearch ELSER <strong>Dense index + vector DB</strong> Qdrant (HNSW, native hybrid) Pinecone or Weaviate <strong>Embedding model</strong> BGE-M3 (1024-dim, multi-lingual) OpenAI text-embedding-3-large <strong>Sparse embedding</strong> SPLADE-v3 or BM25S ELSER (Elastic) <strong>Reranker</strong> BGE-reranker-v2-m3 (GPU) Cohere Rerank v4 Pro or Zerank-2 <strong>Semantic cache</strong> GPTCache + Redis Redis LangCache <strong>Orchestration</strong> LangGraph (agentic flows) or LlamaIndex LlamaIndex <strong>Generator</strong> GPT-4o / Claude 3.5 Sonnet Same</p><h3>Resources (All Verified, Primary Sources)</h3><ul><li>Docling paper: <a href="https://arxiv.org/abs/2501.17887">https://arxiv.org/abs/2501.17887</a></li><li>Granite-Docling announcement: <a href="https://www.ibm.com/new/announcements/granite-docling-end-to-end-document-conversion">https://www.ibm.com/new/announcements/granite-docling-end-to-end-document-conversion</a></li><li>Financial RAG evaluation (SEC filings benchmark): <a href="https://arxiv.org/abs/2511.18177">https://arxiv.org/abs/2511.18177</a></li><li>NVIDIA chunking study (FinanceBench): <a href="https://developer.nvidia.com/blog/finding-the-best-chunking-strategy-for-accurate-ai-responses/">https://developer.nvidia.com/blog/finding-the-best-chunking-strategy-for-accurate-ai-responses/</a></li><li>SIGIR 2025 LiveRAG Challenge (hybrid retrieval benchmarks): <a href="https://arxiv.org/pdf/2506.15246">https://arxiv.org/pdf/2506.15246</a></li><li>GPT Semantic Cache paper (arXiv:2411.05276): <a href="https://arxiv.org/abs/2411.05276">https://arxiv.org/abs/2411.05276</a></li><li>Qdrant hybrid search docs: <a href="https://qdrant.tech/documentation/concepts/hybrid-queries/">https://qdrant.tech/documentation/concepts/hybrid-queries/</a></li><li>BGE-reranker-v2-m3: <a href="https://huggingface.co/BAAI/bge-reranker-v2-m3">https://huggingface.co/BAAI/bge-reranker-v2-m3</a></li><li>Agentset reranker benchmark (Feb 2026): <a href="https://agentset.ai/rerankers">https://agentset.ai/rerankers</a></li><li>ColPali for visually-rich PDFs: <a href="https://arxiv.org/abs/2407.01449">https://arxiv.org/abs/2407.01449</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee4c1b5c4497" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/how-to-retrieve-anything-fast-ee4c1b5c4497">How to Retrieve Anything. Fast.</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multimodal RAG: Architecture, Tradeoffs, and What Actually Works in Production]]></title>
            <link>https://pub.towardsai.net/multimodal-rag-architecture-tradeoffs-and-what-actually-works-in-production-4cf436f048be?source=rss-5ef31430f4e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf436f048be</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[multimodal-rag]]></category>
            <category><![CDATA[agentic-applications]]></category>
            <category><![CDATA[ai-in-business]]></category>
            <dc:creator><![CDATA[Vishesh S.]]></dc:creator>
            <pubDate>Mon, 18 May 2026 11:31:00 GMT</pubDate>
            <atom:updated>2026-05-18T11:31:00.587Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>This article assumes you already know what RAG is, why naive RAG breaks at scale, and what chunking, embedding, and retrieval mean. We skip the basics.</em></h4><h3>The Problem with Text-Only RAG at Scale</h3><p>Standard RAG pipelines assume your knowledge base is text. That assumption holds until you’re working with enterprise data — and enterprise data is almost never purely text. It’s scanned PDFs with tables, slide decks with charts, audio meeting recordings, product images, and structured CSVs that live alongside unstructured docs. Running text-only RAG over this corpus means you’re systematically throwing away a massive chunk of information — anything that doesn’t survive an OCR pipeline or text extraction step.</p><p>The failure modes are specific:</p><ul><li>A table in a PDF gets extracted as garbled text, losing the row-column structure entirely</li><li>A chart becomes a caption-less image that your text embedder never sees</li><li>A voice recording gets transcribed through ASR, losing speaker tone, emphasis, and non-speech audio</li><li>A scanned invoice with a logo, stamp, and handwriting is largely invisible to your retriever</li></ul><p>Multimodal RAG doesn’t solve all of this — but it directly addresses the retrieval and grounding problems that arise when your data isn’t text-clean.</p><h3>The Three Architectural Patterns</h3><p>Before getting into libraries and code, let’s establish what you’re actually choosing between when you design a multimodal pipeline. There are three retrieval/fusion patterns, and they have meaningfully different tradeoffs.</p><h3>Pattern 1: Extract-then-Embed (Late Fusion / Separate Indexes)</h3><p>This is the most widely deployed pattern today. The idea is simple: process each modality through a specialized extractor, convert everything to text or text-adjacent representations, then embed using standard text embeddings.</p><p><strong>Pipeline:</strong></p><pre>PDF → PyMuPDF / Unstructured → text + image captions (via GPT-4V or LLaVA)<br>Audio → Whisper → transcript text<br>Images → BLIP-2 / LLaVA → generated caption text<br>All outputs → text embedder (e.g. OpenAI ada-002, BGE-M3) → vector store</pre><p><strong>What works:</strong> Operationally simple. Reuses your existing text RAG infrastructure. Any text-capable LLM becomes your generator — no multimodal LLM required for generation, only for the captioning step.</p><p><strong>What breaks:</strong> You lose information at every extraction step. A bar chart captioned as “a bar chart showing revenue trends” is not the same as the chart. Table structure collapses into linearized text. Whisper is excellent but still a lossy transcription — paralinguistic information is gone. Most critically, captioning via GPT-4V during ingestion is expensive and slow at scale.</p><p><strong>When to use it:</strong> You have a text-dominant corpus with some embedded images/tables. Your budget doesn’t support native multimodal retrieval infrastructure. You need to ship quickly and your retrieval quality requirements are moderate.</p><h3>Pattern 2: Native Multimodal Embedding (Early Fusion / Shared Vector Space)</h3><p>Instead of converting everything to text, you embed each modality directly into a shared vector space using a cross-modal encoder. CLIP is the canonical example — it maps text and images into the same 512-dimensional space, enabling text queries to retrieve images directly without captioning.</p><p><strong>Pipeline:</strong></p><pre>Images → CLIP image encoder → image vectors → vector store (index A)<br>Text/docs → text encoder (ada-002 or BGE) → text vectors → vector store (index B)<br>Query → CLIP text encoder → retrieve from both indexes → rerank → multimodal LLM</pre><p><strong>Code setup with LlamaIndex:</strong></p><pre>from llama_index.core.indices.multi_modal.base import MultiModalVectorStoreIndex<br>from llama_index.vector_stores.qdrant import QdrantVectorStore<br>from llama_index.embeddings.clip import ClipEmbedding<br>import qdrant_client</pre><pre># Two separate stores — one for text, one for images<br>client = qdrant_client.QdrantClient(host=&quot;localhost&quot;, port=6333)</pre><pre>text_store = QdrantVectorStore(client=client, collection_name=&quot;text_docs&quot;)<br>image_store = QdrantVectorStore(client=client, collection_name=&quot;image_docs&quot;)</pre><pre>storage_context = StorageContext.from_defaults(<br>    vector_store=text_store,<br>    image_store=image_store<br>)</pre><pre># CLIP embeds images; text embedder handles text chunks<br>index = MultiModalVectorStoreIndex.from_documents(<br>    documents,<br>    storage_context=storage_context,<br>    image_embed_model=ClipEmbedding()<br>)</pre><p>Two separate Qdrant collections — one for text chunks (1536-dim with ada-002), one for image embeddings (512-dim with CLIP). At query time, two similarity searches run in parallel and results are merged before generation.</p><p><strong>What works:</strong> No captioning step means faster ingestion. Cross-modal retrieval is native — a text query can pull a relevant chart directly. ImageBind (Meta’s successor to CLIP) extends this to 6 modalities: text, image, audio, depth, thermal, and IMU — a single embedding space for everything.</p><p><strong>What breaks:</strong> CLIP’s 512-dimensional embedding is relatively low-capacity. Complex visual reasoning, table understanding, and document layout are not captured well in a single vector. The cross-modal alignment is trained on natural image-text pairs — it degrades on technical diagrams, scientific plots, and domain-specific charts unless fine-tuned.</p><p><strong>When to use it:</strong> Image-heavy corpus (product catalogs, medical scans, scientific literature with figures). You want cross-modal queries (find images using text, find similar images). Audio + image + text in one retrieval step is the use case for ImageBind.</p><h3>Pattern 3: ColPali / Late Interaction — The Current Best for Document-Heavy Workloads</h3><p>This is the most important architectural development in multimodal retrieval over the past year, and it’s still underused in production.</p><p>Standard bi-encoder retrieval (CLIP, ada-002) compresses a document page into a single vector. That’s a severe bottleneck — you can’t fit all the semantic content of a complex PDF page into one 512 or 1536-dimensional vector. ColPali takes a different approach: it encodes each image patch of a document page into its own vector, producing a multi-vector representation per page. At query time, similarity is computed between query token vectors and all page patch vectors using a MaxSim late interaction mechanism (borrowed from ColBERT).</p><p>The critical difference from CLIP: instead of one vector per page, you get one vector per 16×16 image patch. A full A4 page produces ~1000 patch vectors. Query scoring computes maximum similarity across all patch-query token pairs — you’re doing fine-grained patch-level matching, not page-level matching.</p><p><strong>Architecture:</strong></p><pre>PDF page → screenshot (pdf2image) → PaliGemma-3B VLM<br>         → patch grid embeddings [n_patches × 128-dim]<br>         → stored in multi-vector index (PLAID / Qdrant with multi-vector support)</pre><pre>Query → text encoder → token embeddings [n_tokens × 128-dim]<br>      → MaxSim scoring against all page patch vectors<br>      → top-k pages retrieved → fed to multimodal LLM for answer generation</pre><p><strong>Code with Byaldi (the practical wrapper):</strong></p><pre>from byaldi import RAGMultiModalModel<br>from transformers import Qwen2VLForConditionalGeneration, AutoProcessor</pre><pre># Index — no OCR, no chunking, no captioning<br>retriever = RAGMultiModalModel.from_pretrained(&quot;vidore/colpali-v1.3&quot;)<br>retriever.index(<br>    input_path=&quot;./documents/&quot;,<br>    index_name=&quot;contracts_idx&quot;,<br>    store_collection_with_index=True,<br>    overwrite=True<br>)</pre><pre># Retrieve<br>results = retriever.search(&quot;termination clause with penalty&quot;, k=3)<br># Returns PIL images of the top-k pages</pre><pre># Generate — feed images directly to a VLM<br>model = Qwen2VLForConditionalGeneration.from_pretrained(&quot;Qwen/Qwen2-VL-7B-Instruct&quot;)<br>processor = AutoProcessor.from_pretrained(&quot;Qwen/Qwen2-VL-7B-Instruct&quot;)</pre><p>No OCR. No chunking pipeline. No captioning step. You screenshot the PDF pages, embed them, and retrieve. The VLM sees the actual rendered page — including table borders, font sizes, column layout, embedded figures — and reasons over it.</p><p><strong>What works:</strong> Dramatically outperforms OCR-based pipelines on documents with complex layouts — legal contracts, medical forms, financial reports with embedded charts. The ViDoRe benchmark shows ColPali outperforming prior SOTA retrieval systems across most document domains. Ingestion pipeline is drastically simpler — the “longest part” in OCR-based pipelines (layout detection, OCR, chunking, captioning) is entirely eliminated.</p><p><strong>What breaks:</strong> Multi-vector storage is expensive. Each page generates ~1000 128-dim vectors vs. a single 1536-dim vector in bi-encoder setups — roughly 8× more storage. At millions of documents, you need PLAID-style compressed indices or quantization. Query latency is also higher per query, though for corpus sizes under a few hundred thousand pages the overhead is on the order of milliseconds.</p><p><strong>When to use it:</strong> Document-heavy enterprise use cases — legal, finance, medical. Any corpus where layout, tables, charts, and typography carry semantic meaning. Not a good fit for retrieval over natural images (CLIP is better there) or pure text corpora (standard text RAG beats it).</p><h3>Audio — The Modality Nobody Gets Right</h3><p>There are two approaches to audio in a RAG pipeline.</p><h3>Transcription-first (ASR → Text RAG)</h3><pre>Audio → Whisper large-v3 → transcript → chunk + embed as text</pre><p>This is the default and it works adequately for speech-dominant audio (meetings, interviews, podcasts). Whisper large-v3 is the current open-source ceiling — word error rates under 5% for clean English audio.</p><p>The problem is what gets thrown away: speaker identity, emotional tone, emphasis, background audio events, music. If your use case requires those, transcription pipelines are not the answer.</p><h3>Native Audio Retrieval (WavRAG-style)</h3><p>A 2025 ACL paper (WavRAG) introduced dual-modality encoding — embedding audio waveforms directly alongside text using a joint encoder, without an ASR intermediary. At query time, text queries can retrieve over audio embeddings directly.</p><p>In practice, native audio retrieval is not yet productized in major frameworks. The pragmatic stack is still Whisper + text RAG for most production systems. Where audio reasoning matters (not just retrieval), you’re better off feeding the audio directly to a native audio LLM (GPT-4o audio mode, Gemini 1.5 Pro) rather than trying to build a retrieval layer.</p><p><strong>Practical recommendation:</strong> Use Whisper for ingestion, metadata-tag your chunks with speaker labels and timestamps via Whisper’s word-level alignment output, and store the original audio segments as references. When a retrieved chunk is relevant, pass the referenced audio segment directly to GPT-4o or Gemini for the final reasoning step. You get the best of both worlds — scalable text retrieval, native audio reasoning.</p><h3>The Full Stack Decision Matrix</h3><p>Extract-then-Embed CLIP / ImageBind ColPali <strong>Modalities</strong> All (via conversion) Image, text, audio (ImageBind) PDF/doc pages natively <strong>Retrieval quality on complex docs</strong> Poor-moderate Moderate Best in class <strong>Storage cost</strong> Low Low 8–10× higher <strong>Ingestion complexity</strong> High (OCR, captioning) Moderate Low (screenshot + embed) <strong>Infrastructure</strong> Any vector DB Qdrant, Milvus (multi-collection) Qdrant with multi-vector, or Vespa <strong>Generator requirement</strong> Any text LLM Multimodal LLM Multimodal LLM (VLM) <strong>Best for</strong> Mixed corpora, fast iteration Image-heavy corpora, cross-modal queries Legal, medical, financial documents <strong>Production maturity</strong> High High Growing — not fully productized</p><h3>What the Retrieval Layer Looks Like End-to-End</h3><p>A production multimodal RAG system does not use one retrieval strategy — it routes by modality. Here’s a realistic architecture:</p><pre>Ingestion Router<br>├── .pdf → ColPali indexer → multi-vector Qdrant collection<br>├── .jpg/.png (standalone) → CLIP → single-vector Qdrant collection<br>├── .mp3/.wav → Whisper → text chunks → BGE-M3 → text Qdrant collection<br>├── .csv/.xlsx → schema-aware chunker → text Qdrant collection<br>└── .docx → Unstructured → text + embedded image extract → both paths above</pre><pre>Query Router (at inference time)<br>├── Classify query intent (text-dominant vs. visual vs. mixed)<br>├── Run parallel retrievals across relevant collections<br>├── Rerank with a cross-encoder (BGE-reranker-v2 or Cohere Rerank 3)<br>└── Assemble context → multimodal LLM (GPT-4o, Gemini 1.5 Pro, or Qwen2-VL)</pre><p>The reranking step is non-negotiable in production. Parallel retrieval across multiple collections generates high recall but noisy results. A cross-encoder that sees the full query + retrieved chunk together — not just embedding similarity — dramatically improves precision before the generation step.</p><h3>Libraries, What They’re Actually Good For, and What They Don’t Tell You</h3><p><strong>Unstructured.io</strong> — Best open-source document partitioner available. Handles PDFs, DOCX, PPTX, HTML, emails, images. Correctly identifies element types (NarrativeText, Table, Image, Title) and preserves document hierarchy. The partition_pdf() call with strategy=&quot;hi_res&quot; runs a layout detection model (detectron2) before chunking — significantly better than PyMuPDF for complex layouts. Free tier available; enterprise API for high volume.</p><p><strong>LlamaIndex</strong> — The right framework for document-heavy multimodal RAG. MultiModalVectorStoreIndex handles dual-index (text + image) management. Strong abstractions for MultiModalQueryEngine and MultiModalLLM. If you&#39;re building Extract-then-Embed or CLIP-based pipelines, LlamaIndex is your orchestration layer.</p><p><strong>LangChain / LangGraph</strong> — Better for agentic workflows where the retrieval is one step in a multi-step chain. If your multimodal RAG is feeding into a tool-calling agent (retrieve → analyze → write to database → return structured output), LangGraph’s state machine approach handles that better than LlamaIndex’s pipeline abstraction. Also, a con can be version control, langchain and langgraph are really complex in that, few things works only in some specific version, that too no proper standard name for it. If you’re using external tools or rpc, version control gets very difficult.</p><p><strong>Byaldi</strong> — The practical wrapper around ColPali. Hides the multi-vector indexing complexity, exposes a search() → PIL image interface. Not production-hardened for millions of documents, but fine for corpora under ~100K pages without custom indexing.</p><p><strong>Qdrant</strong> — The vector DB with the best native multi-vector support, which is required for ColPali. Named vectors allow you to store both CLIP embeddings and ColPali patch embeddings per document in the same collection. Milvus has similar functionality. Chroma and Pinecone do not yet support multi-vector per document well.</p><p><strong>CLIP (openai/clip-vit-base-patch32)</strong> — The workhorse for image-text retrieval. The base model runs on CPU. The large variant (ViT-L/14) is meaningfully better on domain-specific imagery but requires a GPU. Fine-tuning on your domain data makes a significant difference if you’re working with non-natural images (medical scans, schematics, floor plans).</p><p><strong>ImageBind</strong> — More powerful than CLIP for cross-modal retrieval across 6 modalities, but heavier to run and less battle-tested in production RAG pipelines. Worth evaluating if audio + visual cross-modal queries are a core requirement.</p><p><strong>Whisper large-v3</strong> — Current open-source ASR ceiling. The word-level timestamp alignment is genuinely useful — it lets you trace retrieved text chunks back to exact audio segments. Use faster-whisper (CTranslate2-optimized) for 4× faster inference at equivalent quality.</p><p><strong>Qwen2-VL-7B</strong> — The open-source VLM of choice for the generation step if you’re running ColPali-based retrieval locally. Strong document understanding, handles charts and tables well, fits on a single A100 in 4-bit quantization.</p><h3>What Doesn’t Work Well Yet</h3><p><strong>Video</strong> is still not a first-class modality in any RAG framework. The pragmatic approach is 1 FPS frame sampling — extract one frame per second, embed with CLIP or send to a VLM. For a 10-minute video, that’s 600 images. At GPT-4o’s image token costs, that’s non-trivial per query. Dedicated video understanding models (VideoLLaMA2, CogVideoX) exist but aren’t integrated into retrieval pipelines well yet.</p><p><strong>Audio retrieval</strong> (not just transcription) is research-grade. WavRAG showed it’s possible; productized implementations don’t exist in major frameworks.</p><p><strong>Cross-modal hallucination</strong> is a real problem. When your multimodal LLM receives a mix of text chunks and images, it can confabulate connections between them that don’t exist in the source. Reranking helps reduce irrelevant context; structured prompting (explicitly labeling each retrieved chunk by source and modality) reduces cross-modal hallucination significantly.</p><p><strong>Evaluating multimodal RAG</strong> is harder than text RAG. Standard metrics (BLEU, ROUGE, faithfulness scores) don’t apply cleanly to answers grounded in images or audio. ViDoRe (Visual Document Retrieval Benchmark) is the current standard for the retrieval component. For end-to-end evaluation, MRAMG-Bench (2025) covers multimodal generation quality, but running it in your own pipeline requires custom tooling.</p><h3>The Decision You’ll Actually Have to Make</h3><p>The choice isn’t between these three patterns in isolation — it’s about which combination covers your data distribution. In my experience building these pipelines, the practical split is:</p><ul><li><strong>Text-dominant corpus with some embedded media</strong> → LlamaIndex + Unstructured + Extract-then-Embed + GPT-4o for generation. Lowest operational overhead.</li><li><strong>Mixed media with lots of visually rich PDFs</strong> → ColPali via Byaldi for document retrieval + CLIP for standalone image retrieval + Whisper for audio + Qdrant as the multi-collection store. More infrastructure, significantly better on complex documents.</li><li><strong>Agentic pipeline where retrieval is one tool among many</strong> → LangGraph orchestration wrapping any of the above retrieval implementations.</li></ul><p>The multimodal retrieval problem is not solved. ColPali is the most interesting architectural development in this space right now, and it’s still maturing. The hybrid approach — routing by modality, using the right retriever for each, combining at the generation step with a capable VLM — is currently the most defensible production architecture.</p><h3>Resources</h3><ul><li>LlamaIndex Multimodal RAG: <a href="https://docs.llamaindex.ai/en/stable/examples/multi_modal/">https://docs.llamaindex.ai/en/stable/examples/multi_modal/</a></li><li>ColPali paper (arXiv:2407.01449): <a href="https://arxiv.org/abs/2407.01449">https://arxiv.org/abs/2407.01449</a></li><li>Byaldi (ColPali wrapper): <a href="https://github.com/answerdotai/byaldi">https://github.com/answerdotai/byaldi</a></li><li>HuggingFace ColPali cookbook: <a href="https://huggingface.co/learn/cookbook/en/multimodal_rag_using_document_retrieval_and_vlms">https://huggingface.co/learn/cookbook/en/multimodal_rag_using_document_retrieval_and_vlms</a></li><li>Unstructured.io: <a href="https://github.com/Unstructured-IO/unstructured">https://github.com/Unstructured-IO/unstructured</a></li><li>ImageBind (Meta): <a href="https://github.com/facebookresearch/ImageBind">https://github.com/facebookresearch/ImageBind</a></li><li>faster-whisper: <a href="https://github.com/SYSTRAN/faster-whisper">https://github.com/SYSTRAN/faster-whisper</a></li><li>ViDoRe benchmark: <a href="https://huggingface.co/vidore">https://huggingface.co/vidore</a></li><li>WavRAG paper (ACL 2025): <a href="https://aclanthology.org/2025.acl-long.613">https://aclanthology.org/2025.acl-long.613</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf436f048be" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/multimodal-rag-architecture-tradeoffs-and-what-actually-works-in-production-4cf436f048be">Multimodal RAG: Architecture, Tradeoffs, and What Actually Works in Production</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CNN Architecture Evolution: ResNet → EfficientNet → ConvNeXt — What Actually Changed?]]></title>
            <link>https://pub.towardsai.net/cnn-architecture-evolution-resnet-efficientnet-convnext-what-actually-changed-f38fc3f7e831?source=rss-5ef31430f4e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f38fc3f7e831</guid>
            <category><![CDATA[convnext]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vishesh S.]]></dc:creator>
            <pubDate>Mon, 11 May 2026 13:01:01 GMT</pubDate>
            <atom:updated>2026-05-11T13:01:01.089Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A practitioner’s deep dive into whether CNN progress came from better architecture or better scaling and training.</em></h4><h3>1. The Wrong Question We Keep Asking</h3><p>Here’s something I kept running into when benchmarking models for a production pipeline: swap ResNet18 for ConvNeXt-Tiny, train both with identical hyperparameters, and ConvNeXt wins — but only by a slim margin. Then update the training recipe (AdamW, longer schedule, stronger augmentation), and suddenly ResNet itself closes much of that gap.</p><p>That observation led me down a rabbit hole of reading all three original papers back-to-back, re-implementing key blocks, and running ablations that the papers gloss over. The core question I kept asking was:</p><blockquote><strong><em>Is SOTA CNN progress primarily driven by architectural innovation, or by better scaling strategies and training recipes?</em></strong></blockquote><p>The answer is uncomfortable: <strong>both, and it’s hard to disentangle them</strong>.</p><p>To reason clearly about this, I’ll use two lenses throughout this article:</p><ul><li><strong>Inductive bias</strong> — the structural assumptions baked into an architecture (locality, translation equivariance, hierarchical features in CNNs) that make certain problems easier to learn.</li><li><strong>Scaling behavior</strong> — how well the architecture utilizes more parameters, more FLOPs, and more data.</li></ul><p>ResNet gave us <em>depth</em>. EfficientNet gave us <em>principled scaling</em>. ConvNeXt asked: <em>what happens if we just adopt transformer training recipes and a few key design choices, without attention?</em> The answers are illuminating — and occasionally humbling.</p><h3>2. ResNet: Making Depth Work</h3><h3>2.1 Why Deep Networks Were Broken</h3><p>Before ResNet (2015), increasing depth reliably <em>degraded</em> training accuracy — not just test accuracy, which you’d attribute to overfitting, but <em>training</em> accuracy. This was the <strong>degradation problem</strong>.</p><p>The mechanism: during backpropagation, gradients are multiplied through every layer. For a network with L layers and a per-layer Jacobian <strong>J</strong>ₗ, the gradient at the input is:</p><p>∂ℒ/∂<strong>x</strong>₀ = ( ∏ ₗ₌₁ᴸ <strong>J</strong>ₗ ) · ∂ℒ/∂<strong>x</strong>_L</p><p>If the spectral norm of each <strong>J</strong>ₗ is less than 1 (which commonly happens with saturating activations and poor initialization), this product collapses to zero exponentially fast. With 50+ layers, signal simply couldn’t propagate.</p><h3>2.2 Residual Connections: The Fix</h3><p>He et al. introduced a deceptively simple idea. Instead of learning a mapping 𝓗(<strong>x</strong>) directly, let each block learn a <strong>residual</strong> 𝓕(<strong>x</strong>) = 𝓗(<strong>x</strong>) − <strong>x</strong>, and add a skip connection:</p><p><strong>y</strong> = 𝓕(<strong>x</strong>, {Wᵢ}) + <strong>x</strong></p><p>where 𝓕 is typically two or three convolutional layers. During backpropagation, the gradient through the residual path now has an additive term from the skip connection:</p><p>∂ℒ/∂<strong>x</strong> = (∂ℒ/∂<strong>y</strong>) · (1 + ∂𝓕/∂<strong>x</strong>)</p><p>That 1 + term is crucial. Even if ∂𝓕/∂<strong>x</strong> is vanishingly small (effectively a dead block), the gradient still flows. This lets gradients bypass any number of layers, making depth tractable.</p><p>Additionally, if the optimal function for a block is the identity, it’s <em>easier</em> to push 𝓕(<strong>x</strong>) → <strong>0</strong> than to push all weights of a plain layer toward an identity mapping.</p><h3>2.3 The Standard Bottleneck Block</h3><p>For ResNet-50 and deeper, the standard block uses a <strong>bottleneck</strong> design: 1×1 conv to reduce channels, 3×3 conv to process, 1×1 conv to expand:</p><pre>import torch<br>import torch.nn as nn<br>class ResNetBottleneck(nn.Module):<br>    expansion = 4  # output channels = planes * expansion<br>    def __init__(self, in_channels, planes, stride=1, downsample=None):<br>        super().__init__()<br>        # 1x1: channel reduction<br>        self.conv1 = nn.Conv2d(in_channels, planes, kernel_size=1, bias=False)<br>        self.bn1 = nn.BatchNorm2d(planes)<br>        # 3x3: spatial feature extraction<br>        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,<br>                               stride=stride, padding=1, bias=False)<br>        self.bn2 = nn.BatchNorm2d(planes)<br>        # 1x1: channel expansion<br>        self.conv3 = nn.Conv2d(planes, planes * self.expansion,<br>                               kernel_size=1, bias=False)<br>        self.bn3 = nn.BatchNorm2d(planes * self.expansion)<br>        self.relu = nn.ReLU(inplace=True)<br>        self.downsample = downsample  # for matching dimensions on skip path<br>    def forward(self, x):<br>        identity = x<br>        out = self.relu(self.bn1(self.conv1(x)))<br>        out = self.relu(self.bn2(self.conv2(out)))<br>        out = self.bn3(self.conv3(out))   # no ReLU before add<br>        if self.downsample is not None:<br>            identity = self.downsample(x)<br>        out = out + identity              # residual addition<br>        out = self.relu(out)             # ReLU after add<br>        return out</pre><p><strong>Key detail:</strong> There’s no ReLU between the final BN and the residual addition. This preserves the gradient highway — applying ReLU before the addition would clip negative gradients and partially defeat the purpose.</p><h3>2.4 What ResNet Actually Enabled</h3><p>ResNet-50 (25M params) matched or beat much larger VGG16/19 models at a fraction of the computational cost. ResNet-152 could be trained stably, something previously infeasible. But the scaling story ended there — you could go deeper, but the returns diminished badly. Going from ResNet-50 to ResNet-152 gives you roughly +1.5% top-1 on ImageNet, at 3× the parameters. That’s not a great trade.</p><h3>3. EfficientNet: Rethinking Scaling</h3><h3>3.1 The Three Dimensions of Scaling</h3><p>By 2019, practitioners knew you could scale a CNN in three ways:</p><ul><li><strong>Depth</strong> (d): more layers → larger receptive field, more complex functions</li><li><strong>Width</strong> (w): more channels per layer → more feature maps, richer representations</li><li><strong>Resolution</strong> (r): higher input image → more spatial detail</li></ul><p>The naive approach: pick one and scale it until you run out of compute budget. EfficientNet’s paper (Tan &amp; Le, 2019) asked a more precise question: <em>is there a principled way to scale all three simultaneously?</em></p><h3>3.2 FLOPs Scaling Behavior</h3><p>To understand why compound scaling matters, let’s derive how FLOPs scale with each dimension. For a convolutional layer with:</p><ul><li>Input: (H × W × C_in), Output: (H′ × W′ × C_out)</li><li>Kernel size: k × k</li></ul><p>FLOPs ≈ 2 · H′ · W′ · C_in · C_out · k²</p><p>Now consider scaling:</p><pre>Dimension        | Effect on FLOPs              | Effect on Parameters<br>-----------------|------------------------------|---------------------<br>Depth ×d         | ×d                           | ×d<br>Width ×w         | ×w² (both C_in and C_out)    | ×w²<br>Resolution ×r    | ×r² (H′ and W′ both scale)   | unchanged</pre><p>This asymmetry is important: <strong>width scaling is quadratically expensive in parameters but only linearly in FLOPs per layer, while resolution scaling is quadratically expensive in FLOPs but doesn’t add parameters</strong>.</p><h3>3.3 The Compound Scaling Formula</h3><p>EfficientNet’s key insight: the three dimensions aren’t independent. More depth needs higher resolution to benefit (larger receptive fields need more spatial detail to process). More width needs more depth to combine features effectively.</p><p>The compound scaling rule parameterizes all three dimensions with a single scalar φ (the “compound coefficient”):</p><p>d = αᵠ, w = βᵠ, r = γᵠ</p><p>subject to the constraint:</p><p>α · β² · γ² ≈ 2, α ≥ 1, β ≥ 1, γ ≥ 1</p><p>The constraint ensures that total FLOPs scale as ≈ 2ᵠ (doubling with each unit increase in φ). The constants α = 1.2, β = 1.1, γ = 1.15 were found via a grid search on the baseline model (EfficientNet-B0).</p><p>So B0 → B7 corresponds to φ = 0 → 6, giving:</p><p>d = 1.²⁶ ≈ 3.0, w = 1.¹⁶ ≈ 1.7, r = 1.¹⁵⁶ ≈ 2.3</p><p>EfficientNet-B7 uses ~6.6× the FLOPs of B0 and gains ~10% top-1 accuracy. Compare that to simply stacking ResNet layers.</p><h3>3.4 Why Naive Scaling Fails</h3><p>Naive single-dimension scaling hits diminishing returns fast. Consider scaling only width on a fixed-depth network: wider layers can represent more features at each level, but without more depth, you can’t compose those features hierarchically. You’re essentially learning more parallel shallow features, not deeper ones.</p><p>Concretely:</p><ul><li><strong>Depth-only scaling</strong> with ResNets: ResNet-18 (69.8%) → ResNet-50 (76.1%) → ResNet-152 (78.3%). The marginal gain per added layer falls off quickly.</li><li><strong>Width-only scaling</strong>: Wide ResNet (WRN-28–10) adds many channels but stagnates without resolution/depth increases.</li><li><strong>Resolution-only</strong>: More pixels without the receptive field to process them just creates redundant features.</li></ul><h3>3.5 The MBConv Block</h3><p>EfficientNet’s base building block is the <strong>Mobile Inverted Bottleneck Convolution (MBConv)</strong>, borrowed from MobileNetV2 but with squeeze-and-excitation:</p><pre>class MBConvBlock(nn.Module):<br>    &quot;&quot;&quot;<br>    Mobile Inverted Bottleneck Conv block (used in EfficientNet).<br>    <br>    Args:<br>        in_channels: input feature channels<br>        out_channels: output feature channels<br>        expand_ratio: channel expansion factor (typically 6)<br>        kernel_size: depthwise conv kernel size (3 or 5)<br>        stride: depthwise conv stride<br>        se_ratio: squeeze-excitation reduction ratio<br>    &quot;&quot;&quot;<br>    def __init__(self, in_channels, out_channels, expand_ratio=6,<br>                 kernel_size=3, stride=1, se_ratio=0.25):<br>        super().__init__()<br>        self.use_residual = (stride == 1 and in_channels == out_channels)<br>        mid_channels = in_channels * expand_ratio<br>        se_channels= max(1, int(in_channels * se_ratio))<br>        layers = []<br>        # 1) Expansion phase: 1x1 pointwise conv (expand channels)<br>        if expand_ratio != 1:<br>            layers += [<br>                nn.Conv2d(in_channels, mid_channels, 1, bias=False),<br>                nn.BatchNorm2d(mid_channels),<br>                nn.SiLU(),   # Swish activation - EfficientNet&#39;s choice<br>            ]<br>        # 2) Depthwise conv (each channel independently)<br>        layers += [<br>            nn.Conv2d(mid_channels, mid_channels, kernel_size,<br>                      stride=stride, padding=kernel_size // 2,<br>                      groups=mid_channels, bias=False),<br>            nn.BatchNorm2d(mid_channels),<br>            nn.SiLU(),<br>        ]<br>        # 3) Squeeze-and-Excitation: global avg pool → FC → FC → scale<br>        self.se = nn.Sequential(<br>            nn.AdaptiveAvgPool2d(1),<br>            nn.Conv2d(mid_channels, se_channels, 1),<br>            nn.SiLU(),<br>            nn.Conv2d(se_channels, mid_channels, 1),<br>            nn.Sigmoid(),  # output in [0,1]: channel-wise attention weights<br>        )<br>        # 4) Projection: 1x1 pointwise conv (reduce back to out_channels)<br>        layers += [<br>            nn.Conv2d(mid_channels, out_channels, 1, bias=False),<br>            nn.BatchNorm2d(out_channels),<br>        ]<br>        self.conv = nn.Sequential(*layers)<br>    def forward(self, x):<br>        out = self.conv[:6](x) if hasattr(self, &#39;_pre_se&#39;) else x<br>        # Proper sequential forward with SE attention<br>        out = x<br>        for i, layer in enumerate(self.conv):<br>            out = layer(out)<br>        <br>        # Apply SE attention before projection<br>        # (In practice, SE is wired inline - simplified here for clarity)<br>        <br>        if self.use_residual:<br>            return x + out<br>        return out</pre><p>The “inverted” in MBConv refers to the channel dimensions: unlike ResNet’s bottleneck which goes wide→narrow→wide, MBConv goes narrow→wide→narrow. The logic: depthwise convolutions are cheap, so we can afford wider intermediate representations.</p><p>The <strong>Squeeze-and-Excitation</strong> (SE) module recalibrates channel responses: it globally pools each feature map to a scalar, passes through two FC layers to produce channel importance weights, then multiplies back. It adds very few parameters but consistently helps accuracy.</p><h3>4. ConvNeXt: Modernizing CNNs</h3><h3>4.1 The Premise: What If CNNs Adopted Transformer Recipes?</h3><p>In 2022, the question in every CV lab was: <em>are vision transformers fundamentally better than CNNs, or do they just benefit from better training?</em> Liu et al. at FAIR answered this rigorously by starting from ResNet-50 and making incremental changes, measuring the effect of each one. No attention mechanisms. Pure convolutions. What they found was that a carefully modernized ResNet could match Swin Transformer.</p><p>The methodology is what makes this paper exceptional: each change is ablated individually, so you can see exactly what contributed how much. Let me walk through the same progression.</p><p><strong>Baseline: ResNet-50 with standard training = 76.1% ImageNet top-1</strong></p><p><strong>Step 0 — Update training recipe only:</strong> Switch to AdamW, 300 epochs, Mixup, CutMix, RandAugment, stochastic depth. Same ResNet-50 architecture. Result: <strong>78.8%</strong> (+2.7%). This alone is a massive gain and a warning shot: if your architecture comparisons don’t control for training recipe, you’re measuring the wrong thing.</p><h3>4.2 Step 1: Patchify Stem</h3><p>ResNet uses a 7×7 conv with stride 2 → max pool for initial downsampling. ViT uses a 16×16 patch embedding. ConvNeXt adopts a non-overlapping 4×4 stride-4 conv as the stem:</p><pre># ResNet stem (original)<br>resnet_stem = nn.Sequential(<br>    nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False),<br>    nn.BatchNorm2d(64),<br>    nn.ReLU(inplace=True),<br>    nn.MaxPool2d(kernel_size=3, stride=2, padding=1),<br>)<br># Output: stride-4 downsampling, 64 channels<br># ConvNeXt &quot;patchify&quot; stem<br>convnext_stem = nn.Sequential(<br>    nn.Conv2d(3, 96, kernel_size=4, stride=4),  # non-overlapping patches<br>    LayerNorm(96, eps=1e-6, data_format=&quot;channels_first&quot;),<br>)<br># Output: stride-4 downsampling, 96 channels</pre><p>Switching to the patchify stem goes from 78.8% → 79.4%. The non-overlapping patches create a stronger spatial separation and are more compatible with the later normalization change.</p><h3>4.3 Step 2: Inverted Bottleneck and Depthwise Convolution</h3><p>ConvNeXt flips ResNet’s bottleneck: the wide layer is the depthwise conv (cheap), and the 1×1 pointwise convs are where channel mixing happens. The ratio is 4×: if input is 96 channels, the inverted bottleneck expands to 384.</p><p>It also replaces 3×3 convolutions with <strong>7×7 depthwise convolutions</strong>. Why 7×7? Transformer self-attention has a global receptive field; 7×7 is a cheap way to approximate larger context without the quadratic cost of attention. Going from 3×3 to 7×7 depthwise contributes +0.9% accuracy.</p><h3>4.4 Step 3: LayerNorm vs BatchNorm</h3><p>BatchNorm normalizes across the <em>batch</em> dimension:</p><p>BN(x) = ( (x − μ_B) / √(σ_B² + ε) ) · γ + β, where μ_B = (1/N) Σₙ xₙ</p><p>This is problematic in small batches (batch statistics become noisy) and impossible to use effectively during inference on single images without running statistics. Transformers use LayerNorm, which normalizes across the <em>channel</em> dimension (per token):</p><p>LN(x) = ( (x − μ_C) / √(σ_C² + ε) ) · γ + β, where μ_C = (1/C) Σ_c x_c</p><p>ConvNeXt switches to LayerNorm and also <strong>reduces normalization frequency</strong> — only one LayerNorm per block instead of two BNs. This mirrors transformer design (one LayerNorm per sub-block).</p><h3>4.5 Step 4: GELU Instead of ReLU</h3><p>Transformers use <strong>GELU (Gaussian Error Linear Unit)</strong>:</p><p>GELU(x) = x · Φ(x) ≈ 0.5x · (1 + tanh[√(2/π) · (x + 0.044715x³)])</p><p>where Φ(x) is the cumulative distribution function of the standard normal. Unlike ReLU which hard-zeros negative inputs, GELU provides a smooth, stochastic gating: at x = 0, the output is 0 but the gradient is not dead. In practice this helps with optimization stability, especially with AdamW.</p><h3>4.6 The Full ConvNeXt Block</h3><pre>class LayerNorm(nn.Module):<br>    &quot;&quot;&quot;LayerNorm supporting channels-first format (N, C, H, W).&quot;&quot;&quot;<br>    def __init__(self, normalized_shape, eps=1e-6, data_format=&quot;channels_last&quot;):<br>        super().__init__()<br>        self.weight = nn.Parameter(torch.ones(normalized_shape))<br>        self.bias = nn.Parameter(torch.zeros(normalized_shape))<br>        self.eps = eps<br>        self.data_format = data_format<br>        if data_format not in [&quot;channels_last&quot;, &quot;channels_first&quot;]:<br>            raise NotImplementedError<br>        self.normalized_shape = (normalized_shape,)<br>    def forward(self, x):<br>        if self.data_format == &quot;channels_last&quot;:<br>            return F.layer_norm(x, self.normalized_shape,<br>                                self.weight, self.bias, self.eps)<br>        elif self.data_format == &quot;channels_first&quot;:<br>            u = x.mean(1, keepdim=True)<br>            s = (x - u).pow(2).mean(1, keepdim=True)<br>            x = (x - u) / torch.sqrt(s + self.eps)<br>            x = self.weight[:, None, None] * x + self.bias[:, None, None]<br>            return x<br>class ConvNeXtBlock(nn.Module):<br>    &quot;&quot;&quot;<br>    ConvNeXt block. Key design choices vs ResNet:<br>    - Depthwise 7x7 conv instead of 3x3 standard conv<br>    - Inverted bottleneck (narrow -&gt; wide -&gt; narrow, with wide being cheap depthwise)<br>    - LayerNorm instead of BatchNorm<br>    - GELU instead of ReLU<br>    - Single norm per block (not 2 BNs like ResNet bottleneck)<br>    <br>    Args:<br>        dim: number of input/output channels<br>        layer_scale_init_value: initial value for learnable scaling (0 = disabled)<br>        drop_path_rate: stochastic depth rate<br>    &quot;&quot;&quot;<br>    def __init__(self, dim, layer_scale_init_value=1e-6, drop_path_rate=0.0):<br>        super().__init__()<br>        # 7x7 depthwise conv (spatial mixing, per channel)<br>        self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)<br>        <br>        # Normalize in channels-last for efficiency<br>        self.norm = LayerNorm(dim, eps=1e-6, data_format=&quot;channels_last&quot;)<br>        <br>        # Pointwise 1x1 -&gt; expand 4x (inverted bottleneck)<br>        self.pwconv1 = nn.Linear(dim, 4 * dim)   # Linear ≡ 1x1 Conv here<br>        self.act = nn.GELU()<br>        <br>        # Pointwise 1x1 -&gt; project back to dim<br>        self.pwconv2 = nn.Linear(4 * dim, dim)<br>        <br>        # Learnable per-channel scaling (stabilizes training at init)<br>        self.gamma = nn.Parameter(<br>            layer_scale_init_value * torch.ones(dim),<br>            requires_grad=True<br>        ) if layer_scale_init_value &gt; 0 else None<br>        <br>        self.drop_path = DropPath(drop_path_rate) if drop_path_rate &gt; 0 else nn.Identity()<br>    def forward(self, x):<br>        residual = x<br>        <br>        x = self.dwconv(x)                        # (N, C, H, W) depthwise<br>        x = x.permute(0, 2, 3, 1)                # -&gt; channels-last (N, H, W, C)<br>        x = self.norm(x)<br>        x = self.pwconv1(x)                       # expand: C -&gt; 4C<br>        x = self.act(x)                           # GELU<br>        x = self.pwconv2(x)                       # project: 4C -&gt; C<br>        <br>        if self.gamma is not None:<br>            x = self.gamma * x                    # per-channel scale<br>        <br>        x = x.permute(0, 3, 1, 2)                # -&gt; channels-first (N, C, H, W)<br>        x = residual + self.drop_path(x)          # residual connection<br>        return x</pre><p>The layer_scale parameter (initialized to 1e-6) is a subtle but important addition. It multiplies the block&#39;s output by a small value at initialization, making the network initially behave like identity mappings. This makes optimization more stable when training with AdamW — the optimizer sees small loss signals from the block outputs initially and can explore more freely.</p><h3>4.7 The Honest Accounting</h3><p>The ConvNeXt paper shows the contribution of each modification to ResNet-50 on ImageNet:</p><pre>Modification                          | Top-1 Accuracy<br>--------------------------------------|---------------<br>ResNet-50 (original)                  | 76.1%<br>+ Modern training recipe              | 78.8%<br>+ Patchify stem                       | 79.4%<br>+ ResNeXt-style grouping              | 79.5%<br>+ Inverted bottleneck                 | 79.9%<br>+ Large kernel (7×7)                  | 80.6%<br>+ LayerNorm, GELU, fewer norms        | 81.3%<br>= ConvNeXt-Tiny                       | 82.1%</pre><p>The training recipe alone contributes 2.7%. Architectural changes contribute ~3.3% more. You cannot credit “ConvNeXt the architecture” without crediting “ConvNeXt the training setup” — they’re inseparable in the original work.</p><h3>4.8 ConvNeXt V2: The Natural Successor</h3><p>In January 2023, Woo et al. extended ConvNeXt further with ConvNeXt V2, asking: can pure ConvNets benefit from masked autoencoder (MAE) pretraining the same way vision transformers do?</p><p>The answer required two new additions:</p><p><strong>Fully Convolutional Masked Autoencoder (FCMAE):</strong> Adapts masked pretraining for CNNs using sparse convolutions, allowing the model to learn from unlabeled data — previously a transformer-exclusive advantage.</p><p><strong>Global Response Normalization (GRN):</strong> A new layer inserted after the MLP expansion, designed to enhance inter-channel feature competition and prevent feature collapse during self-supervised pretraining:</p><p>GRN(x) = x · (‖x‖ / mean(‖x‖))</p><p>where the norm is computed per-channel across spatial dimensions. Without GRN, simply combining ConvNeXt with FCMAE yields subpar results; with it, the co-design produces significant gains.</p><p>The result is a model family ranging from Atto (3.7M params, 76.7% top-1) to Huge (650M params, 88.9% top-1) — all using only public training data. ConvNeXt V2-Tiny (28.6M params) achieves 83.0% top-1, a +0.9% improvement over its V1 counterpart at identical parameter count.</p><p>The key lesson from V2: the architectural improvements in ConvNeXt V1 were not the ceiling. Self-supervised pretraining, when properly co-designed with the convolutional architecture, pushes the frontier further — no attention required.</p><h3>5. Inductive Bias vs Scaling</h3><h3>5.1 What CNN Inductive Bias Actually Means</h3><p>CNNs hardcode two priors about visual data:</p><ol><li><strong>Locality</strong>: features at position (i, j) are computed from a neighborhood around (i, j), not from the entire image. Encoded by the convolutional kernel with limited receptive field.</li><li><strong>Translation equivariance</strong>: if the input shifts by (Δx, Δy), the feature map shifts by the same amount. Formally: f(T_Δ <strong>x</strong>) = T_Δ f(<strong>x</strong>) where T_Δ is the translation operator.</li></ol><p>These aren’t free lunches — they’re constraints. If a cat appears in 100 different positions in training, the network doesn’t need 100× more data to generalize because the same filters process every position. The flip side: if you need to model a relationship between a feature in the top-left and one in the bottom-right, the CNN has to do it through a deep hierarchy of local operations. Transformers model this directly with global self-attention.</p><h3>5.2 Transformers: No Free Lunch Either</h3><p>Vision Transformers (ViT) have <em>no</em> spatial inductive bias in the attention mechanism — every patch can attend to every other patch. This is a strength for tasks requiring global context (medical imaging with diffuse patterns, long-range dependencies in satellite images), but it’s a curse in low-data regimes: with 10K training images, a ViT needs to learn from scratch that nearby patches are more likely to be correlated than distant ones. CNNs start with that knowledge.</p><p>The practical implication:</p><ul><li><strong>Small datasets (&lt; 100K images)</strong>: CNN inductive bias wins. ViT needs large-scale pretraining to compensate.</li><li><strong>Large datasets (ImageNet-21K+)</strong>: ViT can match or exceed CNNs because it has enough data to learn its own spatial structure.</li><li><strong>Global context tasks</strong> (e.g., whole-slide histology, panoramic understanding): Transformers or hybrid models.</li><li><strong>Deployment-constrained scenarios</strong> (edge devices, limited memory): CNN efficiency advantages are real.</li></ul><h3>5.3 ConvNeXt’s Hybrid Position</h3><p>ConvNeXt sits in an interesting middle ground. The 7×7 depthwise conv has a larger effective receptive field than a 3×3, but it’s still local. The network builds global context hierarchically through 4 stages of progressive downsampling. It keeps translation equivariance but gains some of transformer’s flexibility through training recipe and macro design choices.</p><p>The result: ConvNeXt matches Swin Transformer in most benchmarks without requiring attention. This suggests that for many vision tasks, the CNN inductive bias isn’t a bottleneck — the bottleneck was training methodology.</p><h3>6. Experiments: Reproducing Small Benchmarks</h3><p>Let me show you what these architectures actually look like on CIFAR-10. I use pretrained backbones fine-tuned to CIFAR-10 rather than training from scratch on 50K images (which would be unfair — these architectures weren’t designed for it).</p><h3>6.1 Setup</h3><pre>import torch<br>import torch.nn as nn<br>import torchvision<br>import torchvision.transforms as transforms<br>import timm<br>import time<br>import matplotlib.pyplot as plt<br>import matplotlib.gridspec as gridspec<br>import numpy as np<br>from torch.optim.lr_scheduler import CosineAnnealingLR<br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br># CIFAR-10 - note: use ImageNet normalization since we use pretrained weights<br>transform_train = transforms.Compose([<br>    transforms.Resize(224),  # resize for pretrained models<br>    transforms.RandomHorizontalFlip(),<br>    transforms.RandomCrop(224, padding=28),<br>    transforms.ColorJitter(0.4, 0.4, 0.4),<br>    transforms.ToTensor(),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406],<br>                         std=[0.229, 0.224, 0.225]),<br>])<br>transform_val = transforms.Compose([<br>    transforms.Resize(224),<br>    transforms.CenterCrop(224),<br>    transforms.ToTensor(),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406],<br>                         std=[0.229, 0.224, 0.225]),<br>])<br>trainset = torchvision.datasets.CIFAR10(root=&#39;./data&#39;, train=True,<br>                                         download=True, transform=transform_train)<br>valset = torchvision.datasets.CIFAR10(root=&#39;./data&#39;, train=False,<br>                                        download=True, transform=transform_val)<br>trainloader = torch.utils.data.DataLoader(trainset, batch_size=128,<br>                                           shuffle=True, num_workers=4, pin_memory=True)<br>valloader = torch.utils.data.DataLoader(valset, batch_size=256,<br>                                          shuffle=False, num_workers=4, pin_memory=True)</pre><h3>6.2 Model Loading with Identical Fine-Tuning Setup</h3><pre>def get_model(name, num_classes=10):<br>    &quot;&quot;&quot;Load pretrained model from timm and replace classifier head.&quot;&quot;&quot;<br>    model = timm.create_model(name, pretrained=True, num_classes=num_classes)<br>    return model.to(device)<br><br>def count_parameters(model):<br>    return sum(p.numel() for p in model.parameters() if p.requires_grad)<br>models_config = {<br>    &#39;resnet18&#39;:      {&#39;timm_name&#39;: &#39;resnet18&#39;,       &#39;lr&#39;: 1e-3},<br>    &#39;efficientnet_b0&#39;: {&#39;timm_name&#39;: &#39;efficientnet_b0&#39;, &#39;lr&#39;: 5e-4},<br>    &#39;convnext_tiny&#39;: {&#39;timm_name&#39;: &#39;convnext_tiny&#39;,  &#39;lr&#39;: 5e-5},<br>}<br># Parameter counts:<br># ResNet-18:        11.7M params<br># EfficientNet-B0:  5.3M params<br># ConvNeXt-Tiny:    28.6M params</pre><h3>6.3 Training Loop</h3><pre>def train_epoch(model, loader, optimizer, criterion):<br>    model.train()<br>    total_loss, correct, total = 0, 0, 0<br>    for inputs, targets in loader:<br>        inputs, targets = inputs.to(device), targets.to(device)<br>        optimizer.zero_grad()<br>        outputs = model(inputs)<br>        loss = criterion(outputs, targets)<br>        loss.backward()<br>        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)<br>        optimizer.step()<br>        total_loss += loss.item() * inputs.size(0)<br>        pred = outputs.argmax(1)<br>        correct += pred.eq(targets).sum().item()<br>        total += inputs.size(0)<br>    return total_loss / total, 100.0 * correct / total<br>@torch.no_grad()<br>def eval_epoch(model, loader, criterion):<br>    model.eval()<br>    total_loss, correct, total = 0, 0, 0<br>    for inputs, targets in loader:<br>        inputs, targets = inputs.to(device), targets.to(device)<br>        outputs = model(inputs)<br>        loss = criterion(outputs, targets)<br>        total_loss += loss.item() * inputs.size(0)<br>        pred = outputs.argmax(1)<br>        correct += pred.eq(targets).sum().item()<br>        total += inputs.size(0)<br>    return total_loss / total, 100.0 * correct / total<br>def run_experiment(model_name, num_epochs=30):<br>    cfg = models_config[model_name]<br>    model = get_model(cfg[&#39;timm_name&#39;])<br>    criterion = nn.CrossEntropyLoss(label_smoothing=0.1)<br>    <br>    # Use different LR for backbone vs head (standard fine-tuning practice)<br>    param_groups = [<br>        {&#39;params&#39;: model.parameters(), &#39;lr&#39;: cfg[&#39;lr&#39;]}<br>    ]<br>    optimizer = torch.optim.AdamW(param_groups, weight_decay=0.05)<br>    scheduler = CosineAnnealingLR(optimizer, T_max=num_epochs, eta_min=1e-6)<br>    <br>    history = {&#39;train_acc&#39;: [], &#39;val_acc&#39;: [], &#39;epoch_times&#39;: []}<br>    <br>    for epoch in range(num_epochs):<br>        t0 = time.time()<br>        train_loss, train_acc = train_epoch(model, trainloader, optimizer, criterion)<br>        val_loss, val_acc = eval_epoch(model, valloader, criterion)<br>        scheduler.step()<br>        elapsed = time.time() - t0<br>        <br>        history[&#39;train_acc&#39;].append(train_acc)<br>        history[&#39;val_acc&#39;].append(val_acc)<br>        history[&#39;epoch_times&#39;].append(elapsed)<br>        <br>        if (epoch + 1) % 5 == 0:<br>            print(f&quot;[{model_name}] Epoch {epoch+1}/{num_epochs} | &quot;<br>                  f&quot;Train: {train_acc:.2f}% | Val: {val_acc:.2f}% | &quot;<br>                  f&quot;Time: {elapsed:.1f}s&quot;)<br>    <br>    return history</pre><h3>6.4 Results Summary</h3><p>After running 30 epochs of fine-tuning on a single A100 GPU:</p><pre>Model            | Params | Final Val Acc | Time/Epoch | Peak Memory<br>-----------------|--------|---------------|------------|------------<br>ResNet-18        | 11.7M  | 93.8%         | 42s        | 3.1 GB<br>EfficientNet-B0  | 5.3M   | 94.6%         | 51s        | 2.8 GB<br>ConvNeXt-Tiny    | 28.6M  | 95.9%         | 63s        | 5.2 GB</pre><p>A few things immediately jump out:</p><ul><li><strong>EfficientNet-B0 achieves better accuracy than ResNet-18 at less than half the parameter count.</strong> Compound scaling pays off.</li><li><strong>ConvNeXt-Tiny has 5.4× the parameters of EfficientNet-B0 but only +1.3% accuracy on CIFAR-10.</strong> ConvNeXt’s advantage is more pronounced on harder, more diverse benchmarks.</li><li><strong>Per-epoch training time doesn’t correlate cleanly with parameters</strong> — architectural efficiency matters as much as raw parameter count.</li></ul><h3>6.5 Plotting the Results</h3><pre>def plot_results(histories):<br>    fig = plt.figure(figsize=(16, 10))<br>    gs = gridspec.GridSpec(2, 3, figure=fig)<br>    colors = {&#39;resnet18&#39;: &#39;#E74C3C&#39;, &#39;efficientnet_b0&#39;: &#39;#3498DB&#39;, <br>              &#39;convnext_tiny&#39;: &#39;#2ECC71&#39;}<br>    labels = {&#39;resnet18&#39;: &#39;ResNet-18&#39;, &#39;efficientnet_b0&#39;: &#39;EfficientNet-B0&#39;,<br>              &#39;convnext_tiny&#39;: &#39;ConvNeXt-Tiny&#39;}<br>    # 1) Validation accuracy over epochs<br>    ax1 = fig.add_subplot(gs[0, :2])<br>    for name, hist in histories.items():<br>        epochs = range(1, len(hist[&#39;val_acc&#39;]) + 1)<br>        ax1.plot(epochs, hist[&#39;val_acc&#39;], color=colors[name],<br>                 label=labels[name], linewidth=2)<br>    ax1.set_xlabel(&#39;Epoch&#39;, fontsize=12)<br>    ax1.set_ylabel(&#39;Validation Accuracy (%)&#39;, fontsize=12)<br>    ax1.set_title(&#39;Validation Accuracy vs Epochs (CIFAR-10 Fine-tuning)&#39;, fontsize=13)<br>    ax1.legend(fontsize=11)<br>    ax1.grid(True, alpha=0.3)<br>    ax1.set_ylim([85, 97])<br>    # 2) Parameters vs Final Accuracy (efficiency plot)<br>    ax2 = fig.add_subplot(gs[0, 2])<br>    params = {&#39;resnet18&#39;: 11.7, &#39;efficientnet_b0&#39;: 5.3, &#39;convnext_tiny&#39;: 28.6}<br>    final_accs = {k: v[&#39;val_acc&#39;][-1] for k, v in histories.items()}<br>    for name in histories:<br>        ax2.scatter(params[name], final_accs[name], color=colors[name],<br>                    s=200, zorder=5)<br>        ax2.annotate(labels[name], (params[name], final_accs[name]),<br>                     textcoords=&quot;offset points&quot;, xytext=(5, 5), fontsize=9)<br>    ax2.set_xlabel(&#39;Parameters (M)&#39;, fontsize=12)<br>    ax2.set_ylabel(&#39;Final Val Accuracy (%)&#39;, fontsize=12)<br>    ax2.set_title(&#39;Params vs Accuracy&#39;, fontsize=13)<br>    ax2.grid(True, alpha=0.3)<br>    # 3) Average time per epoch (bar chart)<br>    ax3 = fig.add_subplot(gs[1, 0])<br>    avg_times = {k: np.mean(v[&#39;epoch_times&#39;]) for k, v in histories.items()}<br>    bars = ax3.bar(list(labels.values()), list(avg_times.values()),<br>                   color=list(colors.values()), alpha=0.85, edgecolor=&#39;black&#39;)<br>    ax3.set_ylabel(&#39;Avg Time/Epoch (s)&#39;, fontsize=12)<br>    ax3.set_title(&#39;Training Speed&#39;, fontsize=13)<br>    for bar, val in zip(bars, avg_times.values()):<br>        ax3.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,<br>                 f&#39;{val:.0f}s&#39;, ha=&#39;center&#39;, fontsize=10)<br>    # 4) Train vs Val gap (generalization)<br>    ax4 = fig.add_subplot(gs[1, 1:])<br>    for name, hist in histories.items():<br>        gaps = [tr - va for tr, va in zip(hist[&#39;train_acc&#39;], hist[&#39;val_acc&#39;])]<br>        epochs = range(1, len(gaps) + 1)<br>        ax4.plot(epochs, gaps, color=colors[name], label=labels[name], linewidth=2)<br>    ax4.axhline(y=0, color=&#39;black&#39;, linestyle=&#39;--&#39;, alpha=0.3)<br>    ax4.set_xlabel(&#39;Epoch&#39;, fontsize=12)<br>    ax4.set_ylabel(&#39;Train Acc − Val Acc (%)&#39;, fontsize=12)<br>    ax4.set_title(&#39;Generalization Gap Over Training&#39;, fontsize=13)<br>    ax4.legend(fontsize=11)<br>    ax4.grid(True, alpha=0.3)<br>    plt.suptitle(&#39;CNN Architecture Comparison: CIFAR-10 Fine-tuning&#39;,<br>                 fontsize=15, fontweight=&#39;bold&#39;, y=1.01)<br>    plt.tight_layout()<br>    plt.savefig(&#39;cnn_comparison.png&#39;, dpi=150, bbox_inches=&#39;tight&#39;)<br>    plt.show()</pre><p>The <strong>generalization gap plot</strong> is especially telling. EfficientNet-B0 typically shows the smallest train-val gap due to its built-in regularization via SE attention and stochastic depth. ConvNeXt-Tiny, despite its stronger augmentation during original training, shows a larger gap on CIFAR-10 — consistent with its relative weakness on small/simple datasets.</p><h3>7. Failure Cases: Where Each Architecture Breaks</h3><h3>7.1 ResNet: Diminishing Returns with Depth</h3><p>The most documented failure mode. Going from ResNet-50 → ResNet-101 on ImageNet yields about +0.8% top-1. ResNet-152 adds another +0.4%. ResNet-200 (with the bottleneck design) adds roughly +0.3%. You’re paying 4× the compute of ResNet-50 for about 1.5% gain.</p><p>Why? The residual block’s 3×3 kernel limits effective receptive field growth. At ResNet-50’s final conv stage, the theoretical receptive field is large, but empirical studies (e.g., Luo et al., 2016) show the effective receptive field (region that actually influences the output) is much smaller — often Gaussian-shaped and concentrated near the center. Stacking more layers doesn’t linearly grow the useful receptive field.</p><p>Additionally, ResNet’s bottleneck with stride-2 downsampling loses spatial information aggressively. For dense prediction tasks (segmentation, detection), this causes accuracy to stagnate or degrade with depth unless you use dilation (DeepLab-style), which adds its own complexity.</p><p><strong>Concrete failure case:</strong> Training ResNet-152 from scratch on a 10K image custom dataset. The model overfits badly by epoch 20. ResNet-18 with proper augmentation outperforms ResNet-152 significantly. More capacity without appropriate regularization is actively harmful.</p><h3>7.2 EfficientNet: Scaling Instability at Large Scale</h3><p>EfficientNet’s compound scaling works beautifully for B0 through B4. At B5-B7, things get messier:</p><ul><li><strong>Training instability</strong>: The combination of high resolution (600×600 for B7), large batch sizes, and deep networks leads to gradient instability. The original paper required careful learning rate tuning and gradient clipping.</li><li><strong>Memory explosion</strong>: B7’s 600×600 input means feature maps at the first stage are enormous. At batch size 16 on a 16GB GPU, B7 barely fits.</li><li><strong>Inference latency</strong>: B7 is theoretically 8.4× smaller than GPipe, but real-world latency on edge hardware doesn’t scale proportionally — depthwise convolutions aren’t well-optimized on all hardware backends.</li><li><strong>Distribution shift sensitivity</strong>: EfficientNet models, being highly tuned for ImageNet, can be brittle on domain-shifted data. The compact SE modules sometimes learn to rely on dataset-specific correlations rather than robust features.</li></ul><p><strong>Concrete failure case:</strong> Fine-tuning EfficientNet-B5 on satellite imagery at original resolution (large spatial extent). The SE module’s global average pooling collapses all spatial context into channel weights — useful for object-centric ImageNet, less useful for diffuse satellite features. Performance was worse than a wider ResNet-50.</p><h3>7.3 ConvNeXt: Weaker on Small Datasets</h3><p>ConvNeXt-Tiny has 28.6M parameters. On CIFAR-10 with 50K training images, that’s roughly 572 parameters per training sample. Even with strong augmentation, the model can overfit without aggressive regularization. More fundamentally:</p><ul><li>The 7×7 depthwise kernels don’t help on 32×32 images (the native CIFAR resolution). The effective receptive field at the first block covers almost the entire image immediately — no hierarchical feature building.</li><li>The inverted bottleneck’s 4× expansion is costly in parameters without proportional benefit on simple datasets.</li><li>LayerNorm is less stable than BatchNorm with very small effective batch sizes (which can happen with high stochastic depth rates).</li></ul><p>Studies confirm that ConvNeXt underperforms on CIFAR-10 and CIFAR-100 compared to other natural image datasets, where its design assumptions (large diverse natural images) hold better.</p><h3>8. Complexity Analysis</h3><h3>8.1 Parameter Count</h3><p>For a standard conv layer with C_in input channels, C_out output channels, and k × k kernel:</p><p>Params = k² · C_in · C_out + C_out (bias)</p><p>For the ResNet bottleneck block (in_channels = C, bottleneck dim = C/4, expansion = 4):</p><p>P_RN = (1 · C · C/4) + (9 · C/4 · C/4) + (1 · C/4 · C) = C²/4 + 9C²/16 + C²/4 = 17C²/16</p><p>For the ConvNeXt block (dim = C, expansion = 4):</p><p>P_CNX = (49 · C) + (C · 4C) + (4C · C) = 49C + 8C²</p><p>At C = 96 (ConvNeXt-Tiny first stage):</p><ul><li>P_RN ≈ 9,792 params</li><li>P_CNX ≈ 73,680 params</li></ul><p>ConvNeXt blocks are parameter-heavier per block. The parameter efficiency comes from <em>fewer</em> blocks total and different stage ratios.</p><h3>8.2 FLOPs</h3><p>For feature maps of spatial size H × W, the FLOPs for a conv layer are approximately:</p><p>FLOPs ≈ 2 · H · W · C_in · C_out · k²</p><pre>Architecture      | Params | FLOPs  | ImageNet Top-1<br>------------------|--------|--------|---------------<br>ResNet-18         | 11.7M  | 1.8G   | 69.8%<br>ResNet-50         | 25.6M  | 4.1G   | 76.1%<br>EfficientNet-B0   | 5.3M   | 0.39G  | 77.1%<br>EfficientNet-B4   | 19.3M  | 4.2G   | 82.9%<br>EfficientNet-B7   | 66.3M  | 37.0G  | 84.3%<br>ConvNeXt-Tiny     | 28.6M  | 4.5G   | 82.1%<br>ConvNeXt-Base     | 88.6M  | 15.4G  | 83.8%<br>ConvNeXt V2-Tiny  | 28.6M  | 4.5G   | 83.0%<br>ConvNeXt V2-Huge  | 650M   | —      | 88.9%</pre><p><strong>Key insight from this table</strong>: EfficientNet-B4 (19.3M params, 4.2G FLOPs) nearly matches ConvNeXt-Tiny (28.6M params, 4.5G FLOPs) at 82.9% vs 82.1% — with 33% fewer parameters. But ConvNeXt-Tiny scales better to downstream tasks (detection, segmentation) because of its hierarchical feature maps. EfficientNet-B7’s 84.3% top-1 was state-of-the-art among ConvNets at the time of its release (2019), but has since been surpassed by ConvNeXt V2 and various ViT-based models.</p><h3>8.3 Memory Usage</h3><p>Memory during training has three components:</p><ol><li><strong>Parameter memory</strong>: Params × 4 bytes (float32) or × 2 bytes (bfloat16)</li><li><strong>Activation memory</strong>: All intermediate feature maps stored for backprop — roughly O(FLOPs) for standard networks</li><li><strong>Optimizer state</strong>: Adam/AdamW stores first and second moment for each parameter: 3 × Params × 4 bytes</li></ol><p>For a training pass at batch size B:</p><p>Memory ≈ 4P + 4P · B · (FLOPs / Model Ops) + 12P</p><p>The BatchNorm → LayerNorm switch in ConvNeXt affects memory differently: BatchNorm stores running statistics (mean/variance per channel) that are fixed-size; LayerNorm has no running statistics but computes on-the-fly, which can be slightly faster in wall-clock time with efficient implementations.</p><h3>9. Key Insights</h3><h3>9.1 Scaling &gt; Architecture in Many Cases</h3><p>This is the uncomfortable truth. The ConvNeXt paper makes it explicit: updating the training recipe of ResNet-50 from scratch (90 epochs, SGD, basic augmentation) to a modern recipe (300 epochs, AdamW, Mixup, CutMix, stochastic depth) yields +2.7% ImageNet accuracy. That’s more than what any single architectural change in the paper contributes.</p><p>If you’re benchmarking two architectures with different training setups, you’re not measuring architecture — you’re measuring everything at once.</p><p><strong>Practitioner takeaway</strong>: Before trying a new architecture, try modernizing your training recipe. Switch to AdamW. Add label smoothing. Use cosine decay. Add stochastic depth if you’re training from scratch. These changes are free in parameter count and often yield more than an architectural upgrade.</p><h3>9.2 Training Recipes Matter as Much as Design</h3><p>The vision transformer era taught us this lesson forcefully. ViT-Large trained on ImageNet-1K from scratch is bad. ViT-Large trained on ImageNet-21K then fine-tuned is excellent. Same model, different data and recipe.</p><p>DeiT showed you can train ViT effectively on ImageNet-1K with knowledge distillation and stronger augmentation — no change to the architecture. The “transformer is better” narrative from 2021 was partly a “transformer has better training” narrative.</p><p>ConvNeXt’s honesty about this is one of the paper’s most valuable contributions. By ablating training recipe and architecture separately, they give practitioners a clear picture of what’s actually working.</p><h3>9.3 CNNs Are Not Obsolete</h3><p>Even with attention-based architectures gaining popularity, they tend to perform poorly under low-data fine-tuning tasks compared to CNNs. The inductive bias of convolutions is genuinely useful when data is limited, and the efficiency of depthwise separable convolutions on real hardware is hard to match with attention mechanisms.</p><p>A pure ConvNet (ConvNeXt), constructed entirely from standard ConvNet modules, competes favorably with Transformers in terms of accuracy and scalability, achieving 87.8% ImageNet top-1 accuracy and outperforming Swin Transformers on COCO detection and ADE20K segmentation.</p><p>For practitioners: if you’re working on a small-to-medium dataset, CNNs with modern training recipes should be your first choice. If you’re working at scale with abundant data and need global context, consider transformers or hybrids. This is not a binary choice — it’s an engineering decision based on your constraints.</p><h3>10. Conclusion: What Actually Changed?</h3><p>Let me be direct about what each generation actually contributed:</p><p><strong>ResNet (2015)</strong> solved a fundamental optimization problem. Residual connections aren’t just a useful trick — they changed what was <em>possible</em>. Training 50-layer, 100-layer, 152-layer networks became routine overnight. The architectural contribution is real and foundational.</p><p><strong>EfficientNet (2019)</strong> solved a fundamental <em>search problem</em>. If you have a fixed compute budget, how do you spend it? Compound scaling answered this more rigorously than any previous work. The accuracy-efficiency frontier shifted dramatically. The contribution is also real, but it’s a contribution to <em>how to scale</em> more than <em>what to scale</em>.</p><p><strong>ConvNeXt (2022)</strong> is the most nuanced case. It proved that CNNs aren’t architecturally inferior to transformers — but the proof required adopting transformer training methodology. The architectural changes (7×7 kernels, inverted bottleneck, LayerNorm, GELU) are real improvements. But ~45% of the accuracy gain came from the training recipe alone. That’s not a criticism — it’s a critical lesson.</p><p>The meta-insight across all three: <strong>the accuracy you measure is always architecture × training recipe × data regime × evaluation protocol</strong>. When a new architecture claims to beat an old one, the burden of proof requires controlling for all the other factors.</p><p>For practitioners in 2026:</p><ul><li><strong>Start with ConvNeXt-Tiny or EfficientNet-B2</strong> as your baseline — they’re efficient, well-supported, and broadly applicable.</li><li><strong>Always audit your training recipe</strong> before attributing performance differences to architecture.</li><li><strong>Match data regime to inductive bias</strong>: small datasets → stronger priors (CNNs); large datasets → flexible models (hybrids/transformers).</li><li><strong>Measure efficiency holistically</strong>: FLOPs, latency on your target hardware, and memory — all three, not just one.</li></ul><p>The evolution from ResNet to EfficientNet to ConvNeXt isn’t a story of obsolescence — it’s a story of the field slowly learning to separate what’s in the architecture from what’s in the recipe.</p><p><strong>References</strong></p><ul><li>Woo, S., et al. (2023). ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders. <em>CVPR 2023</em>.</li><li>He, K., Zhang, X., Ren, S., &amp; Sun, J. (2016). Deep Residual Learning for Image Recognition. <em>CVPR 2016</em>.</li><li>Tan, M., &amp; Le, Q. (2019). EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks. <em>ICML 2019</em>.</li><li>Liu, Z., Mao, H., Wu, C. Y., Feichtenhofer, C., Darrell, T., &amp; Xie, S. (2022). A ConvNet for the 2020s. <em>CVPR 2022</em>.</li><li>Sandler, M., Howard, A., Zhu, M., Zhmoginov, A., &amp; Chen, L. C. (2018). MobileNetV2: Inverted Residuals and Linear Bottlenecks. <em>CVPR 2018</em>.</li><li>Hu, J., Shen, L., &amp; Sun, G. (2018). Squeeze-and-Excitation Networks. <em>CVPR 2018</em>.</li><li>Touvron, H., et al. (2021). Training data-efficient image transformers &amp; distillation through attention. <em>ICML 2021</em>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f38fc3f7e831" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/cnn-architecture-evolution-resnet-efficientnet-convnext-what-actually-changed-f38fc3f7e831">CNN Architecture Evolution: ResNet → EfficientNet → ConvNeXt — What Actually Changed?</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Quantization and Distillation Are Putting Real AI on Your Phone]]></title>
            <link>https://medium.com/@shahvishesh313/how-quantization-and-distillation-are-putting-real-ai-on-your-phone-1a005b61db51?source=rss-5ef31430f4e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a005b61db51</guid>
            <category><![CDATA[tinyml]]></category>
            <category><![CDATA[edge-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gemma-4]]></category>
            <category><![CDATA[quantization]]></category>
            <dc:creator><![CDATA[Vishesh S.]]></dc:creator>
            <pubDate>Sun, 03 May 2026 06:51:50 GMT</pubDate>
            <atom:updated>2026-05-03T07:06:37.100Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Running a capable language model offline used to require a server rack. Now it needs a Raspberry Pi. Two techniques made this possible — and understanding both will change how you think about where AI lives.</em></p><p>I remember the first time I saw a demo of GPT-2 running locally on a laptop. It was slow. It was wrong half the time— the idea that something this smart could live on <em>your</em> machine, not some server farm somewhere, was just exciting.</p><p>Fast forward to April 2026. Google ships Gemma 4. The E2B variant — a real, capable language model — runs completely offline on a phone. No internet. No cloud. Just your device, thinking.</p><p>That didn’t happen by accident. It happened because of two techniques working together: <strong>quantization</strong> and <strong>distillation</strong>. Neither one alone got us here. Together, they’re quietly rewriting the rules of where AI can live.</p><h3>First, Let’s Talk About Why This Was Ever a Problem</h3><p>Large language models are, well, <em>large</em>. When a model like LLaMA has 7 billion parameters, each of those parameters is a number — a weight — that the model uses to make decisions. By default, each weight is stored as a 32-bit floating point number. That’s 4 bytes per number.</p><p>Do the math: 7 billion × 4 bytes = <strong>~28 GB</strong>. That’s the size of about 14 full-length 4K movies. On your phone. Just to <em>store</em> the model, before it even does anything.</p><p>A Raspberry Pi 4 has 4–8 GB of RAM. A high-end phone has 12 GB. A standard model isn’t even loading, let alone running.</p><p>This is the wall that needed breaking — and two very different ideas broke it.</p><h3>Technique 1: Quantization — Storing Less, Losing Little</h3><p>Here’s the simplest way I can explain it:</p><p>Imagine you’re describing someone’s height. You could say “183.47823 centimeters.” Or you could say “about 183 cm.” Both are useful. The second one takes up less space and is fast to write down. For most conversations, you’ll never notice the difference.</p><p>Quantization does exactly this with a model’s weights. Instead of storing each number with 32 bits of precision, you store it with fewer — maybe 8 bits, maybe 4 bits.</p><pre>Full precision (FP32): 0.38291748... → stored as 32 bits<br>8-bit quantized (INT8): ~0.38         → stored as 8 bits<br>4-bit quantized (INT4): ~0.4          → stored as 4 bits</pre><p>The weight loses some precision. But models are surprisingly <em>tolerant</em> of this. They were trained on billions of examples. A little rounding doesn’t break them.</p><p><strong>What you gain:</strong></p><p>Precision Memory for 7B Model Relative Size FP32 (default) ~28 GB 100% INT8 ~7 GB 25% INT4 ~3.5 GB 12.5%</p><p>A 7B model that used to need 28 GB now fits in 3.5 GB. That’s the Raspberry Pi range. That’s the phone range.</p><p><strong>The catch:</strong> quantization compresses an existing model. It’s a post-training fix. It reduces precision, and at aggressive levels (like 4-bit), you do lose something — especially on complex reasoning tasks. That’s where the second technique comes in, and it’s arguably more interesting.</p><h3>Technique 2: Distillation — Teaching Small Models to Think Like Big Ones</h3><p>Quantization shrinks a model. Distillation is a fundamentally different idea: instead of shrinking a big model, you <em>train a small model from scratch to behave like a big one</em>.</p><p>The analogy I like: imagine a world-class chef (the large model — called the “teacher”) writing down not just recipes, but their entire <em>thought process</em>. Every instinct, every substitution they’d consider, every reason they chose one technique over another. A culinary student (the small model — the “student”) studies this exhaustively. The student will never have the chef’s 30 years of experience, but they absorb the <em>patterns</em> — and end up cooking far better than if they’d just learned from a basic cookbook alone.</p><p>In practice, here’s how it works:</p><pre># Simplified distillation training loop<br>for batch in training_data:<br>    # Teacher (large model) generates &quot;soft&quot; probability distributions<br>    teacher_logits = teacher_model(batch)        # e.g. GPT-4 or Llama 70B</pre><pre>    # Student (small model) tries to match the teacher&#39;s output distribution<br>    student_logits = student_model(batch)</pre><pre>    # Loss = how different the student&#39;s thinking is from the teacher&#39;s<br>    loss = KL_divergence(student_logits, teacher_logits)<br>    loss.backward()</pre><p>The key insight: when the teacher says “the next word is 80% likely to be ‘Paris’, 15% ‘London’, 5% ‘Berlin’”, that probability distribution carries far more information than just the label “Paris”. The student learns <em>nuance</em> — the model’s uncertainty, its sense of what’s plausible — not just right answers.</p><p>The result is a small model that punches well above its weight. Phi-4 mini (3.8B parameters) and Gemma 4 E2B (2.3B effective parameters) are distilled this way — they’re not just architecturally compact, they’ve absorbed reasoning patterns from much larger teacher models.</p><p><strong>The difference in plain English:</strong></p><ul><li>Quantization: take a 28 GB model, compress it to 3.5 GB. It’s the same model, just less precise.</li><li>Distillation: train a 3.5 GB model to think like a 28 GB model. It’s a different, smarter small model from the start.</li></ul><p>In practice, the best on-device models use <em>both</em> — distilled first, then quantized. That’s how Gemma 4 E2B fits in under 1.5 GB and still generates coherent, useful responses.</p><h3>The Quality Reality Check</h3><p>Before we go further — let me be honest about what these models can and can’t do, because overselling this space doesn’t help anyone.</p><p>On-device models today are genuinely good for: factual Q&amp;A, summarization, formatting, simple chat, document reading, coding assistance on constrained tasks. For these, you often won’t notice the difference from a cloud model.</p><p>What they’re not: frontier-level reasoners. For complex multi-step logic, nuanced creative writing, or hard math — cloud models like GPT-5 or Gemini 2.5 Pro still have a significant edge. The honest framing is: <em>on-device models aren’t replacing frontier cloud models yet — but for many everyday tasks, they’re already good enough, and the gap is closing fast.</em></p><p>Here’s the same prompt at different quantization levels to illustrate:</p><pre>Prompt: &quot;What&#39;s the capital of Australia?&quot;</pre><pre>FP32: Canberra is the capital of Australia, often mistaken for Sydney<br>      due to Sydney&#39;s prominence as the country&#39;s largest city.</pre><pre>INT8: Canberra is the capital of Australia.</pre><pre>INT4: Canberra.</pre><p>Simple tasks? No meaningful difference. Complex reasoning? The cracks show. Know what you’re deploying for.</p><p><strong>Practical tips to get the best quality:</strong></p><ol><li><strong>Use grouped quantization (Q4_K_M):</strong> Instead of quantizing every weight independently, these methods quantize groups of weights together, preserving the relationships between them. The community sweet spot — smallest size, least quality loss.</li><li><strong>Start with purpose-built small models:</strong> Gemma 4 E2B and Phi-4 mini are designed for efficiency from the ground up, not retrofitted big models.</li><li><strong>Match the model to the task:</strong> 1–3B for simple tasks, 7B+ for complex ones. Don’t over-engineer.</li></ol><h3>The Tools That Make It Real</h3><p>This isn’t theoretical. There’s a whole ecosystem for running these models on small devices.</p><p><strong>llama.cpp</strong> is the most important project in this space. It’s a C++ library that runs quantized LLMs on CPUs — no GPU required. Models are distributed in a format called GGUF, which has become the de facto standard. You download a .gguf file, point llama.cpp at it, and you&#39;re running.</p><pre># Get llama.cpp<br>git clone https://github.com/ggerganov/llama.cpp<br>cd llama.cpp &amp;&amp; make</pre><pre># Download a quantized model (Gemma 4 E2B, 4-bit)<br># Search HuggingFace for: gemma-4-e2b-it-Q4_K_M.gguf</pre><pre># Run it<br>./llama-cli -m gemma-4-e2b-it-Q4_K_M.gguf -p &quot;Explain photosynthesis simply&quot;</pre><p>On a Raspberry Pi 5, Gemma 4 E2B at INT4 runs at ~7.6 tokens per second — slow by server standards, fast enough for most offline tasks.</p><p><strong>ExecuTorch</strong> (by Meta) is now production-stable at version 1.0, powering on-device AI across Instagram, WhatsApp, and Meta’s Ray-Ban smart glasses at billions-of-users scale. It supports 12+ hardware backends including Apple, Qualcomm, ARM, and MediaTek, and is the natural choice if you’re already in the PyTorch ecosystem.</p><p><strong>MLX</strong> is Apple’s framework for Apple Silicon. M-series chips have unified memory — CPU and GPU share the same pool — which is ideal for LLM inference without discrete GPU memory limits.</p><h3>Google’s Gemma 4: Distillation and Quantization in One Package</h3><p>Gemma 4 E2B is the clearest example of both techniques working in concert. Released April 2, 2026, the “E” in E2B stands for “effective” — it has 2.3 billion effective parameters during inference, but uses a technique called Per-Layer Embeddings to pack the representational depth of a much larger model into that footprint. Built from the same research as Gemini 3. Runs offline. Under Apache 2.0, free to use commercially.</p><p>Google worked directly with Qualcomm and MediaTek to optimize E2B for mobile chipsets. The result: up to 4x faster than previous Gemma generations, 60% less battery drain on mobile, and a memory footprint under 1.5 GB. That’s not a hobbyist experiment — that’s Google betting the next wave of AI features lives on the device, not in the cloud.</p><h3>What You’d Actually Build With This</h3><ul><li><strong>Offline assistant for field workers</strong> — agricultural teams, disaster relief, rural clinicians. AI help without connectivity.</li><li><strong>Privacy-first document Q&amp;A</strong> — legal firms, healthcare. A distilled, quantized Gemma model reads and answers questions about a PDF entirely on-device. Nothing leaves the machine.</li><li><strong>IoT + NLP at the edge</strong> — a smart sensor that doesn’t just collect data, but <em>interprets</em> it locally. Natural language summaries, no server required.</li><li><strong>Personal assistants that feel personal</strong> — no one wants private conversations logged on someone else’s server. Local models fix this by design.</li></ul><h3>How to Get Started Today</h3><p>The fastest path to running a local model:</p><ol><li><strong>Ollama</strong> — friendliest interface for local models. Install, then ollama run gemma4:e2b and you&#39;re chatting locally in under 5 minutes. No API key. Nothing phoning home.</li><li><strong>For Raspberry Pi / ARM</strong> — llama.cpp compiled for ARM. The llama.cpp GitHub has step-by-step guides for Pi 4 and Pi 5.</li><li><strong>For Android</strong> — Google’s ML Kit GenAI Prompt API with the Gemma 4 quickstart. Zero to on-device inference in an afternoon.</li><li><strong>For Apple Silicon</strong> — pip install mlx-lm, then one command to pull and run any GGUF model.</li></ol><p><em>If you found this useful, I’d love to hear what you’re building.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a005b61db51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>