<?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 RandomResearchAI on Medium]]></title>
        <description><![CDATA[Stories by RandomResearchAI on Medium]]></description>
        <link>https://medium.com/@randomresearchai?source=rss-fb8e21113540------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b9il40BWLtnlaFqo76dwyQ.png</url>
            <title>Stories by RandomResearchAI on Medium</title>
            <link>https://medium.com/@randomresearchai?source=rss-fb8e21113540------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:38:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@randomresearchai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Video Model Got Better With the Screen Off]]></title>
            <link>https://randomresearchai.medium.com/the-video-model-got-better-with-the-screen-off-992bd0553955?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/992bd0553955</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 23:04:41 GMT</pubDate>
            <atom:updated>2026-11-21T23:04:41.899Z</atom:updated>
            <content:encoded><![CDATA[<p>An experiment in video question answering shows what fine-tuning can learn from the answer choices, and how a constraint on the weight update changes the result.</p><p>The clip opens on a hand resting beside a block. The question asks which way the block moved. “To the left” and “to the right” are both plausible from the first frame. In a well-designed test, two clips could share that opening and require opposite answers. A deterministic system that sees only the question has to give the same answer to both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65jS1e4mplv1_4b7Ozp60g.png" /></figure><p><em>Illustrative example inspired by the Something-Something v2 action families.</em></p><p>On a held-out split derived from Something-Something v2, Qwen2.5-VL-7B answered 19.3% of questions correctly without video. After standard supervised fine-tuning, it answered 49.8% correctly without video. With the clips present, its score also rose, from 49.1% to 89.6%. If the evaluation had recorded only the score from the complete input, the adaptation would have looked like an unqualified success. The screen-off test shows a second thing the model learned. The two results come from Table 1 of the <a href="https://arxiv.org/html/2611.25776v1">November 19 preprint by Youngwoo Shin, Jongsuk Kim, and Junmo Kim</a>.</p><h3>The filter passed items the base model could miss</h3><p>The researchers started with a version of the dataset in which each clip has a multiple-choice question about an action. They grouped action templates into families so that a distractor could describe a closely related motion, such as uncovering the same object that the person in the actual clip covers. They tested each item without the clip, shuffling the choices on three passes. When the base model got all three right, the item was removed. The authors supply scripts for constructing and filtering the manifests in the <a href="https://github.com/Youngwoo-git/VETO">VETO repository</a>.</p><p>That test measures what one checkpoint can already extract from a set of prompts. It leaves open what the next checkpoint can learn when those prompts come with a training signal. Imagine that two phrases are roughly equally plausible to the base model, while one turns out to be a more common label in the fine-tuning data. Each individual prompt can look hard during filtering. Across examples, the wording may still carry information about the answer. The paper shows the model exploiting some textual signal after fine-tuning. It does not identify which features of the options account for the gain. Reshuffling the options during training had little effect, which makes a fixed answer-letter preference a poor explanation by itself.</p><p>An older image question-answering experiment offers a way to see the distinction. In <a href="https://openaccess.thecvf.com/content_cvpr_2017/papers/Goyal_Making_the_v_CVPR_2017_paper.pdf">VQA v2</a>, Yash Goyal and colleagues paired one question with similar images that required different answers. If the text is literally identical within a pair, a text-only rule must fail on at least one half. Filtering by a model’s current success gives a weaker guarantee. <a href="https://aclanthology.org/2024.findings-acl.517/">TempCompass</a> applies the paired-example idea to video. Its authors construct clips with shared static content and conflicting temporal events so a still image is a weak substitute for the sequence. Those designs change the evidence the dataset demands. The new preprint changes which directions the model can learn in.</p><h3>Put a constraint on the adapter</h3><p>The researchers fine-tuned with <a href="https://arxiv.org/abs/2106.09685">LoRA</a>, the method Edward Hu and colleagues introduced for adding a low-rank update to an existing weight matrix. For a linear layer with frozen weight W, write the adapted weight as W + BA. The small matrix A reads the input into a space with fewer dimensions, and B maps that result into the layer’s output. The paper’s method, VETO, restricts what A can read.</p><p>To estimate the directions to restrict, the researchers ran the base model on 400 held-out calibration prompts with their videos removed. They collected the input activations for each adapted module. For one module, stack those vectors as columns of H. The matrix HHᵀ / n, where n is the number of collected token positions, summarizes where the activations have most of their squared magnitude. Keeping the leading eigenvectors until they account for 95% of that magnitude gives an orthonormal basis U. An individual direction in U need not correspond to a word or a human-readable rule. In the Qwen2.5-VL-7B experiment the basis used about 7% of the input dimensions while capturing 94.8% of the energy on held-out text activations in the authors’ calibration analysis. See <a href="https://arxiv.org/html/2611.25776v1">Appendix C</a>.</p><p>After each optimizer step, the method changes A to A(I − UUᵀ). For a vector u spanned by U, the factor in parentheses maps u to zero. The adapter therefore adds nothing to that layer’s response to u, leaving Wu. The same adapter remains free to change the response to components outside that span. In two dimensions, think of an adapter row that initially reads both coordinates, [3, 2]. If the protected direction is the horizontal axis, the projection turns the row into [0, 2]. The frozen layer can still use the horizontal coordinate. Only the adapter’s new contribution loses access to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQbTG3Wn4QNzXV67pSb79w.png" /></figure><p><em>An illustrative two-dimensional projection. The coordinates explain the algebra and are not model measurements.</em></p><p>This is a local constraint on a particular layer. A text-only prompt can still contain directions outside U, and activations arriving at a deeper adapted layer can differ from the base model’s. There is also no special exemption for useful language information inside U. What makes the experiment interesting is that the authors got most of the full-input improvement even with this fairly blunt restriction.</p><p>The timing ablation is telling. On the filtered Something-Something v2 split, projecting once after ordinary training cut full-input accuracy to 82.4%. Projecting during every step yielded 89.2%. The adapter had room to develop a different solution during training. Deleting part of a finished adapter is a different experiment, because the remaining weights were trained alongside the part that was cut. A projection onto a random subspace of the same rank also left the text-only score near the ordinary fine-tuning result. The intervention depends on which directions are excluded, as <a href="https://arxiv.org/html/2611.25776v1">Tables 5–6 and Appendix D</a> report.</p><h3>Change the test and the two gains separate</h3><p><a href="https://proceedings.neurips.cc/paper_files/paper/2023/hash/8540fba4abdc7f9f7a7b1cc6cd60e409-Abstract.html">Perception Test</a>, introduced by Viorica Patraucean and colleagues, gives this experiment a different source of clips and question wording. On the authors’ blind-filtered subset, ordinary fine-tuning left full-input accuracy at 61.1%, the same reported mean as the base model. Text-only accuracy went from 21.3% to 38.3%. VETO reached 64.3% with the clip and 26.2% without it. These are results for the filtered subset, with the fine-tuned values averaged across three seeds. The source is <a href="https://arxiv.org/html/2611.25776v1">Appendix E, Table L</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoSGj9UAxaXv76EkP8L6SA.png" /></figure><p><em>Accuracy (%) from Shin, Kim, and Kim, Appendix E, Table L. Fine-tuned bars show means over three seeds.</em></p><p>The unchanged 61.1% can hide a change in which questions the system gets right. A text cue might rescue some answers as the model loses others that once depended on seeing the clip. Comparing two aggregate accuracies cannot establish that swap. The researchers therefore added an attention-blocking test: leave the video in the input while preventing text tokens from attending to the video tokens. They counted how many of the model’s originally correct answers survived the block. On the filtered Perception Test, 45.7% survived after ordinary fine-tuning, compared with 26.3% under VETO. Since the clip remains in the input, this test helps separate the model’s access to information in the clip from the simpler effect of changing the prompt’s shape by withholding video.</p><p>The authors report this as a preprint result. Its cross-benchmark comparison uses Qwen2.5-VL-7B on filtered multiple-choice sets. The broader seven-model comparison is on the Something-Something v2 task used for fine-tuning. An open-ended answer may look grounded while quietly substituting a plausible event for the one on screen. These experiments offer no direct measure of that case. And a model that reacts when it sees a video may have noticed a static object or a single diagnostic frame. Across video benchmarks, <a href="https://arxiv.org/abs/2505.14321">Feng and colleagues</a> use frame shuffling to separate questions that survive a changed frame order from those that need the temporal sequence.</p><p>That suggests a useful next test for VETO. Show the model two clips with identical text and opposite correct answers. Count a pair as correct only when the model answers both halves correctly. Then run it again after preserving the frames and damaging their order. If the adapter has learned to read the action itself, the intact pairs should be where its improvement is clearest. The model has already shown that it can change its answer when the screen turns on. The next question is whether it changes its answer when the same hand moves the same block the other way.</p><h3>References</h3><p><a href="https://arxiv.org/abs/2611.25776">Shin, Kim, and Kim. Suppressing the Shortcut Hidden Behind the Gains of VideoLLM Fine-Tuning (2026).</a></p><p><a href="https://github.com/Youngwoo-git/VETO">Shin and colleagues. VETO implementation.</a></p><p><a href="https://openaccess.thecvf.com/content_cvpr_2017/papers/Goyal_Making_the_v_CVPR_2017_paper.pdf">Goyal and colleagues. Making the v in VQA Matter (2017).</a></p><p><a href="https://aclanthology.org/2024.findings-acl.517/">Liu and colleagues. TempCompass (2024).</a></p><p><a href="https://arxiv.org/abs/2106.09685">Hu and colleagues. LoRA (2021 preprint).</a></p><p><a href="https://proceedings.neurips.cc/paper_files/paper/2023/hash/8540fba4abdc7f9f7a7b1cc6cd60e409-Abstract.html">Patraucean and colleagues. Perception Test (2023).</a></p><p><a href="https://arxiv.org/abs/2505.14321">Feng and colleagues. Breaking Down Video LLM Benchmarks (2025).</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=992bd0553955" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built the Same AI Memory System Three Different Ways. Here’s What Actually Mattered.]]></title>
            <link>https://randomresearchai.medium.com/i-built-the-same-ai-memory-system-three-different-ways-heres-what-actually-mattered-dce2022da1d5?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/dce2022da1d5</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[semantic-search]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 19:25:45 GMT</pubDate>
            <atom:updated>2026-09-07T19:25:45.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*A6kfg1IkRexlqP75" /><figcaption>ResearchGate</figcaption></figure><h3>My first AI memory system had an impeccable memory.</h3><p>It remembered abandoned ideas, temporary assumptions, corrected mistakes, irrelevant detours, and every confident sentence I later wished I had never written. If I changed my mind on Tuesday, the system would happily retrieve Monday’s opinion on Wednesday and present both with the diplomatic neutrality of someone refusing to get involved in a family argument.</p><p>Technically, it worked.</p><p>That was the problem.</p><p>I had begun with the same vague ambition behind most “persistent memory” features: I wanted an AI system that could carry useful context between conversations. If I explained how a project worked today, I wanted tomorrow’s conversation to begin somewhere beyond introductions. If I corrected an assumption, I wanted the correction to survive. If I established a preference once, repeating it every session felt like paperwork.</p><p>The phrase “give the model memory” made this sound suspiciously easy.</p><p>It eventually forced me to rebuild the same idea three different ways.</p><p>The first version treated conversation history as memory. The second used embeddings and semantic retrieval. The third became much more selective about what deserved to be remembered at all.</p><p>The surprising part was not that the third system worked better.</p><p>The surprising part was how little the biggest improvements had to do with the vector database.</p><h3>Version One: Remember Everything</h3><p>The first implementation followed the obvious strategy.</p><p>I stored previous conversations and fed relevant portions back into the model during future interactions. Recent context went in, the model read it, and continuity appeared.</p><p>For a while, this felt almost embarrassingly effective.</p><p>If I mentioned that an application used a particular framework and asked a related question ten minutes later, the model already knew what I meant. No retrieval pipeline was necessary. No embedding model was necessary. There were no similarity thresholds to tune and no diagrams requiring seventeen arrows.</p><p>The whole system depended on a wonderfully unsophisticated principle: if the model might need something later, keep giving it everything.</p><p>That principle ages badly.</p><p>Conversations accumulate debris incredibly quickly. A technical discussion rarely consists entirely of durable facts. It contains guesses, questions, rejected approaches, half-finished debugging theories, temporary constraints, copied error messages, and sentences whose useful lifespan ends approximately three minutes after they are written.</p><p>My memory system preserved all of them with equal devotion.</p><p>Imagine a conversation that evolves like this:</p><p>You begin by considering Redis.</p><p>Later, deployment complexity makes Redis unattractive.</p><p>Eventually, you remove Redis entirely.</p><p>Several days afterward, you ask the model how the application should handle caching.</p><p>A transcript has preserved the entire intellectual journey. Unfortunately, the application usually needs the destination.</p><p>The model now receives evidence supporting multiple incompatible states of the world. Sometimes it correctly infers the chronology. Sometimes it gives too much weight to the older statement because its wording resembles the current question more closely. Sometimes it politely resurrects an idea that had already been buried.</p><p>The problem grew more obvious as histories became longer.</p><p>Large context windows make it tempting to postpone this problem indefinitely. If a model can accept an enormous prompt, why bother deciding what matters?</p><p>Because storage capacity and attention are separate resources.</p><p>A model can technically receive a fact without meaningfully using it. Relevant information competes with outdated information, duplicated information, and whatever fascinating tangent occurred forty messages earlier. Larger context windows reduce one engineering constraint while leaving the underlying selection problem intact.</p><p>At some point, I realized that I had built an archive and started calling it memory.</p><p>Those are different systems. An archive preserves what happened. Memory needs an opinion about what still matters.</p><h3>Version Two: Embeddings Save the Day, Briefly</h3><p>The natural next step was semantic retrieval.</p><p>Instead of feeding entire conversations into the model, I embedded stored text and retrieved only the passages most similar to the current query.</p><p>This was immediately better.</p><p>A question about deployment could retrieve previous deployment decisions instead of dragging in an unrelated discussion about UI spacing. Prompt sizes dropped. Retrieval became targeted. The system finally seemed capable of finding the right fragment without rereading its autobiography before every response.</p><p>This is roughly where many AI memory architectures stop.</p><p>I understand why. Vector retrieval is elegant. It converts an uncomfortable question about human-like memory into a tractable search problem. Turn text into vectors, compare distances, retrieve the nearest matches, and send them into the model.</p><p>Then semantic similarity began doing exactly what semantic similarity is supposed to do.</p><p>That exposed the second problem. Similarity does not know whether something is true anymore.</p><p>Consider three statements:</p><blockquote>“We are considering Redis.”</blockquote><blockquote>“We decided against Redis.”</blockquote><blockquote>“We are reconsidering Redis for a different service.”</blockquote><p>A query asking about Redis may retrieve all three because, semantically, they are excellent matches.</p><p>The vector database has performed admirably.</p><p>The memory system has created a small constitutional crisis.</p><p>Cosine similarity has no inherent concept of supersession. It does not understand that one statement corrected another. It does not know that a decision applied to Project A while another applied to Project B. It cannot infer that “I usually prefer X” and “I prefer Y for this particular project” may coexist without contradiction.</p><p>Once I noticed this, I began trying the standard remedies.</p><p>I added metadata. I considered recency. I experimented with different chunk boundaries. I tightened retrieval thresholds. I changed how many memories came back.</p><p>Each adjustment improved some cases, but they all shared an assumption I had stopped trusting.</p><p>They assumed the database contained memories worth retrieving. That assumption was wrong.</p><h3>Retrieval Was Solving the Wrong Half of the Problem</h3><p>The turning point came when I inspected what the system was actually storing.</p><p>A typical conversation might contain dozens of messages while producing only one or two facts that deserve to survive the session.</p><p>Someone asks whether a function should be synchronous.</p><p>They paste code. The model proposes one approach. They reject it. They clarify a constraint. The implementation changes.</p><p>Several messages later, the actual durable fact becomes clear: this project requires asynchronous database access because synchronous calls interfere with its execution model.</p><p>A transcript stores the whole discussion. A naive vector system embeds the whole discussion. A useful memory system should probably store the final constraint. That distinction changed the architecture more than any retrieval tweak had.</p><p>I stopped treating every conversational fragment as a potential memory and introduced a separate memory-writing step. New information had to earn persistence.</p><p>The system began asking questions that sounded less like search and more like state management.</p><p>Does this statement describe a durable preference or a temporary request Does it apply globally or only inside one project? Does it replace an older fact? Does it refine an older fact?</p><p>Will knowing this information materially change a future response? If the answer was no, the system could simply let the information die. This felt strangely radical after spending so much time improving storage.</p><p>AI applications are exceptionally good at accumulating information because storing text is cheap. Deleting, ignoring, or superseding information requires judgment. Memory quality therefore depended heavily on restraint. The best memory I stored was often the message I decided not to store.</p><h3>A Memory Has to Survive Outside Its Original Conversation</h3><p>Once I started storing fewer memories, another issue became obvious. Raw conversational sentences are frequently terrible memory objects. Suppose someone says:</p><p>“Yeah, let’s do that because the other one kept breaking.” Inside the conversation, this sentence makes perfect sense. Retrieved three weeks later, it reads like evidence collected from a witness with a personal grudge against nouns.</p><p>A durable memory needs enough context to stand on its own.</p><p>Instead of preserving the sentence itself, the system might represent the underlying decision as:</p><p>“The project uses asynchronous database operations because the previous synchronous approach caused blocking behavior.”</p><p>The second version is less conversational and far more useful.</p><p>It identifies the subject, the decision, and the reason.</p><p>That gave me one of the most useful rules from the entire experiment:</p><p>A memory should remain interpretable after the conversation that created it disappears.</p><p>This also changed how I thought about chunking.</p><p>Vector search discussions often treat chunk size as a retrieval optimization problem. Larger chunks contain more context but produce less precise embeddings. Smaller chunks produce sharper embeddings but can separate facts from the information required to interpret them.</p><p>Memory introduces another criterion.</p><p>The unit should correspond to an idea the system can independently reason about.</p><p>A paragraph containing six unrelated project decisions is too broad.</p><p>“Redis bad” is too narrow.</p><p>“Redis was removed from this project because its deployment overhead outweighed the caching benefit” is much closer to something a future model can actually use.</p><p>The goal is not merely to create chunks.</p><p>The goal is to create state.</p><h3>Time Became More Complicated Than Recency</h3><p>My next instinct was to favor newer memories.</p><p>That works until it does not.</p><p>Some information should decay quickly. A temporary implementation choice from last week may already be obsolete. A debugging hypothesis from yesterday may deserve almost no authority today.</p><p>Other information barely decays at all.</p><p>A stable preference does not become less true because it was mentioned six months ago. A project’s core purpose does not automatically lose relevance because nobody discussed it last week.</p><p>This made simple recency scoring feel increasingly crude.</p><p>The problem was not determining how old a memory was.</p><p>The problem was determining how age should affect that kind of memory.</p><p>A temporary task state and a durable user preference should not share the same expiration logic. Neither should an architectural decision and a personal fact. Time matters differently depending on what the information represents.</p><p>The obvious engineering solution is metadata.</p><p>The more interesting design lesson is that memory systems eventually need a theory of change.</p><p>Some facts expire.</p><p>Some facts persist.</p><p>Some facts are replaced.</p><p>Some facts become more specific.</p><p>Some facts were never facts in the first place.</p><p>Once you acknowledge that, “store embeddings and retrieve the nearest five” begins looking less like a memory architecture and more like one component inside a larger one.</p><h3>Contradictions Were the Real Stress Test</h3><p>The hardest cases appeared when the user changed something.</p><p>Imagine the system remembers:</p><p>“I prefer concise answers.”</p><p>Later, the user says:</p><p>“For technical explanations, I want considerably more detail.”</p><p>Those statements can coexist.</p><p>The second statement narrows the first one.</p><p>Now imagine the user says:</p><p>“I generally prefer detailed answers now.”</p><p>That probably changes the earlier preference.</p><p>A system that blindly stores both facts leaves the model to resolve the conflict every time they are retrieved. A system that blindly deletes the older fact may erase useful history. A system that only ranks by recency assumes the newest statement always has greater authority.</p><p>None of those rules is reliable enough by itself.</p><p>I eventually found it more useful to think about memory updates using relationships.</p><p>A new memory might extend an existing one.</p><p>It might refine an existing one.</p><p>It might contradict an existing one.</p><p>It might supersede an existing one entirely.</p><p>The difference sounds semantic until the system begins behaving strangely.</p><p>Without explicit update logic, a memory store slowly becomes a museum of every state the user has ever occupied. All exhibits remain open simultaneously.</p><p>The resulting model can sound uncannily knowledgeable while being subtly wrong.</p><p>That failure mode is worse than forgetting.</p><p>When a system forgets, the user can correct it.</p><p>When a system confidently remembers an obsolete fact, the user must first realize that the model is answering from an outdated world.</p><h3>The Retrieval Question Also Changed</h3><p>By the third version, even retrieval itself started looking different.</p><p>My earlier system effectively asked:</p><p>Which stored memories are most similar to this query?</p><p>The better question became:</p><p>Which stored memories would materially change the answer to this query?</p><p>Those questions overlap, but they produce different behavior.</p><p>Suppose the system knows that someone prefers PostgreSQL for production applications.</p><p>Then they ask for the derivative of x2x².</p><p>The stored preference is vaguely related to their technical background. It may even appear semantically relevant under a sufficiently broad search.</p><p>It should still remain nowhere near the prompt.</p><p>Every retrieved memory consumes more than tokens. It introduces another piece of information the model may weigh, interpret, or overuse.</p><p>Personalization can become noise surprisingly quickly.</p><p>A memory system should therefore be capable of remembering something without mentioning it.</p><p>That sounds obvious until retrieval is framed entirely as nearest-neighbor search.</p><p>Good recall includes knowing when silence is better.</p><h3>The Vector Database Was Never the Villain</h3><p>After rebuilding the system three times, I did not conclude that embeddings were unnecessary.</p><p>I concluded that I had been asking them to solve too much.</p><p>Vector search remains extremely useful for discovering semantically related information. It is fast, flexible, and well suited to finding candidate memories from a larger store.</p><p>The mistake was allowing similarity to become the definition of relevance.</p><p>The third architecture still used semantic retrieval, but retrieval happened after memory formation had already removed a large amount of conversational debris. The candidate set contained cleaner, more contextualized information. Metadata provided scope. Update logic handled superseded facts. Temporal behavior depended on memory type rather than a single decay function.</p><p>Suddenly, the retrieval layer became considerably less dramatic.</p><p>That was a good sign.</p><p>The most reliable infrastructure often feels boring after the surrounding model becomes correct.</p><h3>I Started With a Search Problem and Ended With a State Problem</h3><p>The three versions changed how I think about AI memory.</p><p>The first system asked, “How much history can I preserve?”</p><p>The second asked, “How accurately can I retrieve history?”</p><p>The third asked, “What state should still be true?”</p><p>That final question turned out to be the one I actually cared about.</p><p>A useful AI memory system needs to compress conversations into something closer to a maintained model of the user, task, or project. It needs enough history to preserve continuity without treating every historical statement as current truth. It needs retrieval, but also forgetting. It needs persistence, but also revision.</p><p>This creates an awkward reality for anyone hoping that memory is simply a database feature.</p><p>The database is the easy part.</p><p>The difficult part is deciding what deserves to enter it, what should leave it, what should replace something already there, and what should remain stored without affecting the current response.</p><p>Those decisions determine whether the system feels like it remembers you or merely has access to your transcripts.</p><p>By the end of the experiment, my memory architecture had become less magical and more opinionated. It stored less, represented memories more deliberately, tracked their scope, and treated contradictions as updates rather than additional documents.</p><p>The system forgot far more information than my first version ever did.</p><p>It also remembered far more of what mattered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dce2022da1d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Databases and Embeddings: How AI Finds Meaning in Millions of Pieces of Data]]></title>
            <link>https://randomresearchai.medium.com/vector-databases-and-embeddings-how-ai-finds-meaning-in-millions-of-pieces-of-data-1c69a5950ca7?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c69a5950ca7</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[embedding]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 20:24:04 GMT</pubDate>
            <atom:updated>2026-07-15T20:24:04.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7gcU7-JNfgbY_ycz.png" /><figcaption>Credit: Machine Learning Mastery</figcaption></figure><h3>The technology behind semantic search, recommendation systems, AI memory, and retrieval-augmented generation</h3><p>Imagine searching a company knowledge base for:</p><blockquote><em>“How do I fix the issue where customers are charged twice?”</em></blockquote><p>The exact phrase may never appear in any document.</p><p>One support ticket might say “duplicate payment.” Another might mention “repeated billing.” An engineering note could describe an “idempotency failure in the checkout service.”</p><p>A traditional keyword search may miss all three because the words do not match closely enough.</p><p>A modern AI search system can recognize that these documents describe the same underlying problem.</p><p>The technology that makes this possible begins with two concepts:</p><ol><li><strong>Embeddings</strong>, which convert information into numerical representations of meaning.</li><li><strong>Vector databases</strong>, which store those representations and retrieve the most relevant ones quickly.</li></ol><p>Together, they allow software to search by meaning rather than exact wording.</p><p>They power document search, recommendation engines, fraud detection systems, image retrieval, conversational memory, and many retrieval augmented generation systems.</p><p>Understanding them is essential for understanding how modern AI applications actually work.</p><h3>What Is an Embedding?</h3><p>An embedding is a list of numbers that represents the meaning or characteristics of some piece of data.</p><p>That data could be:</p><ol><li>A sentence</li><li>A paragraph</li><li>An image</li><li>A product</li><li>A user profile</li><li>A song</li><li>A section of source code</li></ol><p>Consider these three sentences:</p><blockquote><em>“The customer was billed twice.”</em></blockquote><blockquote><em>“A duplicate payment appeared on the account.”</em></blockquote><blockquote><em>“The weather is sunny today.”</em></blockquote><p>An embedding model converts each sentence into a vector.</p><p>Conceptually, the result might look like this:</p><pre>&quot;The customer was billed twice.&quot;<br>[0.82, 0.14, 0.63, 0.09, ...]</pre><pre>&quot;A duplicate payment appeared on the account.&quot;<br>[0.79, 0.18, 0.67, 0.11, ...]</pre><pre>&quot;The weather is sunny today.&quot;<br>[0.05, 0.91, 0.12, 0.73, ...]</pre><p>Real embeddings often contain hundreds or thousands of values.</p><p>The individual numbers usually do not have simple human readable meanings. You cannot reliably say that one dimension represents billing while another represents weather.</p><p>Meaning is distributed across the full vector.</p><p>The important property is the relationship between vectors.</p><p>Sentences with similar meanings tend to produce vectors that are close together. Unrelated sentences tend to produce vectors that are farther apart.</p><p>This gives software a mathematical way to compare meaning.</p><h3>Embeddings Turn Meaning Into Geometry</h3><p>Once information is represented as vectors, semantic relationships become geometric relationships.</p><p>Suppose a simplified embedding has only two dimensions.</p><p>A system might place these concepts near one another:</p><pre>payment      refund      invoice      billing</pre><p>It might place these concepts in another region:</p><pre>rain      sunlight      temperature      weather</pre><p>In a real embedding space, there may be hundreds or thousands of dimensions. Humans cannot visualize that space directly, but the same principle applies.</p><p>Related concepts occupy nearby regions.</p><p>This allows a system to perform semantic search.</p><p>A query such as:</p><blockquote><em>“Why was I charged more than once?”</em></blockquote><p>can be embedded and compared with stored document embeddings.</p><p>Documents about duplicate billing should appear close to the query vector, even when they use different words.</p><p>That distinction is fundamental.</p><p>Keyword search asks:</p><blockquote><em>“Which documents contain these words?”</em></blockquote><p>Vector search asks:</p><blockquote><em>“Which documents express a similar meaning?”</em></blockquote><h3>How Similarity Is Measured</h3><p>A vector database needs a mathematical method for deciding which vectors are close.</p><p>Three common measurements are cosine similarity, dot product, and Euclidean distance.</p><h3>Cosine Similarity</h3><p>Cosine similarity measures the angle between two vectors.</p><p>Its formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*5uZR7FX1sbvhBt4E3cO7ww.png" /></figure><p>Two vectors pointing in similar directions receive a high score.</p><p>For many normalized embeddings, a larger cosine similarity means stronger semantic similarity.</p><p>Cosine similarity focuses mainly on direction rather than magnitude, which makes it useful when the direction of a vector represents meaning.</p><h3>Dot Product</h3><p>The dot product multiplies corresponding values and adds the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*5Xuip0WbreoIPcAMlPMHVg.png" /></figure><p>It is computationally efficient and commonly used when the embedding model was trained for dot product comparison.</p><p>For normalized vectors, dot product and cosine similarity produce closely related rankings.</p><h3>Euclidean Distance</h3><p>Euclidean distance measures the direct distance between two points.</p><p>A smaller distance means the vectors are closer.</p><p>There is no universally best metric. The correct choice depends on the embedding model and how its representations were trained.</p><h3>A Small Similarity Example</h3><p>The following Python code compares three simplified vectors using cosine similarity:</p><pre>import numpy as np</pre><pre>def cosine_similarity(a: np.ndarray, b: np.ndarray) -&gt; float:<br>    denominator = np.linalg.norm(a) * np.linalg.norm(b)</pre><pre>    if denominator == 0:<br>        raise ValueError(&quot;Vectors must have nonzero magnitude.&quot;)</pre><pre>    return float(np.dot(a, b) / denominator)<br></pre><pre>duplicate_charge = np.array([0.82, 0.14, 0.63])<br>repeated_payment = np.array([0.79, 0.18, 0.67])<br>sunny_weather = np.array([0.05, 0.91, 0.12])</pre><pre>print(cosine_similarity(duplicate_charge, repeated_payment))<br>print(cosine_similarity(duplicate_charge, sunny_weather))</pre><p>The first score should be much higher because the first two vectors represent similar ideas.</p><p>Real systems use much larger vectors, but the comparison process follows the same principle.</p><h3>What Is a Vector Database?</h3><p>A vector database is a database designed to store embeddings and retrieve the nearest vectors efficiently.</p><p>A typical record contains more than the vector itself.</p><pre>{<br>  &quot;id&quot;: &quot;support_document_1842&quot;,<br>  &quot;vector&quot;: [0.82, 0.14, 0.63, 0.09],<br>  &quot;text&quot;: &quot;Duplicate charges can occur when checkout requests are retried.&quot;,<br>  &quot;metadata&quot;: {<br>    &quot;department&quot;: &quot;support&quot;,<br>    &quot;product&quot;: &quot;payments&quot;,<br>    &quot;updated_at&quot;: &quot;2026-06-14&quot;<br>  }<br>}</pre><p>The vector supports semantic comparison.</p><p>The original text provides the information returned to the application.</p><p>The metadata allows the system to filter results.</p><p>For example, an application might request documents that are semantically similar to a query while also requiring:</p><pre>department = support<br>product = payments<br>updated_at after January 1, 2026</pre><p>This combination of semantic retrieval and structured filtering is one of the most valuable properties of vector databases.</p><h3>Why a Normal Database Is Often Insufficient</h3><p>Traditional relational databases are excellent for exact structured queries.</p><p>They can answer questions such as:</p><pre>SELECT *<br>FROM orders<br>WHERE customer_id = 1842<br>AND status = &#39;refunded&#39;;</pre><p>This works because the requested conditions are precise.</p><p>Semantic questions are less structured:</p><blockquote><em>“Find previous incidents similar to this checkout failure.”</em></blockquote><blockquote><em>“Which products have a style similar to this jacket?”</em></blockquote><blockquote><em>“Which research papers discuss related methods?”</em></blockquote><blockquote><em>“Which code files are relevant to this bug report?”</em></blockquote><p>These requests require similarity rather than exact equality.</p><p>A relational database can store vectors, and many relational systems now support vector search through extensions. The distinction is therefore architectural rather than absolute.</p><p>The real requirement is an indexing system capable of searching high dimensional vectors efficiently.</p><h3>The Scaling Problem</h3><p>Suppose a database contains ten million document embeddings.</p><p>A simple search could compare the query vector against all ten million vectors, calculate every similarity score, sort the scores, and return the best matches.</p><p>This is called exact nearest neighbor search.</p><p>It can provide accurate results, but the computational cost grows with the number of stored vectors.</p><p>For large systems, comparing against every vector for every query becomes too slow or expensive.</p><p>Vector databases therefore use approximate nearest neighbor search.</p><p>Approximate search avoids examining every stored vector. It searches the most promising regions of the embedding space and returns results that are usually very close to the exact nearest neighbors.</p><p>The system accepts a small possibility of missing the mathematically perfect result in exchange for much lower latency and computational cost.</p><h3>How Vector Indexes Work</h3><p>Several indexing strategies are commonly used.</p><h3>Hierarchical Navigable Small World Graphs</h3><p>A Hierarchical Navigable Small World index, commonly called HNSW, organizes vectors into a graph.</p><p>Each vector is connected to nearby vectors.</p><p>The graph contains multiple layers. Higher layers provide broad navigation across the space, while lower layers contain more detailed local connections.</p><p>A search begins at an upper layer, moves toward promising regions, and gradually descends into more precise neighborhoods.</p><p>Instead of comparing the query against every vector, the system follows graph connections toward likely matches.</p><p>HNSW often provides strong retrieval quality and low query latency, although its graph can consume substantial memory.</p><h3>Inverted File Indexes</h3><p>An inverted file index, commonly called IVF, divides the vector space into clusters.</p><p>Each cluster has a representative center.</p><p>During a search, the system first identifies the clusters whose centers are closest to the query. It then searches only the vectors inside those clusters.</p><p>This reduces the number of comparisons.</p><p>Searching more clusters generally improves recall but increases latency. Searching fewer clusters improves speed but raises the chance of missing relevant results.</p><h3>Product Quantization</h3><p>Product quantization compresses vectors into smaller representations.</p><p>Instead of storing every vector using full precision numbers, the system approximates portions of each vector using a collection of learned codes.</p><p>This reduces memory usage and can accelerate distance calculations.</p><p>The tradeoff is reduced precision.</p><p>Large systems often combine clustering, compression, and graph based indexing to balance memory, latency, and retrieval quality.</p><h3>The Complete Semantic Search Pipeline</h3><p>A production semantic search system usually follows this sequence:</p><pre>User query<br>↓<br>Embedding model<br>↓<br>Query vector<br>↓<br>Vector index<br>↓<br>Nearest candidate documents<br>↓<br>Optional reranking model<br>↓<br>Final results</pre><p>Suppose the user asks:</p><blockquote><em>“How can I stop the checkout service from creating duplicate orders?”</em></blockquote><p>The system performs the following operations.</p><h3>Step 1: Embed the Query</h3><p>The query is sent to the same embedding model used to process the stored documents.</p><pre>Query text → Query vector</pre><p>Using compatible embedding models is essential. Vectors created by unrelated models generally should not be compared directly because their coordinate spaces have different meanings.</p><h3>Step 2: Search the Vector Index</h3><p>The query vector is compared against the indexed document vectors.</p><p>The database retrieves a set of nearby candidates.</p><pre>Query vector → Top 20 candidate chunks</pre><h3>Step 3: Apply Metadata Filters</h3><p>The system may restrict results by access level, product, date, language, organization, or document type.</p><p>This step is especially important in enterprise systems where users should only retrieve information they are authorized to view.</p><h3>Step 4: Rerank the Results</h3><p>Vector similarity is useful but imperfect.</p><p>A separate reranking model can examine the query and each candidate more carefully, then assign a more precise relevance score.</p><p>The vector database may retrieve twenty candidates quickly. The reranker can reorder those candidates and select the best five.</p><p>This two stage design balances speed and accuracy.</p><h3>Step 5: Return or Generate an Answer</h3><p>A search application can display the retrieved documents directly.</p><p>A retrieval augmented generation application can provide the documents to a language model as context.</p><p>The language model then generates an answer based on the retrieved evidence.</p><h3>Vector Databases and Retrieval Augmented Generation</h3><p>Retrieval augmented generation, commonly called RAG, connects a language model to external information.</p><p>A language model has limited context and does not automatically know the private contents of a company database, classroom folder, legal archive, or project repository.</p><p>RAG retrieves relevant information before asking the model to answer.</p><p>The architecture looks like this:</p><pre>Question<br>↓<br>Create query embedding<br>↓<br>Search vector database<br>↓<br>Retrieve relevant passages<br>↓<br>Insert passages into model context<br>↓<br>Generate answer</pre><p>Consider a company assistant answering:</p><blockquote><em>“What is our refund policy for annual subscriptions?”</em></blockquote><p>The vector database may retrieve sections from the billing policy, customer support handbook, and latest product terms.</p><p>The language model receives those passages and constructs an answer.</p><p>The vector database supplies evidence. The language model interprets and communicates it.</p><p>This distinction matters because a language model can produce a fluent answer even when retrieval fails. A well designed system must therefore expose sources, validate relevance, and refuse to invent unsupported details.</p><h3>The Most Overlooked Part: Chunking</h3><p>Documents are often too large to embed as single units.</p><p>A fifty page report may contain multiple unrelated topics. Representing the entire report with one vector compresses too much information into a single point.</p><p>Systems therefore divide documents into smaller pieces called chunks.</p><p>For example:</p><pre>Document<br>↓<br>Section<br>↓<br>Paragraph group<br>↓<br>Embedding</pre><p>Chunking has a major effect on retrieval quality.</p><h3>Chunks That Are Too Large</h3><p>Large chunks provide more context but may contain several topics.</p><p>The resulting embedding becomes less precise, and irrelevant text consumes the language model context window.</p><h3>Chunks That Are Too Small</h3><p>Small chunks can produce precise matches but may remove necessary context.</p><p>A retrieved sentence might refer to “this policy” without including the policy it references.</p><h3>Better Chunking Strategies</h3><p>Useful approaches include:</p><ol><li>Splitting by headings and document structure</li><li>Keeping related paragraphs together</li><li>Adding limited overlap between adjacent chunks</li><li>Preserving titles and section names in each chunk</li><li>Storing links to neighboring chunks</li><li>Creating different chunk sizes for different query types</li><li>Using semantic boundaries rather than fixed character counts</li></ol><p>There is no universal chunk size.</p><p>Technical documentation, legal contracts, support tickets, source code, and research papers have different structures. Each requires different segmentation rules.</p><h3>Hybrid Search Is Often Better Than Vector Search Alone</h3><p>Vector search is powerful, but semantic similarity does not solve every retrieval problem.</p><p>Consider a user searching for:</p><pre>Error code PX 1947</pre><p>The exact identifier matters more than semantic meaning.</p><p>An embedding model may not preserve rare codes, product names, version numbers, or exact phrases reliably.</p><p>Keyword search performs well on these cases.</p><p>Hybrid search combines semantic vector retrieval with lexical retrieval such as BM25.</p><p>A hybrid system can capture both:</p><ol><li>Meaning level similarity</li><li>Exact word and identifier matches</li></ol><p>The system then combines or reranks the results.</p><p>For many production search systems, hybrid retrieval performs more consistently than either method alone.</p><h3>Metadata Is Part of Retrieval Quality</h3><p>A vector database should rarely contain only vectors and text.</p><p>Useful metadata might include:</p><pre>{<br>  &quot;document_type&quot;: &quot;engineering_runbook&quot;,<br>  &quot;team&quot;: &quot;payments&quot;,<br>  &quot;language&quot;: &quot;English&quot;,<br>  &quot;created_at&quot;: &quot;2026-04-12&quot;,<br>  &quot;access_group&quot;: &quot;payment_engineering&quot;,<br>  &quot;source&quot;: &quot;internal_wiki&quot;,<br>  &quot;version&quot;: 7<br>}</pre><p>Metadata supports:</p><ol><li>Security filtering</li><li>Time based filtering</li><li>Source prioritization</li><li>Version control</li><li>Language filtering</li><li>Department specific search</li><li>Deletion and document updates</li></ol><p>Without metadata, a semantically relevant result may still be unusable because it is outdated, unauthorized, duplicated, or drawn from the wrong source.</p><h3>Common Failure Modes</h3><p>Vector systems often appear simple during a prototype and become difficult during production deployment.</p><p>Several failures repeatedly appear.</p><h3>The Wrong Embedding Model</h3><p>Different embedding models are optimized for different data and tasks.</p><p>A model that performs well on English prose may perform poorly on source code, medical terminology, multilingual content, or short product identifiers.</p><p>Embedding quality should be measured using real queries from the intended application.</p><h3>Weak Evaluation</h3><p>A system can produce plausible search results while still performing poorly.</p><p>Teams need a labeled evaluation set containing:</p><ol><li>Representative user queries</li><li>Relevant documents for each query</li><li>Difficult negative examples</li><li>Queries requiring exact matching</li><li>Queries requiring semantic understanding</li></ol><p>Metrics such as recall at k, precision at k, mean reciprocal rank, and normalized discounted cumulative gain can help measure retrieval performance.</p><p>Human review remains important because a high similarity score does not guarantee that a passage answers the question.</p><h3>Stale Embeddings</h3><p>When a document changes, its old embedding may remain in the index.</p><p>This can cause the system to retrieve outdated policies or deleted content.</p><p>Production pipelines need reliable synchronization among source documents, chunks, metadata, and embeddings.</p><h3>Missing Access Control</h3><p>Filtering after retrieval can create security and quality problems.</p><p>Authorization rules should be integrated into retrieval so that inaccessible documents never enter the model context.</p><h3>Blind Trust in Similarity Scores</h3><p>Similarity scores are relative signals rather than universal probabilities.</p><p>A score of 0.82 does not automatically mean an 82 percent chance that a result is relevant.</p><p>Score distributions vary across models, data sets, query types, and distance metrics.</p><p>Thresholds must be calibrated using application specific evaluation.</p><h3>Poor Handling of No Result Cases</h3><p>A system should recognize when no retrieved document provides sufficient evidence.</p><p>Returning the least irrelevant result can be worse than returning no result.</p><p>Good systems use relevance thresholds, reranking, answer validation, or explicit uncertainty handling.</p><h3>Vector Databases Are More Than AI Memory</h3><p>Vector databases are frequently described as memory for language models.</p><p>That description is incomplete.</p><p>A vector database does not remember in the human sense. It stores numerical representations and retrieves nearby records.</p><p>The application decides:</p><ol><li>What information gets stored</li><li>How that information is divided</li><li>Which embedding model represents it</li><li>Which metadata is attached</li><li>When records are updated or deleted</li><li>How retrieved results are interpreted</li></ol><p>A poorly designed memory system may repeatedly retrieve irrelevant or outdated information. A well designed one can provide useful long term context across conversations.</p><p>The database is only one component of the memory architecture.</p><h3>Where Vector Databases Are Used</h3><h3>Semantic Document Search</h3><p>Users can find documents based on concepts rather than exact wording.</p><p>This is useful for internal knowledge bases, academic archives, customer support systems, and legal research platforms.</p><h3>Recommendation Systems</h3><p>Products, songs, videos, articles, and users can be represented as vectors.</p><p>Nearby vectors can indicate similar items or preferences.</p><h3>Image and Multimodal Search</h3><p>Images and text can sometimes be embedded into compatible spaces.</p><p>A user can search an image collection with a text query such as:</p><blockquote><em>“A red sports car driving through snow.”</em></blockquote><p>The system retrieves images whose vectors are close to the text vector.</p><h3>Fraud and Anomaly Detection</h3><p>Transactions or behavioral patterns can be embedded and compared with known examples.</p><p>A new event far from normal clusters may deserve additional investigation.</p><h3>Source Code Search</h3><p>Code embeddings allow developers to search repositories using natural language.</p><p>A query such as:</p><blockquote><em>“Where is payment retry logic implemented?”</em></blockquote><p>can retrieve relevant functions even when those exact words do not appear.</p><h3>Entity Resolution</h3><p>Embeddings can help determine whether differently written records refer to similar organizations, products, addresses, or people.</p><p>Structured rules and human verification are still necessary for high stakes cases.</p><h3>When You Should Not Use a Vector Database</h3><p>Vector search is unnecessary when the problem is primarily exact and structured.</p><p>A traditional database may be better for:</p><ol><li>Looking up a user by identification number</li><li>Filtering orders by date and status</li><li>Calculating financial totals</li><li>Enforcing transactional consistency</li><li>Joining normalized relational tables</li><li>Retrieving an exact record by key</li></ol><p>Many applications need both systems.</p><p>A relational database can store authoritative business records. A vector index can support semantic discovery across descriptions, documents, and unstructured content.</p><p>The two technologies solve different retrieval problems.</p><h3>How to Design a Strong Vector Search System</h3><p>A practical implementation process can follow these stages.</p><h3>1. Define the Retrieval Task</h3><p>Determine exactly what the system needs to retrieve.</p><p>Searching support articles requires different behavior from finding similar images or matching source code.</p><h3>2. Collect Real Queries</h3><p>Use actual or realistically simulated user questions.</p><p>Synthetic examples alone often fail to represent ambiguous wording, misspellings, rare identifiers, and incomplete questions.</p><h3>3. Build a Labeled Evaluation Set</h3><p>For each query, identify which documents should be considered relevant.</p><p>Include difficult queries where keyword search and vector search behave differently.</p><h3>4. Test Multiple Embedding Models</h3><p>Compare models on the actual evaluation set.</p><p>Avoid selecting a model only because it performs well on a broad public benchmark.</p><h3>5. Experiment With Chunking</h3><p>Test multiple chunking strategies and measure their effect on retrieval quality.</p><h3>6. Choose an Index Configuration</h3><p>Balance latency, memory, cost, and recall.</p><p>Exact search may be reasonable for a small data set. Approximate search becomes more valuable as the collection grows.</p><h3>7. Add Hybrid Retrieval</h3><p>Use lexical search when exact terms, names, codes, or numbers matter.</p><h3>8. Add Reranking</h3><p>Retrieve a broad candidate set, then use a more precise model to reorder it.</p><h3>9. Evaluate the Full Pipeline</h3><p>Measure the final answers, not only the vector similarity.</p><p>A strong index can still produce weak answers if chunking, prompting, reranking, or source quality is poor.</p><h3>10. Monitor Production Behavior</h3><p>Track failed searches, low confidence queries, outdated results, latency, cost, and user feedback.</p><p>Retrieval quality changes as documents and user behavior change.</p><h3>The Real Quality Equation</h3><p>The performance of a vector application depends on the entire pipeline.</p><p>A useful mental model is:</p><pre>Retrieval quality<br>=<br>source quality<br>×<br>chunk quality<br>×<br>embedding quality<br>×<br>index recall<br>×<br>filter accuracy<br>×<br>reranking quality</pre><p>This is a conceptual model rather than a literal mathematical law.</p><p>Its purpose is to show that improving one component cannot fully compensate for failures elsewhere.</p><p>A powerful vector database cannot repair badly divided documents.</p><p>A strong embedding model cannot retrieve information that was never indexed.</p><p>A precise reranker cannot recover a relevant document that the initial search failed to retrieve.</p><p>The system must be designed as a connected retrieval pipeline.</p><h3>The Bigger Idea</h3><p>Embeddings create a numerical interface between human meaning and computation.</p><p>They allow software to compare concepts that use different words, connect related objects across different data types, and retrieve information from collections too large for manual organization.</p><p>Vector databases make those comparisons practical at scale.</p><p>They transform millions of high dimensional representations into a searchable information system.</p><p>The basic pattern is simple:</p><pre>Represent information as vectors.<br>Store the vectors with their source data.<br>Embed the user query.<br>Retrieve nearby vectors.<br>Validate and use the results.</pre><p>The difficult work lies in everything surrounding that pattern: data quality, chunking, evaluation, indexing, metadata, security, reranking, and failure handling.</p><p>Vector databases are therefore neither a magical replacement for traditional databases nor a temporary feature attached to language models.</p><p>They are specialized retrieval infrastructure for applications that need to search, compare, and organize information by meaning.</p><p>As software becomes capable of processing larger collections of text, images, audio, code, and behavior, that capability will become increasingly important.</p><p>The future of search will still involve words, filters, and structured queries.</p><p>It will also involve geometry.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c69a5950ca7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Reduce Token Usage in Vibe Coding Without Making Agents Dumber]]></title>
            <link>https://randomresearchai.medium.com/how-to-reduce-token-usage-in-vibe-coding-without-making-agents-dumber-3ac840d4ef8d?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ac840d4ef8d</guid>
            <category><![CDATA[token]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[usage]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 23:34:39 GMT</pubDate>
            <atom:updated>2026-06-30T23:34:39.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*A-vFb-zKSzZ7M09v" /><figcaption>LinkedIn</figcaption></figure><p>Vibe coding has a hidden cost. It feels fast because you can throw a broad instruction at an agent and watch it move through a codebase, but behind that speed is a massive amount of repeated context. The agent rereads the same files, rediscovers the same architecture, forgets decisions from twenty minutes ago, and burns tokens explaining code it already understood. Most teams treat this as normal. It is not normal. It is a systems design problem.</p><p>The future of agentic coding will not be won only by better models. It will be won by better memory, better context compression, and better ways of representing a codebase. The best coding agent is not the one with the largest context window. It is the one that knows what to ignore.</p><h3>The token problem in vibe coding</h3><p>Most token waste comes from four patterns.</p><p>First, agents repeatedly reload global context. A developer asks for a bug fix, but the agent scans half the repo because it does not know which files matter. The model spends thousands of tokens rebuilding a mental map that should already exist.</p><p>Second, agents carry stale conversation history. Every message from earlier stays in the working context, even after the important decision has already been made. The useful information is small, but it is buried inside a large transcript.</p><p>Third, agents receive bloated prompts. Many prompts include vague instructions like “make this production ready” or “understand the whole codebase.” Those prompts force the agent to over search, over explain, and over edit because the scope is not bounded.</p><p>Fourth, agents lack durable memory. They do not remember project conventions, architectural decisions, naming patterns, testing strategy, or previous failed attempts unless the user restates them. This creates the worst kind of token waste: repeated thinking.</p><p>Reducing token usage does not mean starving the model. It means feeding it cleaner context.</p><h3>The core principle</h3><p>The goal is not smaller prompts. The goal is higher context density.</p><p>A good context system should preserve the information that changes the agent’s behavior and discard everything else. File paths matter. Interfaces matter. Invariants matter. Recent diffs matter. Known bugs matter. Old explanations usually do not.</p><p>A high density prompt might be only 800 tokens but contain exactly the files, constraints, and decisions needed to solve the task. A low density prompt might be 20,000 tokens and still leave the agent confused.</p><p>This is why token reduction should be treated like memory engineering, not prompt trimming.</p><h3>Caveman context</h3><p>Caveman is the simplest layer. It is the brutal, obvious, low intelligence version of memory that works because it removes ambiguity.</p><p>Every repo should have a small set of plain language files that tell agents how to behave. These files should not be essays. They should be operational contracts.</p><p>A good Caveman memory file says:</p><ol><li>What the app does.</li><li>What stack it uses.</li><li>Where the important folders are.</li><li>What commands run tests, linting, type checks, and builds.</li><li>What must never be changed without approval.</li><li>What conventions the codebase follows.</li><li>What common mistakes previous agents made.</li></ol><p>This sounds basic, but that is the point. Agents waste tokens when they must infer simple things. Caveman memory makes the obvious explicit.</p><p>For example, instead of forcing an agent to inspect package files, directory names, and old commits to understand the stack, the repo can provide a short truth source:</p><p>Frontend uses Next.js with TypeScript. Backend uses FastAPI. Database is Postgres. Auth is Clerk. Do not replace the auth layer. Do not introduce a second state management library. Use existing components before creating new ones.</p><p>That paragraph can save thousands of tokens across a single session because the agent stops rediscovering project reality.</p><p>Caveman memory should be boring, stable, and aggressively practical.</p><h3>Graphify the codebase</h3><p>Caveman gives the agent rules. Graphify gives the agent structure.</p><p>Most agents understand a repo as a pile of files. That is inefficient. A codebase is not a pile. It is a graph.</p><p>Components import utilities. API routes call services. Services touch database models. UI screens depend on state hooks. Tests cover specific modules. Bugs usually travel along these edges.</p><p>Graphify means converting the repo into a navigable map of nodes and relationships.</p><p>The nodes can be files, functions, components, routes, database tables, environment variables, or product features. The edges can represent imports, calls, ownership, data flow, test coverage, or runtime dependency.</p><p>Once the repo is graphified, the agent no longer needs to read everything. It can traverse the relevant subgraph.</p><p>If the user asks, “Fix profile image upload,” the agent should not scan the entire app. It should jump to the nodes connected to profile settings, upload components, S3 logic, image validation, user schema, and relevant tests. That is a context cut. The agent receives the neighborhood of the bug, not the entire city.</p><p>Graph based context also makes memory more durable. When the agent learns that a bug in one file was caused by a schema mismatch in another, that relationship can be stored as an edge. The next agent does not need to rediscover it.</p><p>Graphify turns context from a transcript into infrastructure.</p><h3>Use summaries as memory, not decoration</h3><p>Summaries are usually treated as a convenience feature. They should be treated as a compression primitive.</p><p>A useful summary is not “we worked on the dashboard.” That is weak memory. A useful summary captures the decision, the reason, and the consequence.</p><p>Bad memory:</p><p>Worked on auth flow.</p><p>Good memory:</p><p>Auth uses Clerk middleware. Do not add custom JWT verification in API routes because middleware already guarantees user identity. Server handlers should read the user id from the existing auth helper.</p><p>The second version changes future behavior. That is the test for memory quality.</p><p>Every coding session should end with a compact memory update:</p><ol><li>What changed.</li><li>Why it changed.</li><li>What files were touched.</li><li>What commands passed</li><li>What remains broken.</li><li>What future agents should avoid.</li></ol><p>This creates a rolling project memory that gets stronger over time instead of a chat history that gets longer over time.</p><p>The key is that memory should be rewritten, not appended forever. A memory file that only grows becomes another token sink. The best system continuously compresses old work into stable facts.</p><h3>Separate working memory from long term memory</h3><p>A coding agent needs at least three memory layers.</p><p>Working memory is the current task. It includes the user request, relevant files, current errors, and immediate plan. It should be small and temporary.</p><p>Project memory is stable knowledge about the codebase. It includes architecture, conventions, commands, dependencies, and product constraints. It should persist across sessions.</p><p>Experience memory is what the agent learned from previous attempts. It includes bugs fixed, failed approaches, hidden gotchas, and successful patterns. It should be searchable and linked to files or features.</p><p>Most vibe coding sessions mix all three together inside the chat. That is why context gets messy. The agent cannot tell whether a sentence is a temporary idea, a permanent rule, or an outdated thought.</p><p>Separating memory layers reduces token usage because each layer has a clear job. The agent only loads the memory needed for the current decision.</p><h3>Make agents diff aware</h3><p>Agents burn tokens when they reason from the entire current codebase instead of the actual change.</p><p>A diff aware workflow gives the model the smallest useful unit of context: what changed since the last known good state.</p><p>Before asking for a fix, provide the error, the changed files, and the relevant diff. This is much cheaper than asking the model to inspect the whole project.</p><p>The best agent loop looks like this:</p><ol><li>Load task.</li><li>Retrieve relevant memory.</li><li>Traverse the graph to find affected files.</li><li>Inspect only the necessary code.</li><li>Make a small patch.</li><li>Run verification.</li><li>Store what changed.</li></ol><p>This loop reduces token use because the agent acts like an engineer with a map, not a tourist with a flashlight.</p><h3>Write prompts that constrain search</h3><p>The easiest way to waste tokens is to give an agent an unbounded mission.</p><p>“Fix the app” is expensive.</p><p>“Fix the profile image upload bug. Start by inspecting the upload component, the API route, and the storage helper. Do not redesign unrelated UI. After the patch, run type check and the relevant upload test” is cheaper and better.</p><p>Good prompts reduce search space. They tell the agent where to start, what not to touch, what output matters, and how success will be verified.</p><p>A strong vibe coding prompt should include:</p><ol><li>The target behavior.</li><li>The current failure.</li><li>The relevant area of the codebase.</li><li>The files or graph nodes likely involved.</li><li>Constraints on what not to change.</li><li>Verification commands.</li><li>Expected final output.</li></ol><p>This does not make the agent less creative. It makes the agent less wasteful.</p><h3>Build a context budget</h3><p>Every agent should operate with a context budget.</p><p>A context budget is a rule for how much information the agent is allowed to load before it must justify why more is needed.</p><p>For example:</p><p>Initial task context should stay under 2,000 tokens.<br>Relevant file snippets should stay under 6,000 tokens.<br>Full file reads require a reason.<br>Whole repo scans are forbidden unless the task is architectural.<br>Old chat history should be summarized before reuse.</p><p>This forces better retrieval. The agent must choose what matters.</p><p>A context budget also makes performance measurable. You can track tokens used per issue, tokens used per passing test, and tokens wasted on repeated reads. Once token usage becomes visible, it becomes optimizable.</p><h3>Improve memory through retrieval, not bigger context windows</h3><p>Large context windows are useful, but they are not a substitute for memory.</p><p>A larger context window lets you carry more information. It does not decide what information deserves attention. Without retrieval and compression, a larger window just allows larger messes.</p><p>Better memory means the agent can answer three questions quickly:</p><ol><li>What do I already know about this codebase?</li><li>What part of the codebase is relevant now?</li><li>What previous decision should constrain tis change?</li></ol><p>Retrieval should be semantic, structural, and temporal.</p><p>Semantic retrieval finds memories similar to the task.<br>Structural retrieval finds files connected in the graph.<br>Temporal retrieval finds recent changes that may have caused the issue.</p><p>The strongest systems combine all three. A bug report should pull related memories, relevant graph nodes, and recent diffs. That gives the agent a focused packet of context instead of a giant transcript.</p><h3>The ideal vibe coding stack</h3><p>A serious token efficient vibe coding stack should have five layers.</p><p>First, a Caveman file for basic project truth. This is the stable instruction layer.</p><p>Second, a graph index of the repo. This is the structural layer.</p><p>Third, a memory store of decisions, bugs, and conventions. This is the durable learning layer.</p><p>Fourth, a retrieval engine that assembles task specific context. This is the compression layer.</p><p>Fifth, an agent loop that patches, verifies, summarizes, and updates memory. This is the execution layer.</p><p>Together, these layers turn vibe coding from a chat based workflow into an operating system for software creation.</p><p>The agent no longer starts from zero. It starts from compressed project intelligence.</p><h3>What this changes</h3><p>Token reduction is not just about cost. It changes the quality of the work.</p><p>When agents use less irrelevant context, they make fewer unrelated edits. When they have better memory, they repeat fewer mistakes. When they understand the graph, they touch the right files faster. When prompts constrain search, the final patch is smaller and easier to review.</p><p>The result is not only cheaper coding. It is more controlled coding.</p><p>That matters because vibe coding has a trust problem. Developers like the speed, but they fear the chaos. They fear silent regressions, random rewrites, and agents that appear confident while misunderstanding the system.</p><p>Better context engineering directly attacks that problem. It gives agents boundaries, memory, and structure.</p><h3>The final rule</h3><p>The best way to reduce token usage is to stop treating context as text and start treating it as state.</p><p>Text is what the agent sees in one moment. State is what the system knows over time.</p><p>Caveman captures stable truths. Graphify captures structure. Memory captures decisions and experience. Retrieval turns all of that into the smallest useful prompt for the current task.</p><p>That is the path forward for vibe coding. Not bigger prompts. Not endless context windows. Not dumping the whole repo into the model.</p><p>The future is smaller context with sharper memory.</p><p>The agents that win will not be the ones that read the most. They will be the ones that remember the right things.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ac840d4ef8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Brain Trick Behind the World’s Best AI Models]]></title>
            <link>https://randomresearchai.medium.com/the-brain-trick-behind-the-worlds-best-ai-models-43cd0f9dfc53?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/43cd0f9dfc53</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mixture-of-experts]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 19:59:33 GMT</pubDate>
            <atom:updated>2026-03-21T20:00:08.261Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Brain Trick Behind the World’s Best AI Models — How Mixture of Experts lets labs build trillion-parameter models they can actually afford to run</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Ql1530R-tWg8-eI.png" /><figcaption>HuggingFace</figcaption></figure><p>There is a dirty secret about the AI models everyone is using right now.</p><p>GPT-5, Gemini 3, Mixtral, Grok — none of them work the way people assume. Most people picture a neural network as a single giant brain that thinks about your every input. Every parameter fires. Every neuron contributes. The whole machine runs.</p><p>That is not what is happening.</p><p>What is actually happening is closer to a hospital emergency room than a single brain. You walk in, a triage nurse figures out what is wrong, and she sends you to exactly the right specialist. The cardiologist does not examine your broken arm. The orthopedist does not read your EKG. Each expert handles what they are good at, and the patient gets better care at lower cost than if every doctor examined every patient for every complaint.</p><p>This is Mixture of Experts. It is the architecture powering most frontier models right now, and once you understand how it works, the recent history of AI makes a lot more sense.</p><h3>First: How a Normal Neural Network Uses Compute</h3><p>To understand why Mixture of Experts is a big deal, you need to know what it is solving.</p><p>A standard transformer-based language model processes text in layers. Each layer has two main components: a self-attention block and a feedforward network (FFN). The attention block lets tokens communicate with each other. The FFN processes each token individually.</p><p>Here is the key thing: in a standard model, every parameter in the model activates for every token. If you are running GPT-3 with 175 billion parameters, and you type a one-word prompt, the model runs all 175 billion parameters to produce a single output token. Then it does it again for the next token. And the next.</p><p>The compute cost is linear with parameter count. Double the parameters, double the compute per token. The math does not negotiate.</p><p>This becomes a serious infrastructure problem at scale. The cost of running a 175 billion parameter model is enormous. The cost of running a 1 trillion parameter model is roughly 6x that, for every single token, on every single query, across millions of users.</p><p>The question researchers started asking around 2017 was: what if you did not run all the parameters every time?</p><h3>The Mixture of Experts Idea</h3><p>The answer was to split the feedforward network inside each transformer layer into multiple smaller networks, called experts, and train a separate small network called a router to decide which expert handles each token.</p><p>For any given input token, the router picks only 1 or 2 experts. Those experts process the token. Everything else sits idle.</p><p>The result: you can have a model with 1 trillion total parameters but only activate 50 to 100 billion of them per token. You pay the compute cost of a 50–100B model. You get the capacity of a 1T model.</p><p>That gap is the whole architecture.</p><p><strong>DIAGRAM 1: Dense Model vs Mixture of Experts</strong></p><pre>DENSE MODEL                          MIXTURE OF EXPERTS<br>─────────────────────────────────    ─────────────────────────────────────────</pre><pre>Input Token                          Input Token<br>     │                                    │<br>     ▼                                    ▼<br>┌─────────────────┐                  ┌──────────┐<br>│                 │                  │  ROUTER  │ ← small learned       matrix  <br>│  ALL parameters │                  └────┬─────┘<br>│  activate for   │                       │ scores each expert<br>│  every token    │              ┌────────┼─────────┐<br>│                 │              ▼        ▼         ▼<br>└────────┬────────┘         ┌────────┐ ┌───────┐ ┌────────┐<br>         │                  │Expert 1│ │Expert2│ │Expert 3│  ...and more<br>         ▼                  │ ACTIVE │ │ idle  │ │ ACTIVE │<br>     Output                 └────┬───┘ └───────┘ └───┬────┘<br>                                 │                    │<br>                            only top-2 experts fire   │<br>                                 └──────────┬─────────┘<br>                                            ▼<br>                                        weighted sum<br>                                            │<br>                                            ▼<br>                                         Output</pre><p><em>In a dense model, the cost of inference scales directly with total parameter count. In a MoE model, only 1–2 experts activate per token regardless of how many experts exist total.</em></p><h3>Where Experts Live Inside the Transformer</h3><p>It helps to know exactly which part of the transformer gets replaced. The answer is: just the feedforward network inside each layer.</p><p>A transformer layer has this structure:</p><pre>Input Tokens<br>     │<br>     ▼<br>┌──────────────────────────┐<br>│   Multi-Head Attention   │  ← stays DENSE (all params active)<br>└──────────────┬───────────┘<br>               │<br>               ▼<br>┌──────────────────────────┐<br>│    LayerNorm + Residual  │<br>└──────────────┬───────────┘<br>               │<br>               ▼<br>┌──────────────────────────┐<br>│   Feed-Forward Network   │  ← THIS gets replaced by MoE<br>└──────────────┬───────────┘<br>               │<br>               ▼<br>┌──────────────────────────┐<br>│    LayerNorm + Residual  │<br>└──────────────┬───────────┘<br>               │<br>               ▼<br>          Next Layer</pre><p>In a MoE model, that FFN box becomes:</p><pre>│<br>               ▼<br>┌─────────────────────────────────────────────────────┐<br>│                     ROUTER                          │<br>│              softmax(W_r × token_embedding)         │<br>└──┬──────────┬──────────┬──────────┬─────────────┬──┘<br>   │          │          │          │             │<br>   ▼          ▼          ▼          ▼             ▼<br>┌──────┐  ┌──────┐  ┌──────┐  ┌──────┐  ... ┌──────┐<br>│ FFN  │  │ FFN  │  │ FFN  │  │ FFN  │      │ FFN  │<br>│  E1  │  │  E2  │  │  E3  │  │  E4  │      │  En  │<br>│      │  │ACTIVE│  │      │  │ACTIVE│      │      │<br>│ idle │  │      │  │ idle │  │      │      │ idle │<br>└──────┘  └──┬───┘  └──────┘  └──┬───┘      └──────┘<br>             │                    │<br>             └─────────┬──────────┘<br>                       │<br>                  weighted sum<br>                  (score × output)<br>                       │<br>                       ▼<br>               Continue to next layer</pre><p>The attention layers are unchanged and fully dense. Every token still attends to every other token. Only the FFN stage goes sparse.</p><h3>The Router: How It Actually Decides</h3><p>The router is a learned weight matrix, nothing more. Call it W_r. It is small, maybe a few megabytes, compared to the billions of parameters in the expert FFNs.</p><p>For each input token, the router does this:</p><pre>Step 1: Compute scores for every expert<br>        scores = W_r × token_embedding<br>        (one score per expert)</pre><pre>Step 2: Convert to probabilities<br>        probabilities = softmax(scores)</pre><pre>Step 3: Pick the top-K experts (almost always K = 2)<br>        selected = argtop_k(probabilities, k=2)</pre><pre>Step 4: Compute weighted output<br>        output = sum(<br>            probabilities[i] × Expert_i(token)<br>            for i in selected<br>        )</pre><p>The weights used in Step 4 mean the expert with the higher routing score contributes more to the final output. If Expert 2 got a score of 0.71 and Expert 5 got 0.29, the output is 71% Expert 2’s answer and 29% Expert 5’s answer.</p><p>Nobody designs this by hand. The router trains through backpropagation along with everything else. The model learns to route. Over training, real specialization tends to emerge.</p><p><strong>DIAGRAM 2: Router Scoring Mechanics for One Token</strong></p><pre>Token embedding (vector of numbers, e.g. 4096 dimensions)<br>         │<br>         │   W_r (router weight matrix, learned)<br>         │   shape: [num_experts × embedding_dim]<br>         ▼<br>   Raw scores (one per expert)<br>   ┌────────────────────────────────────────────────┐<br>   │ E1: -0.3  E2: 1.8  E3: 0.2  E4: -1.1  E5: 0.9│<br>   └────────────────────────────────────────────────┘<br>         │<br>         │   softmax (converts to probabilities, sum to 1)<br>         ▼<br>   Routing probabilities<br>   ┌────────────────────────────────────────────────┐<br>   │ E1: 0.05  E2: 0.61  E3: 0.12  E4: 0.01  E5:0.21│<br>   └────────────────────────────────────────────────┘<br>         │<br>         │   argtop_2 (pick highest 2)<br>         ▼<br>   Selected: E2 (0.61), E5 (0.21)<br>   Dropped:  E1, E3, E4 get zero gradient for this token</pre><pre>         │<br>         ▼<br>   Output = (0.61 × Expert_2(token)) + (0.21 × Expert_5(token))<br>          ────────────────────────────────────────────────────<br>          Note: scores are renormalized before weighting in practice</pre><h3>The Training Problem Nobody Talks About Enough: Expert Collapse</h3><p>Here is where most explanations stop, and where the actual difficulty begins.</p><p>If you build a MoE model and just train it the normal way, something predictable and catastrophic happens: all tokens route to the same 1–2 experts. The other experts never receive meaningful gradients. They never learn anything useful. You end up with a model that has 95% of its theoretical capacity sitting completely unused, and 2 experts doing all the work.</p><p>This is called expert collapse, and it is the core training challenge in MoE research.</p><p>The reason it happens is intuitive. Early in training, some experts randomly produce slightly better outputs for slightly more token types. The router, which is also learning, starts preferring those experts. Those experts get more training signal. They get better. The router prefers them even more. The other experts starve. You have created a feedback loop.</p><p><strong>DIAGRAM 3: Expert Collapse vs Balanced Routing</strong></p><pre>WITHOUT LOAD BALANCING LOSS<br>─────────────────────────────────────────────────────<br>Token traffic per expert (100 tokens total):</pre><pre>Expert 1  ████████████████████████████████████████ 78 tokens<br>Expert 2  ████ 12 tokens<br>Expert 3  ██ 5 tokens<br>Expert 4  █ 3 tokens<br>Expert 5  ░ 1 token<br>Expert 6  ░ 1 token<br>Expert 7  ░ 0 tokens  ← learns nothing<br>Expert 8  ░ 0 tokens  ← learns nothing</pre><pre>Result: 75% of model capacity wasted<br></pre><pre>WITH LOAD BALANCING LOSS (auxiliary loss term added)<br>─────────────────────────────────────────────────────<br>Token traffic per expert (100 tokens total):</pre><pre>Expert 1  █████████████ 14 tokens<br>Expert 2  ████████████ 13 tokens<br>Expert 3  ████████████ 13 tokens<br>Expert 4  █████████████ 13 tokens<br>Expert 5  ████████████ 12 tokens<br>Expert 6  ████████████ 12 tokens<br>Expert 7  ████████████ 12 tokens<br>Expert 8  ███████████ 11 tokens</pre><pre>Result: Full model capacity utilized</pre><h3>The Fix: Auxiliary Load Balancing Loss</h3><p>The fix, introduced in the Shazeer et al. 2017 paper “Outrageously Large Neural Networks” and refined in many papers since, is to add a penalty term to the training loss that measures routing imbalance and penalizes it.</p><p>The total loss during training becomes:</p><pre>Total Loss = Language Modeling Loss + α × Load Balancing Loss</pre><pre>where:<br>   Language Modeling Loss = standard next-token prediction loss<br>   Load Balancing Loss    = measure of how unevenly tokens distribute<br>                            across experts<br>   α                      = small coefficient (e.g. 0.01 or 0.001)<br>                            balances the two objectives</pre><p>The load balancing loss is typically computed as the dot product of two vectors: the fraction of tokens routed to each expert, and the average routing probability assigned to each expert. When routing is uniform, this term is small. When it is concentrated, the term grows and the optimizer pushes back.</p><p>There is a tension here that the researchers had to navigate carefully. If α is too large, the model learns to route uniformly regardless of what the task needs. Every expert gets equal traffic, but they stop specializing. If α is too small, collapse still happens. Getting the balance right is part of what separates a well-trained MoE from a broken one.</p><h3>What Experts Actually Specialize In</h3><p>This is a genuinely interesting empirical question, and the answer is more complicated than people expect.</p><p>Early intuitions suggested experts might cleanly specialize: one expert handles code, another handles math, another handles French, another handles named entities. Some papers found evidence of this. Artetxe et al. (2021) in the paper on multilingual MoE found that certain experts did strongly prefer specific languages. Other experiments found experts clustering around syntactic structure or token position.</p><p>But in practice, the specialization is messier than a taxonomy. Most tokens get routed to a fairly wide set of experts across the full training distribution. An expert that handles code tokens heavily might also handle some punctuation-heavy English and some structured JSON. The clusters are real but fuzzy.</p><p>What is not in question: the routing is not random. Tokens of similar type do tend to go to similar experts. The model is not just doing load balancing, it is doing load balancing while also routing semantically similar inputs together. Both objectives run simultaneously.</p><p><strong>DIAGRAM 4: Expert Specialization (Approximate, Illustrative)</strong></p><pre>What kinds of tokens tend to route to each expert?<br>(Illustrative based on published findings, not exact)</pre><pre>Expert 1  ████ Code tokens (Python, JS)         ██ Structured data (JSON, XML)<br>Expert 2  ██████████ Mathematical expressions   █ Numbers<br>Expert 3  ████████ French / Spanish tokens      ██ Other Romance languages<br>Expert 4  ███ English prose (factual)            ████████ Named entities<br>Expert 5  █████ Question words / logical ops    ████ Reasoning patterns<br>Expert 6  ██████ English prose (narrative)      ███ Dialogue turns<br>Expert 7  ████ Markup / formatting tokens       ███ Whitespace-heavy inputs<br>Expert 8  Mix of above (generalist)</pre><pre>Note: Real expert boundaries are fuzzy. A token can activate experts<br>      with very different apparent specializations. This is the current<br>      limit of our interpretability tools, not proof that specialization<br>      is absent.</pre><h3>Real Numbers: Mixtral 8x7B</h3><p>The most studied open MoE model is Mixtral 8x7B from Mistral AI. The name is somewhat misleading. It is not 56 billion parameters (8 times 7). Experts share parameters in the non-FFN parts of the architecture (attention weights, embeddings), so total parameter count lands at about 46.7 billion. Active parameters per token: about 12.9 billion.</p><p>Here is how that compares:</p><pre>Model                   Total Params    Active Params/Token    Architecture<br>─────────────────────────────────────────────────────────────────────────<br>Llama 2 7B              7B              7B                     Dense<br>Llama 2 13B             13B             13B                    Dense<br>Llama 2 70B             70B             70B                    Dense<br>Mixtral 8x7B            46.7B           12.9B                  MoE (8 experts, top-2)<br>GPT-4 (estimated)       ~1.8T           ~220B                  MoE (rumored ~16 experts)<br>Gemini 1.5 Pro          unknown         ~50B (estimated)       MoE (confirmed)</pre><p>Mixtral 8x7B matches or beats Llama 2 70B on most standard benchmarks. It runs inference at roughly 18% of the compute cost per token. That is the concrete value proposition of the architecture.</p><h3>The Memory Problem (The Catch People Miss)</h3><p>MoE saves compute at inference time. It does not save memory.</p><p>You still have to load all the expert weights into GPU memory, including the experts that stay idle for any given token. Mixtral 8x7B takes about 90 GB in half precision (bfloat16). You need multiple high-end GPUs just to hold the model, regardless of the sparsity.</p><p>This creates a specific deployment shape that most articles ignore:</p><pre>SINGLE USER, LOW THROUGHPUT<br>─────────────────────────────<br>Memory cost:    HIGH (all 46.7B params loaded)<br>Compute cost:   LOW (only 12.9B active per token)<br>Idle experts:   Wasting RAM, producing nothing<br>Result:         You pay for the memory; you barely use the compute savings</pre><pre>HIGH THROUGHPUT (many concurrent users)<br>─────────────────────────────────────────<br>Memory cost:    HIGH (same 46.7B params loaded once)<br>Compute cost:   LOW (12.9B per token, but amortized across many users)<br>Expert usage:   Different requests route to different experts simultaneously<br>Result:         Memory cost amortized; compute savings fully realized</pre><p>MoE is a good deal at scale. It is a worse deal for a single-user local deployment. This is why Mixtral running locally on a MacBook feels surprisingly manageable for its benchmark scores, but requires enough RAM that most consumer hardware cannot fit it.</p><p><strong>DIAGRAM 5: Memory vs Compute Tradeoff at Scale</strong></p><pre>Memory Required<br>                     (stays constant regardless of batch size)<br>                          │<br>    Dense 70B  ───────────┼──────────────────────────────────────────<br>    ~140 GB               │<br>                          │<br>    MoE 8x7B  ────────────┼──────────────────────────────────────────<br>    ~90 GB                │<br>                          │<br>                          │<br>                          └─────────────────────────────────────────▶<br>                              1 user    10 users   100 users  1000 users<br></pre><pre>                     Compute Cost Per Token<br>                     (MoE advantage grows with throughput)<br>                          │<br>    Dense 70B  ──────────────────────────────────────────────────────<br>    (flat, high)          │<br>                          │<br>                          │<br>    MoE 8x7B  ────────────────────────────────────────────────────────<br>    (flat, low)           │<br>                          │<br>                          └─────────────────────────────────────────▶<br>                              1 user    10 users   100 users  1000 users</pre><pre>The compute advantage is the same regardless of batch size.<br>The memory cost amortizes better with more users sharing the loaded weights.</pre><h3>How MoE Changes Training</h3><p>Training a MoE model is harder than training a dense model of equivalent active parameters. Several things go wrong that do not go wrong in dense training.</p><p><strong>Routing instability early in training.</strong> At initialization, the router is random. Some experts get lucky early, start receiving more traffic, get more gradient signal, improve faster, get more traffic. The feedback loop toward collapse starts immediately. This is why the auxiliary loss and careful initialization matter.</p><p><strong>Expert capacity constraints.</strong> In distributed training across many GPUs, experts often live on different devices. Each token needs to be sent to its assigned experts across the network. If too many tokens route to the same expert in a single batch, you hit a capacity constraint: that expert can only process so many tokens before it becomes a bottleneck. Tokens that exceed the capacity limit are either dropped or routed elsewhere. Both options hurt.</p><p>The capacity factor is a hyperparameter that sets how much buffer each expert gets. Higher capacity factor means fewer dropped tokens but more wasted memory. Lower means tighter memory but more routing waste. This does not exist in dense models at all.</p><pre>CAPACITY FACTOR TRADEOFF</pre><pre>Capacity Factor = (tokens per batch / num_experts) × capacity_factor_multiplier</pre><pre>Low capacity factor (e.g. 1.0):<br>  ┌─────────────────────────────────────────────┐<br>  │ Expert queue: ████████████ (some overflow)   │<br>  │ Memory use:   LOW                            │<br>  │ Dropped tokens: YES → training signal lost   │<br>  └─────────────────────────────────────────────┘</pre><pre>High capacity factor (e.g. 2.0):<br>  ┌─────────────────────────────────────────────┐<br>  │ Expert queue: ████ (plenty of room)          │<br>  │ Memory use:   HIGH                           │<br>  │ Dropped tokens: RARE → clean gradients       │<br>  └─────────────────────────────────────────────┘</pre><p><strong>Communication overhead.</strong> In a distributed MoE setup, each token gets routed to an expert that may live on a different GPU or even a different machine. This “all-to-all” communication pattern is expensive. At scale, it can eat a significant fraction of the training throughput. Managing it efficiently is a large part of what the engineering work in papers like Switch Transformer (Google, 2022) and DeepSpeed-MoE (Microsoft, 2022) is actually about.</p><h3>Switch Transformer: The Simplification That Made MoE Practical</h3><p>The original MoE paper (Shazeer 2017) used top-2 routing and a complex noisy gating mechanism. The Switch Transformer paper from Google (Fedus et al., 2021) made a counterintuitive finding: top-1 routing (route to only one expert per token) works just as well or better for training stability, and it halves the communication overhead.</p><pre>TOP-2 ROUTING (Shazeer 2017)<br>   Each token → 2 experts<br>   Output = weighted sum of 2 expert outputs<br>   Communication: each token crosses 2 network boundaries<br>   Capacity: each expert receives ~2/N of all tokens<br>   Balance loss: needed, complex</pre><pre>TOP-1 ROUTING (Switch Transformer 2021)<br>   Each token → 1 expert<br>   Output = that expert&#39;s output directly<br>   Communication: each token crosses 1 network boundary<br>   Capacity: each expert receives ~1/N of all tokens<br>   Balance loss: simpler to compute<br>   Result: faster training, similar or better quality</pre><p>The Switch Transformer scaled to 1.6 trillion parameters, training on Google TPU infrastructure. It achieved a 7x speedup in pre-training compared to a dense T5 model at equivalent compute budget.</p><p>This paper is what made MoE go from “interesting research direction” to “production viable.”</p><h3>The Open Questions</h3><p>The architecture is in production at every major lab. That does not mean researchers have figured out everything about it.</p><p><strong>How many experts is right?</strong> Mixtral uses 8. GPT-4 rumors suggest 16. Some papers experiment with 64, 128, or more. More experts give more total capacity but increase communication overhead and make load balancing harder. The right number likely depends on the task distribution and hardware topology.</p><p><strong>Should K be fixed?</strong> In standard MoE, K is fixed (usually 2). Some newer work explores dynamic K, where the router learns to activate more or fewer experts depending on the difficulty of the token. Simple tokens might need only 1 expert. Complex reasoning tokens might need 4. This is not yet standard.</p><p><strong>Is expert specialization actually happening at the right granularity?</strong> Current interpretability tools are limited. We can measure routing statistics but we cannot fully characterize what each expert has learned. Whether the specialization is as meaningful as people assume, or whether experts are just learning arbitrary but consistent routing patterns, is genuinely open.</p><p><strong>How do you handle expert load at inference time, not just training?</strong> During training you have full control over batches. During inference, user requests arrive randomly and route unpredictably. If 1000 users simultaneously ask questions that all route to Expert 3, you hit the same capacity constraint problem. Production serving systems for MoE models handle this with request batching, replica placement, and expert replication across GPUs, none of which is simple.</p><p><strong>DIAGRAM 6: Full MoE Transformer Block (Complete Picture)</strong></p><pre>Input sequence: [&quot;The&quot;, &quot;quick&quot;, &quot;brown&quot;, &quot;fox&quot;]<br>                      │<br>                      ▼<br>         ┌────────────────────────────┐<br>         │   Token + Position         │<br>         │   Embeddings               │<br>         └────────────┬───────────────┘<br>                      │<br>                      ▼<br>    ┌─────────────────────────────────────────────┐<br>    │              LAYER 1 of N                   │<br>    │                                             │<br>    │  ┌───────────────────────────────────────┐  │<br>    │  │  Multi-Head Self-Attention (DENSE)    │  │<br>    │  │  All tokens attend to all tokens      │  │<br>    │  │  All attention params active          │  │<br>    │  └──────────────────┬────────────────────┘  │<br>    │                     │                       │<br>    │              Add &amp; LayerNorm                │<br>    │                     │                       │<br>    │  ┌──────────────────▼────────────────────┐  │<br>    │  │           ROUTER                       │  │<br>    │  │  W_r × token_emb → softmax → top-2     │  │<br>    │  └──┬──────────┬──────────┬──────────┬───┘  │<br>    │     │          │          │          │       │<br>    │   ┌─▼─┐      ┌─▼─┐      ┌─▼─┐     ┌─▼─┐   │<br>    │   │FFN│      │FFN│      │FFN│     │FFN│   │<br>    │   │ 1 │      │ 2 │      │ 3 │     │ 4 │   │  ...more experts<br>    │   │ACT│      │idl│      │ACT│     │idl│   │<br>    │   └─┬─┘      └───┘      └─┬─┘     └───┘   │<br>    │     │                     │               │<br>    │     └─────────┬───────────┘               │<br>    │               │  weighted sum             │<br>    │               │                           │<br>    │        Add &amp; LayerNorm                    │<br>    │               │                           │<br>    └───────────────┼───────────────────────────┘<br>                    │<br>               (repeat for N layers)<br>                    │<br>                    ▼<br>         ┌──────────────────┐<br>         │  Output Head     │  → next token probabilities<br>         └──────────────────┘</pre><h3>Why This Architecture Won</h3><p>MoE did not win because it is elegant. It won because it solved a real problem that dense scaling could not solve: you cannot keep doubling parameters and proportionally doubling inference cost forever. The economics break.</p><p>MoE decouples two things that were previously coupled: total model capacity and per-token compute cost. Once you decouple them, you can scale capacity without scaling cost at the same rate. That is a fundamentally different position to be in when you are trying to build the largest, most capable model you can afford to serve to millions of users.</p><p>The tradeoffs are real. Memory cost stays high. Training is harder. Serving infrastructure is more complex. But the labs decided these were engineering problems worth solving, because the alternative (dense scaling) was hitting a wall.</p><p>That decision is why GPT-4 is likely a MoE model, why Gemini 1.5 is a confirmed MoE model, and why the next generation of models from every lab will almost certainly be MoE too.</p><p>You are not using a single brain. You are using a team of specialists, managed by a router that has read every token you have ever sent.</p><h3>The TL;DR (for people who scrolled here first)</h3><pre>WHAT IS MOE?<br>   A neural network architecture that replaces the dense feedforward<br>   network in each transformer layer with multiple smaller &quot;expert&quot;<br>   networks and a router that selects 1-2 per token.</pre><pre>WHY DOES IT MATTER?<br>   You can have 1 trillion total parameters but only activate<br>   50 billion per token. Inference cost of a 50B model.<br>   Quality of a 1T model.</pre><pre>WHAT IS THE CATCH?<br>   Memory footprint stays high (all experts must be loaded).<br>   Training is harder (expert collapse, load balancing, communication).<br>   Serving is more complex at scale.</pre><pre>WHO IS USING IT?<br>   GPT-4 (almost certainly), Gemini 1.5 (confirmed),<br>   Mixtral 8x7B (open source, confirmed), Grok 2 (confirmed).</pre><pre>KEY PAPERS TO READ:<br>   Shazeer et al. 2017  — &quot;Outrageously Large Neural Networks&quot;<br>   Fedus et al. 2021    — &quot;Switch Transformers&quot;<br>   Jiang et al. 2024    — &quot;Mixtral of Experts&quot;</pre><p><em>If something in this was unclear or wrong, I want to know. This stuff moves fast and I would rather be corrected than wrong.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43cd0f9dfc53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Intro to Calculus-Based Quant Trading Models in Python]]></title>
            <link>https://randomresearchai.medium.com/an-intro-to-calculus-based-quant-trading-models-in-python-b591352a6868?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/b591352a6868</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[quantconnect]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 02:14:43 GMT</pubDate>
            <atom:updated>2026-01-13T02:14:43.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FwCeTd2IK_QA_7j5.png" /></figure><p>Most people’s first exposure to quantitative trading is overwhelming.</p><p>They see complex indicators, machine learning models, and dense math and assume that profitable strategies must be complicated.</p><p>That is not true. Some of the cleanest and most instructive quant models come directly from basic calculus and a few foundational ideas in finance.</p><p>In this post, I will walk through how to think about and build a simple, legitimate quant model in Python on <strong>QuantConnect</strong>, without hiding behind technical blagaboo.</p><h3>Thinking About Price the Right Way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RgFU_cUw_Yn--J2M.jpg" /><figcaption>Credits — EDUCBA</figcaption></figure><p>At its core, a financial market is just a function of time.</p><p>Price moves, pauses, accelerates, and decelerates. If you are comfortable with calculus, this framing should feel natural.</p><p>Instead of treating price as a bizarre signal, treat it as a function</p><pre>P(t) # Just a function</pre><p>The moment you do this, familiar ideas come back into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wCwW-xKQyIJ1EJwq.jpg" /><figcaption>Credits — M. Rodriguez</figcaption></figure><p>The first derivative tells you how fast something is changing. The second derivative tells you whether that change is speeding up or slowing down.</p><p>In finance, we do not usually work with raw price differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JY22Byuxd9raiTHF.png" /><figcaption>Credits — G. Gunderson</figcaption></figure><p>We use <strong>log returns</strong>, which behave nicely over time and across price scales. A log return is essentially a discrete approximation of the first derivative of price.</p><p>When returns increase or decrease from one step to the next, you are observing a second derivative effect.</p><p>That change in returns is what traders casually call “momentum picking up” or “momentum dying out.”</p><p>Turns out that your high school calculus class was not a waste of time!</p><h3>From Derivatives to a Trading Signal</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*R2y47ZeJHICmChIY" /><figcaption>Credits — Stochastip</figcaption></figure><p>Once you start thinking in derivatives, a simple idea emerges. If returns are increasing, price acceleration is positive. If returns are decreasing, acceleration is negative.</p><p>Markets often exhibit short bursts where acceleration persists long enough to be tradable, especially in liquid instruments like major equities or index ETFs.</p><p>Of course, raw acceleration is noisy. Markets are full of randomness, and treating every tiny change as meaningful will get you chopped up by transaction costs.</p><p>This is where basic statistics come into play.</p><p>By normalizing acceleration with recent volatility, you turn it into a standardized signal.</p><p>In plain terms, you are asking: “Is this change in momentum large relative to what is normal for this asset?”</p><p>That single question already incorporates risk awareness into the model. You are no longer reacting to noise; you are reacting to statistically meaningful movement. Now, let&#39;s get into the code.</p><h3>Building a Simple QuantConnect Model With Calculus, Then Implementing It Cleanly in Python</h3><p>Earlier, we built the signal using three steps: log returns (a discrete first derivative), acceleration (a discrete second derivative), and then a normalization step so the signal is scaled by risk.</p><h4>Part 1: Imports and the algorithm</h4><pre>from AlgorithmImports import *<br>import math<br>from collections import deque<br>class CalculusAccelerationModel(QCAlgorithm):<br>    pass</pre><p>QuantConnect AlgorithmImports gives you the Lean API. We also import:</p><ul><li>math for log and sqrt</li><li>deque for rolling windows (fast and simple)</li></ul><p>Rolling windows are the backbone of this model, because the math depends on “the last (N) values.”</p><h3>Part 2: Initialize backtest, add the asset, and define parameters</h3><pre>class CalculusAccelerationModel(QCAlgorithm):<br>    def Initialize(self):<br>        self.SetStartDate(2015, 1, 1)<br>        self.SetEndDate(2025, 1, 1)<br>        self.SetCash(100000)<br>        self.symbol = self.AddEquity(&quot;SPY&quot;, Resolution.Daily).Symbol</pre><p>This is standard boilerplate: dates, capital, and which instrument you trade. SPY is a good default because it is liquid and has high data quality.</p><p>Now we define the actual “math knobs”:</p><pre>self.N = 20        # window length for rolling volatility<br>        self.k = 2.0       # aggressiveness: smaller k means bigger positions<br>        self.w_max = 1.0   # max portfolio weight (1.0 means fully long/short)<br>        self.eps = 1e-8    # avoid divide-by-zero in normalization<br>        self.deadband = 0.05  # ignore tiny weights to reduce churn</pre><p>Here is the mapping to the model:</p><ul><li>(N) controls how stable your volatility estimate is.</li><li>(k) controls how quickly you ramp exposure as the signal grows.</li><li>w_max caps risk.</li><li>deadband reduces overtrading when the signal is basically noise.</li></ul><p>Then we set warmup and define rolling storage:</p><pre>self.SetWarmUp(self.N + 3, Resolution.Daily)<br>self.prices = deque(maxlen=self.N + 3)<br>self.returns = deque(maxlen=self.N + 2)</pre><p>Why N + 3 and N + 2? Because to compute acceleration, you need at least two returns, and to compute volatility, you need a full window of returns. This ensures you do not trade until the model can actually compute every term correctly.</p><h3>Part 3: Schedule the decision point (rebalance)</h3><pre>self.Schedule.On(<br>            self.DateRules.EveryDay(self.symbol),<br>            self.TimeRules.AfterMarketOpen(self.symbol, 5),<br>            self.Rebalance<br>        )</pre><p>This line is the difference between a strategy that is easy to reason about and one that becomes a spaghetti loop.</p><p>Every trading day, five minutes after open, we compute the newest signal and set holdings once.</p><h3>Part 4: Ingest daily data and compute log returns in OnData</h3><pre>def OnData(self, data: Slice):<br>        if self.symbol not in data.Bars:<br>            return<br><br>        close = float(data.Bars[self.symbol].Close)<br>        self.prices.append(close)<br><br>        if len(self.prices) &gt;= 2:<br>            p_t = self.prices[-1]<br>            p_tm1 = self.prices[-2]<br>            r_t = math.log(p_t / p_tm1)<br>            self.returns.append(r_t)</pre><p>This is exactly where the calculus comes in.</p><ul><li>We store (P(t)) (closing price).</li><li>Then compute the log return</li><li>Those returns will later be used for both acceleration and volatility.</li></ul><p>Notice we do not trade here. We are just updating state.</p><h3>Part 5: Compute the signal and trade in Rebalance</h3><pre>    def Rebalance(self):<br>        if self.IsWarmingUp:<br>            return<br><br>        if len(self.returns) &lt; self.N + 1:<br>            return</pre><p>These guards prevent trading until the model has enough data to compute:</p><ul><li>rolling volatility (needs (N) returns)</li><li>acceleration (needs two returns)</li></ul><p>Now compute acceleration:</p><pre>r_t = self.returns[-1]<br>        r_tm1 = self.returns[-2]<br>        a_t = r_t - r_tm1</pre><p>Now compute rolling volatility of the last (N) returns:</p><pre>recent = list(self.returns)[-self.N:]<br>        mu = sum(recent) / self.N<br>        var = sum((x - mu) ** 2 for x in recent) / (self.N - 1)<br>        sigma = math.sqrt(var)</pre><p>That is just the sample standard deviation. We keep it explicit so you can see exactly what is happening, rather than hiding it inside a library call.</p><p>Now normalize the acceleration:</p><pre>z = a_t / (sigma + self.eps)</pre><p>This is your standardized acceleration. It answers: is acceleration “big” relative to typical return movement?</p><p>Now map that signal to a portfolio weight:</p><pre>w = z / self.k<br>        w = max(-self.w_max, min(self.w_max, w))</pre><p>So if z is large and positive, you go long; if it is large and negative, you go short, but you never exceed your cap.</p><p>Finally apply the deadband:</p><pre>if abs(w) &lt; self.deadband:<br>            w = 0.0</pre><p>This is a practical “market microstructure” tweak. It reduces small flip-flops that usually do not survive fees and slippage.</p><p>Then place the trade:</p><pre>self.SetHoldings(self.symbol, w)<br>        self.Debug(f&quot;{self.Time.date()} r={r_t:.5f} a={a_t:.5f} sig={sigma:.5f} z={z:.3f} w={w:.2f}&quot;)</pre><p>SetHoldings sets your target weight. QuantConnect will generate the necessary orders to reach that allocation.</p><h3>Full working algorithm (paste into QuantConnect)</h3><pre>from AlgorithmImports import *<br>import math<br>from collections import deque<br><br>class CalculusAccelerationModel(QCAlgorithm):<br>    def Initialize(self):<br>        self.SetStartDate(2015, 1, 1)<br>        self.SetEndDate(2025, 1, 1)<br>        self.SetCash(100000)<br><br>        self.symbol = self.AddEquity(&quot;SPY&quot;, Resolution.Daily).Symbol<br><br>        self.N = 20<br>        self.k = 2.0<br>        self.w_max = 1.0<br>        self.eps = 1e-8<br>        self.deadband = 0.05<br><br>        self.SetWarmUp(self.N + 3, Resolution.Daily)<br><br>        self.prices = deque(maxlen=self.N + 3)<br>        self.returns = deque(maxlen=self.N + 2)<br><br>        self.Schedule.On(<br>            self.DateRules.EveryDay(self.symbol),<br>            self.TimeRules.AfterMarketOpen(self.symbol, 5),<br>            self.Rebalance<br>        )<br><br>    def OnData(self, data: Slice):<br>        if self.symbol not in data.Bars:<br>            return<br><br>        close = float(data.Bars[self.symbol].Close)<br>        self.prices.append(close)<br><br>        if len(self.prices) &gt;= 2:<br>            p_t = self.prices[-1]<br>            p_tm1 = self.prices[-2]<br>            r_t = math.log(p_t / p_tm1)<br>            self.returns.append(r_t)<br><br>    def Rebalance(self):<br>        if self.IsWarmingUp:<br>            return<br><br>        if len(self.returns) &lt; self.N + 1:<br>            return<br><br>        r_t = self.returns[-1]<br>        r_tm1 = self.returns[-2]<br>        a_t = r_t - r_tm1<br><br>        recent = list(self.returns)[-self.N:]<br>        mu = sum(recent) / self.N<br>        var = sum((x - mu) ** 2 for x in recent) / (self.N - 1)<br>        sigma = math.sqrt(var)<br><br>        z = a_t / (sigma + self.eps)<br><br>        w = z / self.k<br>        w = max(-self.w_max, min(self.w_max, w))<br><br>        if abs(w) &lt; self.deadband:<br>            w = 0.0<br><br>        self.SetHoldings(self.symbol, w)<br>        self.Debug(f&quot;{self.Time.date()} r={r_t:.5f} a={a_t:.5f} sig={sigma:.5f} z={z:.3f} w={w:.2f}&quot;)</pre><p>And, that&#39;s it!</p><p>We are done. You just created your first quant (calculus-based) model!</p><p>Great job. In the next article, we will discuss how to actually use QuantConnect to execute your model and what each metric means.</p><p>~ RandomResearchAI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b591352a6868" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your First Quantitative Finance Lesson (No Math Degree Required)]]></title>
            <link>https://randomresearchai.medium.com/your-first-quantitative-finance-lesson-no-math-degree-required-bf20de00ebcb?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf20de00ebcb</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[backtesting]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 06:23:05 GMT</pubDate>
            <atom:updated>2025-12-22T06:23:05.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*06UbnX0CBo56VJZe" /><figcaption>Credit: good work_</figcaption></figure><p>Quantitative trading sounds intimidating at first, but at its heart, it is simply a structured way of thinking about markets.</p><p>Instead of relying on gut feelings, hot takes, or dramatic headlines, quant trading asks a calmer question: <em>what does the data actually say, and how can we act on it consistently?</em></p><p>If stories drive traditional trading, quantitative trading is driven by measurements. The goal is not to predict the future perfectly, but to make better decisions on average by using math, statistics, and clear rules.</p><p>To understand quant trading, it helps to start with how quants look at markets. A market is not a single moving line on a chart.</p><p>It is a stream of numbers changing over time. Every price, every trade, every time step is data.</p><p>Quants take this data seriously. They do not ask whether a price “feels high” or “looks cheap.”</p><p>They ask how prices have behaved historically under similar conditions and whether there is a repeatable pattern worth exploiting.</p><p>One of the first ideas you encounter in quant trading is the difference between <strong>price</strong> and <strong>return</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2dxp7Zap2txoLTHz.png" /></figure><p><strong>Price</strong> is just the level of an asset, like a stock trading at 150 dollars.</p><p><strong>Return</strong> is how that price changes over time, usually expressed as a percentage.</p><p>For example, if a stock goes from 100 to 105, the return is 5 percent. Quants almost always work with returns instead of prices because returns are easier to compare across assets and time periods.</p><p>A five-dollar move means very different things for a 20-dollar stock and a 500-dollar stock, but a five percent return means the same thing everywhere.</p><p>This shift alone already makes markets easier to analyze.</p><p>Once returns are defined, quants start summarizing behavior using basic statistics.</p><p>One key term is the <strong>mean</strong>, often called the <em>expected return</em>. This is simply the average return over time.</p><p>It answers the question: if I repeat this process many times, what do I get on average.</p><p>Another critical concept is <strong>variance</strong>, which measures how spread out returns are around the average.</p><p>High variance means outcomes are unpredictable. Low variance means returns cluster tightly around the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DU056LabZw9e8Wzq.png" /></figure><p>Closely related to variance is <strong>volatility</strong>, which is just the square root of variance and is easier to interpret because it has the same units as returns.</p><p>Volatility is what people usually mean when they say an asset is risky, but in quant trading, risk is something you calculate, not something you feel.</p><p>With these tools, quants can begin forming ideas, which are called <strong>signals</strong>.</p><p>A signal is any measurable quantity that might contain information about future returns.</p><p>For example, a signal could be recent momentum, a moving average difference, or a relationship between two assets.</p><p>Importantly, a signal is not a belief. It is a number. If that number crosses a certain threshold, it may trigger an action.</p><p>This is where rules come in. A quantitative strategy is defined entirely by rules such as when to enter a trade, how much to invest, and when to exit. These rules are written down or coded before any real money is involved.</p><p>To see whether a strategy is worth anything, quants use <strong>backtesting</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eS3h-mvMH9m34GJJ.png" /></figure><p>A backtest applies the strategy’s rules to historical data as if the strategy had been running in the past. This allows the trader to evaluate performance using clear metrics.</p><p><strong>Profit</strong> is one metric, but it is far from the only one.</p><p><strong>Drawdown</strong> measures the largest peak-to-trough loss and shows how painful the strategy can be during bad periods.</p><p>The <strong>Sharpe</strong> ratio compares return to volatility and answers whether the strategy is being rewarded enough for the risk it takes.</p><p>Consistency metrics look at how often the strategy wins or loses. A strategy that makes money but experiences massive drawdowns or extreme volatility may be unusable in practice.</p><p>Another key idea in quant trading is <strong>randomness</strong>.</p><p>Markets are noisy, meaning that a lot of price movement is essentially random in the short term. This is often modeled using the idea of a random walk, where price changes resemble random steps rather than smooth, predictable paths.</p><p>Quants accept this uncertainty rather than fighting it. They design strategies that do not need to be right every time. A strategy might only be correct 55 percent of the time and still be profitable if losses are controlled and gains are allowed to run.</p><p>This probabilistic thinking is one of the hardest but most important mental shifts for beginners.</p><p>Once a strategy passes testing, it can be automated or followed mechanically. This is one of the biggest advantages of quantitative trading.</p><p>A rules-based system executes the same way every time.</p><p>It does not panic during crashes or get greedy during rallies.</p><p>Emotions are replaced with execution.</p><p>This does not mean quant traders are emotionless. It means emotions are not allowed to interfere with decisions that have already been carefully designed and tested.</p><p>The power of this approach has been proven at the highest levels of finance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pbsiZFxGpk6YKWWX.png" /></figure><p>Firms built entirely around quantitative methods dominate large parts of modern markets.</p><p>A famous example is Renaissance Technologies, founded by Jim Simons, who showed that systematically exploiting small statistical edges, repeated thousands or millions of times, can outperform intuition-driven trading over long periods.</p><p>Their success did not come from knowing what the market would do tomorrow, but from understanding probabilities better than others.</p><p>Quantitative trading is not magic, and it is not easy.</p><p>Models break, relationships change, and strategies stop working. That is normal.</p><p>What makes quant trading different is that failure is measurable and informative. When something stops working, the data shows it, and the strategy can be adjusted or abandoned.</p><p>In that sense, quant trading is closer to science than speculation. It treats ideas as experiments, data as evidence, and performance as something that must be proven, not claimed.</p><p>In simple terms, quantitative trading is about using data and math to make better decisions under uncertainty.</p><p>It replaces stories with statistics, feelings with measurements, and improvisation with rules. For beginners, the most important takeaway is not the formulas or the code, but the mindset.</p><p>Once you start thinking this way, markets stop being mysterious and start becoming something you can analyze, test, and understand step by step.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf20de00ebcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graphs Are Eating the World: A Deep Dive into GNNs]]></title>
            <link>https://randomresearchai.medium.com/graphs-are-eating-the-world-a-deep-dive-into-gnns-2cf600d27236?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf600d27236</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computational-graphs]]></category>
            <category><![CDATA[gnn]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 17:43:48 GMT</pubDate>
            <atom:updated>2025-11-09T17:43:48.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J-tvva4oWWWq5dJn.png" /><figcaption>Credit: ionio</figcaption></figure><p>We live in a world of connections, not just isolated data points.</p><p>Your social network is a graph. The molecules that make up medicine are graphs. The roads you drive on, the proteins in your body, and the flow of information on the internet are all graphs.</p><p>For decades, machine learning has been obsessed with data that fits neatly into rows and columns, or pixels in a grid (images), or words in a sequence (text).</p><p>But this clean, structured data misses the most important part of reality: <strong>the relationships.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f5j3ZHgUwwGE1oUP.jpg" /><figcaption>Credit: SNAP</figcaption></figure><p>How do you feed a social network into a standard neural network?</p><p>How do you teach a machine that the <em>structure</em> of a molecule is just as important as the atoms it contains?</p><p>The answer is the <strong>Graph Neural Network (GNN)</strong>. This is not just another passing trend. It is a fundamental shift in machine learning, allowing us to build models that think in terms of connections.</p><p>This post is a deep dive. We will dissect how a GNN <em>really</em> works, build one from scratch, and then look at the powerful variants that are pushing the boundaries of science and technology.</p><h3>Part 1: How a GNN Actually Thinks</h3><p>Forget complex math for a second. Let’s use an analogy.</p><p>Imagine you are at a large, crowded party. You want to figure out who at this party is an “influencer.” You can’t know this just by looking at one person. You need context.</p><p>So, you start with a simple guess for everyone. Maybe you guess based on how they are dressed (their initial <strong>node features</strong>).</p><p>Then, you do the following:</p><ol><li><strong>Round 1: Talk to Your Friends.</strong> You go to every person (every <strong>node</strong>) and ask them to look at their immediate friends (their <strong>neighbors</strong>). Each person writes down a summary of what their friends are like. “I see I’m friends with two people in suits and one in a band t-shirt.” This is the <strong>AGGREGATION</strong> step.</li><li><strong>Round 2: Update Your Opinion.</strong> Now, you go back to every person. You tell them, “Okay, take your <em>own</em> style (your original features) and combine it with the summary you just collected from your friends.” A person in a suit who is only friends with other people in suits might become more “Corporate.” But a person in a suit who is friends with band members and artists might become “Creative” or “Connected.” This is the <strong>UPDATE</strong> step.</li></ol><p>After this two-step process, everyone’s “label” is now richer. It’s not just based on <em>them</em>; it’s based on <em>their 1-hop neighborhood</em>.</p><p><strong>Now, do it again.</strong></p><p>In <strong>Round 2</strong>, you tell everyone to <em>again</em> ask their friends for <em>their</em> new, updated labels.</p><p>But wait —their friends’ labels were updated too. This means that when you aggregate in Round 2, you are implicitly getting information from your friends&#39;<em> friends</em> (your 2-hop neighborhood).</p><p>This iterative process of <strong>aggregating</strong> neighbor information and <strong>updating</strong> your own representation is the core mechanism of all GNNs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/0*2qPUrUiiB9iLj-cE" /><figcaption>Research Gate</figcaption></figure><p>A GNN layer is just one round of this “gossip.” By stacking k GNN layers, you allow each node to gather information from its k-hop neighborhood.</p><p>The “magic” is that the GNN <em>learns</em> the best way to combine this information. It learns (using neural networks) what to pay attention to during the aggregation and update steps to best solve the final task.</p><p>This task could be:</p><ul><li><strong>Node Classification:</strong> Is this <em>user</em> a bot? (Like our influencer example)</li><li><strong>Graph Classification:</strong> Is this <em>molecule</em> toxic?</li><li><strong>Link Prediction:</strong> Will <em>these two people</em> become friends?</li></ul><h3>Part 2: The Code: Building a GNN in Python</h3><p>Let’s make this concrete. The most popular library for GNNs is <strong>PyTorch Geometric (PyG)</strong>. We will build a simple Graph Convolutional Network (GCN) to classify nodes in the Cora dataset.</p><p>The Cora dataset is a classic. It&#39;s a graph of 2,708 scientific papers.</p><ul><li><strong>Nodes:</strong> The papers.</li><li><strong>Node Features:</strong> A 1433-dimension vector for each paper, representing the presence (1) or absence (0) of specific words.</li><li><strong>Edges:</strong> Citations (if paper A cites paper B, there is an edge).</li><li><strong>The Goal:</strong> Classify each paper into one of seven subject areas.</li></ul><p>Here is the full, commented code.</p><p>Python:</p><pre># Lets import all libs<br>import torch<br>import torch.nn.functional as F<br>from torch_geometric.datasets import Planetoid<br>from torch_geometric.nn import GCNConv</pre><pre># 1. Load the Cora Dataset<br># PyG handles all the downloading and data processing.<br># &#39;data&#39; is a single Graph object holding all info.<br>dataset = Planetoid(root=&#39;/tmp/Cora&#39;, name=&#39;Cora&#39;)<br>data = dataset[0]<br># data contains:<br># data.x: Node features [2708, 1433]<br># data.edge_index: Graph connectivity [2, 13264] (COO format)<br># data.y: Node labels [2708] (0-6)<br># data.train_mask: Boolean mask for training nodes<br># data.val_mask / data.test_mask: Masks for validation and testing<br># 2. Define the GNN Model (a 2-layer GCN)<br>class GCN(torch.nn.Module):<br>    def __init__(self, in_features, hidden_features, out_features):<br>        super(GCN, self).__init__()<br>        torch.manual_seed(42)<br>        <br>        # Our first GNN layer (Round 1 of gossip)<br>        # It takes the initial node features and transforms them<br>        self.conv1 = GCNConv(in_features, hidden_features)<br>        <br>        # Our second GNN layer (Round 2 of gossip)<br>        # It takes the &#39;hidden&#39; features and transforms them to the final 7 classes<br>        self.conv2 = GCNConv(hidden_features, out_features)<br>    def forward(self, x, edge_index):<br>        # x: Node features<br>        # edge_index: Graph structure<br>        <br>        # Pass data through the first layer<br>        x = self.conv1(x, edge_index)<br>        x = F.relu(x)<br>        x = F.dropout(x, p=0.5, training=self.training)<br>        <br>        # Pass data through the second layer<br>        x = self.conv2(x, edge_index)<br>        <br>        # We return the raw &#39;logits&#39; for the loss function<br>        # The final activation (log_softmax) will be applied outside<br>        return x<br># 3. Setup the Training<br>model = GCN(in_features=dataset.num_node_features,<br>            hidden_features=16, # A small hidden layer<br>            out_features=dataset.num_classes)<br>optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)<br>criterion = torch.nn.CrossEntropyLoss()<br># 4. The Training Loop<br>def train():<br>    model.train()<br>    optimizer.zero_grad()  # Clear gradients<br>    <br>    # Perform a single forward pass<br>    out = model(data.x, data.edge_index)<br>    <br>    # Calculate loss ONLY on the training nodes<br>    loss = criterion(out[data.train_mask], data.y[data.train_mask])<br>    <br>    loss.backward()  # Derive gradients<br>    optimizer.step()   # Update parameters<br>    return loss<br># 5. The Testing Function<br>def test():<br>    model.eval()<br>    out = model(data.x, data.edge_index)<br>    pred = out.argmax(dim=1)  # Get the class with the highest score<br>    <br>    # Check accuracy ONLY on the test nodes<br>    test_correct = pred[data.test_mask] == data.y[data.test_mask]<br>    test_acc = int(test_correct.sum()) / int(data.test_mask.sum())<br>    return test_acc<br># 6. Run it!<br>print(&quot;Starting training...&quot;)<br>for epoch in range(1, 201):<br>    loss = train()<br>    if epoch % 20 == 0:<br>        val_acc = test() # Using test() for simplicity, often you&#39;d use a val set<br>        print(f&#39;Epoch: {epoch:03d}, Loss: {loss:.4f}, Test Accuracy: {val_acc:.4f}&#39;)<br>print(&quot;Training finished.&quot;)<br>test_acc = test()<br>print(f&#39;Final Test Accuracy: {test_acc:.4f}&#39;)</pre><p>When you run this, you will see the model quickly learns to classify the papers with high accuracy, something that would be impossible without using the graph’s citation structure.</p><h3>Part 3: Cool Expansions (Beyond the Basic GCN)</h3><p>The GCN we just built is the “Hello, World!” of GNNs. The field has exploded with powerful expansions that solve its initial weaknesses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pG2lWhQ7MoIq_jn5.png" /><figcaption>Credit: AAA</figcaption></figure><h4>1. Graph Attention Networks (GAT)</h4><p><strong>The Problem:</strong> Our GCN treats all neighbors equally. When it aggregates, it just takes a weighted <em>average</em>. But in a social network, is your “boss” neighbor as important as your “best friend” neighbor for predicting your interests? Probably not.</p><p><strong>The Solution:</strong> Use <strong>attention</strong>. A GAT layer learns a “importance score” (an attention weight) for every edge. When a node aggregates messages from its neighbors, it multiplies each neighbor’s message by this learned weight. It learns to “pay more attention” to the neighbors that matter for the specific task. This is the same mechanism that powers Transformers like BERT and GPT, but applied to graph structures.</p><h4>2. GraphSAGE (SAmple and aggreGatE)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r1YkGZ4vBu1jYbGN.png" /><figcaption>Credit: Stanford</figcaption></figure><p><strong>The Problem:</strong> Our GCN is “transductive.” It requires the <em>entire</em> graph to be present during training. What happens if a new user joins your social network? You would have to retrain the whole model. This does not scale to graphs with billions of nodes.</p><p><strong>The Solution:</strong> GraphSAGE changes the game.</p><ul><li><strong>Sample:</strong> Instead of using <em>all</em> neighbors, for each node, you <em>sample</em> a fixed number (e.g., 10) of its neighbors.</li><li><strong>Aggregate:</strong> You use a more sophisticated aggregator on this fixed-size sample. Instead of a simple mean, you could use a max-pool (taking the most &quot;active&quot; neighbor) or even pass the neighbors&#39; features through a small LSTM.</li></ul><p>This “sample and aggregate” approach is <strong>inductive</strong>. You are not learning an embedding for <em>a</em> node; you are learning an <em>aggregator function</em> that can generate an embedding for <em>any</em> node, even ones it has never seen before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*jGMbB5-wdiC6CdGq.jpg" /><figcaption>Credit: ScienceDIrect</figcaption></figure><h4>3. Graph Isomorphism Networks (GIN)</h4><p><strong>The Problem:</strong> Some graphs are structurally different but look the same to a simple GCN.</p><p>For example, a “star” graph (one central node, 5 neighbors) and a “path” graph (5 nodes in a line) might confuse a GCN if the node features are all identical.</p><p><strong>The Solution:</strong> GIN is a GNN variant designed to be maximally powerful at distinguishing graph structures.</p><p>It was shown to be as powerful as the Weisfeiler-Lehman (WL) test, a classic algorithm for graph isomorphism (i.e., determining whether two graphs are structurally identical).</p><p>It achieves this by using a specific update rule: it sums its neighbors’ features (rather than averaging) and passes the result through a small Multi-Layer Perceptron (MLP). This simple change dramatically boosts its expressive power.</p><h3>The Future is Connected</h3><p>Graph Neural Networks are not just a tool. They are a new way of thinking. They allow us to model systems, not just isolated points.</p><p>Today, GNNs are being used to discover new antibiotics (by modeling molecules), stop fraud in financial networks (by finding strange patterns), and build better recommendation engines (by understanding the “user-item” graph).</p><p>You have seen the core idea of message passing, built a model yourself, and seen its powerful expansions.</p><p>The world is full of graphs.</p><p>Now you have the tool to understand them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf600d27236" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Overfitting Hurts Your Machine Learning Models & How to Prevent It]]></title>
            <link>https://randomresearchai.medium.com/why-overfitting-hurts-your-machine-learning-models-how-to-prevent-it-8d4b2d6b4db0?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d4b2d6b4db0</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 23:05:06 GMT</pubDate>
            <atom:updated>2025-10-20T23:05:06.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bstHvaLxLTkBHjtf.png" /><figcaption>G4G</figcaption></figure><p>Overfitting is one of those problems that every machine learning practitioner encounters at some point. It’s when your model performs extremely well on the data it was trained on but struggles when faced with new, unseen examples.</p><p>In simple terms, the model has learned the training data too specifically: it’s memorized the answers instead of understanding the patterns.</p><p>When we train a model, our goal is to help it generalize.</p><p>We want it to capture the real trends in the data so that it can make accurate predictions in the future.</p><p>But overfitting breaks that balance. It happens when the model starts treating noise, outliers, or random coincidences in the training set as if they were important patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7FViv9jG7GPFsTga" /><figcaption>Encord</figcaption></figure><p>The result is a system that looks smart during training but performs poorly in the real world.</p><p>One common reason for overfitting is that the model is too complex for the problem it’s trying to solve. Deep neural networks with millions of parameters can represent extremely detailed relationships, and if your dataset is small or inconsistent, the network might end up memorizing it completely.</p><p>Even decision trees can overfit if they grow too deep, splitting the data into increasingly tiny segments until each one fits perfectly, but only for that particular dataset.</p><p>Data quantity and quality matter a lot.</p><p>If your dataset isn’t diverse enough, your model doesn’t have enough examples to learn what truly generalizes.</p><p>It’s like training a handwriting recognition model on one person’s handwriting: it’ll work great for them, but fail for everyone else. Models learn what they see, and <em>if what they see is narrow, so will be their understanding. (Same goes for us!)</em></p><p>Another subtle cause is training for too long.</p><p>During training, the model’s loss on the training set keeps improving, but at some point, the validation loss starts increasing again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WBGcFSXy3GsKmhYJ.png" /><figcaption>Grammarly</figcaption></figure><p>That’s the moment it begins to overfit. The model is now memorizing noise instead of a meaningful signal. Monitoring this balance between learning and memorizing is one of the most essential habits in model development.</p><p>The consequences of overfitting show up quickly once you test the model in real-world conditions. Predictions become unreliable, performance metrics drop, and confidence scores no longer reflect reality.</p><p>In production systems, this can be disastrous. An overfitted fraud detection model might flag legitimate transactions as frauds.</p><p>A medical diagnosis model might perform well in lab tests but fail with data from a new hospital. In each case, the model’s “knowledge” isn’t real; it’s an illusion created by excessive memorization.</p><p>There are several practical ways to address overfitting. The first is <strong>simplifying the model</strong>. Use fewer layers, smaller architectures, or less complex algorithms when your data doesn’t justify large capacity. A simpler model is less likely to memorize every detail and more likely to learn general patterns.</p><p>Another approach is <strong>regularization</strong>, which adds a penalty for large or unnecessary weights. This prevents the model from depending too heavily on specific parameters. Techniques like L1 and L2 regularization, dropout, and early stopping are common tools for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*2DsrB7ylQv5F9Zzr.png" /><figcaption>Analytics Yogi</figcaption></figure><p>Dropout, for instance, randomly removes neurons during training so the network doesn’t rely too much on any single connection. Early stopping halts training once the validation loss stops improving.</p><p><strong>Data augmentation</strong> is another powerful tool. By creating modified versions of your data — rotated images, added noise, shifted pixels — you effectively increase the variety of examples your model sees. This helps it learn to focus on the core features rather than irrelevant details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Vx2t71pJ5xB3IGag.png" /><figcaption>Ubiai</figcaption></figure><p>Similarly, <strong>cross-validation</strong> ensures your model performs consistently across multiple subsets of the data, not just one lucky split.</p><p>Finally, <strong>more data</strong> is often the simplest and most effective fix. When the model has access to a wider variety of examples, it naturally becomes better at distinguishing real patterns from noise.</p><p>Of course, collecting more data isn’t always easy, but it’s almost always worth it.</p><p>Overfitting isn’t inherently evil: it’s a sign that your model is powerful enough to capture details, but lacks the restraint to know which ones matter.</p><p>So when your next training run shows 99% accuracy, don’t celebrate too early. Check how it performs on unseen data. A brilliant model doesn’t just remember, it predicts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d4b2d6b4db0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How an AI Model Thinks: From Your Prompt to a Finished Answer]]></title>
            <link>https://randomresearchai.medium.com/how-an-ai-model-thinks-from-your-prompt-to-a-finished-answer-4f411d65f5d4?source=rss-fb8e21113540------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f411d65f5d4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[explanation]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[RandomResearchAI]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 19:27:43 GMT</pubDate>
            <atom:updated>2025-08-13T19:27:43.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*1SS8FrjhcSzGgN8Q.jpg" /><figcaption>Tech Xplore</figcaption></figure><p>When you type a question into an AI model, it feels almost magical.</p><p>You write a sentence, hit enter, and a fully formed response flows back as if the machine had been thinking about it all day.</p><p>But behind that illusion of simplicity, there’s an intricate chain of events happening in milliseconds — a blend of language processing, mathematical precision, high-performance hardware, and careful safety systems, all working together like a finely tuned orchestra.</p><p>It starts the moment you submit your prompt.</p><p>That text doesn’t just drop straight into the model; it’s first received by a server that handles all incoming requests, often called the API gateway.</p><p>This is the model’s “front door,” where some early housekeeping happens: your text might be lightly cleaned to remove strange formatting or hidden characters, and quick security scans might check for dangerous content or injection attempts.</p><p>This ensures that what goes deeper into the system is both safe and well-structured.</p><p>Once cleared, your words are passed into a tokenizer — a specialized piece of software that breaks language into bite-sized chunks called tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjjpIw_PLSVp1EIeMQ9ZTQ.png" /><figcaption>OpenVINO</figcaption></figure><p>These aren’t full words in most cases; they can be whole words, parts of words, or even single characters depending on the language and vocabulary.</p><p>The tokenizer then translates each token into a number, like a secret code from a fixed dictionary the model understands.</p><p>By now, your prompt has stopped being “English” or “Python code” in any human sense — it’s become a list of integers.</p><p>These token IDs are sent into the inference runtime, which is the backstage manager deciding how and where your request will be run.</p><p>In big deployments, there may be dozens or hundreds of GPUs ready to process requests, and the runtime chooses which one will handle yours.</p><p>It may even bundle your request with others arriving at the same time, a trick called batching, to keep the hardware fully occupied.</p><p>If your prompt contains a familiar prefix — for example, the same system prompt used in every query — the runtime can pull that part from a cache so the model doesn’t have to reprocess it.</p><p>Now the heavy lifting begins.</p><p>Your tokens are loaded into the GPU’s memory alongside the model’s weights — the billions of learned parameters that define its “knowledge.”</p><p>This memory is often high-bandwidth VRAM designed to move enormous amounts of data at breathtaking speeds.</p><p>Inside the GPU, thousands of tiny cores work together to perform the enormous matrix multiplications that drive modern transformers. In a single forward pass, your tokens are embedded into high-dimensional vectors, run through multiple transformer blocks, and processed by attention mechanisms that figure out which parts of the input are most relevant to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_8QSIgASan0SmwxP.png" /></figure><p>At the same time, feedforward layers mix and transform these vectors, building a richer and richer representation of what your prompt is asking.</p><p>In the very last stage of the pass, the model produces a probability distribution over every token in its vocabulary, essentially saying, “Given everything I’ve seen so far, here’s how likely each next token is.”</p><p>The inference engine picks the next token according to decoding rules — maybe choosing the most likely one for deterministic tasks, or sampling from the top candidates for more creativity.</p><p>That token is appended to your sequence, and the whole process repeats for the next one, using a key-value cache to avoid recomputing past attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/0*_sTlAhJHlKoQapmd" /><figcaption>Deepgram</figcaption></figure><p>This loop continues until the model hits a stop signal, either from reaching a special end token or a maximum length.</p><p>While this is happening, the system’s orchestration software manages more than just the math.</p><p>Networking layers stream tokens back to you as they’re generated so you can start reading before the model finishes.</p><p>Observability tools measure timing at each stage — prefill, decode, batching — to monitor performance and spot slowdowns.</p><p>Safety layers may run in parallel, scanning generated text for disallowed content before it’s fully displayed.</p><p>And if you’re using a hosted service, autoscaling controllers watch GPU queues and spin up more hardware when demand surges.</p><p>From your perspective, all you see is the text arriving on your screen. But inside those milliseconds is a chain of translation, parallel computation, memory juggling, statistical prediction, and security oversight — from the moment your words leave your keyboard to the moment the last token arrives.</p><p>The next time your AI assistant replies in under a second, remember: that answer traveled through an entire ecosystem of hardware and software, from front-end gateways and tokenizers to high-bandwidth GPUs, caching systems, safety filters, and back to you, each piece playing its part so the magic feels effortless.</p><p>Before a model can answer even a single question, it first has to be taught how to speak, reason, and write code.</p><p>This process, called training, is where the real shaping of its “mind” happens — and it’s an entirely different beast from inference.</p><p>If inference is like a musician playing a song on stage, training is the years of practice, drills, and lessons that prepare them for that performance.</p><p>It begins with data — oceans of it. Text from books, articles, websites, open-source code repositories, conversations, and carefully curated datasets. But the data isn’t just thrown into the model raw.</p><p>Just like with inference, the first step is tokenization: turning all that text into sequences of numbers that the model can work with. These sequences are grouped into batches so they can be processed in parallel.</p><p>The difference here is that in training, the model already knows the “right answer” for each sequence — because the right next token is simply the next one in the text.</p><p>The model starts out knowing nothing except how to multiply numbers. When the first batch of token sequences flows in, the model makes its best guess at what the next token should be for each position.</p><p>At the start, these guesses are basically random.</p><p>The real magic is in what happens immediately after: the model compares its guesses to the actual correct tokens, and the difference — the error — is measured using a loss function. This number tells the training system how far off the model was.</p><p>From there, the backward pass begins.</p><p>Using an algorithm called backpropagation, the model calculates exactly how much each parameter — all billions of them — contributed to the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l7wKOfUA56sKyKXG.png" /><figcaption>Analytics Vidhya</figcaption></figure><p>These parameters are then nudged in the right direction using an optimizer, the most common being Adam or its variants.</p><p>This is gradient descent in action: the model slowly walks downhill on the loss landscape, batch by batch, towards better predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5bKHwuSfsaompvjq.png" /><figcaption>Suryansh S.</figcaption></figure><p>Training is insanely resource-hungry. While inference might run on a single high-end GPU, training a modern frontier model can require thousands of GPUs running for weeks or months.</p><p>These GPUs are linked together with high-speed interconnects like NVLink and InfiniBand so they can share their progress every step of the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*mg7lSai5pt6f6yhX.jpg" /><figcaption>FiberMall</figcaption></figure><p>The model’s parameters are split across devices (tensor parallelism), layers might be spread across pipelines (pipeline parallelism), and multiple copies of the model might process different batches in parallel (data parallelism), all synchronized at blistering speeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvfJDqG76Cqa9DRRZACUyQ.png" /><figcaption>uva dl</figcaption></figure><p>Even then, training requires careful scheduling, mixed-precision math to fit in memory, and constant checkpointing so progress isn’t lost if hardware fails.</p><p>Over time, the model learns statistical patterns in the data — how words follow one another, how sentences are structured, how code compiles and runs. But raw pretraining alone only makes a model a skilled imitator.</p><p>To make it follow instructions and behave helpfully, a second stage often kicks in: fine-tuning.</p><p>This can involve smaller, more specific datasets, human-annotated examples, or a process called reinforcement learning from human feedback (RLHF), where the model generates responses, humans rank them, and the model adjusts to prefer higher-ranked outputs.</p><p>By the end of this process, the model has effectively built an internal map of language and concepts.</p><p>It doesn’t memorize every sentence it’s seen — instead, it encodes the patterns in the billions of parameters in its neural network.</p><p>Those parameters are what get loaded into memory when you run inference, letting the model apply everything it learned during training to brand-new prompts it has never seen before.</p><p>And that’s the hidden half of the story.</p><p>When you watch a model respond in real time, you’re seeing the final, polished result of months of invisible labor: data gathered, cleaned, and tokenized; billions of weight updates spread across racks of humming GPUs; algorithms and optimizations bending the raw chaos of text into something coherent, helpful, and — if the engineers have done their job right — safe.</p><p>But what’s really happening behind the scenes? Let’s pull the curtain back.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f411d65f5d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>