<?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 Onn Yun Hui on Medium]]></title>
        <description><![CDATA[Stories by Onn Yun Hui on Medium]]></description>
        <link>https://medium.com/@onnyunhui?source=rss-39fbf3f21f31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lvKeTdkQ4tOm0lJn0KQqVw.png</url>
            <title>Stories by Onn Yun Hui on Medium</title>
            <link>https://medium.com/@onnyunhui?source=rss-39fbf3f21f31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:15:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@onnyunhui/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[Why Anthropic Replaced Git With Scion for AI Coding Agents]]></title>
            <link>https://onnyunhui.medium.com/why-anthropic-replaced-git-with-scion-for-ai-coding-agents-4f31eae67e00?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f31eae67e00</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[anthropics]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 01:54:24 GMT</pubDate>
            <atom:updated>2026-10-26T14:38:59.510Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scion and Antique: How Anthropic Replaced Git to Merge 30,000 Changes a Day</h3><figure><img alt="Git to Scion: over 30,000 changes merged in one day, and median time per agent change down from 34 min to 3.7 min" src="https://cdn-images-1.medium.com/max/1024/1*YSpUDeagmYyx4f0_WtrWHA.png" /><figcaption>Anthropic’s monorepo, September 2026. Source: Anthropic.</figcaption></figure><p>Updated 26 October 2026</p><p><em>Last verified: 19 October 2026 against Anthropic’s engineering post of 13 October 2026.</em></p><p>Anthropic no longer uses git for its monorepo. Its engineers say the bottleneck is now the developer infrastructure built for human scale: source control, builds and CI.</p><p>At the September 2026 peak, Anthropic merged one change every 2.9 seconds.</p><p>A team of 7 people took 5 months to build a new version control system called Scion and a code review tool called Antique. You can read Anthropic’s full write-up here: <a href="https://www.anthropic.com/engineering/redesigning-source-control">Redesigning source control at Anthropic</a>.</p><figure><img alt="Line chart of changes merged per day, January to September 2026" src="https://cdn-images-1.medium.com/max/1024/1*RJ68BYqJG9sXtOo4r50cnw.png" /><figcaption>Changes merged per day in Anthropic’s monorepo, January to September 2026. Antique change requests (orange) replaced pull requests (blue) from June onwards. Source: Anthropic.</figcaption></figure><h3>1. Git bottlenecks agentic coding</h3><p>With git, every developer has a full copy of the repository on their own machine and can work offline. You clone everything, commit locally, and push when you are ready. This workflow stops working at Anthropic’s size. The history of their main branch is almost 100 GB, a compressed copy of the code is over 25 GB, and they run about 25 million CI checkouts a day.</p><p>The usual fix is using mirrors and seeds. A <strong>mirror</strong> is a read-only copy of the repository on another server. Instead of every machine asking the same main server for code, the requests spread out across hundreds of mirrors, the same way a popular website uses many servers to share the load. A <strong>seed</strong> is a pre-made snapshot of the repo, saved at some point in time. A new instance starts from the seed, so it only has to fetch the changes made since then.</p><p>But the repo outgrew a mirror’s disk and memory. A plain git fetch also comes back as one big packfile (git’s bundle of objects), which can run to several gigabytes.</p><figure><img alt="Jobs fetch code through a pile of git mirrors to upstream. Below, two commit lines with the same time since the seed refresh: in May, 3 commits are missing from the seed; in September, 36 are." src="https://cdn-images-1.medium.com/max/1024/1*RexbkDb1_3SumS_90l4LUA.png" /><figcaption>Before Scion, jobs fetched code through several hundred git mirrors. As daily merges grew from about 2,500 to over 30,000, many more commits landed between seed refreshes, so each new node had more to fetch.</figcaption></figure><p>Normally, a coding agent (or you) does not need the entire repository to build a feature or fix a bug, and Anthropic runs tens of thousands of agents. So Anthropic built two things. Scion replaces git itself, the layer that stores files, history and commits. Antique sits on top of it and plays the role of GitHub pull requests.</p><figure><img alt="Two grids of files. In the git grid every file is filled in. In the Scion grid only four files are highlighted." src="https://cdn-images-1.medium.com/max/1024/1*A0TQmCYvp0TXuAwdycAWDA.gif" /><figcaption>To fix one bug, git downloads the whole 25 GB+ repo. Scion fetches only the few files the agent needs to do its work.</figcaption></figure><h3>2. Agents and CI runners both live in the cloud</h3><p>Git was built for people who work offline on their own machine. Coding agents and CI runners are always online and fast, so Scion moves the heavy work onto the server and keeps the client thin.</p><figure><img alt="Side-by-side diagram. In git a full copy flows from server to agent, which runs commit, merge, rebase, diff and blame. In Scion the agent sends only what changed and the server runs those operations." src="https://cdn-images-1.medium.com/max/1024/1*maxh8oY32Sw46wj3YpS0jA.png" /><figcaption>In git, commit, merge, rebase, diff and blame run on the agent’s machine. In Scion they run on the server, and the agent sends only what changed.</figcaption></figure><p>Think of the monorepo as one huge shared Google Drive, with thousands of Google Docs inside.</p><ul><li><strong>You don’t need to download the whole Drive.</strong> You open the doc you need, and the browser loads only the pages you are looking at. In a Scion virtual checkout, files appear on disk only when the agent opens them.</li><li><strong>The doc lives on the server.</strong> Your edits are saved there, not on your laptop. In Scion, the client sends only what changed, and the server creates the commit.</li><li><strong>You can ask questions without opening it.</strong> Google Docs shows you the version history and who edited what. In Scion, every query is available as an API, so a CI job that wants a diff or a blame can ask the server directly.</li><li><strong>Thousands of people can edit at once.</strong> Nobody has to send an edited file back and forth. Scion is built for thousands of agents working on the same codebase at the same time.</li></ul><h3>3. Cheap, incremental and lock-free commits</h3><p>Scion’s unit of history is a <strong>changeset</strong>: an entry in a write-ahead log (an append-only record of changes) stored in Google Cloud Spanner.</p><figure><img alt="A changeset record in Spanner listing author, message, parent and file changes, with arrows from two file hashes to matching blobs in Cloud Storage, and one file marked Deleted." src="https://cdn-images-1.medium.com/max/1024/1*cS70Cs2XkFAp6aO14-ZlTQ.png" /><figcaption>A Scion changeset is a small record in Spanner. File contents stay compressed in Cloud Storage, and the record points to them by hash. Example values from Anthropic’s figure.</figcaption></figure><p>In git, landing a change means moving the main pointer, one change at a time. Anthropic says git’s design is right for the vast majority of repositories. At 30,000 changes a day, though, every extra step in a commit adds up.</p><p>Scion keeps those steps small. It works out the folder snapshots later, and writing a change needs no locks. Moving main is a separate step: a single row update in Spanner.</p><figure><img alt="Left, a folder tree with the path from handler.py up to the root highlighted and main pointing at the root. Right, a list of changesets with one new entry added at the bottom." src="https://cdn-images-1.medium.com/max/1024/1*dsWUhuauLrNhO1o-itpSJA.gif" /><figcaption>A git commit rewrites every folder from the changed file up to the root. A Scion commit adds one entry to the log.</figcaption></figure><h3>4. The server works out blame and history</h3><p>A changeset records only what changed. On its own, it cannot quickly tell you who last edited a line or which commits touched a file. So Scion builds extra data from the changesets, which Anthropic calls derived data. This includes blame, path history and skip lists for the commit graph (shortcuts that speed up history queries). Some of it is worked out ahead of time and some only when an agent asks for it.</p><figure><img alt="A chain of eight changesets with arrows from each to its parent. Below, rows for blame, path history and skip lists each have five filled boxes and three empty ones." src="https://cdn-images-1.medium.com/max/1024/1*Ka6hTSZEpkDjZk9ncVY3UA.png" /><figcaption>Each changeset’s blame, path history and skip-list entries are built from its parent’s, so the server fills them in one changeset after another.</figcaption></figure><p>Because this lives on the server:</p><ul><li><strong>Agents can ask questions without downloading history.</strong> In git, a tool that wants to know who last changed a line needs a local copy of the repo, or has to hope a vendor-specific API has the answer, Anthropic says. In Scion, the server answers.</li><li><strong>New features need no client update.</strong> If a new data structure would make some query faster, Anthropic can add it as a new kind of derived data. The client never sees these structures, so the team can change them without updating tens of thousands of agents and CI machines.</li></ul><h3>5. The client fetches only what it needs, through three cache layers</h3><p>When a machine does need files on disk, Scion’s client checks its local store for missing trees (git’s folder snapshots), then fetches the missing files.</p><figure><img alt="Stacked bars from bottom to top: CI and cluster jobs, scion-daemon per node, scion-cache per region, scion-server, then Spanner and Cloud Storage. Each tier shows a hit rate over 99%, with dashed arrows labelled miss between them." src="https://cdn-images-1.medium.com/max/1024/1*I05_6bMyzXTtXvQ-wShCgg.png" /><figcaption>A file request stops at the first tier that has the file. Each of the three tiers answers more than 99% of the requests it gets.</figcaption></figure><p>Each layer speaks the same RPCs (the calls clients make to the server), so any of them can answer a request. Keeping the layers separate also limits how far a failure can spread.</p><h3><strong>The results</strong></h3><figure><img alt="Bar chart of four median times, git then Scion: change request 34 min vs 3.7 min, new worktree 7.1 min vs 5.1 s, CI checkout 31 s vs 3.5 s, status 3.9 s vs 19 ms" src="https://cdn-images-1.medium.com/max/1024/1*el2DwCfdKkMUhZ8XIsJQvg.png" /><figcaption>Median times with git and with Scion, from Anthropic’s measurements.</figcaption></figure><figure><img alt="A grid of 200 squares. 199 are grey and one in the bottom-right corner is orange, labelled 200x less." src="https://cdn-images-1.medium.com/max/1024/1*1Z3fxvyZ4HMKGRICekyxNA.png" /><figcaption>Scion uses about 200 times less CPU and memory than the old git mirrors used.</figcaption></figure><figure><img alt="Comparison table of git and Scion. Query history without a checkout: git no, Scion yes via API. Branches: git cheap and used everywhere, Scion only main and releases. Works offline: git yes, Scion no. Available to you: git yes, Scion no, internal only." src="https://cdn-images-1.medium.com/max/1024/1*kYRPbAT5GElFsfszSQZgQA.png" /><figcaption>Scion gives up offline work and widespread branches. In return, agents can query history from the server without a checkout.</figcaption></figure><h3>6. Code review: Humans are still in control of the intent</h3><p>With 30,000 changes landing a day, someone still has to review them. Antique is Anthropic’s code review tool. The team writes the rules about who has to approve which kind of change, and Antique enforces them. A comment-only edit does not need the same scrutiny as a change to the core logic. Human reviewers can focus on the most consequential changes.</p><p>Anthropic also says managing “safety, security, and compliance in a massive monorepo is as important as managing the size and scale.” Scion can set permissions on individual folders to protect the most sensitive code.</p><p>Before a human sees a change, other AI models review it adversarially, looking for bugs and edge cases the coding agent missed. Anthropic says this review is effective but “can be myopic”: it focuses on the lines in front of it and can push toward over-engineering. In one case, a review was overly defensive about trusting another internal service. Humans still review every change request, and they check that the change does what it was meant to do rather than reading every line of code.</p><p>If you’d like to use Scion and Antique yourself, unfortunately they are not open source. Anthropic expects these problems to become more common over the next six to 12 months for other teams that use AI coding tools.</p><p>PS. oh i found someone actually doing an opensource of Scion: <br>feder-cr/git-ai (<a href="https://github.com/feder-cr/git-ai">https://github.com/feder-cr/git-ai</a>)</p><p>If you found this helpful, do remember to follow, comment and give claps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f31eae67e00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic Image Search using OpenAI CLIP and Milvus]]></title>
            <link>https://pub.aimind.so/semantic-image-search-using-openai-clip-and-milvus-412f406280d2?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/412f406280d2</guid>
            <category><![CDATA[clip]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[milvus]]></category>
            <category><![CDATA[image-vectorization]]></category>
            <category><![CDATA[semantic-search]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 14:16:53 GMT</pubDate>
            <atom:updated>2025-11-12T15:06:33.687Z</atom:updated>
            <content:encoded><![CDATA[<p>I always struggle finding the images I want on my photo album.</p><p>When i was young i was wondering would it be great if i can just recall the words related to the photo that I’ve taken years ago, and the photo would just appear as a result in my query?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7eNVONRQdP9qTEQk6cRf9A.jpeg" /><figcaption>If I were to think of an image I’ve taken from my Australia trip from 10 years ago, I’d have to search my photos all the way back. Now, i can query search on my images. Image Generation by NanoBanana</figcaption></figure><p>This is no longer a dream. We can already do it since 2021. When CLIP was launched. Contrastive Language Image Pretraining or CLIP, is a dual encoder model pre-trained to learn semantic connections between text and images. What’s more, you don’t have to pay for any APIs and you can even run this on your local desktop!</p><p>Before going into the code walkthrough, I will summarise the important information from CLIP’s 2021 paper and implementing a semantic image search using Milvus and CLIP on a notebook. If you want to skip to the code, you can scroll all the way down.</p><h3>CLIP ARCHITECTURE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oIC6GVR3cS8VMyvAl_uovA.png" /><figcaption>CLIP pre-trains an image encoder and a text encoder to predict which images were paired with which texts in our dataset. These dataset is then converted to classes such as “image of a dog” and predict the class of caption into CLIP estimates. <a href="https://openai.com/index/clip/">Source</a></figcaption></figure><p>CLIP is built based on a dual-encoder architecture that projects both text and image vectors into a shared multi-modal embedding space through projections, to allow their representations to be compared directly.</p><ul><li><strong>Image encoder</strong>: uses either ResNet or Vision Transformer (ViT), the ViT-L14 image encoder was ultimately selected for its superior performance over the other image encoders.</li><li><strong>Text encoder</strong>: a 63-million parameter text transformer that encodes text inputs, capped at only 76-sequence length</li></ul><h3>TRAINING PROCESS</h3><p>CLIP was trained using a self-supervised learning approach on a massive corpus of image-text pairs (around 400M) from public sources. This meant that the cost and labour intensive process of manual labelling of each image is minimal.</p><h3>Contrastive Loss</h3><p>This is a core concept in the training process of CLIP. Within a batch of N image-text pair, CLIP aims to maximise the similarities within the true image-text pairs, and minimise the similarity between incorrect image-text pairs. This is done through calculating the cosine similarity between the image and text embedding in the batch and optimising to select the true matched pairs.</p><p>Due to its large training size and large classification, it has has allowed CLIP to have zero-shot transfer learning and strong performance across &gt;30 benchmarks when it was being created.</p><h3>Prompt Engineering with CLIP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*yEaHZKn90rWWZz6Z2Rk_Vg.png" /><figcaption>The team that made CLIP also found out the prompt engineering using the format “a photo of a {label}” helps improve the zero shot performance across 36 dataset by almost 5 points. <a href="https://arxiv.org/pdf/2103.00020">Source</a></figcaption></figure><p>This is due to the nature of the pre-training dataset as they are often text in full sentences that describe the image and paired with a image. Hence having this format of “a photo of a {label}” helps improve the performance over baseline. <a href="https://arxiv.org/pdf/2103.00020">Source</a></p><p>The paper noted that the zero-shot performance can be improved by a few non-exhaustive examples such as:</p><ul><li>Adding <strong>category context</strong>: <em>“A photo of {label}, a type of pet/aircraft.”</em></li><li>Specifying the <strong>image type</strong>: <em>“A satellite photo of a {label}.”</em></li><li>Adding <strong>size context</strong>: <em>“A photo of a big {label}.”</em> or <em>“A photo of a small {label}”</em></li></ul><h3>Limitations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phnV7pPHFfqBXriU13wL_g.png" /><figcaption>CLIP’s image encoder has a bias towards larger objects in the image, for the text encoder, it prioritizes first mentioned objects and larger objects, in a multi object scenario. <a href="https://arxiv.org/pdf/2502.19842">Source</a></figcaption></figure><p>Despite it’s zero-shot capabilities, CLIP exhibits certain biases and struggles with specific tasks:</p><ul><li><strong>Fine-grained recognition</strong> (e.g., distinguishing specific types of plants, car models, or airplane variants).</li><li><strong>Specialized or complex domains</strong> (e.g., satellite image classification, lymph node tumor detection).</li><li><strong>Abstract/Quantitative tasks</strong> (e.g., counting objects in synthetic scenes like CLEVRCounts).</li><li><strong>Real-world safety tasks</strong> (e.g., recognizing the distance to the nearest car in self-driving contexts).</li><li><strong>Prompt sensitivity</strong> (results can be highly dependent on the exact wording of the prompt) <a href="https://arxiv.org/pdf/2502.19842">Source</a>.</li></ul><h3>Code walkthrough</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/252fce191fc5475a83d3c40aca9ff22c/href">https://medium.com/media/252fce191fc5475a83d3c40aca9ff22c/href</a></iframe><p><strong>Important Note: </strong>Milvus-lite is only available for Linux-based operating systems. Windows users must use Docker to run Milvus standalone.</p><p><strong>Setting Up Milvus on Windows</strong></p><p>Docker Desktop must be installed and running on your Windows machine, if not, you can go to docker’s website and download the application.</p><p><strong>Step 1: Download the Standalone Setup Script</strong></p><p>Open <strong>PowerShell</strong> and run:</p><pre>Invoke-WebRequest https://raw.githubusercontent.com/milvus-io/milvus/refs/heads/master/scripts/standalone_embed.bat -OutFile standalone.bat</pre><p><strong>Step 2: Navigate to Download Directory</strong></p><p>In PowerShell/CMD, navigate to the folder where standalone.bat was downloaded:</p><pre>cd path\to\download\directory</pre><p><strong>Step 3: Start Milvus Docker Container</strong></p><p>In <strong>Command Prompt (cmd)</strong>, run:</p><pre>standalone.bat start</pre><p>This script will:</p><ul><li>Pull the Milvus Docker image</li><li>Start a Milvus container</li><li>Expose the service on <em>localhost:19530</em></li></ul><p><strong>Step 4: Initialize Milvus Client in Your Notebook</strong></p><p>In your Jupyter notebook, use this code to connect:</p><pre>from pymilvus import MilvusClient<br># Initialize Milvus client<br>milvus_client = MilvusClient(<br>uri=&quot;http://localhost:19530&quot;,<br>token=&quot;root:Milvus&quot;<br>)<br>print(&quot;Milvus client initialized successfully!&quot;)</pre><p>If you found this useful, dont forget to give me 10 claps 👏👏👏 (it’s free) and subscribe to my page. I will be doing more of such tutorials in the future!</p><h4>A Message from AI Mind</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*5Wm7sOfTpe5DEbhg.gif" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://pub.aimind.so/">AI Mind Publication</a></li><li>🧠 Improve your <a href="https://www.aimind.so/prompt-generator?utm_source=pub&amp;utm_medium=message">AI prompts effortlessly and FREE</a></li><li><strong>🧰 Discover </strong><a href="https://www.aimind.so/?utm_source=pub&amp;utm_medium=message"><strong>Intuitive AI Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=412f406280d2" width="1" height="1" alt=""><hr><p><a href="https://pub.aimind.so/semantic-image-search-using-openai-clip-and-milvus-412f406280d2">Semantic Image Search using OpenAI CLIP and Milvus</a> was originally published in <a href="https://pub.aimind.so/">AI Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Deterministic, Consistent and Reproducible text in LLMs]]></title>
            <link>https://pub.aimind.so/creating-deterministic-consistent-and-reproducible-text-in-llms-e589ba230d44?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/e589ba230d44</guid>
            <category><![CDATA[temperature]]></category>
            <category><![CDATA[llamas]]></category>
            <category><![CDATA[determinism-llm]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Sun, 04 May 2025 08:35:00 GMT</pubDate>
            <atom:updated>2025-05-05T17:26:08.423Z</atom:updated>
            <content:encoded><![CDATA[<h3>Achieving Consistency and Reproducibility in Large Language Models (LLMs)</h3><p>Large Language Models (LLMs) have revolutionized text generation, but their stochastic nature — where outputs can vary even with identical inputs — poses challenges for applications requiring consistency. This article explores how LLMs produce stochastic outputs, why reproducibility matters, and the methods to achieve deterministic and reproducible text, addressing hardware, software, and architectural factors.</p><h3>HOW LLMs PRODUCE STOCHASTIC OUTPUTS</h3><p>LLMs generate text by computing a probability distribution over their vocabulary at each step, using softmax-scaled logits to determine the likelihood of each token. The next token is selected by sampling from this distribution, which introduces randomness. (<a href="https://genai.stackexchange.com/questions/1922/is-the-text-of-a-llm-determined-by-a-random-seed">Source</a>). This stochasticity stems from:</p><ul><li><strong>Sampling Algorithms:</strong> Methods like nucleus (top-p) or top-k sampling add variability by selecting tokens from a subset of probable candidates (<a href="https://arxiv.org/html/2411.14914v1">Source</a>).</li><li><strong>Floating-Point Variability:</strong> Differences in floating-point computations can cause slight logit divergences, leading to different token choices (<a href="https://arxiv.org/html/2411.14914v1">Source</a>).</li><li><strong>Numerical Operations on GPUs:</strong> Floating-point operations, such as matrix multiplications and reductions, are not bit-wise identical across runs due to non-deterministic CUDA kernels and parallel execution order (<a href="https://arxiv.org/html/2411.14914v1">Source</a>).</li></ul><p>You can make LLM produce consistent and reproducible text to a very large extent but achieving perfect determinism is complex due to its software and hardware limitations which we will cover in today’s article.</p><h3>WHY DO WE NEED REPRODUCIBILITY?</h3><p>Reproducibility underpins the scientific method by allowing independent validation, comparison of models, and iterative improvements. It is a cornerstone of scientific research and engineering. In the context of LLMs, reproducibility ensures:</p><ul><li><strong>RELIABLE DEBUGGING</strong> — Developers can debug and optimize models effectively as output are consistent every run.</li><li><strong>FAIR BENCHMARKING</strong> — Researchers can compare algorithms and architectures fairly, while holding every variables constant.</li><li><strong>RELIABILITY</strong> — End-users receive reliable and predictable outputs.</li><li><strong>AUDIT AND COMPLIANCE </strong>— in domains like healthcare and finance demand consistent, verifiable model decisions over time</li></ul><p>In scientific, industrial, and safety-critical applications — such as healthcare diagnostics, financial forecasting, and autonomous control — variability undermines trust and hinders systematic evaluation.</p><h3>CONFIGURING REPRODUCIBILITY AND DETERMINISM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AYIcTOibg7jA8Ca3RssDw.png" /><figcaption>Stack needed for full reproducibility- Created from ChatGPT</figcaption></figure><p><strong>SEED AND API SETTINGS</strong></p><ol><li><strong>Setting Random Seeds </strong>— to control machine learning operations such as weight initialisation, data shuffling. Ensuring that all seeds are set at the very start can control randomness thorughout the execution of the script. This can be done through <a href="https://www.ingonyama.com/post/solving-reproducibility-challenges-in-deep-learning-and-llms-our-journey">Source</a>:</li></ol><ul><li><strong>Seed All RNGs</strong>: Initialize Python’s random, NumPy, and framework-specific generators (e.g., torch.manual_seed) at the very start of your script (<a href="https://ml-science-book.com/reproducibility.html">Source</a>).</li><li><strong>Environment Variables</strong>: For PyTorch, set CUBLAS_WORKSPACE_CONFIG=:16:8 and torch.use_deterministic_algorithms(True) to enforce deterministic kernels where available (<a href="https://pytorch.org/docs/stable/notes/randomness.html">Source</a>)</li><li><strong>Distributed/Parallel</strong>: In multi-process or multi-node setups, ensure seeds are synchronized across all workers and that execution order is consistent to prevent ordering-related nondeterminism (<a href="https://arxiv.org/abs/2503.07329">Source</a>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*6OQ4D0friimoQ7ft_nyT2Q.png" /><figcaption>OpenAI’s controls for more consistent output for seed and system_fingerprint <a href="https://cookbook.openai.com/examples/reproducible_outputs_with_the_seed_parameter">Source</a></figcaption></figure><p>For certain models such as OpenAI’s gpt-4–1106-preview and gpt-3.5-turbo-1106, a seed parameter can be used to ensure reproducibility. According to the OpenAI Cookbook, setting the seed to the same integer and matching all other parameters (prompt, temperature, etc.) can lead to mostly deterministic outputs (<a href="https://cookbook.openai.com/examples/reproducible_outputs_with_the_seed_parameter">Source</a>).</p><p>The response includes a system_fingerprint to indicate backend configuration, which must remain consistent for reproducibility (<a href="https://cookbook.openai.com/examples/reproducible_outputs_with_the_seed_parameter">Source</a>).</p><p>When using other libraries or API such as Ollama/ vLLM you can set temperature, top_p and top_k arguments. These controls the model to pick the next most likely word.</p><p><strong>2. Temperature Scaling</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mN_U3jCpYo2tXpOs6Efawg.png" /><figcaption>How applying softmax influences probability of the distribution <a href="https://www.hopsworks.ai/dictionary/llm-temperature">Source</a></figcaption></figure><p>When LLMs generate output, there are usually a few candidates in the vocabulary for each word and each candidate word has a certain likelihood of being chosen. Those likelihoods are represented by a set of logits. Then the softmax function takes the set of logits and transforms them into probabilities that sum to 1. A <strong>temperature value</strong> in the softmax function scales these logits, influencing the final probability distribution of the subsequent token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*q-LRsJ-_mnd3kgpBHKUpdA.png" /><figcaption>LLM temperature (T) acts as a control mechanism. It affects the probabilities assigned to each candidate word by scaling the logits. <a href="https://www.hopsworks.ai/dictionary/llm-temperature">Source</a></figcaption></figure><ul><li><strong>Low Temperature (&lt;1)</strong>: Sharpens distribution, reducing randomness and increasing consistency of output text, output will be more predictable and repetitive.</li><li><strong>High Temperature (&gt;1)</strong>: Flattens distribution, output can explore a wider range of potential token choice, enhancing creativity but decreasing reproducibility.</li></ul><p><strong>3. Top-k Sampling</strong></p><p>Restricts sampling to the k tokens only the top-k highest-probability tokens at each generation step. Upon recognizing these tokens, the model normalizes their probability and samples the subsequent token from this constrained set. This method decreases computational complexity and inhibits the model from selecting low-probability tokens that may result in incoherent outputs. The parameter 𝑘 dictates the magnitude of the candidate pool:</p><ul><li><strong>Small k </strong>(e.g., 1): More predictable and probable token generation, but potentially conservative.</li><li><strong>Large k</strong>(e.g., 50): Increases diversity at the cost of consistency of output (<a href="https://www.ingonyama.com/post/solving-reproducibility-challenges-in-deep-learning-and-llms-our-journey">Source</a>).</li></ul><p><strong>4. Top-p (Nucleus) Sampling</strong></p><p>Samples from the smallest set of tokens whose cumulative probability ≥ p:</p><ul><li><strong>Low p </strong>(e.g., 0.1) : only the top 10% most likely tokens are considered, yields more focused and reproducible outputs</li><li><strong>High p </strong>(e.g., 0.95): Allows broader sampling, boosting novelty but possibly adding unpredictability. (<a href="https://www.ingonyama.com/post/solving-reproducibility-challenges-in-deep-learning-and-llms-our-journey">Source</a>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*DoDR0ycdiYUGLIZkGPTQcA.png" /><figcaption>Imporant message from Azure AI Services <a href="https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/reproducible-output?tabs=pyton">Source</a></figcaption></figure><p>Even with these seeds fixed and hyperparameters of LLMs optimised, it d<strong>oes not guarantee 100% determinism</strong> of LLMs in practice. There are a few reasons for this due to small software and hardware non- determinism, which can result in in non-reproducible outputs.</p><ul><li><strong>Ties or equal probabilities:</strong> If two or more next-token options have (practically) the same highest probability, the model or decoding library might break ties in an arbitrary way. This situation is rare but possible. In such a case, even with temperature 0, <a href="https://www.pamelatoman.net/blog/2023/08/nondeterminism-in-llms/">the choice between tokens could be nondeterministic</a>.</li><li><strong>Upstream variability:</strong> <a href="https://www.pamelatoman.net/blog/2023/08/nondeterminism-in-llms/">Randomness can creep in</a> <em>before</em> the greedy selection happens. Ideally, the model’s predicted probabilities for the next token are a pure, deterministic function of the input and the model weights. In reality, how those probabilities are computed can introduce slight variability run-to-run (as we’ll explore below). If something causes the model’s computed probabilities to differ ever so slightly between runs, the identity of the “most probable token” could change. Essentially, temperature=0 removes deliberate randomness from <strong>sampling</strong>, but it doesn’t account for subtle randomness in the <strong>model’s computation</strong> itself.</li></ul><h3>KERNEL DETERMINISM AND MODEL ARCHITECTURE</h3><p>Since fixing seeds and hyperparameters of LLM does not guarantee 100% determinism, we can dive deeper in what happens when each computation happen and how it affects the downstream representation of a token in a deep-learning model.</p><p>Computation kernels refer to the low-level operations executed on hardware such as matrix multiplication, and are often optimised for GPUs. Having kernel determinism ensures that these operations using GPUs are consistent across runs regardless of hardware and software variations. We will discuss several factors leading up to this non-determinism, the impacts and how we can fix this limitations.</p><h4>Floating Point Non-Associativity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*11CWvpVDDQ-i7k5cOHpuxA.png" /><figcaption>Rounding errors propagates differently based on the ordering of the additions. <a href="https://www.youtube.com/watch?v=TB07_mUMt0U">Source</a></figcaption></figure><p>Rounding errors propagate differently based on the order of operations due to the nature of floating-point arithmetic. Unlike basic mathematics, floating point numbers are approximate real numbers in computers with finite precision. Computers represent decimal numbers in binary and due to its limited precision, operations like addition and multiplication incur rounding errors.</p><p>In addition, floating point operations are not associative, as seen in the image above:</p><blockquote>(a + b) + c ≠ a + (b + c).</blockquote><p>This discrepancies in the output is due to the difference in rounding the intermediate sums which is dependent on the sequence of operations, leading to a variability in the final output (<a href="https://community.openai.com/t/a-question-on-determinism/8185">Source</a>).</p><p>When GPUs compute these operations across thousands of threads in parallel, understanding how general matrix multiplications (GEMM) or reductions (e.g., summing activations) work is the key to understanding the origins of these non-deterministic nature in deep-learning and LLMs.</p><p>Atomic operations in reduction kernels (e.g., GEMM backprop in cuDNN) inherently introduce thread-ordering races. Each run may schedule threads differently, yielding slightly different sums and thus, different token scores (<a href="https://news.ycombinator.com/item?id=37006224">Source</a>).</p><h3>Non-Determinism in Quantized Models</h3><p>Within the machine learning community, quantization has been viewed as a potential solution for reducing variability and improving determinism in model outputs. By reducing the precision of model weights — from 32-bit floating point (FP32) to lower-precision formats such as FP16, FP8, or INT8 — quantization decreases memory usage and accelerates inference. This makes it particularly suitable for deployment in resource-constrained environments. Frameworks like llama.cpp using the GGUF format leverage this technique effectively.</p><p>However, experiments conducted by Ingonyama, documented in <a href="https://www.ingonyama.com/post/solving-reproducibility-challenges-in-deep-learning-and-llms-our-journey"><em>Solving Reproducibility Challenges in Deep Learning and LLMs</em></a>, tested quantized models such as LLaMA2–7B-Q8 and Meta-LLaMA-3–8B-Q8_0 on NVIDIA GPUs (RTX 3090, RTX 4080, L4) using CUDA Toolkit 12.0. The results revealed that quantization did not ensure reproducibility across different machines. This failure is primarily due to the continued use of floating-point operations in certain layers and during runtime dequantization. As a result, the notion that quantization guarantees determinism has been largely debunked.</p><p><strong>Why Quantization Fails to Guarantee Determinism</strong></p><ol><li><strong>Unquantized Layers</strong>: Critical layers like LayerNorm or Softmax often remain in floating-point to maintain accuracy, as their operations are sensitive to precision loss. These layers introduce floating-point non-associativity, undermining determinism (<a href="https://medium.com/%40kevin.lopez.91/simple-tutorial-to-quantize-models-using-llama-cpp-from-safetesnsors-to-gguf-c42acf2c537d?utm_source=chatgpt.com">Source</a>). <br>Mixed-precision training, which combines lower-precision formats (e.g., FP16 or BFloat16) with FP32 for critical operations like gradient accumulation, can still introduce non-determinism <a href="https://discuss.pennylane.ai/t/mixed-precision-training-numerical-stability-for-pytorch-pennylane/3285?utm_source=chatgpt.com">Source</a>.</li><li><strong>Runtime Dequantization</strong>: During inference, quantized weights are frequently dequantized back to floating-point in order to compute logits. This step reintroduces the floating-point arithmetic and its inherent variability into the computation pipeline.</li><li><strong>Lower-Precision Noise</strong>: Lower-precision formats such as FP16 and FP8 have limited dynamic range and reduced precision. This increases rounding errors and introduces quantization noise, especially in sensitive operations like reductions. While using FP32 can reduce such noise and improve determinism, it significantly increases memory and computational costs.</li></ol><h3><strong>MODEL ARCHITECTURE: MIXTURE OF EXPERTS (MoE)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tjwMX8ayVW2htLrH.png" /><figcaption>MoE architecture (<a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-mixture-of-experts">Source</a>)</figcaption></figure><p>Many advanced LLMs, including GPT-4, employ a Mixture of Experts architecture. This design improves scalability and computational efficiency by dividing the model into multiple sub-networks / experts, with each specialising in specific data patterns/ tasks.</p><p>Dense transformer models, such as older GPT-3 versions or Meta’s LLaMA series, route all tokens through the same set of parameters, creating a fixed computational path. Apart from low-level floating-point variability, these models are more deterministic by design. In contrast, MoE models introduce dynamic routing, which inherently adds variability due to fluctuating expert assignments. Data from Sparse MoE studies show that models like text-davinci-002 (dense) are far more consistent than GPT-4 or GPT-3.5-turbo (suspected MoE).</p><p>This is unlike in dense models, where all parameters are used for every inputs. A MoE model only activate a subset of experts per token. A learnt gating network evaluates each input and selects the most appropriate experts, based on affinity scores. The output from the selected experts are combined, typically by weighted gating scores — to produce a final output of the LLM. This selective activation of experts approach allows models to scale to billions of parameters while keep inference efficient as compared to dense architecture. However, these advantages comes with non-determinism, expecially during inference.</p><p><strong>Sources of Non-Determinism in MoE model:</strong></p><ol><li><strong>Batched Inference and Expert Capacity Constraints: </strong>In production environments, LLMs typically use batched inference to maximise throughput by processing multiple input sequences simultaneously- hence, optimizing resource utilization. <br>In MoE models, each expert has a limited token capacity each batch. When too many tokens in a batch are routed to an expert, some are rerouted to secondary experts. This rerouting is not solely based on the token’s content but is influenced by the batch’s composition (<a href="https://www.pamelatoman.net/blog/2023/08/nondeterminism-in-llms/">Source</a>).<br>As explained in <a href="https://152334h.github.io/blog/non-determinism-in-gpt-4/">Non-determinism in GPT-4 is caused by Sparse MoE</a>, sparse MoE models group tokens into fixed-sized batches and enforces load balancing across experts. When groups include tokens from different sequences, they compete for expert buffer spots, leading to variable expert assignments across runs. Thus, the same input sequence may follow different computational paths across runs, producing different outputs <a href="https://152334h.github.io/blog/knowing-enough-about-moe/">Source</a>.</li><li><strong>Sequence-Level vs. Batch-Level Determinism: </strong>Key distinction — MoE models are deterministic at the batch level but not at the sequence level. If the entire batch is processed is identical, the outputs are consistent. However, in practice, especially for public APIs, batches are dynamically composed of various user requests. As a result, the expert assignments depend on other sequences in the batch, causing non-determinism for single inputs. This behavior is frequently observed in GPT-4, where users report varying responses even at temperature 0 (<a href="https://152334h.github.io/blog/non-determinism-in-gpt-4/">Source</a>).</li></ol><p>For API users, MoE-related non-determinism means that identical prompts may yield different responses across calls, as the backend dynamically batches requests. This is particularly problematic in scenarios requiring exact reproducibility, such as debugging or benchmarking. The lack of transparency about batching and model architecture (e.g., whether GPT-4 uses MoE) complicates mitigation efforts. Users of dense models, or providers processing requests independently, may experience less variability, but no major API provider currently guarantees fully deterministic outputs (<a href="https://community.openai.com/t/why-the-api-output-is-inconsistent-even-after-the-temperature-is-set-to-0/329541">Source</a>).</p><h3>Potential Mitigation Strategies</h3><p>Several approaches could reduce MoE non-determinism, though each involves trade-offs:</p><ol><li><strong>Single-Sequence Processing</strong>: Processing each sequence with a batch size of 1 ensures consistent expert assignments, as there is no competition from other sequences. However, this significantly reduces throughput, making it impractical for large-scale APIs.</li><li><strong>Deterministic Routing</strong>: Enforcing fixed expert assignments per sequence, regardless of batch composition, could enhance determinism. This requires modifying the gating mechanism to prioritize consistency over load balancing.</li><li><strong>Soft MoE Variants</strong>: Research, such as the Soft MoE paper, proposes averaging expert outputs rather than selecting top-k experts, potentially reducing variability. However, these methods are computationally intensive and not widely adopted in production.</li><li><strong>Provider Transparency</strong>: API providers could offer deterministic modes, clearly documenting batching strategies and model architectures. Currently, no major provider commits to such guarantees (<a href="https://community.openai.com/t/why-the-api-output-is-inconsistent-even-after-the-temperature-is-set-to-0/329541">Source</a>).</li></ol><h3>FRAMEWORK VARIATION: CONTROLLING DETERMINISTIC OUTPUTS</h3><p>GPU-accelerated framework libraries like PyTorch and Tensorflow open prioritise speed and this can result in the calculation of floating points being non-deterministic by default even though the model weights and inputs are identical. However, there are several ways to configure flags and techniques to mitigate this behaviour for a more deterministic output (<a href="https://www.ingonyama.com/post/solving-reproducibility-challenges-in-deep-learning-and-llms-our-journey">Source</a>).</p><p><strong>PyTorch Determinism</strong></p><p><a href="https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html">PyTorch </a>allows users to enforce deterministic behavior:</p><pre>torch.use_deterministic_algorithms(True)</pre><p>By enabling this flag, it forces the use of deterministic kernels when available. However, some operations (e.g., certain backward passes in convolution or pooling) lacks deterministic implementations. In such cases, PyTorch would raise an error if no fallback exists <a href="https://darinabal.medium.com/deep-learning-reproducible-results-using-pytorch-42034da5ad7">Source</a>.</p><p><strong>PyTorch and cuDNN Kernel-Level Non-Determinism</strong></p><p>CuDNN is a kind of Deep Learning library that uses CUDA, and CUDA is the way to contact the GPU.</p><p>Additionally for cuDNN PyTorch offers (<a href="https://darinabal.medium.com/deep-learning-reproducible-results-using-pytorch-42034da5ad7">Source</a>):</p><pre>torch.backends.cudnn.deterministic = True<br>torch.backends.cudnn.benchmark = False</pre><ul><li>Setting cudnn.deterministic = True ensures that cuDNN only uses deterministic convolution algorithms (<a href="https://github.com/soumith/cudnn.torch/issues/270">Source</a>).</li><li>Setting cudnn.benchmark = False disables auto-tuning, which otherwise dynamically selects the fastest kernel for each input size — potentially introducing variability across runs. Conversely, torch.backends.cudnn.benchmark = True causes cuDNN to benchmark multiple convolution algorithms and select the fastest.</li></ul><p>Across <strong>different GPU architectures</strong> (e.g., RTX 3090 vs. A100), cuDNN does <strong>not</strong> guarantee consistent results, as kernel behavior and instruction ordering may differ.</p><p><strong>TensorFlow Determinism</strong></p><p>In TensorFlow, similar issues arise due to <strong>cuDNN auto-tuning</strong> and use of non-deterministic ops. You can enforce deterministic behavior by setting:</p><pre>TF_CUDNN_DETERMINISTIC=1</pre><p>This flag disables cuDNN auto-tuning, ensuring that TensorFlow selects deterministic backpropagation algorithms during convolutions <a href="https://www.youtube.com/watch?v=TB07_mUMt0U">Source</a>.</p><p>The <strong>cuDNN library</strong> (built on top of CUDA) provides GPU-accelerated operations for deep learning. While cuDNN aims for bit-wise reproducibility on the <strong>same hardware</strong>, some operations remain <strong>inherently non-deterministic</strong> due to their use of atomicAdd() and similar instructions.</p><p>Enabling framework flags for deterministic kernels and setting relevant environment variables can eliminate many sources of variability, though some operations (e.g. ConvolutionBackwardData, PoolingBackward) may still lack deterministic implementations (<a href="https://darinabal.medium.com/deep-learning-reproducible-results-using-pytorch-42034da5ad7">Source</a>)</p><h3>HARDWARE INDUCED NON-DETERMINISM</h3><p>GPUs and TPUs, which are used to optimised for speed and parallelism, inherently introduces non-determinism. As mentioned, GPU thread scheduling is non-deterministic, whereby the order in which threads aggregate partial sums can vary across runs. As mentioned in the earlier portion, the non-associativity of floatng points means that these differences accumulates.</p><p>In a deep learning model, there are multiple layers with numerous floating point operations, these minor discrepancies accumulate and cascades through billions of operations, in unpredictable ways. <a href="https://arxiv.org/pdf/2408.05148?utm_source=chatgpt.com">Source</a></p><p>In LLMs, the final output token is selected based on the computed probability from various numerous matrix multiplication and activations. Consequently, minute variations in these computations due to the compounding can result in the different argmax output across runs, which results in a different output tokens every run (<a href="https://www.ingonyama.com/post/solving-reproducibility-challenges-in-deep-learning-and-llms-our-journey">Source</a>). This issue become more pronounced in large models requiring model parallelism across multiple GPUs, where merging results from different GPUs amplifies the floating-point differences across hardware and exacerbates non-determinism (<a href="https://arxiv.org/html/2408.05148v3?utm_source=chatgpt.com">Source</a>).</p><p>When a language model runs on different hardware setups — whether across GPU models or in distributed environments — floating-point computations may not behave identically. As a result, even when the model weights and inputs remain unchanged, the outputs can vary slightly depending on the underlying hardware.</p><ul><li><strong>Model size and hardware parallelism:</strong> Very large LLMs that require model-parallelism (e.g., spanning across multiple GPUs or machines) which might may introduce more non-determinism than smaller models that run on a single device. When models are split across devices, partial results are merged — often in parallel — introducing minor floating point discrepancies that can accumulate. <br>In constrast, smaller models (or distilled versions) that run in on one GPU could be more stable in output than a 175B model spread over dozens of GPUs, simply because there are fewer moving pieces in the computation.</li><li><strong>Multi-Core CPU Behavior</strong>: Non-determinism isn’t exclusive to GPUs — it can occur on multi-core CPUs as well. In parallel computing, the order of the thread execution and how partial results are collected introduces minute variations due to floating point non-associativity (<a href="https://github.com/openai/baselines/issues/805">Source</a>). These difference, although tiny can accumulate across multiple iterations.</li></ul><h3>Emerging Deterministic Hardware</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*OCIm91ZnMQbzyL6W9_bKGQ.png" /><figcaption>Groq’s LPU is said to be deterministic <a href="https://groq.com/the-groq-lpu-explained/">Source</a></figcaption></figure><p>New hardware solutions aim to address this challenge. For example, <strong>Groq’s LPU (Language Processing Unit)</strong>, based on its <strong>Tensor Streaming Processor (TSP)</strong> architecture, is explicitly designed for <strong>deterministic execution</strong>. This architectural shift avoids the non-determinism inherent to traditional CPU/GPU designs, ensuring consistent results in LLM inference.</p><p>Groq’s LPU, built on the Tensor Streaming Processor (TSP), showcases a departure from traditional CPU/GPU architectures, focusing on deterministic and predictable execution to enhance performance for language model inference tasks.</p><h4>Architectural Implications</h4><p>While model architectures like transformers don’t cause non-determinism themselves, their interaction with computational kernels can amplify it. This is particularly problematic for models using softmax-based token selection, where <strong>small numerical shifts</strong> in logits can lead to entirely different token predictions — especially when outputs are chained, as in autoregressive LLMs.</p><h4>A Message from AI Mind</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*5Wm7sOfTpe5DEbhg.gif" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://pub.aimind.so/">AI Mind Publication</a></li><li>🧠 Improve your <a href="https://www.aimind.so/prompt-generator?utm_source=pub&amp;utm_medium=message">AI prompts effortlessly and FREE</a></li><li><strong>🧰 Discover </strong><a href="https://www.aimind.so/?utm_source=pub&amp;utm_medium=message"><strong>Intuitive AI Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e589ba230d44" width="1" height="1" alt=""><hr><p><a href="https://pub.aimind.so/creating-deterministic-consistent-and-reproducible-text-in-llms-e589ba230d44">Creating Deterministic, Consistent and Reproducible text in LLMs</a> was originally published in <a href="https://pub.aimind.so/">AI Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart AI Traffic Detection with YOLOv12 Real-Time Vehicle Monitoring for Singapore-JB Causeway+…]]></title>
            <link>https://pub.aimind.so/smart-ai-traffic-detection-with-yolov12-real-time-vehicle-monitoring-for-singapore-jb-causeway-c509a80165ea?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/c509a80165ea</guid>
            <category><![CDATA[real-time-counting]]></category>
            <category><![CDATA[ai-traffic-detection]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolov12]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Sun, 20 Apr 2025 14:53:51 GMT</pubDate>
            <atom:updated>2026-09-14T14:24:42.043Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>YOLOv12: Using Attention Mechanisms for Traffic Detection on the Singapore-JB Causeway</strong> + Collab Code</h3><p><em>Updated 14 September 2026</em></p><p>The Singapore Johor Causeway is one of the busiest land customs in the world. There are almost 100–140 million people crossing the land customs yearly. Wouldn’t it be great if we have some object detection system that can help to build a detection system to count the number of vehicles, if it exceeds a threshold, it will send a notification about the road condition.</p><p>By leveraging object detection models like YOLOv12, we can automate the process of identifying vehicles, counting them, and classifying traffic conditions (JAM or NO JAM). This real-time information can then be used to optimize traffic flow, improve response times to accidents, and enhance overall traffic management.</p><p>In this walkthrough, we’ll explore what makes YOLOv12 unique and implement a traffic detection pipeline that counts vehicles and classifies traffic conditions across the Causeway using Google Colab.</p><h3>Introducing the YOLOv12</h3><p>In February 2025, YOLOv12 introduces attention-centric architectures, marking a break from traditional convolutional neural network (CNN) reliance (<a href="https://github.com/sunsmarterjie/yolov12">YOLOv12 GitHub</a>).</p><p>Key differences from YOLOv11 include: Area Attention (A²) Module and Residual Efficient Layer Aggregation Networks (R-ELAN)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhmjF2v5vymZNPMohTPFvg.png" /><figcaption>YOLOv12 is more performant than previous object detection models in terms of latency-accuracy (left) and FLOPs-accuracy (right) trade-offs <a href="https://arxiv.org/pdf/2502.12524">Source</a></figcaption></figure><p>YOLOv12-N delivers a mean Average Precision (mAP) of 40.6%, surpassing YOLOv11-N by 1.2% while maintaining similar inference latency, as reported in the YOLOv12 paper. Its attention-based architecture likely enhances generalization in complex scenes compared to YOLOv11. Additionally, YOLOv12 outperforms real-time detectors like RT-DETR and RT-DETRv2, achieving 42% faster inference with reduced parameters and computational demands. (<a href="https://arxiv.org/abs/2502.12524">YOLOv12 Paper</a>)</p><h4>mAP vs Latency</h4><p>YOLOv12 achieves higher mAP with competitive or better latency than previous YOLO models, seen on the red curve. The larger YOLOv12-X model reaches 55.2% mAP, a 0.6% improvement over YOLOv11-X, reflecting enhanced accuracy and efficiency. These advancements position YOLOv12 as highly effective for time-critical applications requiring rapid and accurate detection.</p><h4>mAP vs FLOPs (floating-point operations per second)</h4><p>The red curve representing YOLOv12 consistently lies above those of competing models, indicating higher accuracy at equivalent or lower FLOPs. This efficiency is critical for deploying models on resource-constrained devices, such as edge and mobile platforms. YOLOv12 scales effectively across model sizes, outperforming prior models with similar or fewer FLOPs. For instance, YOLOv12-L achieves 53.7% mAP with 88.9 GFLOPs, compared to YOLOv11-L’s 53.3% mAP with 86.9 GFLOPs, underscoring the benefits of its architectural optimizations.(<a href="https://arxiv.org/abs/2502.12524">YOLOv12 Paper</a>)</p><h3>Architecture of YOLOv12</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3K07b0So3oR5Ij9gREVeg.png" /><figcaption>(a) Architecture of the YOLOv12 object detection model that integrated Area Attention (A²) modules, R-ELAN blocks, and a streamlined detection head. <a href="https://arxiv.org/pdf/2406.19407">Source</a></figcaption></figure><p><strong>Key Innovations:</strong></p><ul><li><strong>Area Attention (A²) Module</strong>: Reduces the complexity of vanilla attention by segmenting feature maps for localized yet broad attention.</li><li><strong>Residual Efficient Layer Aggregation Networks (R-ELAN)</strong>: Enhances feature reuse and gradient flow while minimizing computational overhead.</li><li><strong>Flash Attention</strong>: Boosts performance by eliminating positional encoding and reducing memory access.</li></ul><p><strong>Area Attention Module (A²)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*aYSKzQoss9LbEiQ0q1NDig.png" /><figcaption>A comparison of the differnet local attentional methods. <a href="https://arxiv.org/pdf/2504.11995">Source</a></figcaption></figure><p>The A² module in YOLOv12 tackles the computational inefficiencies of traditional vanilla attention mechanisms, which incur a complexity of O(L²d) for an input sequence of length L and feature dimension d. By dividing a feature map of dimensions (H, W) into l equal, non-overlapping segments (default l=4) along either horizontal or vertical axes, the A² module reduces complexity to O((L/l)²d).</p><p>This segmentation enables independent processing of each area, significantly lowering computational overhead while preserving a broad receptive field.</p><p>Unlike global attention mechanisms that process interactions across the entire image, the A² module partitions the feature map into segments (default is 4) using a simple reshape operation.</p><p>This approach avoids the complexity of other local attention methods, such as Shifted Window, Criss-Cross Attention, or Axial Attention, which often increase computational demands. <a href="https://arxiv.org/pdf/2504.11995">Source</a></p><p>YOLOv12 paper visually contrasts the A² module with these variants, showing that while criss-cross attention limits interactions to row and column patterns, window attention restricts context to fixed regions, and axial attention processes dimensions sequentially, the A² module’s straightforward division maintains a larger receptive field with minimal computational cost</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ie4d7fm2_bdyPBr8v_wiQ@2x.png" /><figcaption>Heatmap showing the improved attention mechanism allows model to focus more accurately on object boundaries and key features. <a href="https://docs.ultralytics.com/models/yolo12/">Source</a></figcaption></figure><p>Heatmaps from the study demonstrate that this mechanism improves focus on object boundaries and key features, enabling YOLOv12 to handle large-scale images effectively while maintaining high detection accuracy. <a href="https://docs.ultralytics.com/models/yolo12/">Source</a></p><p>This balance of efficiency and robust performance makes the A² module particularly valuable for object detection tasks requiring global dependency modeling.</p><p><strong>Flash Attention</strong></p><p>YOLOv12 incorporates <em>Flash Attention</em> to enhance computational efficiency by eliminating positional encoding, reducing memory access overhead, and minimizing the number of operations.</p><p>This optimization boosts processing speed while preserving detection accuracy, maintaining a large receptive field to capture broad contextual information despite segment-wise processing. To further improve performance, YOLOv12 adjusts the MLP ratio from 4 to 1.2 (or 2 for certain scales), balancing computation between attention and feed-forward networks, reduces the depth of stacked blocks for easier optimization, and maximizes the use of convolution operators for their efficiency. <a href="https://arxiv.org/abs/2502.12524">Source</a></p><p>However, Flash Attention requires specific <em>CUDA configurations</em>, which may limit its applicability on non-GPU hardware. <a href="https://arxiv.org/abs/2504.11995">Source</a></p><p>By integrating these attention modules, YOLOv12 enhances its focus on critical image regions, significantly improving detection accuracy for object detection tasks</p><p><strong>Residual Efficient Layer Aggregation Networks (R-ELAN)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ms7qKHECoc0wZhddjWFL4Q.png" /><figcaption>The architecture comparison with popular modules including (a): CSPNet [55], (b) ELAN [56], © C3K2 (a case of GELAN) [28, 58], and (d) the proposed R-ELAN (residual efficient layer aggregation networks). It shows the improvement in the gradient propagation, feature reuse and computational efficiencies at each iteration <a href="https://arxiv.org/pdf/2502.12524">Source</a></figcaption></figure><p>The R-ELAN architecture in YOLOv12 enhances feature aggregation and gradient flow, addressing limitations of prior modules like CSPNet, ELAN, and C3K2.</p><p><strong>CSPNet (Cross-Stage Partial Network)</strong>: CSPNet enhances gradient flow by splitting the feature map into two parts, processing one through convolutions while keeping the other unchanged, and then merging them. This reduces redundant computation while preserving representational capacity. <a href="https://arxiv.org/pdf/2504.11995">Source</a></p><p>Previous YOLO models utilized <strong>Efficient Layer Aggregation Networks (ELAN)</strong>, which split the output of 1×1 convolution layers into multiple parallel streams for feature fusion before merging them back together. <a href="https://arxiv.org/pdf/2502.12524">Source</a></p><p>However, this approach of the 2 input parts introduced 2 major drawbacks: gradient blocking and optimization difficulties. These issues were particularly evident in deeper models (such as the L and X models), where the lack of direct residual connections between the input and output impeded effective gradient propagation, leading to slow or unstable convergence. <a href="https://arxiv.org/pdf/2502.12524">Source</a></p><p><strong>C3K2 (a variant of GELAN)</strong>: C3K2 modifies ELAN with additional transformations but inherits its gradient-blocking issues, failing to fully address optimization challenges in deep networks. <a href="https://arxiv.org/pdf/2504.11995">Source</a></p><p><strong>R-ELAN</strong> overcomes these issues by introducing residual shortcuts with a scaling factor (default 0.01) and a revised feature aggregation strategy, improving gradient propagation with minimal computational overhead, preventing the loss of important details in images during training.</p><p><strong>R-ELAN</strong> applies a transition layer to adjust channel dimensions upfront, processes the unified feature map through bottleneck layers, and then concatenates the results. This bottleneck structure reduces computational costs and parameters while maintaining performance. <a href="https://arxiv.org/pdf/2502.12524">Source</a></p><h3><strong>Additional Limitations of YOLOv12</strong></h3><p>YOLOv12’s attention-based architecture, featuring the Area Attention (A²) module, Flash Attention, and Residual Efficient Layer Aggregation Networks (R-ELAN), delivers superior accuracy but introduces several limitations, particularly in resource-constrained environments.</p><ol><li><strong>Memory bottlenecks:</strong> Attention-based architectures require higher VRAM usage due to extensive feature maps and matrix multiplications. <a href="https://arxiv.org/pdf/2504.11995">Source</a></li><li><strong>Inference Latency: </strong>YOLOv12 reduces attention overhead compared to Vision Transformers but lags behind CNN-based YOLO models on edge hardware. <a href="https://arxiv.org/pdf/2504.11995">Source</a></li></ol><p>Now, we know all the basics of YOLOv12, we can now head back to the walkthrough. You can follow and run the walkthrough at the same time by running the code in <a href="https://gist.github.com/yheyyyy/ee644f30a172971f0b2e4093843e3c91">Google Colab</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eb7a615cfe3246eb3f228c80b6381f6/href">https://medium.com/media/4eb7a615cfe3246eb3f228c80b6381f6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiEwUICkiSVlX58ALi84uQ.png" /><figcaption>Different detection sensitivities of the YOLOv12 model sizes.</figcaption></figure><p><strong>Setting up the Environment</strong></p><p>To implement our traffic jam detection system, we’ll be using Google Colab, a cloud-based platform that provides free access to GPUs (Remember to turn it on!) for accelerated computations.</p><p>Here are the key steps for setting up the environment:</p><ol><li><strong>Install Necessary Libraries:</strong></li></ol><pre>!pip install -q git+https://github.com/sunsmarterjie/yolov12.git flash-attn supervision<br>!pip install -q ultralytics==8.3.107</pre><p>2. <strong>Import Libraries:</strong></p><pre>import os<br>import requests<br>from bs4 import BeautifulSoup<br>from ultralytics import YOLO<br>from IPython.display import Image<br>import matplotlib.pyplot as plt<br>from PIL import Image<br>import locale<br>import cv2<br><br>locale.getpreferredencoding = lambda: &quot;UTF-8&quot;</pre><p>3. <strong>Loading the YOLOv12 Models</strong></p><p>Next, we load the pre-trained YOLOv12 models, to allow you to experiment with different model sizes, balancing accuracy and computational resources.</p><pre># Load the YOLOv12 models for comparison<br>n_model = YOLO(&quot;yolo12n.pt&quot;)<br>s_model = YOLO(&quot;yolo12s.pt&quot;)<br>m_model = YOLO(&quot;yolo12m.pt&quot;)<br>l_model = YOLO(&quot;yolo12l.pt&quot;)<br>x_model = YOLO(&quot;yolo12x.pt&quot;)</pre><p><strong>4. Fetching Live Traffic Images</strong></p><p>The Singapore’s LTA has kindly provided these information online for easy access.</p><pre>website_url = &quot;https://onemotoring.lta.gov.sg/content/onemotoring/home/driving/traffic_information/traffic-cameras/woodlands.html&quot;<br><br>image_src = None<br>print(f&quot;Fetching HTML from: {website_url}&quot;)<br><br>try:<br>    # Send a GET request to the website<br>    response = requests.get(website_url, timeout=10) # Added timeout<br>    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)<br>    <br>    # Get the HTML content<br>    html_content = response.text<br>    <br>    # Parse the HTML<br>    soup = BeautifulSoup(html_content, &#39;html.parser&#39;)<br>    img_tag = soup.find(&#39;img&#39;, alt=&quot;View from Woodlands Causeway (Towards Johor)&quot;) <br>    <br>    if img_tag and img_tag.has_attr(&#39;src&#39;):<br>        image_src = img_tag[&#39;src&#39;]<br>        if image_src.startswith(&#39;//&#39;):<br>            image_src = &#39;https:&#39; + image_src<br>        elif not image_src.startswith(&#39;http&#39;):<br>            from urllib.parse import urljoin<br>            image_src = urljoin(website_url, image_src)<br>            <br>        print(f&quot;Extracted Image Source: {image_src}&quot;)<br>    else:<br>        print(&quot;Image tag with the specified criteria not found on the page.&quot;)<br><br>except requests.exceptions.RequestException as e:<br>    print(f&quot;Error fetching website content: {e}&quot;)<br>except Exception as e:<br>    print(f&quot;An error occurred during parsing: {e}&quot;)<br><br>if image_src:<br>    IMAGE_DIR = &quot;traffic_images&quot; <br>    os.makedirs(IMAGE_DIR, exist_ok=True)<br>    <br>    try:<br>        print(f&quot;\nDownloading image from: {image_src}&quot;)<br>        img_response = requests.get(image_src, timeout=15)<br>        img_response.raise_for_status()<br>        # Create a filename<br>        img_filename = os.path.basename(image_src.split(&#39;?&#39;)[0])<br>        if not img_filename:<br>             img_filename = &quot;downloaded_traffic_image.jpg&quot;<br>        save_path = os.path.join(IMAGE_DIR, img_filename) <br>        # Save the image<br>        with open(save_path, &#39;wb&#39;) as f:<br>            f.write(img_response.content)<br>        print(f&quot;Image downloaded successfully to: {save_path}&quot;)<br>        <br>    except requests.exceptions.RequestException as e:<br>        print(f&quot;Failed to download image: {e}&quot;)<br>    except Exception as e:<br>        print(f&quot;An error occurred saving or displaying the image: {e}&quot;)</pre><p>This ensures we have real-world data to test our system.</p><p>Running the image analysis for night road condition, on a long weekend. Trying out all the different sizes of the models.</p><pre>original_img = Image.open(save_path)<br><br>fig, axes = plt.subplots(2, 3, figsize=(15, 10))<br>axes[0, 0].imshow(original_img)<br>axes[0, 0].set_title(&#39;Original Image&#39;)<br>axes[0, 0].axis(&#39;off&#39;)<br><br>models = [n_model, s_model, m_model, l_model, x_model]<br>model_names = [&#39;YOLOv12n&#39;, &#39;YOLOv12s&#39;, &#39;YOLOv12m&#39;, &#39;YOLOv12l&#39;, &#39;YOLOv12x&#39;]<br>positions = [(0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]<br><br># Loop through models and plot their results<br>for model, name, (row, col) in zip(models, model_names, positions):<br>    results = model(save_path)<br>    result_img = results[0].plot()<br><br>    axes[row, col].imshow(result_img)<br>    axes[row, col].set_title(f&#39;{name} Detection Results&#39;)<br>    axes[row, col].axis(&#39;off&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oeQ033nQqVuexRKlK0_FLw.png" /></figure><p>Indeed, we can see that while the image is a little foggy probably due to the persistent rain in the morning, the YOLOv12 is able to capture the tiny cars and buses in the image, especially for YOLOv12L and YOLOv12X.</p><p><strong>Step 5. Vehicle Detection and Counting Functions</strong></p><p>We’ll define a function called get_vehicle_class_ids to get the ID of the respective classes so that we can do a count in the subsequent function.</p><pre>def get_vehicle_class_ids(model, vehicle_classes=[&#39;car&#39;, &#39;bus&#39;, &#39;truck&#39;]):<br>    &quot;&quot;&quot;Get class IDs for vehicle classes from the model&#39;s class names.&quot;&quot;&quot;<br>    names = model.names<br>    if isinstance(names, dict):<br>        names_list = list(names.values())<br>    else:<br>        names_list = names<br>    return [names_list.index(cls) for cls in vehicle_classes if cls in names_list]</pre><p>The heart of the system lies in the detect_and_count_vehicles function. It takes an image path, the YOLOv12 model, and vehicle class names as input. The function processes the image, detects vehicles, counts them, and calculates the vehicle density.</p><pre>def detect_and_count_vehicles(image_path, model, vehicle_classes=[&#39;car&#39;, &#39;bus&#39;, &#39;truck&#39;], confidence_threshold=0.01):<br>    if not isinstance(image_path, str) or not os.path.exists(image_path):<br>        print(f&quot;Error: Invalid or non-existent image path provided: {image_path}&quot;)<br>        return None<br>    try:<br>        image = cv2.imread(image_path)<br>        if image is None:<br>            print(f&quot;Error: Could not read image {image_path}&quot;)<br>            return None<br><br>        height, width = image.shape[:2]<br>        image_area = height * width<br><br>        if &#39;model&#39; not in globals():<br>            print(&quot;Error: YOLO model not loaded.&quot;)<br>            return None<br><br>        vehicle_class_ids = get_vehicle_class_ids(model, vehicle_classes)<br><br>        results = model(image, conf=confidence_threshold, classes=vehicle_class_ids)<br>        vehicle_counts = {cls: 0 for cls in vehicle_classes}<br>        total_vehicle_area = 0<br>        annotated_img = image.copy()<br><br>        if results and len(results) &gt; 0:<br>            boxes = results[0].boxes<br>            for box in boxes:<br>                cls_id = int(box.cls.item())<br>                cls_name = model.names[cls_id]<br>                if cls_name in vehicle_classes:<br>                    vehicle_counts[cls_name] += 1<br>                    x1, y1, x2, y2 = map(int, box.xyxy[0].cpu().numpy())<br>                    conf = float(box.conf.item())<br>                    box_area = (x2 - x1) * (y2 - y1)<br>                    total_vehicle_area += box_area<br>                    cv2.rectangle(annotated_img, (x1, y1), (x2, y2), (0, 255, 0), 2)<br>                    label = f&quot;{cls_name}: {conf:.2f}&quot;<br>                    cv2.putText(annotated_img, label, (x1, y1 - 10),<br>                                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)<br><br>        total_vehicles = sum(vehicle_counts.values())<br>        vehicle_density = total_vehicle_area / image_area if image_area &gt; 0 else 0<br><br>        return {<br>            &quot;counts&quot;: vehicle_counts,<br>            &quot;total_count&quot;: total_vehicles,<br>            &quot;density&quot;: vehicle_density,<br>            &quot;annotated_image&quot;: annotated_img<br>        }<br>    except Exception as e:<br>        print(f&quot;An error occurred processing {image_path}: {e}&quot;)<br>        return None</pre><p>The classify_traffic function takes the detection results and applies a threshold-based rule to determine the traffic status:</p><pre>def classify_traffic(detection_results, count_threshold=10):<br>    if detection_results is None:<br>        return &quot;Error&quot;<br>    total_count = detection_results[&#39;total_count&#39;]<br>    density = detection_results[&#39;density&#39;]<br>    if total_count &gt;= count_threshold:<br>        return &quot;JAM&quot;<br>    else:<br>        return &quot;NO JAM&quot;</pre><p><strong>Step 6: Run Detection and Classification</strong></p><p>Finally, the notebook demonstrates how to use these functions with the downloaded traffic image:</p><pre>model = x_model<br>if &#39;save_path&#39; in locals() and os.path.exists(save_path):<br>    print(f&quot;\n--- Analyzing downloaded image: {os.path.basename(save_path)} ---&quot;)<br>    COUNT_THRESHOLD = 1<br><br>    detection_result = detect_and_count_vehicles(save_path, model)<br>    if detection_result:<br>        traffic_status = classify_traffic(detection_result, COUNT_THRESHOLD)<br>        print(f&quot;  Detections: {detection_result[&#39;counts&#39;]}&quot;)<br>        print(f&quot;  Density: {detection_result[&#39;density&#39;]:.4f}&quot;)<br>        print(f&quot;  Status: {traffic_status}&quot;)<br><br>        result_data = {<br>            &#39;Image&#39;: os.path.basename(save_path),<br>            &#39;Total Vehicles&#39;: detection_result[&#39;total_count&#39;],<br>            &#39;Status&#39;: traffic_status<br>        }<br>        result_data.update(detection_result[&#39;counts&#39;])<br><br>        annotated_image_bgr = detection_result[&#39;annotated_image&#39;]<br>        status_color = (0, 0, 255) if traffic_status == &quot;JAM&quot; else (0, 255, 0)<br>        cv2.putText(annotated_image_bgr, f&quot;Status: {traffic_status}&quot;, (40, 80),<br>                    cv2.FONT_HERSHEY_SIMPLEX, 3, status_color, 4)<br>        annotated_image_rgb = cv2.cvtColor(annotated_image_bgr, cv2.COLOR_BGR2RGB)<br>        plt.figure(figsize=(12, 8))<br>        plt.imshow(annotated_image_rgb)<br>        plt.title(f&quot;Analysis: {os.path.basename(save_path)} - Status: {traffic_status}&quot;)<br>        plt.axis(&#39;off&#39;)<br>        plt.show()<br>    else:<br>        print(&quot;Failed to process the downloaded image.&quot;)<br>else:<br>    print(&quot;\nSkipping analysis: &#39;save_path&#39; not defined or file does not exist.&quot;)<br>    print(&quot;Please ensure the previous cell successfully downloaded an image.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*aVHhOQ_TIS4-HOfg7vza6A.png" /><figcaption>68 cars, 2 buses, 2 trucks detected. Status: JAM.</figcaption></figure><p>While YOLOv12 is powerful in detecting vehicles even under challenging conditions, real-world deployment would benefit from a well-labeled dataset tailored for the Singapore-JB Causeway. With careful tuning and resource considerations, this model holds great promise for smart traffic monitoring and management.</p><p>If you found this helpful, do remember to follow, comment and give claps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c509a80165ea" width="1" height="1" alt=""><hr><p><a href="https://pub.aimind.so/smart-ai-traffic-detection-with-yolov12-real-time-vehicle-monitoring-for-singapore-jb-causeway-c509a80165ea">Smart AI Traffic Detection with YOLOv12 Real-Time Vehicle Monitoring for Singapore-JB Causeway+…</a> was originally published in <a href="https://pub.aimind.so/">AI Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Walkthrough: Training YOLOv11 for Brain Tumor Detection]]></title>
            <link>https://medium.com/data-and-beyond/walkthrough-training-yolov11-for-brain-tumor-detection-a194575f3339?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/a194575f3339</guid>
            <category><![CDATA[ultralytics]]></category>
            <category><![CDATA[c3k2-blocks]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-recognition]]></category>
            <category><![CDATA[yolov11]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 15:15:11 GMT</pubDate>
            <atom:updated>2025-04-20T07:00:44.150Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine a tool that can help healthcare practitioners spot brain tumors in medical scans quickly and accurately after the scans are done, allowing for critical interventions when required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3ud-UXx_DULyGJrXJyJ-w.png" /><figcaption>What if, doctors used it to augment their diagnosis? Image generated from ChatGPT</figcaption></figure><p>That’s where YOLOv11, a cutting-edge object detection algorithm can come into play. This article walks you through a Python notebook that shows how to use YOLOv11 to detect brain tumors in X-ray images quickly.</p><p>However, AI in medicine is a supportive tool, not a replacement for human expertise, and its use raises ethical questions about accuracy and patient trust.</p><p>Before going through the walkthrough, I will be running through some of the basics of YOLO and the specific architectures of YOLOv11.</p><h3>The Evolution of YOLO</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FT-yJsKumaycRC4ub3Wv7Q.png" /><figcaption>Evolution of YOLO Algorithms throughout the years. <a href="https://arxiv.org/html/2411.00201v1">Source</a></figcaption></figure><p>YOLO, or “You Only Look Once,” was first introduced in 2015 and has undergone multiple iterations developed by <a href="https://viso.ai/deep-learning/yolov8-guide/">different research groups</a>.</p><p>Unlike traditional methods that scan images multiple times, YOLO processes an image in a single pass, predicting bounding boxes and class probabilities simultaneously, hence, enabling efficient processing of real-time images.</p><p>Models like the <strong>Single Shot MultiBox Detector (SSD) </strong>inspired the YOLO family, particularly in their use of multiple feature maps at various resolutions. These enable detection of objects of different sizes and shapes, enhancing both localization and classification accuracy.</p><h3>YOLOv11 vs. Previous YOLO Models</h3><p>YOLOv11 offers five model sizes — nano, small, medium, large, and extra-large — each tailored for specific needs, from resource-constrained devices to high-accuracy requirements.</p><p>This flexibility supports tasks like <a href="https://www.ultralytics.com/glossary/image-classification">image classification</a>, <a href="https://www.ultralytics.com/glossary/object-detection">object detection</a>, <a href="https://docs.ultralytics.com/guides/instance-segmentation-and-tracking/">instance segmentation</a>, <a href="https://docs.ultralytics.com/modes/track/">tracking</a>, <a href="https://docs.ultralytics.com/tasks/pose/">pose estimation</a>, and <a href="https://docs.ultralytics.com/tasks/obb/">oriented bounding boxes (OBB) object detection</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UDskHY7dmk6_UyIgRjaAQ.png" /><figcaption>YOLOv11 outperforms other models on the COCO dataset in terms of accuracy at for similar latency values on a T4 <a href="https://www.ultralytics.com/blog/all-you-need-to-know-about-ultralytics-yolo11-and-its-applications">Source</a></figcaption></figure><p><strong>Performance of YOLOv11</strong></p><p>On the COCO dataset (benchmark for object recognition), the YOLOv11 outperforms its predecessors. For instance, YOLOv11x achieves 54.7% mAP@50–95 with a latency of ~11.3 ms using TensorRT10 on a T4 GPU.</p><p>Key metrics measured here include:</p><ul><li><strong>Inference Time (ms/img)</strong>- Time taken to process an image and generate predictions.</li><li><strong>Mean Average Precision (mAP@50–95)</strong>: A comprehensive metric averaging precision and recall across classes, and varying conditions within the dataset.</li></ul><h3>Architectural Innovations</h3><p>YOLOv11 introduces significant improvements, focusing on efficiency and accuracy: Key differences include: the C3k2 block and C2PSA module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*gcRtPBO0amFFnGOmCN0PAA.png" /><figcaption>YOLO11 architecture showcasing the new C3k2 blocks and the C2PSA module. <a href="https://medium.com/@paultsoi1014/yolo11-the-cutting-edge-evolution-in-object-detection-a-brief-review-of-the-latest-in-the-yolo-19065729edfe">Source</a></figcaption></figure><p><strong>C3K2 Block</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*6Aaop5mLWfSniMCw.png" /><figcaption>Detailed design of the bottleneck, C3, C2F and C3K2 module <a href="https://medium.com/@paultsoi1014/yolo11-the-cutting-edge-evolution-in-object-detection-a-brief-review-of-the-latest-in-the-yolo-19065729edfe">Source</a></figcaption></figure><p>YOLOv11 replaces YOLOv8’s C2f block with the more efficient <strong>C3K2 (Cross Stage Partial with kernel size 2)</strong> block. The C3K2 block uses smaller 3×3 kernels for convolutions and processes separate feature maps that are later merged after several convolution, This way, it improves feature representation while reducing parameter count.</p><p>C3K2 is actually a transformed version of C2F module.</p><ul><li>When c3k=False, the block behaves like C2F.</li><li>When c3k=True, the C3 module replaces the bottleneck, offering efficiency and better gradient flow.</li></ul><p>The main advantage of the C2f/ C3K2 structure lies in the ability to preserve information. n bottleneck modules — designed to reduce computational cost — these blocks manage information flow while minimizing loss during compression. Unlike the C3 module, which only considers the final output of the bottleneck, C2f/C3K2 concatenates outputs from all intermediate bottlenecks. This preserves more information and produces a richer, more comprehensive representation, which contributes to:</p><ul><li><strong>Improved Gradient Flow</strong>: Enabling more effective learning and faster convergenc</li><li><strong>Better Feature Representation</strong>: Early bottlenecks may capture low-level features (e.g., edges, corners), while later stages extract high-level features (e.g., objects, scenes). Combining these provides a more robust and detailed understanding.</li><li><strong>Potentially Slower, but Superior Results</strong>: Although initially more computationally intensive, the preserved information and enhanced learning dynamics often lead to faster training and improved accuracy.</li></ul><p>Overall, YOLOv11’s replacement of the C2f block with the more efficient C3K2 module delivers better performance without sacrificing speed.</p><p><strong>Attention Mechanisms: C2PSA network architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/0*7AWtPHdCsapgimwW.png" /><figcaption>Detailed design of the C2PSA module <a href="https://medium.com/@paultsoi1014/yolo11-the-cutting-edge-evolution-in-object-detection-a-brief-review-of-the-latest-in-the-yolo-19065729edfe">Source</a></figcaption></figure><p>The C2PSA block uses two PSA (Partial Spatial Attention) modules, which operate on separate branches of the feature map and are later concatenated. These enhances spatial attention, improving accuracy and detection of small and overlapping objects. It extends C2F with Position-Sensitive Attention (PSA), using multi-head attention and feedforward networks to prioritize positional aspects, enhancing spatial relationship understanding <a href="https://arxiv.org/html/2411.00201v1">Source</a>.</p><p>This block introduces attention mechanisms that improve the model’s focus on important regions within an image, such as smaller or partially occluded objects, by emphasizing spatial relevance in the feature maps.</p><p>This setup ensures the model focuses on spatial information while maintaining a balance between computational cost and detection accuracy.</p><p>As usual, I will be going through the code walkthrough now.</p><p>You can find the Google Collab Notebook to run simultaneously while going through the walkthrough.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77b997aea77f87698e35b97dcafedd38/href">https://medium.com/media/77b997aea77f87698e35b97dcafedd38/href</a></iframe><h3>CODE <strong>WALKTHROUGH</strong></h3><h3>Setting Up the Environment</h3><h4>Installing Required Libraries</h4><p>The first step is to set up the environment in Google Collab. The notebook installs the Ultralytics library, which simplifies working with YOLO models, and PyTorch with CUDA support for GPU acceleration:</p><pre>!pip install -q ultralytics==8.3.107<br>!pip install -q torch --index-url https://download.pytorch.org/whl/cu124</pre><h3>Importing Libraries</h3><p>Next, the notebook imports essential libraries:</p><pre>from ultralytics import YOLO<br>from IPython.display import Image<br>import matplotlib.pyplot as plt<br>import cv2<br>import PIL.Image<br>import locale<br><br>locale.getpreferredencoding = lambda: &quot;UTF-8&quot;</pre><h3>Preparing the Dataset</h3><h4>Downloading and Organizing the Brain Tumor Dataset</h4><p>The notebook uses a custom dataset of brain X-ray images, typically sourced from repositories like <a href="https://github.com/ultralytics/assets/releases/download/v0.0.0/brain-tumor.zip">Ultralytics’ GitHub</a>. The dataset is organized into directories:</p><p><em>train/images/: Training Brain Tumor X-ray images.</em></p><p><em>train/labels/: Corresponding annotations in YOLO format (e.g., &lt;class_id&gt; &lt;x_center&gt; &lt;y_center&gt; &lt;width&gt; &lt;height&gt;).</em></p><p><em>valid/images/: Validation images.</em></p><p><em>valid/labels/: Validation annotations.</em></p><p>Each label file lists tumors with normalized coordinates, where classes might be “negative” (no tumor) and “positive” (tumor present).</p><h4>Downloading Custom Brain Tumor Dataset and yaml File from Ultralytics for YOLOv11:</h4><pre># Download the dataset from the Ultralytics GitHub repository<br>!wget -q https://github.com/ultralytics/assets/releases/download/v0.0.0/brain-tumor.zip -O brain-tumor.zip<br>!mkdir -p /content/datasets/brain-tumor<br>!unzip -q /content/brain-tumor.zip -d /content/datasets/brain-tumor<br><br>!wget -q https://raw.githubusercontent.com/ultralytics/ultralytics/main/ultralytics/cfg/datasets/brain-tumor.yaml -O /content/brain-tumor.yaml<br><br># Load a sample image from the dataset to see if it works on the untrained model<br>validation_img_path = &#39;/content/datasets/brain-tumor/valid/images/val_1 (1).jpg&#39;</pre><p>This file tells the model where to find images, how many classes exist, and their names. It’s a critical step to ensure the model knows what to train on.</p><p>If you are curious, this is how the <a href="https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/datasets/brain-tumor.yaml">brain-tumor.yaml</a> file is organised and it is used by the train function in ultralytics model to efficiently train a model.</p><pre># Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license<br><br># Brain-tumor dataset by Ultralytics<br># Documentation: https://docs.ultralytics.com/datasets/detect/brain-tumor/<br># Example usage: yolo train data=brain-tumor.yaml<br># parent<br># ├── ultralytics<br># └── datasets<br>#     └── brain-tumor  ← downloads here (4.05 MB)<br><br># Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]<br>path: ../datasets/brain-tumor # dataset root dir<br>train: train/images # train images (relative to &#39;path&#39;) 893 images<br>val: valid/images # val images (relative to &#39;path&#39;) 223 images<br>test: # test images (relative to &#39;path&#39;)<br><br># Classes<br>names:<br>  0: negative<br>  1: positive<br><br># Download script/URL (optional)<br>download: https://github.com/ultralytics/assets/releases/download/v0.0.0/brain-tumor.zip</pre><h3>Loading and Testing Pre-trained YOLOv11 Models</h3><h4>Loading Different YOLOv11 Variants</h4><p>YOLOv11 comes in multiple sizes — nano (n), small (s), medium (m), large (l), and extra-large (x) — balancing speed and accuracy. The notebook loads them:</p><pre>model_n = YOLO(&#39;yolov11n.pt&#39;)<br>model_s = YOLO(&#39;yolov11s.pt&#39;)<br>model_m = YOLO(&#39;yolov11m.pt&#39;)<br>model_l = YOLO(&#39;yolov11l.pt&#39;)<br>model_x = YOLO(&#39;yolov11x.pt&#39;)</pre><p>Smaller models like nano are faster but less precise, while larger ones like extra-large excel in accuracy but require more resources.</p><h4>Testing on a Validation Image</h4><pre>brain_img = Image.open(validation_img_path)<br><br># Create a 2x3 grid of subplots<br>fig, axes = plt.subplots(2, 3, figsize=(15, 10))<br><br>axes[0, 0].imshow(brain_img)<br>axes[0, 0].set_title(&#39;Original Image&#39;)<br>axes[0, 0].axis(&#39;off&#39;)<br><br># Prepare model names and grid positions (excluding (0, 0))<br>models = [n_model, s_model, m_model, l_model, x_model]<br>model_names = [&#39;YOLOv11n&#39;, &#39;YOLOv11s&#39;, &#39;YOLOv11m&#39;, &#39;YOLOv11l&#39;, &#39;YOLOv11x&#39;]<br>positions = [(0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]  # Skip (0, 0)<br><br># Loop through models and plot their results<br>for model, name, (row, col) in zip(models, model_names, positions):<br>    results = model(validation_img_path)<br>    result_img = results[0].plot()<br><br>    axes[row, col].imshow(result_img)<br>    axes[row, col].set_title(f&#39;{name} Detection Results&#39;)<br>    axes[row, col].axis(&#39;off&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkrRq57XusqyO53tQJy12w.png" /><figcaption>Hmmmm… the model does not seem to know that this is a x-ray image of a brain.</figcaption></figure><p>The notebook tests these models on a sample X-ray. Since they’re pre-trained on general datasets like COCO, they often misclassify medical images. For example, larger models might detect a brain X-ray as containing a “bird” or “donut,” showing they’re not yet suited for this task. The results are visualized in a 2x3 grid using Matplotlib, highlighting the need for custom training.</p><p>Now we will proceed to fine-tune the model based on the brain x-ray scans for tumor detection.</p><h3>Training a Custom Model</h3><p>Notably, Ultralytics has streamlined the process of fine-tuning and customizing YOLO models, a task that was considerably more complex in earlier iterations.</p><p>The introduction of user-friendly interfaces, comprehensive documentation, and pre-built modules has greatly simplified essential tasks such as data augmentation, model training, and evaluation. Moreover, the development of scalable model versions allows users to select models tailored to specific resource constraints and application requirements, thereby facilitating more effective fine-tuning.</p><p>The integration of advanced tools for hyperparameter tuning, automated learning rate scheduling, and model pruning has further refined the customization process. Continuous updates and robust community support have also contributed to making YOLO models more accessible and adaptable for a wide range of applications.</p><p>The notebook trains the smallest model, YOLOv11n, due to Collab&#39;s resource limits. The training command includes specific parameters:</p><pre>model_n.train(data=&#39;brain-tumor.yaml&#39;, <br>              epochs=20, <br>              batch=16, <br>              imgsz=256, <br>              device=0, <br>              workers=0, <br>              scale=0.8, <br>              mosaic=0.8, <br>              mixup=0.12, <br>              copy_paste=0.3<br>)</pre><ul><li>Epochs (20): Number of passes through the dataset.</li><li>Batch Size (16): Images processed per iteration.</li><li>Image Size (256): Input resolution, balancing speed and detail.</li><li>Data Augmentation: Techniques like scaling (0.8), mosaic (0.8), mixup (0.12), and copy-paste (0.3) enhance model robustness.</li><li>Device (0): Uses the GPU.</li><li>Workers (0): Data loading on the main thread.</li></ul><p>Like YOLOv4, YOLOv8 employs Mosaic data augmentation, which combines four different images into one. This technique provides the model with richer contextual information and helps improve generalization. The Bag of Freebies (BoF) introduced in YOLOv4 included various augmentation techniques such as CutMix, CutOut, MixUp, and the newly proposed Mosaic method. Mosaic augmentation, in particular, enhances the model’s ability to learn from diverse spatial contexts by blending four training images into a single composite.</p><p>These settings help the model learn tumor patterns while preventing overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*VYfHc1YJdqNkfa-2s7xd3g.png" /><figcaption>You should see this summary of the YOLOv11n architecture when you run the code above.</figcaption></figure><p>Once the model has finished training- you should see these information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*GrTx25HBwMTwNM1Vu7HBgQ.png" /><figcaption>After 20 epochs, the trained model has <strong>mAP@50-95 </strong>of merely<strong> </strong>0.355</figcaption></figure><p>The trained model has a decent recall (0.861) but lower precision (0.449), meaning it detects most objects but has a higher rate of false positives.</p><h4>Evaluating the Trained Model</h4><pre>import cv2<br>import matplotlib.pyplot as plt<br>from ultralytics import YOLO<br><br># === Load trained YOLO model ===<br>model_path = &#39;/content/runs/detect/train/weights/best.pt&#39;<br>model = YOLO(model_path)<br><br># === List of image-label pairs ===<br>pairs = [<br>    (&quot;/content/datasets/brain-tumor/valid/images/val_1 (1).jpg&quot;,<br>     &quot;/content/datasets/brain-tumor/valid/labels/val_1 (1).txt&quot;),<br><br>    (&quot;/content/datasets/brain-tumor/valid/images/val_1 (2).jpg&quot;,<br>     &quot;/content/datasets/brain-tumor/valid/labels/val_1 (2).txt&quot;),<br><br>    (&quot;/content/datasets/brain-tumor/valid/images/val_1 (3).jpg&quot;,<br>     &quot;/content/datasets/brain-tumor/valid/labels/val_1 (3).txt&quot;),<br>]<br><br># === Loop through each pair ===<br>for img_path, label_path in pairs:<br>    # Load image<br>    image = cv2.imread(img_path)<br>    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>    img_h, img_w, _ = image.shape<br><br>    # Copy for ground truth box drawing<br>    ground_truth_img = image.copy()<br><br>    # Load label(s) and draw<br>    with open(label_path, &#39;r&#39;) as f:<br>        for line in f:<br>            class_id, x_center, y_center, width, height = map(float, line.strip().split())<br>            x1 = int((x_center - width / 2) * img_w)<br>            y1 = int((y_center - height / 2) * img_h)<br>            x2 = int((x_center + width / 2) * img_w)<br>            y2 = int((y_center + height / 2) * img_h)<br><br>            label_name = &quot;positive&quot; if int(class_id) == 1 else &quot;negative&quot;<br>            cv2.rectangle(ground_truth_img, (x1, y1), (x2, y2), (0, 255, 0), 2)<br>            cv2.putText(ground_truth_img, label_name, (x1, y1 - 10),<br>                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)<br><br>    # Model prediction<br>    results = model(img_path)<br>    prediction_img = results[0].plot()<br><br>    # Plot<br>    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))<br>    ax1.imshow(ground_truth_img)<br>    ax1.set_title(&#39;Ground Truth&#39;)<br>    ax1.axis(&#39;off&#39;)<br><br>    ax2.imshow(prediction_img)<br>    ax2.set_title(&#39;Model Prediction&#39;)<br>    ax2.axis(&#39;off&#39;)<br><br>    plt.tight_layout()<br>    plt.show()</pre><p>After training, the model is tested on validation images. The model is now able to pick up and detect the presence of tumor through the training of the labelled tumor images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*jrktWqOgguRDXwahGkGHdw.png" /><figcaption>Model is able to pick up on the tumor!</figcaption></figure><h3>Additional Considerations</h3><p>Applying YOLOv11 to brain tumor detection isn’t just about code — it involves practical and ethical challenges.</p><p><strong>Model Selection</strong></p><p>Choosing the right model size depends on your needs. Nano is ideal for quick prototyping, but larger models might be necessary for clinical accuracy. Testing different variants, as the notebook does, helps find the best fit.</p><p><strong>Data Quality</strong></p><p>Medical datasets require precise annotations. Errors in labeling tumors can mislead the model, so it’s crucial to verify the dataset’s reliability. The notebook assumes a well-prepared dataset, but in practice, you might need to clean or augment it.</p><h3>Performance Optimization</h3><p>To improve results, consider:</p><ul><li>Fix class imbalance</li><li>More Epochs: Training longer (e.g., 50–100 epochs) could boost accuracy.</li><li>Hyperparameter Tuning: Adjusting learning rates or augmentation settings.</li><li>Larger Models: If resources allow, try YOLOv11m or larger for better precision.</li></ul><p>YOLOv11 faces challenges:</p><ul><li><strong>Detecting Small and Rotated Objects</strong>: Struggles with low-resolution and variably oriented objects due to architectural constraints, potentially affecting brain tumor detection accuracy.</li><li><strong>Susceptibility to Overfitting</strong>: Prone to overfitting on limited datasets, necessitating robust data augmentation and generalization strategies.</li><li><strong>Computational Efficiency vs. Accuracy Trade-off</strong>: Balances speed and accuracy, crucial for real-time medical applications but may compromise in complex environments. <a href="https://arxiv.org/pdf/2406.19407">Source</a></li></ul><p>My GitHub Code is available here too:</p><p><a href="https://github.com/yheyyyy/brain-tumor-yolo">GitHub - yheyyyy/brain-tumor-yolo: Brain-tumor analysis using yolov11</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a194575f3339" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/walkthrough-training-yolov11-for-brain-tumor-detection-a194575f3339">Walkthrough: Training YOLOv11 for Brain Tumor Detection</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL vs. Vector Databases: Choosing the Right Tool for Your AI-Powered Application]]></title>
            <link>https://medium.com/data-and-beyond/sql-vs-vector-databases-choosing-the-right-tool-for-your-ai-powered-application-eb3bef40921b?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb3bef40921b</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[pgvector]]></category>
            <category><![CDATA[weaviate]]></category>
            <category><![CDATA[pgsql]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 15:00:01 GMT</pubDate>
            <atom:updated>2025-04-04T06:14:24.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vector Database or SQL for Storing Vectors?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KU-fcYAIPifa80VI96bVhw.jpeg" /><figcaption>Vector database or SQL? That is the question- Image generated from Imagen 3</figcaption></figure><p>During a hackathon, I encountered confusion regarding the functional scope of using specialized vector databases versus SQL databases, particularly those with extensions like pgvector and pgai. The thought centered on the merits and use cases of each solution, which vary significantly based on application needs. Hence, I thought i should pen-down my findings to share with everyone my newfound knowledge.</p><p>This write-up will explore both options, their strengths, underlying technologies, limitations and their ideal use case.</p><p>The choice between vector databases and SQL with extensions, however, REALLY depends on your application needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHbZ5Yc-QrKJj0qIaBlvfA.jpeg" /><figcaption>SQL or Vector DB? <a href="https://www.newsletter.theaiengineering.com/p/understanding-vector-databases-a">Source</a></figcaption></figure><h3>Vector Databases Fundamentals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjfXHTElaIt7O0TYkIqbNQ.png" /><figcaption>Vector search within a 2D space <a href="https://www.metisdata.io/blog/exploring-the-power-of-pgvector-as-an-open-source-vector-database">Source</a></figcaption></figure><p>Vector databases are designed to handle high-dimensional numerical representations of data (text, images, audio) often generated by embedding models. These databases are optimized for storage, indexing and querying of high-dimensional vectors.</p><p>These vector storage systems excel in performing vector arithmetic operations, such as addition, subtraction, and dot products, by employing advanced indexing techniques to make these operations performant, even with millions or billions of vectors.</p><p>This approach makes them ideal for applications in advanced machine learning and computer vision. The challenge, however, lies in how to efficiently store, index and query these large amount of vectors, at scale.</p><p><strong>How are Vectors Stored in Vector Databases?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*8USftX0BBQIxhsG5.png" /><figcaption>Vectors are stored as contigous memory blocks in a Vector DB <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.decube.io%2Fpost%2Fvector-database-concept&amp;psig=AOvVaw1tCh3tCH73J1wsLzlHVzlj&amp;ust=1743517759040000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CAMQjB1qFwoTCPCIn_fDtIwDFQAAAAAdAAAAABAE">Source</a></figcaption></figure><p>Vectors are represented as numerical arrays with hundreds or thousands of dimensions. In the database, these vectors are stored as <strong>contiguous memory blocks</strong> (similar to arrays in programming) to enable efficient arithmetic operations. These blocks facilitates the rapid calculation of similarity for retrieval during semantic searches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*l5gPTLS0quT4qK9t2dAyig.png" /><figcaption>How a vector database work <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.techtarget.com%2Fsearchdatamanagement%2Fdefinition%2FWhat-is-a-vector-database&amp;psig=AOvVaw21EZKfaSb0ucZr_VHaon1G&amp;ust=1743519239685000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBcQjhxqFwoTCOjr4MDJtIwDFQAAAAAdAAAAABAJ">Source</a></figcaption></figure><p>The goal is to find vectors “close” to each other based on a given distance metric (e.g., Euclidean or cosine similarity).</p><p>To optimize searches, vector databases employ indexing techniques such as:</p><ul><li><strong>Approximate Nearest Neighbor (ANN): </strong>Balances speed and accuracy for large-scale similarity searches.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*npFI9n7ucAgZLzsg.png" /><figcaption>HNSW leverages a <strong><em>multi-layer graph structure</em></strong> to enable efficient navigation through complex vector spaces <a href="https://ogre51.medium.com/hnsw-hierarchical-navigable-small-worlds-58db783f55cb">Source</a></figcaption></figure><ul><li><strong>Hierarchical Navigable Small World (HNSW)</strong>: Leverages a multi-layer graph structure, allowing faster traversal than traditional ANN by focusing on relevant top-layer nodes. However, this method requires more memory.</li><li><strong>IVFFlat (Inverted File Flat)</strong>: Divides vector space into clusters, identifies the most relevant clusters during searches, and then performs an exact search within the selected cluster.</li><li><strong>Locality-Sensitive Hashing (LSH)</strong>: Maps similar vectors to the same “buckets” for quick comparison, preserving relative distances between vectors.</li><li><strong>Product Quantization (PQ)</strong>: Compresses vectors into smaller sub-vectors to reduce memory usage while maintaining search accuracy.</li></ul><p>These techniques address the “curse of dimensionality” problem, where traditional indexing methods become ineffective as dimensionality increases. Without such specialized approaches, similarity searches would require exhaustive comparisons across the entire dataset, which would be prohibitively expensive as data volumes grow.</p><p><strong>Core Capabilities of Specialized Vector Databases</strong></p><p>These systems are optimized for efficient searches in a high-dimensional space across large volumes of data. Some of their core features include:</p><ul><li>Storage engines optimized for vector data</li><li>Specialized indexing structures for similarity searches (eg. vector quantization trees or k-d trees)</li><li>Query processors designed for vector operations</li><li>APIs focused on vector manipulation and retrieval</li></ul><p>Most vector databases employ distributed architectures to handle datasets that exceed memory capacity, sharding data across multiple machines to maintain performance at scale. This design allows them to handle massive vector collections while maintaining query performance.</p><p><strong>Notable Examples in Vector Databases:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d-oRSthsZUSQovKp.png" /><figcaption>Some of the Vector DB available in the market <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Flevelup.gitconnected.com%2Fvector-databases-and-how-to-pick-the-right-one-for-your-ai-project-a58769b73b85&amp;psig=AOvVaw21EZKfaSb0ucZr_VHaon1G&amp;ust=1743519239685000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBcQjhxqFwoTCOjr4MDJtIwDFQAAAAAdAAAAABAd">Source</a></figcaption></figure><ul><li><a href="https://github.com/spotify/annoy"><strong>Approximate Nearest Neighbor Oh Yeah(ANNOY)</strong></a>: Developed by Spotify, ANNOY is designed specifically for efficient approximate nearest-neighbor (ANN) search in high-dimensional spaces. It excels at quickly finding items similar to a given query based on vector embeddings.</li><li><a href="https://faiss.ai/index.html">FAISS</a> (Facebook AI Similarity Search): Designed to handle datasets large for RAM by implementing PQ. This approach compresses vectors to save space while maintaining search accuracy, enabling efficient disk-based storage with compressed representations.</li><li><a href="https://github.com/pinecone-io"><strong>Pinecone</strong></a><strong>: </strong>Offers scalable vector storage with automatic sharding across multiple machines, supporting metadata storage for filtering search results.</li><li><a href="https://qdrant.tech/">Qdrant</a>: Implements hybrid search capabilities combining sparse and dense vectors with hardware optimizations for ARM processors.</li><li><a href="https://github.com/vespa-engine/vespa">Vespa</a>: Combines vector search with traditional text search and data processing capabilities, featuring built-in model serving for real-time embedding generation.</li><li><a href="https://milvus.io/">Milvus</a>: Open-source vector database supporting multiple index types (HNSW, IVF_PQ) with distributed architecture. The system adopts a shared-storage architecture featuring storage/computing disaggregation and scalability for its computing nodes.</li><li><a href="https://vald.vdaas.org/">Vald</a> <strong>(Yahoo! Japan Research)</strong>: Designed for efficient retrieval of similar vectors from large-scale datasets.</li><li><a href="https://weaviate.io/">Weaviate</a>: provides flexible vector search capabilities with strong integration options such as utilising models to automatically generate vectors for storage.</li></ul><h3>Strengths and Limitations</h3><p>Vector databases offer significant advantages for specific use cases:</p><ul><li>Specialized indexing techniques optimized for high-dimensional data</li><li>Fast similarity searches using algorithms like HNSW and IVF</li><li>Scalable storage for large volumes of embeddings</li><li>Focus on vector operations that traditional databases were not designed to handle</li></ul><p><strong>Limitations:</strong></p><ul><li>Limited support for data types beyond vectors</li><li>May require additional infrastructure to manage other data types</li><li>Often lack enterprise-grade operational features like observability, high availability, backups, and data integrity</li><li>May have limited client libraries or integration options</li><li>Introduce additional complexity into the technology stack</li></ul><p><strong>Applications</strong></p><ul><li><strong>Fast Similarity Search</strong>: Vector databases enable quick nearest neighbor searches in high-dimensional embedding spaces, which is essential for applications like semantic search and recommendation systems.</li><li><strong>Large-Scale Embedding Storage</strong>: They provide scalable storage solutions for large volumes of embeddings, such as those generated from millions of text documents or images.</li></ul><h3>SQL Databases with Vector Extensions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pqUDovStLKouNE0u.png" /><figcaption>SQL Vector database: a hybrid of both.<a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fmyscale.com%2Fblog%2Fwhat-is-sql-vector-databases%2F&amp;psig=AOvVaw2N8PW7i7tRcY-a-HY1f_qA&amp;ust=1743519182771000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CAMQjB1qFwoTCLiyi5_JtIwDFQAAAAAdAAAAABAE"> Source</a></figcaption></figure><p>Traditional SQL databases have evolved to support vector operations through extensions like <strong>pgvector</strong> and <strong>pgai</strong>. These extensions allow SQL databases to store and query vectors efficiently while benefiting from SQL’s robustness and operational maturity.</p><h3>Implementation Approaches</h3><p>SQL databases store vectors as columns in tables, treating them numerical arrays. Extensions like <strong>pgvector</strong> enable similarity searches using indexing techniques such as <strong>HNSW</strong> and <strong>IVF-Flat</strong>. This allows SQL databases to integrate vector data with relational data, enabling hybrid queries that combine vector similarity with standard SQL filtering.</p><h4>Advantages of SQL with Vector Extensions</h4><ul><li>Operational robustness: High availability, reliability of SQL with comprehensive observability and monitoring tools.</li><li><strong>Versatility</strong>: SQL databases can handle a variety of data types, making them suitable for applications that require both vector and traditional data management.</li><li><strong>Developer Experience</strong>: Familiarity with SQL enables smooth integration within existing AI applications.</li></ul><h3>Other Extensions Supporting Vector Operations</h3><ul><li><a href="https://github.com/timescale/pgai">pgai extension</a> by Timescale: automatically generate vectors for dynamic applications, reducing latency and complexity of implementation.</li><li><a href="https://github.com/pgvector/pgvector">pgvector</a>: The most popular Postgres extension for vector search, supporting IVFFlat and HNSW with optimizations through quantization.</li></ul><p><a href="https://www.timescale.com/blog/pgvector-vs-pinecone">Recent benchmarks</a> have shown that properly configured SQL databases with vector extensions can achieve performance comparable to specialized vector databases. For instance, pgvector with appropriate configuration has demonstrated speed comparable to Pinecone in certain scenarios.</p><h3>Comparison Summary</h3><pre>+-------------------------+--------------------------------------+--------------------------------------------+<br>| Factor                  | → Vector Databases                   | → SQL with Vector Extensions               |<br>+-------------------------+--------------------------------------+--------------------------------------------+<br>| Performance             | → Optimized for vector operations    | → Competitive with proper tuning           |<br>|                         | → High performance for pure vectors  | → Balances vector &amp; traditional data       |<br>|                         | → Designed for scale-out workloads   | → Matured to rival dedicated systems       |<br>+-------------------------+--------------------------------------+--------------------------------------------+<br>| Operational Complexity  | → Additional system to maintain      | → Leverages existing SQL infra             |<br>|                         | → Data duplication &amp; sync needed     | → Simplifies architecture                  |<br>|                         | → New monitoring &amp; recovery needs    | → Uses familiar tools &amp; procedures         |<br>|                         | → Less mature operational tooling    | → High availability with disaster recovery |<br>+-------------------------+--------------------------------------+--------------------------------------------+<br>| Integration             | → Requires middleware/data sync      | → Direct vector ops on app data            |<br>|                         | → Possible latency &amp; consistency     | → Eliminates data movement                 |<br>|                         | → Adds architectural complexity      | → Ensures transactional consistency        |<br>+-------------------------+--------------------------------------+--------------------------------------------+<br>| Ideal Use Cases         | → Pure vector workloads              | → Vector + traditional data mix            |<br>|                         | → Extreme scalability needs          | → Operational simplicity preferred         |<br>|                         | → Workload fits vector DB optimally  | → Teams have SQL expertise                 |<br>|                         | → Willing to manage extra complexity | → AI-enhanced business apps                |<br>+-------------------------+--------------------------------------+--------------------------------------------+</pre><h3>Conclusion</h3><p>The debate between specialized vector databases and SQL databases with vector extensions has evolved significantly as extensions like <strong>pgvector</strong> have matured. While vector databases offer focused optimization for vector operations, SQL databases with vector capabilities provide a more integrated approach that aligns well with existing application architectures and operational practices.</p><p>For many organizations, SQL databases with vector extensions represent a practical and scalable choice that avoids the need for additional infrastructure. As SQL-based vector solutions continue to improve, the performance gap with specialized vector databases has narrowed significantly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb3bef40921b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/sql-vs-vector-databases-choosing-the-right-tool-for-your-ai-powered-application-eb3bef40921b">SQL vs. Vector Databases: Choosing the Right Tool for Your AI-Powered Application</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Choose an Embedding Models?]]></title>
            <link>https://onnyunhui.medium.com/how-to-choose-an-embedding-models-d030571204cd?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/d030571204cd</guid>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[embedding-model]]></category>
            <category><![CDATA[matryosohka]]></category>
            <category><![CDATA[mrl]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 15:16:56 GMT</pubDate>
            <atom:updated>2025-03-25T01:31:08.188Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is in a Word Embedding Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*_mKuemw1lp47WKep" /><figcaption>I asked to generate an image of word embeddings if it were humans. Image Generated from Google Imagen 3</figcaption></figure><p>Humans with similar interests like to gather together. Words/ phrases/ sentences that are similar in meanings are positioned close to each other in a high-dimensional space, capturing semantic relationships in this vector space. That is, words with similar meanings in an embedding space are “close” together.</p><p>This characteristic of word embedding model is what makes it essential for tasks like semantic search, information retrieval, and language understanding.</p><p>These models are foundational for large language models (LLMs) and are critical for applications requiring contextual comprehension. The process involves training on vast corpora to encode relationships — such as synonyms or analogies, based on co-occurrence patterns.</p><h3>Uses of Embedding Models</h3><p>Embedding models supports a range of applications:</p><ul><li><strong>Semantic Search:</strong> Matches queries to documents by meaning, not just keywords.</li><li><strong>Retrieval-Augmented Generation (RAG):</strong> Retrieves context to improve LLM responses.</li><li><strong>Other Applications:</strong> Code search, text classification, recommendation systems, and clustering.</li></ul><p>It is hence important that you choose a right embedding model for your AI task at hand. The quality of the embedding’s semantic space determines the relationships between words and concepts.<em> Accurate embeddings ensure relevant results, while poor embeddings lead to irrelevant or missing information</em>. A well-chosen embedding model that best fits your use-case directly enhances your AI application’s performance by leveraging rich semantic data for coherent, context-aware responses.</p><p>Before diving into model selection, let’s explore <strong>Google’s Gemini Embedding</strong> and the use of the innovative <strong>Matryoshka Representation Learning (MRL)</strong> technique.</p><h3>Google’s Gemini Embedding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6780J54pRoDflr784vJFJA.png" /><figcaption>Top embedding models, ranked by mean as of 24th March 2025 (TaskType) <a href="https://huggingface.co/spaces/mteb/leaderboard">Source</a></figcaption></figure><p>Particularly impressive is the top position Gemini Embedding achieved with a <strong>mean task score of 68.32</strong> on the <strong>MTEB Multilingual Leaderboard </strong>with support over 100 languages and using the Matryoshka Representation for learning efficiency.</p><p><strong>Key Features:</strong></p><ul><li><strong>Expanded Capacity:</strong> Handles up to <strong>8,000 tokens</strong> (double its predecessor).</li><li><strong>Higher Dimensionality:</strong> Output dimensions increased from <strong>768 to 3,072</strong>, enriching text representation.</li><li><strong>Multilingual Mastery:</strong> Supports <strong>100+ languages</strong>, doubling previous capabilities.</li><li><strong>Memory Efficiency:</strong> Uses <strong>MRL</strong> to reduce memory usage without sacrificing accuracy.</li></ul><h3>What is Matryoshka Representation Learning (MRL) ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*uZJFEiFGrbYHXIWi" /><figcaption>Adaptive learning setup of the Matroyoshka Representation, which can be utilised for adaptive deployment. <a href="https://arxiv.org/pdf/2205.13147">Source</a></figcaption></figure><p>MRL is a breakthrough technique that creates <strong>adaptable embeddings</strong> — vectors that can be truncated to smaller sizes <strong>without significant performance loss</strong>. The MRL learns coarse-to-fine representations that are at least as accurate and rich as independently trained low-dimensional representations. It frontloads important information into earlier dimensions, minimally modifies existing representation in pipelines and imposes no additional cost during inference and deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UoH9UmcGOMKS2x_7oISyXA.png" /><figcaption>Source: <a href="https://huggingface.co/blog/matryoshka">https://huggingface.co/blog/matryoshka</a></figcaption></figure><p>Think of it like Russian dolls: the smallest doll (embedding) contains the most critical information, while larger ones add finer details. Every remains the useful toy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaYP-olp22M8hiWfKhTndQ.png" /><figcaption>Matryoshka embedding models can produce useful embeddings of various dimensions. <a href="https://huggingface.co/blog/matryoshka">Source</a></figcaption></figure><p><strong>Why MRL Matters:</strong></p><ul><li><strong>Adaptive Deployment:</strong> A single embedding adjusts to different computational needs, and can be truncated to extract the most useful dimensions.</li><li><strong>Minimal Overhead:</strong> Requires little modification to existing pipelines, with no extra cost during inference.</li><li><strong>Coarse-to-Fine Learning:</strong> Delivers accuracy comparable to independently trained low-dimensional models.</li></ul><p>Beyond the Google Gemini Embedding model, companies like <a href="https://platform.openai.com/docs/guides/embeddings">OpenAI</a>, <a href="https://jina.ai/news/jina-embeddings-v3-a-frontier-multilingual-embedding-model/">JinaAI</a> and Nomic also use the MRL technique to allow developers and researchers to balance between the performance and costs of choosing embedding models.</p><p>Back to the topic of choosing the best embedding model, but first we will have to go through several concepts of an embedding model. We will start off with:</p><h3>Types of Embedding Models: Static vs. Dynamic</h3><p>Embedding models are broadly categorized into static and dynamic types, each with distinct characteristics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*BxWKyBzu0Bgu2ZwJ" /><figcaption>Example of the clustering of related keywords as is typical with word embeddings such as word2vec or GLoVe. <a href="https://www.pinecone.io/learn/series/nlp/dense-vector-embeddings-nlp/">Source</a></figcaption></figure><p><strong>Static embeddings</strong> (like word2vec) generate a fixed vector for each word. These vectors are combined, often by averaging the global co-occurrence, to create a final embedding.</p><p>These types of embeddings are fast and less resource intensive but they don’t consider how a word’s meaning can change in function to the surrounding words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*SSYfgreaFavozZcc" /><figcaption>Embeddings are compared to one another by using the notions of similarity and distance. <a href="https://learn.microsoft.com/en-us/azure/architecture/ai-ml/guide/rag/rag-generate-embeddings">Source</a></figcaption></figure><p><strong>Dynamic embeddings </strong>are based on Transformers (like BERT), which incorporate context awareness using transformer architecture, allowing them to represent words based on the surrounding context, which allows it to handle ambiguous words in contexts.</p><p>However, with this additional capability, it is also more computationally intensive due to the higher resource requirements.</p><h3>How does an Embedding Model Learn? Contrastive Learning</h3><p>Contrastive learning is a prevalent technique for training embedding models, particularly for enhancing semantic similarity. It involves the training of a model with positive text pairs (semantically similar texts), which are closer in embedding space, while pushing the negative text pairs (semantically dissimilar texts) apart. It operates under the premise that instances exhibiting similarity should be closely aligned in the learned embedding space, whereas those that are dissimilar should be positioned further apart.</p><p>Contrastive learning is also often used in fine-tuning embedding models, and it leverages both labeled and unlabeled data, making it efficient for self-supervised learning.</p><h3>How is a Multilingual Embedding Model Trained?</h3><p>The training of an multilingual embedding model works by aligning embeddings across languages, ensuring translations map to similar points in the vector space. <em>The training is based on the idea that a translated sentence should be mapped to the same location in the vector space as the original sentence.</em></p><p><em>The original (monolingual) model to generate sentence embeddings for the source language and then train a new system on translated sentences to mimic the original model.</em></p><p>In short, a teacher model with input text in language A and a student model with input text in language B. The student model is trained to minimize the Euclidean/ cosine distance (depending on the method) between the embeddings of the two languages. In a way, this approach reduces language bias by aligning all languages by design.</p><h3>Does Size of the Embedding Model Matter?</h3><p>The common wisdom is that the larger the model, the better the performance. Which can be seen from the HuggingFace leaderboard.</p><blockquote>In practical applications, the largest and best performing embedding model might not be the best for your applications.</blockquote><p>Using a high number of dimensions results in a better semantic search score, but the model runs slower and requires more memory. Low-dimensional embeddings are less computationally expensive.</p><p>While there is an accuracy-cost tradeoff associated with lower dimensionality, having the flexibility to use smaller embeddings can provide helpful savings on memory and storage requirements.</p><p>The latency of semantic search grows with the dimension of embeddings. Do consider lower dimensional embeddings to minimize latency.</p><h3>Dimensionality of Output Embeddings</h3><ul><li>Higher dimensionality helps capture <strong>complex text relationships</strong>.</li><li><strong>Dense Vector Representations</strong>: Embedding models convert text into high-dimensional vectors that capture semantic meaning, enabling machines to understand linguistic similarities and relationships</li></ul><h3>Hugging Face MTEB Leaderboard: A Benchmarking Tool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*x28elYBWbGdhxR2n3hu3Vw.png" /><figcaption><em>Overview of tasks and datasets in MTEB. Multilingual datasets are marked with a purple shade. </em><a href="https://huggingface.co/blog/mteb"><em>Source</em></a></figcaption></figure><p>The <a href="https://github.com/embeddings-benchmark/mteb">MTEB, Massive Text Embedding Benchmark</a> includes 56 datasets across 8 tasks and currently summarizes &gt;2000 results on the <a href="https://huggingface.co/spaces/mteb/leaderboard">leaderboard</a>. This benchmark is essential for comparing models, especially for multilingual and domain-specific tasks.</p><p>However, it only serves as a guide for the choice of your application. It is still important to conduct your own evaluation on the embedding model based on your own dataset.</p><p>Some considerations:</p><ol><li><strong>Document characteristics:</strong> Volume and type of document and their domain, whether it is these information is being used to train the embedding model.<br><em>Let’s say if you are interested in doing a RAG retrieval task for legal contents. A model that is trained on general purpose contents might not perform as well as a model that has been trained with legal-related content and might be more representative to your dataset.</em></li><li><strong>Performance needs:</strong> Balance accuracy against latency and computing requirements (vector dimension and parameters).<br><em>Sequence length tells us how many tokens a model can consume and compress into a single embedding. You can start off with a moderately sized model with less than 500m params for a start.</em></li><li><strong>Context Length</strong>: How long a sentence/ paragraph are you embedding? Does the length in your context matter? You’ll have to test it.<br><em>Generally speaking, we wouldn’t recommend stuffing more than a paragraph of heft into a single embedding — so models supporting up to 512 tokens are usually more than enough.</em></li><li><strong>Open Source or close-source model</strong>: Depending on your personal and security requirements.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d030571204cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notebook Walkthrough: YouTube Video Summarizer using OpenRouter, LangChain, and Stella Embeddings]]></title>
            <link>https://onnyunhui.medium.com/notebook-walkthrough-youtube-video-summarizer-using-openrouter-langchain-and-stella-embeddings-dcd9a1173221?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcd9a1173221</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[open-router]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[youtube]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 02:43:47 GMT</pubDate>
            <atom:updated>2025-03-09T02:47:31.169Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you have a video you want to watch but don’t have the time to capture all the details? This walkthrough is exactly what you need to take notes efficiently.</p><p>In this tutorial, we’ll build a system to extract, process, and summarize YouTube video transcripts using <strong>LangChain</strong>, <strong>OpenRouter</strong> (with Google’s Gemini Flash 2.0 model), <strong>semantic text chunking and refinement summarisation chain</strong>.</p><p>The final output will be a concise summary of a Youtube video with key takeaways, processed through semantic chunking and refined using a Large Language Model (LLM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NC8NsmdvKyF0eBmt" /><figcaption>Image generated by Google Imagen2</figcaption></figure><h3>Key Features</h3><ul><li><strong>OpenRouter Integration</strong>: Leverages Google’s Gemini model through OpenRouter’s API and connection to LangChain.</li><li><strong>Semantic Chunking</strong>: Instead of simple text splitting, we use semantic understanding to create meaningful chunks.</li><li><strong>Custom Prompts</strong>: Separate prompts are used for the initial summary and refinement.</li><li><strong>Refinement Chain</strong>: Chunks are processed sequentially, refining the summary with each new piece of context.</li></ul><p>Full code in Google Gist here</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dd43cf80cc4c877dc0c8b4fad11eefc/href">https://medium.com/media/4dd43cf80cc4c877dc0c8b4fad11eefc/href</a></iframe><p>Otherwise, you can follow the walkthrough below.</p><h3>Step 1: Download and import necessary library + API Credentials</h3><p>First, install the required libraries:</p><pre>%pip install youtube-transcript-api==0.6.3<br>%pip install langchain-experimental==0.3.4<br>%pip install langchain-huggingface==0.1.2<br>%pip install pydantic==2.10.6<br>%pip install langchain-openai==0.2.3<br>%pip install langchain-experimental==0.3.4<br>%pip install langchain-huggingface==0.1.2<br>%pip install xformers==0.0.29<br>%pip install ipywidgets==7.7.1</pre><p>Next, import the necessary modules:</p><pre>import re<br>import os<br>from typing import Optional<br>from dotenv import load_dotenv<br>from getpass import getpass<br>import huggingface_hub<br>from pprint import pprint<br>from langchain_core.utils.utils import secret_from_env<br>from langchain_openai import ChatOpenAI<br>from langchain.schema import Document<br>from langchain_huggingface import HuggingFaceEmbeddings<br>from langchain_experimental.text_splitter import SemanticChunker<br>from langchain.chains.summarize import load_summarize_chain<br>from langchain.prompts import PromptTemplate<br>from pydantic import Field, SecretStr<br>from youtube_transcript_api import YouTubeTranscriptApi<br>from huggingface_hub import notebook_login</pre><p><strong>OpenRouter Setup:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*qfxKkDN6Rh4zaNtSaHUr2g.png" /><figcaption>Create your API Key on OpenRouter</figcaption></figure><ul><li>Go to the <a href="https://openrouter.ai/">OpenRouter API website</a></li><li>Sign up or log in to your account</li><li>Navigate to the API keys section and generate a new API key</li><li>Copy the API key</li></ul><p>Set up the API key in your environment:</p><pre>api_key = getpass(&quot;Enter your OpenRouter API key here: &quot;)<br>os.environ[&quot;OPENROUTER_API_KEY&quot;] = api_key<br>print(&#39;API key logged&#39;)</pre><p><strong>Hugging Face Setup:</strong></p><ul><li>Go to the <a href="https://huggingface.co/">Hugging Face website</a></li><li>Sign up or log in to your account</li><li>Navigate to Settings -&gt; Access Tokens</li><li>Create a new token with read access</li><li>Copy the token</li></ul><p>For an official walkthrough, refer to the <a href="https://huggingface.co/docs/hub/en/security-tokens">Hugging Face documentation</a>.</p><pre>huggingface_token = getpass(&quot;Enter your HuggingFace token here: &quot;)<br>os.environ[&quot;HF_TOKEN&quot;] = huggingface_token<br>print(&#39;HuggingFace token logged&#39;)<br>huggingface_hub.whoami()</pre><h3>Step 2: YouTube Transcript Extraction</h3><p>We’ll create functions to extract video transcripts from YouTube URLs.</p><h4>Function to Extract Video ID:</h4><pre>def extract_video_id(url):<br>    &quot;&quot;&quot;<br>    Extract YouTube video ID from URL.<br>    Parameters:<br>        url (str): The YouTube URL to extract the video ID from.<br>    Returns:<br>        str: The extracted video ID, or None if no valid ID is found.<br>    &quot;&quot;&quot;<br>    patterns = [<br>        r&#39;(?:v=|\/)([0-9A-Za-z_-]{11}).*&#39;,<br>        r&#39;(?:embed\/)([0-9A-Za-z_-]{11})&#39;,<br>        r&#39;(?:youtu\.be\/)([0-9A-Za-z_-]{11})&#39;<br>    ]<br>    <br>    for pattern in patterns:<br>        match = re.search(pattern, url)<br>        if match:<br>            return match.group(1)<br>    return None</pre><p>This function extracts the YouTube video ID from different URL formats using regex patterns:</p><ul><li>Standard watch URLs (e.g., youtube.com/watch?v=VIDEO_ID)</li><li>Embed URLs (e.g., youtube.com/embed/VIDEO_ID)</li><li>Short URLs (e.g., youtu.be/VIDEO_ID)</li></ul><h4>Function to Get YouTube Transcript:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*O0PKC2Iv9GgxpnNpRvsefA.png" /><figcaption>This function exacts the youtube transcript- All-in Podcast <a href="https://www.youtube.com/watch?v=JoKPVeL1UBw&amp;ab_channel=All-InPodcast">Source</a></figcaption></figure><pre>def get_youtube_transcript(url):<br>    &quot;&quot;&quot;<br>    Get the transcript of a YouTube video.<br>    Parameters:<br>        url (str): The YouTube URL to get the transcript from.<br>    Returns:<br>        str: The transcript of the video, or an error message if the URL is invalid.<br>    &quot;&quot;&quot;<br>    try:<br>        video_id = extract_video_id(url)<br>        if not video_id:<br>            raise ValueError(&quot;Invalid YouTube URL&quot;)<br>            <br>        transcript_list = YouTubeTranscriptApi.get_transcript(video_id)<br>        full_transcript = &#39; &#39;.join(entry[&#39;text&#39;] for entry in transcript_list)<br>        return full_transcript #count<br>        <br>    except Exception as e:<br>        return f&quot;Error: {str(e)}&quot;</pre><p>This function:</p><ol><li>Calls extract_video_id to get the video ID.</li><li>Uses YouTubeTranscriptApi to fetch the transcript.</li><li>Joins all transcript segments into a single text.</li><li>Returns the full transcript or an error message if no transcript is available.</li></ol><h3>Step 3: Text Embedding with Stella Model</h3><p>The <a href="https://huggingface.co/NovaSearch/stella_en_400M_v5">Stella model</a> is trained based on Alibaba-NLP/gte-large-en-v1.5 and Alibaba-NLP/gte-Qwen2-1.5B-instruct. It’s one of the best-performing models on the MTEB leaderboard as of March 2025, with only around 400M parameters.</p><h4>Initialize the Stella Model:</h4><pre># https://huggingface.co/NovaSearch/stella_en_400M_v5/blob/main/README.md<br># Define the model name and configuration<br>model_name = &quot;NovaSearch/stella_en_400M_v5&quot;<br>model_kwargs = {<br>    &#39;trust_remote_code&#39;: True,<br>    &#39;device&#39;: &#39;cuda&#39;, # &#39;cpu&#39; if running on CPU<br>    &#39;config_kwargs&#39;: {<br>        &#39;use_memory_efficient_attention&#39;: False,<br>        &#39;unpad_inputs&#39;: False<br>    }<br>}<br>encode_kwargs = {<br>    &#39;normalize_embeddings&#39;: False<br>}<br><br># Initialize the HuggingFaceEmbeddings with the Stella model<br>stella_embeddings = HuggingFaceEmbeddings(<br>    model_name=model_name,<br>    model_kwargs=model_kwargs,<br>    encode_kwargs=encode_kwargs<br>)<br><br>document_embeddings = stella_embeddings.embed_documents(text)</pre><h4>Semantic Chunking:</h4><p>To split the transcript into meaningful chunks (useful for videos discussing multiple topics), we use semantic chunking. This approach can limit the input context length, for smaller models with shorter context length, which their performance and accuracy might be affected by the longer context length.</p><p>See my medium post on Long-context Evaluation</p><pre>chunker = SemanticChunker(embeddings=stella_embeddings)<br><br># Split the text into chunks<br>chunks = chunker.split_text(text)<br>documents = [Document(page_content=chunk) for chunk in chunks]<br><br>for i, doc in enumerate(documents):<br>    print(f&quot;Document {i + 1}:&quot;)<br>    pprint(doc.page_content)<br>    print(&quot;-&quot; * 50)</pre><p>Honestly, if you ask me about the use-ability for this semantic chunking by langchain as of now, it is still very rudimentary as compared to what was offered by the <a href="https://github.com/FullStackRetrieval-com/RetrievalTutorials/blob/main/tutorials/LevelsOfTextSplitting/5_Levels_Of_Text_Splitting.ipynb">5 levels of splitting</a> which I’ve tried, but requires quite alot of optimisation. You can also consider other splitting techniques if you’d like.</p><h3>Step 4: Setting up OpenRouter with Gemini</h3><p>We create a custom ChatOpenRouter class to use OpenRouter’s API with Google’s Gemini model:</p><pre>load_dotenv()<br><br>class ChatOpenRouter(ChatOpenAI):<br>    openai_api_key: Optional[SecretStr] = Field(<br>        alias=&quot;api_key&quot;,<br>        default_factory=secret_from_env(&quot;OPENROUTER_API_KEY&quot;, default=None),<br>    )<br>    @property<br>    def lc_secrets(self) -&gt; dict[str, str]:<br>        return {&quot;openai_api_key&quot;: &quot;OPENROUTER_API_KEY&quot;}<br><br>    def __init__(self,<br>                 openai_api_key: Optional[str] = None,<br>                 **kwargs):<br>        openai_api_key = (<br>            openai_api_key or os.environ.get(&quot;OPENROUTER_API_KEY&quot;)<br>        )<br>        super().__init__(<br>            base_url=&quot;https://openrouter.ai/api/v1&quot;,<br>            openai_api_key=openai_api_key,<br>            **kwargs<br>        )<br><br>llm = ChatOpenRouter(<br>    model_name=&quot;google/gemini-2.0-flash-exp:free&quot;</pre><p>This class, created by <a href="https://medium.com/@arth2048/openrouter-with-langchain-0eab702b9977">Bryce</a> simplifies OpenRouter API calls using the ChatOpenAI class. As there was no LangChain Support for OpenRouter API calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x2gpLP6V83jJ9LJW.png" /><figcaption><a href="https://developers.googleblog.com/en/gemini-2-family-expands/">Source</a></figcaption></figure><p><strong>Why Gemini 2.0 Flash?</strong></p><ul><li>It’s free on OpenRouter.</li><li>It’s touted by Google as a high-performing model- if the OpenRouter model is the same as the one hosted on Google Vertex AI.</li></ul><p>To be honest, I quite like the end product which was summarised by Gemini 2.0 Flash. I’ll definitely try it on my other projects in time to come.</p><h3>Step 5: Prompting the LLM for Summarization Chain with Refinement</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9SWQ0ck97yx0Nu7r.png" /><figcaption>Refinement Summarisation- <a href="https://arize.com/blog/llm-summarization-getting-to-production/">Source</a></figcaption></figure><p>To enhance summarization quality, we use a <strong>refinement summarization chain</strong>:</p><ol><li>Summarize the first chunk.</li><li>Combine the summary with the next chunk and refine it.</li><li>Repeat until all chunks are processed.</li></ol><p>This sequential refinement process, while time-consuming, ensures a high-quality summary.</p><h4>Define Prompts:</h4><pre>question_template = PromptTemplate.from_template(&quot;&quot;&quot;<br>Write a concise summary of the following youtube transcript with key takeaways for the audience:<br>&quot;{text}&quot;<br>CONCISE SUMMARY:&quot;&quot;&quot;)<br><br>refine_template = PromptTemplate.from_template(&quot;&quot;&quot;Your job is to produce a final key takeaways summary.<br>We have provided an existing summary up to a certain point: {existing_answer}<br><br>We have the opportunity to refine the existing summary (only if needed) with some more context below.<br>------------<br>{text}<br>------------<br>Given the new context, refine the original summary with new key takeaways.<br>If the context isn&#39;t useful, return the original summary.\<br>&quot;&quot;&quot;)</pre><h4>Load the Refinement Summarization Chain:</h4><pre># Load the refine summarization chain<br>chain = load_summarize_chain(<br>    llm,<br>    chain_type=&quot;refine&quot;,<br>    question_prompt=question_template,<br>    refine_prompt = refine_template,<br>    verbose=True,<br>    document_variable_name=&quot;text&quot;, <br>    initial_response_name=&quot;existing_answer&quot;<br>)</pre><p>Here, without much effort, and the good help of the team at <a href="https://medium.com/the-data-perspectives/custom-prompts-for-langchain-chains-a780b490c199">Langchain</a>, the refinement summarisation chain is done. Special shoutout to the article by <a href="https://medium.com/the-data-perspectives/custom-prompts-for-langchain-chains-a780b490c199">Dr. Robert</a> who went into the code, which I didnt, but the details of the components in the summarisation chain is not in the documentations. Kudos to his efforts.</p><h3>Step 6: Putting It All Together</h3><p>Here’s how to use the complete system:</p><pre>output_comb = chain.invoke(documents)<br>pprint(output_comb[&#39;output_text&#39;])</pre><p>And there you have it — a summarized version of a YouTube video!</p><p>In my next article, I’ll compile these learnings into a GitHub repository and a ready-to-run Google Colab Notebook with a Flask front-end application.</p><p>If you find this helpful, do give me applauds and don&#39;t forget to comment and subscribe to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcd9a1173221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating Long Context Lengths in LLMs: Challenges and Benchmarks]]></title>
            <link>https://onnyunhui.medium.com/evaluating-long-context-lengths-in-llms-challenges-and-benchmarks-ef77a220d34d?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef77a220d34d</guid>
            <category><![CDATA[context-length]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 14:45:50 GMT</pubDate>
            <atom:updated>2025-03-04T14:45:50.588Z</atom:updated>
            <content:encoded><![CDATA[<p>Recent advancements in language models (LLMs) claim to push the boundaries of context length, with some models reportedly capable of handling 1–2 million tokens of context. As AI practitioners, it is critical to investigate the truth and practicality of these claims.</p><p>One key concern for those building LLM-based applications is whether these models can truly “understand” and effectively use long-context information in their outputs.</p><p>The ability of an LLM to manage extensive textual inputs from diverse sources can significantly enhance its applications, enabling organizations to create systems that maintain context across extended interactions. This, in turn, opens new business opportunities, such as delivering highly personalized experiences and solutions.</p><h3>What exactly is a context window?</h3><p>At its core, the <strong>context window</strong> is the input that the LLM processes at any given time. It can be likened to the model’s short-term memory, as it only retains a limited amount of information during inference.</p><p>LLMs utilize the <strong>vanilla attention mechanism</strong>, which allows the model to focus on the most relevant parts of the text within its context window. However, this dense attention mechanism scales with <strong>O(T²)</strong> (where <em>T</em> is the context length), making it computationally expensive and limiting the model’s ability to process longer contexts efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*pl8WLCrTqGwM-7g976w0ZA.jpeg" /><figcaption>Various types of attention mechanisms <a href="https://www.oxen.ai/blog/arxiv-dives-efficient-streaming-language-models-with-attention-sinks">Source</a></figcaption></figure><p>Improving the limitation of context lengths and its efficiencies can yield several benefits:</p><ol><li><strong>Increased speed</strong> for models when handling longer contexts.</li><li><strong>Better memory efficiency</strong> for longer input sequences.</li><li><strong>Improved output quality</strong> for tasks requiring extended contexts.</li></ol><p>In this article, we will focus on the issue of the quality of output for the longer context lengths.</p><h3>The “Lost in the Middle” Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*VqiceDAQa7CmPfYUzk4mmA.png" /><figcaption>Notice how the very beginning and the end of the context has better accuracy compared to the middle of the context. <a href="https://arxiv.org/abs/2307.03172">Source</a></figcaption></figure><p>A key challenge with long-context models is the <strong>Lost in the Middle</strong> phenomenon, popularised in <a href="https://arxiv.org/abs/2307.03172">this paper</a>. This refers to the U-shaped performance curve observation that LLMs generally perform better when processing information at the <strong>beginning</strong> or <strong>end</strong> of a context rather than the <strong>middle.</strong></p><p>This is not just a phenomenon in GPT 3.5-turbo but also recent new models.</p><p><a href="https://www.youtube.com/watch?v=KwRRuiCCdmc&amp;ab_channel=GregKamradt">Greg Kamradt</a> has took it to the next level to stress-test the GPT-4 model which claims to have a context length of 128k tokens. During his experiments, he found that the GPT-4 accuracy noticeably degrades with a large context of more than 64k tokens and when text was placed between 10–50% of the context depth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLBf0uUm6nOekth3QVLCGA.png" /><figcaption>Heatmap analyses shows at longer context lengths, GPT-4’s performance started to degrade, with lower accuracy (more red than light green areas towards the right)<a href="https://www.youtube.com/watch?v=KwRRuiCCdmc&amp;ab_channel=GregKamradt"> Source</a></figcaption></figure><p>LLMs seem to perform best when relevant information is at the beginning or end of the input context, and degrade significantly when accessing information in the middle and such results are similarly applicable to extended-context models, which are designed to handle longer context lengths.</p><h3><strong>Model Performance vs (Reported) Context Length</strong></h3><p>Long-context models often claim to support larger context windows (e.g., 128k tokens or more), but their <strong>actual effectiveness</strong> tends to degrade as context size increases. Studies using benchmarks like <strong>RULER</strong> (to be discussed below) suggest a trade-off between:</p><ul><li><strong>Absolute performance</strong> on shorter input sequences.</li><li><strong>Relative degradation</strong> as context size scales.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*3vsTN-01H7PyVdntZ8MfTw.png" /><figcaption>Long Context Performance of popular models and its performance on the RULER Metric. <a href="https://arxiv.org/pdf/2404.06654">Source</a></figcaption></figure><p>A recent study, <strong>NO-L1MA</strong>, evaluated 12 popular models using its own benchmark stress tests. The results confirmed that accuracy decreases significantly for longer contexts, even when models claim to support larger windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*L8-Pow8XTPPNQqoAVvDX0A.png" /><figcaption>Popular models with their claimed lengths and effective performance on the NOL1MA benchmark <a href="https://arxiv.org/pdf/2502.05167">Source</a></figcaption></figure><h3>Evaluating Long-Context Models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbHAkXpTjowCqmCV8kUp5g.jpeg" /><figcaption>How did Google come up with the number- 1M context length? <a href="https://www.wire19.com/google-launches-gemini-1-5-with-1-million-token-context-window/">Source</a></figcaption></figure><p>How are context length measured? Google, for instance, claims that its model <strong>Gemini 1.5 Pro</strong> can handle a <strong>1M token context length</strong>. However, this claim is based on the <strong>Needle-in-a-Haystack (NIAH)</strong> approach, a baseline method for testing long-context capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*1lobKsIz6402mjSCt4kODQ.png" /><figcaption>Gemini 1.5 Pro context length performance was based on a standard needle-in-a-haystack test<a href="https://ai.google.dev/gemini-api/docs/long-context"> Source</a></figcaption></figure><h3>Needle-in-a-Haystack (NIAH)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhWByBYAPagw1QoWRraOzQ.jpeg" /><figcaption>Image generated by Google Imagen3</figcaption></figure><p>The <strong>NIAH</strong> test evaluates a model’s ability to retrieve specific pieces of information (“needles”) embedded within large amounts of irrelevant data (“haystack”).</p><p>While useful for assessing surface-level retrieval capabilities, NIAH is limited: it fails to evaluate tasks that involve multiple themes, interconnected facts, or complex contextual relationships.</p><h3>RULER-Benchmark</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*1G9XJUogI10R76CX9jdAog.png" /><figcaption>RULER evaluates long-context models across 4 categories of complex and multi-step reasoning tasks, retrieval, multi-hop tracing, aggregation and question-answering</figcaption></figure><p>To address the limitations of NIAH, the <a href="https://github.com/NVIDIA/RULER">RULER</a> benchmark expands on it, evaluating long-context models across four categories:</p><ol><li><strong>Retrieval</strong>: Builds on NIAH by testing the retrieval of diverse types of “needles” from long contexts.</li><li><strong>Multi-hop Tracing</strong>: Assesses a model’s ability to trace entities and resolve coreference chains across multi-hop connections.</li><li><strong>Aggregation</strong>: Tests summarization-like abilities by evaluating how well models can aggregate information spanning long contexts.</li><li><strong>Question Answering</strong>: Measures QA performance in the presence of distracting and irrelevant information.</li></ol><p>While RULER offers a more practical measurement of the complexities in the real-world applications, the authors noted that there was a lack of correlation between these synthetic tasks and realistic long-context tasks that prevented the team from verifying the validity of these tests as real world tasks exhibits a variety of forms and evaluation methods.</p><h3>L-CiteEval</h3><p>Traditional long-context evaluation, focuses on the testing of synthetic retrieval tasks for specific position in a long context.</p><p>The <a href="https://arxiv.org/pdf/2410.02115"><strong>L-CiteEval</strong></a> benchmark introduces a comprehensive, multi-task evaluation framework designed to address the limitations of traditional benchmarks like NIAH and RULER. It evaluates long-context models based on their ability to provide evidence-based reasoning across <strong>11 diverse real-world and synthetic tasks + provide relevant citations</strong> on these reasonings.</p><p>The L-CiteEval is a predecessor of <a href="https://arxiv.org/pdf/2409.02897">LongCite</a>- which also requires citation generation for long context question and answering tasks, with a wider range of tasks, and support for longer context lengths and is more reproducible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*w8JpKiOP7tZtBEBHBC2Nug.png" /><figcaption>The five tasks and size of each tasks across different context length in the L-CiteEval method <a href="https://arxiv.org/pdf/2410.02115">Source</a></figcaption></figure><p>There are 5 main categories in the L-CiteEval benchmark: Single-document QA, Multi-document QA, Summarization, Dialogue understanding, and Synthetic tasks, covering both realistic and synthetic tasks.</p><p>L-CiteEval also introduces two benchmark variants:</p><ol><li><strong>L-CiteEval-Length</strong>: Evaluates models based on context length.</li><li><strong>L-CiteEval-Hardness</strong>: Assesses performance based on task difficulty.</li></ol><p>The team also developed two benchmark variants: L-CiteEval-Length and L-CiteEval-Hardness, which evaluate the LLMs from the context length and task difficulty aspects.</p><p>These benchmarks addresses real-world task complexity by requiring models to generate evidence-backed responses, mitigating the challenge of distinguishing between intrinsic knowledge and provided context.</p><h3>Conclusion</h3><p>The ability of LLMs to handle long contexts effectively is critical for real-world applications. However, despite claims of larger context lengths, current models struggle with quality degradation when processing middle portions of long contexts.</p><h3>Key Takeaways:</h3><ol><li><strong>“Lost in the Middle”</strong> remains an unresolved issue, with accuracy degrading significantly for tokens located between 10–50% of the input depth.</li><li>While benchmarks like <strong>NIAH</strong>, <strong>RULER</strong>, and <strong>L-CiteEval</strong> provide valuable insights, they have limitations in correlating synthetic tasks with real-world performance.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef77a220d34d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial Walkthrough: Intelligent Namecard Scanner into Excel Outputs Using Ollama LLMs, Google…]]></title>
            <link>https://onnyunhui.medium.com/tutorial-walkthrough-intelligent-namecard-scanner-into-excel-outputs-using-ollama-llms-google-9f03e1122465?source=rss-39fbf3f21f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f03e1122465</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[gradio]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vlm]]></category>
            <dc:creator><![CDATA[Onn Yun Hui]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 09:21:39 GMT</pubDate>
            <atom:updated>2025-03-02T13:23:40.114Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tutorial Walkthrough: Intelligent Namecard Scanner into Excel Outputs Using Ollama LLMs, Google Colab and Gradio</h3><p>Following my previous guide on <a href="https://onnyunhui.medium.com/using-llama3-2-vision-for-namecard-recognition-a-step-by-step-guide-209a8ba515d7">Using Llama3.2-Vision and NuExtract-v1.5 for Namecard Recognition: A Step-by-Step Guide</a>, I presented a proof of concept that employed two models: the Llama3.2-Vision and NuExtract-v1.5 models for extracting information from name card images using open-sourced LLMs, Visual Language Models (VLMs), to convert the extracted output into a structured format.</p><p>I’ve provided a run-all code in the middle of this article in Google Collab for you to play around without any other dependencies or need to download anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aejY9G42rCm4YzC2OkjI-A.png" /><figcaption>Robot reading namecards: Image Generated from Dall-E3</figcaption></figure><p>Before we go into the walkthrough, I want to go through an important model for this pipeline- NuExtract-v1.5:</p><h3>Introduction to NuExtract-v1.5</h3><p>Our current extraction model uses the fine-tuned version of Phi-3.5-mini-instruct NuExtract-v1.5 version which specialises in extracting JSON template from a series of text. Remarkably, this model claims to outperform GPT-4o in English while being <strong>500 times smaller</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBmCTw7osPc-PWi799RWxg.png" /><figcaption><a href="https://numind.ai/blog/nuextract-1-5---multilingual-infinite-context-still-small-and-better-than-gpt-4o">https://numind.ai/blog/nuextract-1-5---multilingual-infinite-context-still-small-and-better-than-gpt-4o</a></figcaption></figure><p>Abstract from Numind’s website:</p><blockquote>We introduce NuExtract 1.5, the new version of our foundation model for structured extraction. NuExtract 1.5 is multilingual, can handle arbitrarily long documents, and outperforms GPT-4o in English while being 500 times smaller. As usual, we release it under MIT license.</blockquote><h3>Infinite Context Size Problem</h3><p>Most models today struggle with understanding lengthy texts due to the inherent limitations of transformer models that utilize attention mechanisms. While it is technically feasible to process super-long documents, it becomes memory- and computationally intensive since every token must “attend” to all other tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*nWON3PcBN2HSay6Y.png" /><figcaption>Source: <a href="https://numind.ai/blog/nuextract-1-5---multilingual-infinite-context-still-small-and-better-than-gpt-4o">https://numind.ai/blog/nuextract-1-5---multilingual-infinite-context-still-small-and-better-than-gpt-4o</a></figcaption></figure><p>To overcome this continuous attention requirement, the team at NuMind trained NuExtract-v1.5 to extract information from a document based on a provided JSON output and text. The input consists of a template and previously extracted information. This ability to learn from previous and new information based on template allows the NuExtract-v1.5 model to be able to extract information even from very long documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XLtAUYCPEIih5Ga7tVa6Q.png" /><figcaption>Input text and previous information to achieve a desired output based on template. Source:<a href="https://numind.ai/blog/nuextract-1-5---multilingual-infinite-context-still-small-and-better-than-gpt-4o">https://numind.ai/blog/nuextract-1-5---multilingual-infinite-context-still-small-and-better-than-gpt-4o</a></figcaption></figure><p>This is very similar to the refinement summarisation process in LangChain:</p><p>Where information is distilled from large volumes of text by breaking it into smaller chunks that fit within the model’s context length and summarising them iteratively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*JfkSuL1sKaaBiqdg6_R7Jw.jpeg" /><figcaption>Langchain’s refinement process. Source:<a href="https://python.langchain.com/docs/how_to/summarize_refine/">https://python.langchain.com/docs/how_to/summarize_refine/</a></figcaption></figure><h3>Efficient Memory Management</h3><p>Thanks to this innovative approach, NuExtract maintains low GPU memory usage even with context lengths exceeding 10,000 tokens. Below, we illustrate the GPU memory requirements for using NuExtract-v1.5 with a full extraction window compared to a 10,000 tokens extraction window with a 2,000 tokens output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*b48h7n7YSjFu6Tty.png" /><figcaption>Comparison of GPU memory requirements for using NuExtract-v1.5 with a full extraction window and with a 10k tokens extraction window with a 2k tokens output.</figcaption></figure><h3>Walkthrough: Developing your own business card scanner app for FREE using open-sourced models</h3><p>Now, let’s return to the topic of creating a business card scanner using locally hosted models with Gradio. You can run the full code available in my GitHub repository or view it directly from GitHub Gist.</p><p>View the run the full code below from <a href="https://gist.github.com/yheyyyy/c74e5265b0d0bccc2257a918ee97e32f">GitHub Gist</a> (Run-all, with no additional inputs, except your name card for testing) or you can checkout my <a href="https://github.com/yheyyyy/businesscardscanner">GitHub Repo</a> for this project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c43a71e403808599847df4de656b8c3/href">https://medium.com/media/4c43a71e403808599847df4de656b8c3/href</a></iframe><h3>Step 1: Initialize the Environment</h3><p>If you are using Google Colab, follow these steps to set up your environment. If you are running locally, you can skip this section.</p><p>The environment has been set up to download, run and pull Ollama model.</p><pre>%pip install ollama==0.4.7<br>%pip install colab-xterm==0.2.0<br>%pip install gradio==5.20.0<br>!sudo apt-get update<br>!sudo apt-get install pciutils lshw<br>!npm install -g localtunnel<br>!curl -fsSL https://ollama.com/install.sh | sh</pre><pre># Import necessary libraries<br>import subprocess<br>import requests<br>import threading<br>import time<br><br># Run Ollama in the background<br>def run_ollama():<br>  subprocess.Popen([&quot;ollama&quot;, &quot;serve&quot;])<br><br>thread = threading.Thread(target=run_ollama)<br>thread.start()<br>time.sleep(5)</pre><pre># Download the llama3.2-vision:11b model<br>!ollama pull llama3.2-vision:11b<br><br># Download the iodose/nuextract-v1<br>!ollama pull iodose/nuextract-v1.5<br><br># Check if model is downloaded<br>!ollama list<br><br># Check if the Ollama instance is running<br>!curl http://127.0.0.1:11434</pre><h3>Step 2: Create a instance of vision model</h3><pre>%%writefile vision_model.py<br><br>import os<br>import ollama<br>import json<br>from extraction_model import process_data<br><br>def vision_model(image_path):<br>    &quot;&quot;&quot;<br>    This function uses the llama3.2-vision:11b model to extract the name card information from the image.<br>    It takes an image path and returns the name card information in a JSON format.<br>    <br>    Parameters<br>    ----------<br>    image_path : str <br>        The path to the image file.<br>        <br>    Returns<br>    -------<br>    response : str<br>        The name card information in a JSON format.<br>    &quot;&quot;&quot;<br>    <br>    prompt = &quot;&quot;&quot;Return the name card information in the following format:<br>    &quot;Name&quot;: &quot;&quot;, &quot;Job Title&quot;: &quot;&quot;, &quot;Company&quot;:&quot;&quot;, &quot;Contact Number&quot;:&quot;&quot;, &quot;Email Address&quot;:&quot;&quot;, &quot;Website&quot;:&quot;&quot;, &quot;Address&quot;: &quot;&quot;<br>    Keep it to a JSON format and do not output other information, separate any information with a comma.<br>    &quot;&quot;&quot;<br>    <br>    if os.path.exists(image_path):<br>        response = ollama.chat(<br>            model=&quot;llama3.2-vision:11b&quot;,<br>            messages=[{<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: prompt,<br>            &quot;images&quot;: [image_path],<br>            <br>        }]<br>    )<br>        return response[&#39;message&#39;][&#39;content&#39;].strip()<br>    else:<br>        print(f&quot;Image {image_path} does not exist&quot;)<br>        return None<br><br>def image_to_json(image_path):<br>    &quot;&quot;&quot;<br>    This function converts an image to a JSON format.<br>    It takes an image and returns the JSON format of the image.<br>    <br>    Parameters<br>    ----------<br>    image : str<br>        The image to be converted to JSON format.<br>        <br>    Returns<br>    -------<br>    json_data : str<br>        The JSON format of the image.<br>    &quot;&quot;&quot;<br>    single_img_data = vision_model(image_path)<br>    if single_img_data:<br>        cleaned_data = process_data(single_img_data)<br>        return json.loads(cleaned_data)<br>    else:<br>        print(f&quot;Image {image_path} does not exist&quot;)<br>        return None</pre><p><strong>vision_model</strong>: Extraction of name card information using Llamavision VLM using Ollama chat function.</p><p><strong>image_to_json</strong>: from image to output JSON using both the vision model and process_data function (see later)</p><pre>%%writefile extraction_model.py<br>import ollama<br>import re<br>import json<br><br>def json_model(text):<br>    &quot;&quot;&quot;<br>    This function uses the nuextract-v1.5 model to convert the information text into JSON format.<br>    It takes a text and returns the JSON format of the information.<br>    <br>    Parameters<br>    ----------<br>    text : str<br>        The information text to be converted into JSON format.<br>        <br>    Returns<br>    -------<br>    json_data : str<br>        The JSON format of the information.<br>    &quot;&quot;&quot;<br>    prompt_template = &quot;&quot;&quot;Convert the following information text into JSON format:<br>    {text}<br>    Return NIL if information is not found.<br>    &quot;&quot;&quot;<br>    if text:<br>        prompt = prompt_template.format(text=text)<br><br>        return ollama.chat(<br>            model=&quot;iodose/nuextract-v1.5&quot;,<br>            messages=[{<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: prompt<br>            }]<br>        )<br>    else:<br>        print(&quot;No text to process&quot;)<br>        return None<br><br><br>def extract_json_from_text(text):<br>    &quot;&quot;&quot;<br>    This function extracts the JSON data from the given text.<br>    It takes a text and returns the JSON data from the given text.<br>    <br>    Parameters<br>    ----------<br>    text : str<br>        The text to be extracted from.<br>        <br>    Returns<br>    -------<br>    matches : json<br>        The JSON data from the given text.<br>    &quot;&quot;&quot;<br>    if text:<br>        pattern = r&#39;\{.*?\}&#39;<br>        matches = re.findall(pattern, text, re.DOTALL)<br>        return matches<br>    else:<br>        print(&quot;No text to process regex pattern&quot;)<br>        return None<br><br><br>def parse_and_clean_json(matches):<br>    &quot;&quot;&quot;<br>    This function parses and cleans the JSON data from the given text.<br>    It takes a list of text within {} and returns the cleaned JSON data.    <br><br>    Parameters<br>    ----------<br>    matches : list<br>        The list of text within {} from the given text.<br>        <br>    Returns<br>    -------<br>    cleaned_data : str<br>        The cleaned JSON data.<br>    &quot;&quot;&quot;<br>    cleaned_data = str()<br>    for match in matches:<br>        try:<br>            json_data = json.loads(match)<br>            cleaned_data += json.dumps(json_data)<br>        except json.JSONDecodeError as e:<br>            print(f&quot;Error decoding JSON: {e}&quot;)<br>            return None<br>    return cleaned_data<br><br><br>def process_data(text):<br>    &quot;&quot;&quot;<br>    This function processes the text and returns the cleaned JSON data.<br>    It takes a text and returns the cleaned JSON data.<br>    <br>    Parameters<br>    ----------<br>    text : str <br>        The text to be processed.<br>        <br>    Returns<br>    -------<br>    cleaned_json : str<br>        The cleaned JSON data.<br>    &quot;&quot;&quot;<br>    if text:<br>        response = json_model(text)<br>        cleaned_text = response.get(&#39;message&#39;, {}).get(&#39;content&#39;, &#39;&#39;)<br><br>        while True:<br>            matches = extract_json_from_text(cleaned_text)<br>            cleaned_json = parse_and_clean_json(matches)<br><br>            if cleaned_json:<br>                break<br>            else:<br>                print(&quot;Invalid format, retrying&quot;)<br>                response = json_model(text)<br>                cleaned_text = response.get(&#39;message&#39;, {}).get(&#39;content&#39;, &#39;&#39;)<br>        print(cleaned_json)<br>        return cleaned_json<br>    else:<br>        print(&quot;No text to process&quot;)<br>        return Noneimage_to_json: Opens the image, processes it using vision_model, and cleans the data using process_data. Converts the dictionary to a JSON string.<br>JSON to Excel Conversion:</pre><p><strong>json_model</strong>: uses nuextract-v1.5 model to do the extraction and convert into JSON format.</p><p><strong>extract_json_from_text</strong>: given particular output from JSON model, extract anything within the ‘{‘ and ‘}’.</p><p><strong>parse_and_clean_json</strong>: check if output is of json format, else, pass an error.</p><p><strong>process_data</strong>: the full function to iteratively obtain JSON output from nuextractv1.5, if JSON output is not obtained, it will retry again.</p><pre>%%writefile gradio_app.py<br>import os<br>import json<br>import gradio as gr<br>import pandas as pd<br><br>from vision_model import image_to_json<br><br><br>def json_to_df(cleaned_data):<br>    if isinstance(cleaned_data, str):<br>        cleaned_data = [cleaned_data]<br>    data_list = [json.loads(json_str) for json_str in cleaned_data]<br>    columns = [&quot;Name&quot;, &quot;Job Title&quot;, &quot;Company&quot;, &quot;Contact Number&quot;, &quot;Email Address&quot;, &quot;Website&quot;, &quot;Address&quot;]<br>    df = pd.DataFrame(data_list, columns=columns)<br>    return df<br><br>def upload_and_process(images):<br>    &quot;&quot;&quot;<br>    This function processes the uploaded images and converts them to Excel format.<br>    It takes a list of image files and returns the path to the updated Excel file.<br>    <br>    Parameters<br>    ----------<br>    images : list<br>        A list of image files to process.<br>        <br>    Returns<br>    -------<br>    excel_file_path : str<br>        The path to the updated Excel file.<br>    &quot;&quot;&quot;<br>    excel_file_path = &quot;name_card.xlsx&quot;<br>    new_data = []<br><br>    for image_path in images:<br>        try:<br>            print(f&#39;Processing image {image_path}&#39;)<br>            cleaned_data = image_to_json(image_path)<br>            new_data.append(cleaned_data)<br>            print(f&#39;Processed image {image_path}&#39;)<br>        except Exception as e:<br>            print(f&quot;Error processing image {image_path}: {e}&quot;)<br>            <br>    if new_data:<br>        new_df = json_to_df(new_data)<br>        os.makedirs(os.path.dirname(excel_file_path), exist_ok=True)<br>        <br>        if os.path.exists(excel_file_path):<br>            existing_df = pd.read_excel(excel_file_path)<br>            updated_df = pd.concat([existing_df, new_df], ignore_index= True)<br>        else:<br>            updated_df = new_df<br>        updated_df.to_excel(excel_file_path, index=False)<br>    else:<br>        print(&quot;No data to process&quot;)<br>        return None<br>    return excel_file_path<br><br># Create the Gradio interface<br>iface = gr.Interface(<br>    inputs=gr.File(label=&quot;Upload Image(s)&quot;, file_types=[&quot;.jpg&quot;, &quot;.png&quot;, &quot;.jpeg&quot;], file_count=&quot;multiple&quot;),<br>    outputs=gr.File(label=&quot;Download Excel File&quot;),<br>    fn=upload_and_process,<br>    title=&quot;Business Card Reader and Converter&quot;,<br>    description=&quot;Upload multiple name cards and get the processed data in Excel format.&quot;<br>)<br><br>if __name__ == &quot;__main__&quot;:<br>    iface.launch(share=True)</pre><p><strong>json_to_df</strong>: obtain a clear df structure from input cleaned data</p><p><strong>upload_and_process</strong>: Processes each uploaded image, collects the data, and updates the Excel file. Ensures the directory for the Excel file exists and handles the case where no data is processed.</p><p><strong>gr.Interface</strong>: Creates a Gradio interface with an input for uploading multiple images and an output for downloading the Excel file.<br>iface.launch(): Launches the Gradio interface.</p><h3>Step 3: Run the Gradio App</h3><pre>!python gradio_app.py</pre><h3>Step 4: Upload Your Namecards</h3><p>After launching the app, upload your namecards and wait for the <strong>name_card.xlsx</strong> file to be ready for download!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*qNnRb0TT1HGlo3Pmg5zacQ.png" /><figcaption>name_card.xlxs is ready for download!</figcaption></figure><p>If you found this guide useful, please consider applauding and subscribing to my Medium articles!</p><h3>References</h3><p><a href="http://numind.ai/blog/nuextract-1-5---multilingual-infinite-context-still-small-and-better-than-gpt-4o">NuExtract 1.5 — Multilingual, Infinite Context, Still Small, and Better than GPT-4o</a><br><a href="https://huggingface.co/numind/NuExtract-1.5">Hugging Face NuExtract 1.5</a><br><a href="https://python.langchain.com/docs/how_to/summarize_refine/">LangChain Summarization Refinement</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f03e1122465" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>