<?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 Jaideep Ray on Medium]]></title>
        <description><![CDATA[Stories by Jaideep Ray on Medium]]></description>
        <link>https://medium.com/@jaideepray?source=rss-288e3faeb21c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fOExjie8YDPVEDNoWC8Mpg.png</url>
            <title>Stories by Jaideep Ray on Medium</title>
            <link>https://medium.com/@jaideepray?source=rss-288e3faeb21c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 00:50:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaideepray/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[Should models output logits or probabilities ?]]></title>
            <link>https://medium.com/better-ml/should-models-output-logits-or-probabilities-c16ef850fd0d?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c16ef850fd0d</guid>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 05:48:49 GMT</pubDate>
            <atom:updated>2026-10-03T05:56:42.242Z</atom:updated>
            <content:encoded><![CDATA[<p>A classification model does not always need to return probabilities. Use logits for loss calculation, score changes, and some ranking tasks. Use probabilities when a decision depends on an event rate or an expected value. Select the output format for the next process. The training process and the serving process can require different formats.</p><h4>1. What is a logit ?</h4><p>A logit is the raw, unscaled score output by a model say z. <br>The sigmoid function converts z to a model probability, p:</p><p><em>p = 1 / (1 + exp(−z))</em></p><p>The inverse calculation is:</p><p><em>z = log(p / (1 − p))</em></p><p>A zero logit gives a probability of 0.5. A positive logit gives a probability above 0.5. A negative logit gives a probability below 0.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAfbNBy_7BPhvTFvgg8jzA.png" /><figcaption><strong>Figure 1. Convert a binary logit to a model probability.</strong></figcaption></figure><p>For mutually exclusive classes, softmax converts the class logits to a probability distribution:</p><p><em>pᵢ = exp(zᵢ) / Σⱼ exp(zⱼ)</em></p><p>The probabilities sum to one. The difference between two logits has a useful interpretation:</p><p><em>zᵢ − zⱼ = log(pᵢ / pⱼ)</em></p><p>One multi-class logit does not give the log-odds of that class against all other classes. In exact arithmetic, sigmoid is reversible. Softmax preserves all differences between logits. It removes a common additive offset:</p><p><em>softmax(z + c) = softmax(z)</em></p><p>Thus, probability conversion does not always remove useful information. <em>However, rounding, clipping, and retaining only the top k outputs can remove information.</em></p><h4>2. During training use logits for loss calculation</h4><p><strong>A training objective that uses probabilities does not require the model to return probabilities.</strong> CrossEntropyLoss accepts class logits. It combines log-softmax with negative log-likelihood. BCEWithLogitsLoss combines sigmoid with binary cross-entropy. The combined calculation improves numerical stability. [1, 2]</p><p>Consider a binary prediction with z = 100 and label y = 0. The correct loss is approximately 100. An explicit sigmoid calculation can round the probability to one. The expression −log(1 − p) then becomes unstable. The equivalent logits expression avoids this problem:</p><p><strong><em>L(z, y) = max(z, 0) − zy + log(1 + exp(−|z|))</em></strong></p><p>Pass logits directly to CrossEntropyLoss and BCEWithLogitsLoss. An extra softmax or sigmoid changes the objective. These functions interpret their input values as logits.</p><h4>3. Use scores when only order matters</h4><p>Sigmoid is strictly increasing. Thus, binary logits and their probabilities give the same order in exact arithmetic. Softmax also preserves order within one vector:</p><p><em>argmax(z) = argmax(softmax(z))</em></p><blockquote>If a process only selects the top k items, it can use the scores directly. However, softmax probabilities depend on the candidate set. Suppose candidates A and B have scores 2 and 1. Softmax assigns A a probability of 73%. Now add candidate C with score 3. A’s probability falls to 24.5%. A and B keep their scores and relative order.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kq8fsWFMJ5h1nzkOPJGluw.png" /></figure><p>These probabilities <strong>describe a distribution within the candidate set</strong>. They do not automatically give click probabilities.</p><h4>4. Use probabilities for expected value</h4><p>Ranking ads by click probability requires only the correct order. A higher binary logit gives a higher probability after sigmoid. <strong>Thus, logits are sufficient if the goal is to select the ad most likely to receive a click</strong>. <strong>Ranking ads by expected revenue requires the probability value.</strong> The value of a click can differ between ads:</p><blockquote><em>Expected revenue per impression = P(click) × value per click.</em></blockquote><blockquote>Suppose Ad A has a 10% click probability and earns $2 per click. Its expected revenue is $0.20 per impression. Ad B has a 20% click probability and earns $0.75 per click. Its expected revenue is $0.15 per impression.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*182IJX5igeNytsqd0SEUVA.png" /></figure><p>Select A to maximize expected revenue. B is more likely to receive a click, but A earns more on average. Multiplying a logit by the value per click does not calculate this average. <strong>A logit expresses log-odds, not an event probability. </strong>Probability values also let us estimate event totals. If 1,000 users each have a calibrated 10% conversion probability, the expected total is 100 conversions. More generally, add the individual conversion probabilities to estimate the expected total.</p><p>A probability threshold can also be applied directly to binary logits. For example, p ≥ 0.20 is equivalent to z ≥ log(0.20 / 0.80), or approximately −1.39. This conversion preserves the decision. However, interpreting the threshold as a 20% event chance still requires calibrated probabilities.</p><h4>5. Sigmoid and Softmax != Probability</h4><p>Calibration is agreement between predicted probabilities and observed event rates. Suppose a binary model assigns 0.8 to a large group of examples. For calibration, the observed event rate should be near 80% in that group. <strong>Sigmoid and softmax do not establish this agreement.</strong> <strong>They produce the required mathematical form. They do not establish that the values match actual event rates.</strong></p><p>Temperature scaling uses:</p><p><em>p(T) = softmax(z / T)</em></p><p>Fit the positive temperature T on separate labeled data. A positive temperature changes probability values and preserves class order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5MQqG8fCZfw5hk2HDUKcQ.png" /></figure><p>Guo et al. found temperature scaling effective on several classification benchmarks. Check calibration again when the data distribution changes. [3]. Negative sampling and class weighting can change the probability that a model learns. Before you interpret click predictions as production rates, check them against representative traffic. Apply sampling correction or calibration when required.</p><h4>6. Keep logits for distillation and decoding</h4><p>Distillation trains a student model from a teacher model. The teacher provides probabilities for alternative classes. Temperature controls the distribution used for training. Teacher logits let you calculate this distribution directly. Hinton et al. describe this use of soft targets. [4] Complete, exact probabilities also support temperature changes. For positive probabilities at T = 1, raise each pᵢ to 1/T and normalize the results:</p><p><em>qᵢ = pᵢ^(1/T) / Σⱼ pⱼ^(1/T)</em></p><p><strong>However, rounded, clipped, or incomplete probabilities can lose information. Retain logits when later processes need this flexibility.</strong> In language-model decoding, greedy selection requires the highest allowed token score. Apply temperature, token masks, and score changes before normalization.</p><p>Sampling requires a probability distribution. A sampler can calculate this distribution internally. It does not have to return the full probability vector. Use log-probabilities to calculate sequence likelihoods. Add the log-probability of each token in the sequence.</p><h4>7. Specify the output contract</h4><p>An output contract defines what each output means. For a classifier core, I recommend logits as the default output. Provide a named probability output when required. This design supports several uses. It does not establish a speed improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfqDh2KM77h3Y9e0iA7_vA.png" /></figure><p><strong>Figure 4. Use the output that each process requires.</strong></p><p>Specify the <strong>output type, shape, class order, and normalization axis.</strong> Distinguish binary logits, multiclass logits, ranking scores, probabilities, and log-probabilities. Keep calibration and sampling correction versions with the model. Return both logits and probabilities only when both are required. A serving graph can include the complete calibrated probability calculation.<br>In summary,</p><ol><li>Ranking, Regression and embedding models also return useful outputs that are not probabilities.</li><li>Thus, a universal probability-output rule does not apply to all models. Use logits when a process needs scores or score changes.</li><li>Use calibrated probabilities when a decision needs event likelihoods. Specify the conversion in the output contract.</li></ol><h4>8. References</h4><ol><li><a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html">PyTorch — CrossEntropyLoss</a></li><li><a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html">PyTorch — BCEWithLogitsLoss</a></li><li><a href="https://proceedings.mlr.press/v70/guo17a.html">Guo et al. — On Calibration of Modern Neural Networks, ICML 2017</a></li><li><a href="https://arxiv.org/abs/1503.02531">Hinton et al. — Distilling the Knowledge in a Neural Network, 2015</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c16ef850fd0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/should-models-output-logits-or-probabilities-c16ef850fd0d">Should models output logits or probabilities ?</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What do Self-Improving Agents learn from their mistakes ?]]></title>
            <link>https://medium.com/better-ml/darwin-g%C3%B6del-machines-why-self-improving-agents-need-to-keep-their-mistakes-c08744932c06?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c08744932c06</guid>
            <category><![CDATA[autoresearch]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 20:03:53 GMT</pubDate>
            <atom:updated>2026-08-08T07:52:02.829Z</atom:updated>
            <content:encoded><![CDATA[<h4>Darwin Gödel Machines</h4><p>Most AI agents improve because a human changes them. You add a tool, rewrite a prompt, change the control flow, or introduce a reviewer. Recent systems can automate parts of this process by searching over prompts and workflows. But the optimizer usually remains fixed and external to the agent being improved.</p><p>The <a href="https://arxiv.org/pdf/2505.22954">Darwin Gödel Machine</a> (DGM) asks a more ambitious question:</p><blockquote><em>What if the agent that solves coding tasks also modifies the code that defines the agent?</em></blockquote><p>This is often termed as self-referential agent improvement. A coding agent inspects its failures, edits its own repository, evaluates the modified version, and allows successful descendants to perform future self-modifications. But the paper’s most important contribution is not self-editing alone. It is the search strategy around self-editing.</p><p>DGM maintains an archive of many agent versions. It can revisit an imperfect ancestor, branch in a different direction, and preserve changes that are not immediately useful. This lets the system cross performance valleys that defeat greedy hill climbing. That is the central lesson: <strong>a self-improving system needs both inheritance and diversity.</strong></p><h4>1. From a Gödel machine to a Darwinian one</h4><p>The original Gödel machine is a theoretical system that rewrites itself only after proving that the rewrite will improve its objective. That guarantee is largely impractical for real use-cases like coding. For a real coding agent, proving that a new tool or workflow will help across an unknown distribution of repositories is generally impossible.</p><p>A candidate self-modification is executed and evaluated on coding benchmarks. If it remains functional, it enters a growing archive of possible parents. Natural selection replaces formal verification:</p><ol><li>Select an existing agent.</li><li>Diagnose its failures.</li><li>Ask it to modify its own code.</li><li>Test the resulting child.</li><li>Preserve viable children in the archive.</li><li>Repeat from different points in the archive.</li></ol><p>This is a compromise : The system does not know that a change is universally beneficial. It only has <strong>empirical evidence</strong> that the modified agent performs better on a chosen evaluation.</p><h4>2. What actually evolves?</h4><p>The underlying foundation models remain frozen. What evolves is the coding-agent scaffold around them such as:</p><ul><li>File-viewing and editing tools</li><li>Prompts and instructions</li><li>Retry and validation logic</li><li>Context-window management</li><li>Candidate generation and ranking.</li></ul><p>The initial agent is simple. It has a Bash tool and a basic editor that can view or replace entire files. Over successive generations, DGM discovers practical improvements that experienced agent engineers would recognize.</p><p>It adds line-range file viewing and precise string replacement. It validates that patches are non-empty and retries failed edits. It summarizes history when the context window is exhausted. It generates multiple candidate patches and uses another model to rank them.</p><p>Later versions condition new attempts on earlier failures. These are not exotic new reasoning algorithms. They are good pieces of agent engineering. The notable result is that the system discovers and combines them automatically.</p><h4>3. Why this is self-referential ?</h4><p>Suppose one generation acquires a better editing tool. That tool helps it solve benchmark tasks, but it also helps the agent edit its own repository more accurately in the next generation. A better context-management strategy similarly helps with both downstream coding and future self-modification. The improvement can therefore compound:</p><blockquote><em>Better agent code produces a better self-editor, which can produce better agent code.</em></blockquote><p>This closes a self-referential loop at the agent-scaffold level. The recursion is still incomplete. <em>A separate fixed model diagnoses improvement opportunities from evaluation logs.</em> The archive policy and parent-selection algorithm are also fixed. DGM evolves the coding agent, not the full evolutionary process that surrounds it. It is a bounded self-modifying subsystem inside a human-designed experimental loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUtr73JndaZpuCVH4uIr9g.gif" /><figcaption>DGM</figcaption></figure><h4>4. Maintaining agent archive is the real change</h4><p>A naive self-improving agent would keep only its latest or best version. The policy would look like:</p><blockquote><em>Modify the current agent. Keep the change if the score improves. Otherwise revert.</em></blockquote><h4>4.1 The flaw in monotonic optimization</h4><p>Monotonic hill climbing discards any change that doesn’t yield an immediate gain. However, major breakthroughs: like adding new tools, reviewer steps, or context summarization, often cause temporary performance drops before their full benefits are realized. Single, isolated adjustments frequently look harmful until combined with follow-up changes.</p><h4>4.2 How DGM avoids it ?</h4><p>The Darwinian Gödel Machine (DGM) avoids this trap by keeping promising lineages alive:</p><ul><li><strong>Balanced Selection:</strong> It selects parent agents using high benchmark scores (<strong>exploitation</strong>) while giving a bonus to lineages with fewer explored children (<strong>exploration</strong>).</li><li><strong>Non-Monotonic Progress:</strong> This allowed DGM’s top-performing SWE-bench agent to survive two consecutive performance drops: a path a greedy optimizer would have prematurely abandoned.</li></ul><p>Like natural selection, DGM does not require every mutation to be an instant upgrade. It relies on variation, inheritance, selection, and preserved diversity to allow complex, multi-step innovations to emerge over time.</p><p>To understand <em>why</em> DGM works, the authors compared <strong>Full DGM</strong> against a <strong>Fixed Modifying Agent</strong> baseline:</p><p>These results support two separate claims.</p><ol><li>Allowing improved agents to perform later self-modifications works better than using the same fixed meta-agent throughout the search.</li><li>Preserving multiple lineages works better than greedily extending only the latest or best agent.</li></ol><p>The discovered scaffolds also transferred to other foundation models and task slices, although the gains varied substantially. This is useful evidence that DGM did not merely overfit one exact model-agent pairing.</p><h4>5. Lesson for autoresearch systems: Overcoming the valley trap</h4><p>Most automated research and AutoML loops rely on <strong>monotonic hill climbing</strong>: they propose a change, test it, and discard it unless performance instantly improves. This greedy approach fails when breakthroughs require <strong>coordinated, multi-step changes</strong> where individual steps look like downgrades on their own:</p><p><strong>Example (Improving a transformer model):</strong></p><ul><li><em>Increasing sequence length alone</em> =&gt; Harder optimization.</li><li><em>Expanding the model backbone alone</em> =&gt; Overfitting.</li><li><em>Lowering the learning rate alone =&gt; </em>Too slow to converge.</li><li><strong>Combining all three changes together</strong> =&gt; Better performance.</li></ul><p>A standard optimizer rejects every step into this configuration. DGM’s archive-based search preserves these intermediate “failures” until the missing pieces come together.</p><h4>6. How DGM samples from its archive ?</h4><blockquote><em>Prefer capable agents, but reduce the priority of agents that have already produced many children.</em></blockquote><p>DGM normalizes weights into a probability distribution and samples parents with replacement. It uses two parent samples per iteration on SWE-bench and four on Polyglot. Each selected parent modifies a copy of its own implementation. A functioning child can enter the archive even when it performs worse than its parent.</p><h4>Example recipe</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LF82bzMmmX3OI9FKbfI3g.png" /></figure><p>Agent D has better accuracy. But it has already produced five functioning children. Agent B is approximately 3.2 times (0.269/0.083) more likely to be sampled before normalization against the rest of the archive. A possible trajectory is:</p><pre>Agent B: 40%<br>Precise substring editing<br>        ↓<br>Agent B1: 37%<br>Add patch validation and retry logic<br>        ↓<br>Agent B2: 47%<br>Generate several patches and rank them</pre><p>B1 is initially worse than B, but remains viable and enters the archive. Because B1 is underexplored, DGM may sample it later. A complementary modification can then turn its initially harmful mechanism into a stronger agent. DGM’s archive policy simply ensures that the 37% stepping stone is not permanently eliminated.</p><p>DGM provides a recipe for self-improving AI: a process driven by diverse hypotheses, parallel branches, preserved failures, and intelligent selection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c08744932c06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/darwin-g%C3%B6del-machines-why-self-improving-agents-need-to-keep-their-mistakes-c08744932c06">What do Self-Improving Agents learn from their mistakes ?</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent Compute: Think Longer, Branch Wider, or Verify Harder ?]]></title>
            <link>https://medium.com/better-ml/agent-compute-think-longer-branch-wider-or-verify-harder-a064d91b98e2?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a064d91b98e2</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[thinking]]></category>
            <category><![CDATA[autoresearch]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 23:07:49 GMT</pubDate>
            <atom:updated>2026-07-17T23:32:53.703Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>where should an agent spend its next unit of compute ?</em></strong></blockquote><p>Imagine an agent trying to fix a software bug. After ten minutes, it has a plausible diagnosis, a patch, and one stubbornly failing test. You can give it another ten minutes. What should it do with them?</p><p>It could keep working from the same hypothesis. It could start a few fresh attempts and hope one takes a better path. It could run more tests, inspect logs, or search the documentation. Or it could stop generating ideas and spend the time checking the candidates it already has.</p><p>All four choices count as more inference compute. They do not buy the same thing.</p><p>That distinction tends to disappear when models are compared by a single accuracy or pass-rate number. The score tells us how often a system succeeded, but not how much work it was allowed to do before answering or how that work was organized. A million tokens poured into one long trajectory is a very different system from a hundred short attempts run in parallel. A system that generates five patches and tests them carefully is different again.</p><blockquote><strong><em>Given a fixed budget, where should an agent spend its next unit of compute?</em></strong></blockquote><h3>One budget, four different bets</h3><p>For most agent workloads, extra compute goes to some mixture of depth, breadth, interaction, and checking. It helps to look at each one separately.</p><h3>Think longer</h3><p>The simplest option is to extend the current trajectory: inspect another file, refine the hypothesis, make an edit, run a test, and revise. This is a good fit when progress is cumulative. In debugging, for example, the result of one test often determines the next useful test. Restarting from scratch would throw away context the agent worked to acquire.</p><p>The risk is path dependence. If the agent misunderstood the problem early, more tokens can make it more committed to the wrong explanation. Long reasoning traces often look productive because they contain many steps. That does not mean those steps are moving in the right direction.</p><p>Depth works best when the environment provides frequent feedback and the agent is actually using it. Without that feedback, “think longer” can become an expensive way to elaborate the first guess.</p><h3>Branch wider</h3><p>Instead of extending one attempt, the system can launch several independent ones. One branch might investigate a race condition; another might suspect a schema mismatch; a third might trace a recent dependency change. This is the intuition behind best-of-N sampling: diversity increases the chance that at least one attempt finds a good path.</p><p>Branching is attractive when there are several plausible hypotheses, individual attempts are cheap, and parallel hardware is available. Ten one-minute attempts may have roughly the same total trajectory time as one ten-minute attempt, yet return in close to one minute.</p><p>But breadth introduces a selection problem. Producing the right answer somewhere in a batch is not enough. The system still has to recognize it. A weak selector can erase most of the gain from sampling, which is why best-of-N results should always be read alongside the quality of the verifier.</p><h3>Use tools</h3><p>Agents can also spend their budget by interacting with the world: running code, querying a database, inspecting logs, browsing documentation, or calling a simulator. A useful tool result can be worth far more than another page of internal reasoning. A compiler error can kill a bad hypothesis immediately. A unit test can expose an edge case that a fluent explanation missed.</p><p>Tools are valuable because they add information. They also add latency, infrastructure cost, security concerns, and new ways to fail. An agent that reaches for a tool after every uncertain thought may spend most of its budget collecting evidence that never changes the answer. The relevant question is not whether a tool call is available, but whether its result is likely to change the next decision.</p><h3>Verify harder</h3><p>The fourth option is to spend compute on evaluation rather than generation. The system might run tests against candidate patches, check mathematical constraints, ask another model to critique an answer, apply static analysis, or compare several solutions with a judge model.</p><p>This is often where an apparently capable agent breaks down. Suppose ten generated patches include one correct fix. From the generator’s point of view, the task has been solved. If the verifier ranks a broken patch first, the deployed system still fails.</p><p>I find it useful to separate two quantities: the probability that a correct answer was generated, and the probability that the system selected it. The distance between them is the <strong>generation–verification gap</strong>. As candidate generation becomes cheaper, that gap becomes harder to ignore.</p><p>The best checks usually introduce evidence the generator did not already have: hidden tests, formal constraints, retrieved sources, deterministic rules, or a genuinely independent model. Asking the same model to reread its own answer can help, but agreement is weak evidence when both passes share the same blind spot.</p><h3>Compute is not a single number</h3><p>“Use more compute” sounds precise until a system has to be deployed. In practice, builders work with several budgets at once:</p><ul><li><strong>Tokens:</strong> how much context and output the system may consume.</li><li><strong>Money:</strong> the acceptable cost per task or per successful result.</li><li><strong>Latency:</strong> how long the user can wait.</li><li><strong>Tool calls:</strong> how many searches, executions, or external requests are allowed.</li><li><strong>Concurrency:</strong> how many trajectories can run at the same time.</li></ul><p>These constraints are not interchangeable. One ten-minute trajectory and ten one-minute trajectories may consume similar total compute, but they feel completely different to a user if the shorter attempts run in parallel. The parallel version spends more concurrency to buy lower wall-clock latency. The sequential version preserves context and may make better use of intermediate feedback.</p><figure><img alt="A hand-drawn diagram showing an agent compute budget split across thinking, branching, tools, and verification" src="https://cdn-images-1.medium.com/proxy/1*oDMP5JzF4_ekPa1V2z845w.png" /><figcaption>A fixed compute budget can be spent on depth, breadth, tools, or verification.</figcaption></figure><p>This is why there is rarely one best configuration. Real systems live on a frontier: improving quality may cost more money; cutting latency may require more parallel hardware; stronger verification may reduce errors while delaying the response. The right point depends on the product.</p><h3>Match the strategy to the task</h3><p>Long sequential work is most useful when later steps depend heavily on earlier observations. Repository exploration, multi-step data analysis, interactive theorem proving, and debugging with repeated test execution all have this shape. Each useful observation narrows the next move, so a fresh branch would lose valuable state.</p><p>Breadth is a better bet when the solution space contains genuinely different hypotheses and attempts are only weakly dependent on one another. Candidate code patches, competition-style math solutions, alternate query interpretations, and planning problems often benefit from this treatment. The caveat is the same every time: diversity without reliable selection is just noise.</p><p>Verification deserves a larger share of the budget when errors are expensive and correctness can be tested objectively. Code is unusually friendly here because patches can be compiled and run. Some mathematical answers admit symbolic or numerical checks. Database queries can be checked against schemas and constraints.</p><p>Open-ended research summaries are harder. A response can be polished, internally consistent, and subtly wrong. Two model judges may agree because they learned the same shortcut. In those domains, verification should lean on external sources and explicit evidence instead of stylistic confidence.</p><h3>The hardest tasks may be a poor investment</h3><p>It is tempting to route the most compute to the hardest problems. That is not always where the return is highest.</p><p>Easy tasks usually need one short attempt. Extra branches mostly reproduce the same correct answer. At the opposite extreme, a task may require knowledge, tools, or representations the model simply does not have. One hundred variations of the same broken approach will not cross that gap.</p><p>The best return often comes from the middle: tasks near the system’s capability boundary. A little more investigation might uncover the missing fact. A second branch might escape a local pattern. One decisive test might distinguish two plausible patches.</p><p>That makes compute allocation an estimation problem. Is the current answer probably correct? Is the trajectory still making measurable progress? Would a new branch explore something different? Can a check resolve the remaining uncertainty? At what point is the expected improvement smaller than the expected cost?</p><h3>Fixed recipes are easy. Adaptive routing is better.</h3><p>Rules such as “always generate eight candidates” or “always run three critique rounds” are convenient, especially in a benchmark. They are also wasteful. Most tasks do not need the same treatment.</p><p>A practical controller can start cheaply and escalate only when the evidence calls for it:</p><ol><li>Run one inexpensive attempt.</li><li>Apply a lightweight check.</li><li>Stop if the result is clearly good enough.</li><li>If the failure is localized, continue the current trajectory and revise.</li><li>If the agent appears stuck or candidates disagree, branch or invoke a stronger verifier.</li></ol><p>That controller is doing more than solving the task. It is choosing an economical way to solve it. In a mixed workload, this scheduling policy may matter as much as the underlying model.</p><h3>Benchmarks should show curves, not just scores</h3><p>A single success rate hides all of these choices. A system that solves 50 percent of tasks for $0.20 each is not equivalent to one that solves 52 percent for $20. A response in thirty seconds is not equivalent to the same response after forty minutes.</p><p>Useful agent evaluations should report performance across several budget levels. At minimum, I would want to see success versus cost, tokens, wall-clock latency, and tool calls.</p><p>Tail latency and cost per solved task matter too. “Agent X scored 48 percent” tells a deployment team very little. “Agent X reached 40 percent at $0.30, 46 percent at $1.20, and 48 percent at $5, with most gains arriving before the second budget increase” is a much more useful result.</p><h3>An experiment worth running</h3><p>A clean comparison would hold the base model and task set fixed, then vary only the inference strategy. On a software-engineering benchmark, for example, compare five systems:</p><ul><li><strong>Single trajectory:</strong> one long attempt.</li><li><strong>Sequential refinement:</strong> edit, test, and revise repeatedly.</li><li><strong>Parallel sampling:</strong> several shorter independent attempts.</li><li><strong>Verification-heavy:</strong> fewer candidates with more testing and ranking.</li><li><strong>Adaptive:</strong> branch or verify only when the current evidence calls for it.</li></ul><p>Run the comparison once under an equal monetary or token budget, again under an equal wall-clock deadline, and again with the same number of tool calls. The winner will probably change. Sequential refinement should do well when tests provide useful intermediate feedback. Sampling should help when different hypotheses matter. Verification-heavy systems should shine when correctness is objectively testable. An adaptive policy should be the most robust across a mixed task set.</p><p>The interesting output is not a champion. It is the shape of the frontier and the conditions under which each strategy earns its cost.</p><h3>The system matters more than the model name</h3><p>An agent’s capability comes from the whole inference system: the model, prompt, tools, search strategy, verifier, stopping rule, scheduler, and budget. Changing any one of them can change the result.</p><p>A smaller model with a disciplined execution loop and reliable tests can outperform a stronger model used in a single pass. The reverse is also true: an elaborate agent loop can burn through tokens and tool calls while adding almost no value.</p><p>More inference compute helps when it is spent on the bottleneck. Sometimes that means staying with a promising line of reasoning. Sometimes it means starting over in parallel. Sometimes the right move is to stop generating and check the work. And sometimes the answer is simply to stop.</p><p>The next generation of agents will not be defined only by how long they can think. The more important skill will be knowing when to continue, when to explore, when to verify, and when another unit of compute is no longer worth buying.</p><h3>How frontier systems allocate test-time compute</h3><p>Public disclosures do not reveal the complete production schedulers behind ChatGPT, DeepSeek, Gemini, or Claude. They do reveal enough pieces to see a common pattern: route first, reason with a task-dependent budget, use tools when they can add information, and spend verification compute when several plausible answers remain.</p><ul><li><a href="https://arxiv.org/abs/2408.03314"><strong>Compute-optimal test-time scaling</strong></a><strong>.</strong> Snell and colleagues estimate prompt difficulty and change the allocation between sequential revision, parallel sampling, and verifier-guided search. Easy questions often favor revision; harder but still tractable questions benefit from a mixture of sequential and parallel work. Their prompt-dependent policy used up to four times less compute than a uniform best-of-N baseline for comparable performance.</li><li><a href="https://arxiv.org/abs/2501.12948"><strong>DeepSeek-R1</strong></a><strong>.</strong> DeepSeek trains the model with reinforcement learning so that longer reasoning, reflection, and self-correction emerge inside a single trajectory. It can also <strong>spend more compute outside that trajectory by sampling several solutions and applying majority voting</strong>. The paper reports that majority voting raised DeepSeek-R1-Zero’s AIME 2024 score from 71.0 to 86.7 percent. It does not describe a deployed controller that dynamically chooses the reasoning length or number of samples for every request.</li><li><a href="https://arxiv.org/abs/2504.02495"><strong>DeepSeek-GRM</strong></a><strong>.</strong> This work allocates <strong>extra compute to verification</strong>. A generative reward model produces task-specific principles and critiques; parallel sampling creates several evaluations; and a meta-reward model guides the final vote. In other words, the additional budget is spent making the judge stronger rather than merely generating more candidate answers.</li><li><a href="https://openai.com/index/gpt-5-system-card/"><strong>GPT-5 in ChatGPT</strong></a><strong>.</strong> OpenAI describes a <strong>real-time router that chooses between a fast model and a deeper reasoning model. The decision uses conversation type, apparent complexity, tool requirements, and explicit intent such as a request to “think hard.”</strong> This is the clearest public example of a product-level compute controller: simple requests take the cheaper path, while harder requests are routed to a model allowed to spend more inference compute.</li><li><a href="https://openai.com/index/introducing-o3-and-o4-mini/"><strong>OpenAI o3 and o4-mini</strong></a><strong>.</strong> These models <strong>allocate compute within a longer reasoning trajectory and across tool calls. </strong>Reinforcement learning teaches them not only how to call web search, Python, file analysis, and other tools, but when those calls are useful. OpenAI also exposes reasoning-effort settings, which let the surrounding system trade latency and cost for deeper reasoning. The exact internal stopping policy remains private.</li><li><a href="https://openai.com/index/introducing-deep-research/"><strong>OpenAI deep research</strong></a><strong>.</strong> Deep research spends its budget <strong>on a long, environment-grounded trajectory. It searches, reads sources, uses Python, backtracks, and changes direction in response to evidence.</strong> OpenAI reports performance as a function of maximum tool calls, making the tool budget an explicit axis of test-time scaling. The public description explains the learned behavior but not the precise rule that decides when the research is complete.</li><li><a href="https://ai.google.dev/gemini-api/docs/thinking"><strong>Gemini dynamic thinking</strong></a><strong>.</strong> Google documents a dynamic mode that <strong>adjusts reasoning effort according to request complexity</strong>. Developers can also choose explicit thinking levels when they need tighter control over latency, cost, or reasoning depth. This makes the allocation decision partly model-driven and partly a product or application policy.</li><li><a href="https://www.anthropic.com/news/claude-opus-4-6"><strong>Claude adaptive thinking</strong></a><strong>.</strong> Anthropic’s adaptive-thinking mode lets <strong>Claude decide when extended reasoning is useful, while effort levels make the system more or less selective about using it</strong>. For work that separates cleanly, Claude’s agent teams add a second allocation mechanism: multiple agents can run independent subtasks in parallel.</li></ul><h3>The research ideas underneath these systems</h3><p>Several earlier papers isolate the mechanisms now appearing together in frontier products. <a href="https://arxiv.org/abs/2110.14168">Training Verifiers to Solve Math Word Problems</a> generates many solutions and spends additional compute selecting one with a learned verifier. <a href="https://arxiv.org/abs/2203.11171">Self-Consistency</a> samples diverse reasoning paths and chooses the answer with the strongest agreement. <a href="https://arxiv.org/abs/2305.10601">Tree of Thoughts</a> branches, scores, and backtracks over intermediate reasoning states. <a href="https://arxiv.org/abs/2210.03629">ReAct</a> alternates reasoning with actions so that observations from tools can change the plan.</p><p>Taken together, these systems point toward a layered design: an outer router selects the mode or model, the reasoning model controls depth, an agent loop decides whether to seek external evidence, and a verifier or voting procedure resolves disagreement. The broad design is visible. The thresholds, confidence models, stopping rules, and production economics are still mostly proprietary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a064d91b98e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/agent-compute-think-longer-branch-wider-or-verify-harder-a064d91b98e2">Agent Compute: Think Longer, Branch Wider, or Verify Harder ?</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language as the Gradient: From text generation to autonomous execution]]></title>
            <link>https://medium.com/better-ml/language-as-the-gradient-from-text-generation-to-autonomous-execution-d7720ada7d5e?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7720ada7d5e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 21:09:30 GMT</pubDate>
            <atom:updated>2026-07-08T21:09:45.073Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building General-Purpose Problem Solvers</h4><p>We are moving away from models designed for isolated pattern recognition and toward unified architectures capable of sequential decision-making. At the heart of this transition is a powerful, highly generalized recipe: <strong>Reinforcement Learning (RL) combined with Transformer architectures</strong>.</p><p>Together, these technologies turn disparate, complex tasks into a singular, repeatable pattern. By observing a state, reasoning over context, executing an action, and updating policies based on environmental feedback, we can build robust, general-purpose problem solvers.</p><h3>1. The Transformer: A Programmable Substrate</h3><p>To build a general solver, you first need a flexible model capable of unifying diverse data modalities. The Transformer serves as this <strong>programmable substrate</strong>.</p><p>By mapping complex inputs and outputs to a shared token vocabulary, Transformers establish text — or, more broadly, tokens — as a <strong>universal interface</strong>. This interface can elegantly represent:</p><ul><li><strong>States:</strong> The current context of an environment or problem.</li><li><strong>Actions:</strong> Code to execute, API calls to make, or robotic movements to trigger.</li><li><strong>Plans &amp; Programs:</strong> Long-term strategic reasoning or workflow definitions.</li><li><strong>Feedback:</strong> Natural language critiques, error logs, or compiler warnings.</li></ul><p>Because Transformers are adept at in-context learning and sequence modeling, they are perfectly suited to read these representations, maintain an understanding of the state, and generate subsequent tokens that dictate the next logical action.</p><h3>2. The Limits of Next-Token Prediction</h3><p>Despite their flexibility, Transformers trained solely on next-token prediction are fundamentally limited when it comes to long-horizon problem-solving. Next-token prediction is an exercise in imitation; it aims to mimic the statistical distribution of the training data.</p><p>While it can approximate reasoning, it does not inherently provide <strong>goal-directed pressure</strong>. When an agent must navigate a complex environment, write and debug functional code, or prove a mathematical theorem, success is strictly defined by the final outcome — not by how mathematically probable the sequence of text was. To achieve true problem-solving capabilities, the model must transition from passive imitation to active optimization.</p><h3>3. Reinforcement Learning: The Goal-Directed Engine</h3><p>Reinforcement Learning supplies the optimization loop that next-token prediction lacks. Instead of training a model on static, isolated examples, RL places the Transformer in dynamic environments where it must:</p><ol><li>Try an action (or sequence of actions).</li><li>Interact with an environment (e.g., a compiler, a game engine, or a web browser).</li><li>Receive scalar rewards or verifier feedback.</li><li>Improve its behavior over full trajectories.</li></ol><p>In this architecture, the Transformer is the engine, while RL acts as the steering wheel, aggressively optimizing for outcomes. This combination is particularly potent for autonomous agents, ML engineering tasks, and tool use, where the definition of “correct” is grounded in execution rather than linguistic fluency.</p><h3>4. Overcoming Non-Differentiability with TextGrad</h3><p>A significant hurdle in applying RL to text-based environments and tool use is the non-differentiable nature of the environment. You cannot easily backpropagate an error signal through an external compiler or a black-box API.</p><p>This introduces the need to frame text-representable tasks as optimization problems using <strong>TextGrad-based reinforcement learning</strong>. TextGrad solves the credit assignment problem over non-differentiable trajectories by using language itself as the gradient.</p><p>In a TextGrad-powered RL loop, the process looks like this:</p><ul><li><strong>Generation:</strong> An agent proposes a textual artifact (e.g., a block of code, a plan, a model configuration).</li><li><strong>Execution:</strong> The artifact is executed in a tool-mediated environment.</li><li><strong>Evaluation:</strong> The system receives scalar rewards from automated tests or verifiers.</li><li><strong>Textual Credit Assignment:</strong> Instead of numerical gradients, the system generates <strong>textual gradients</strong>. A verifier model explains the specific source of failure in natural language and suggests local, targeted repairs.</li><li><strong>Optimization:</strong> The RL loop continues to drive exploration and reward maximization, while TextGrad provides the high-fidelity, natural-language feedback necessary to iteratively optimize prompts, policies, research workflows, and action sequences.</li></ul><p>Example: <strong>Application to a database query task, broken down into exactly five steps.</strong></p><ol><li><strong>Generation:</strong> An AI agent is tasked with finding the top five highest-spending customers and generates an initial textual artifact (a SQL query): SELECT name FROM customers ORDER BY revenue LIMIT 5;</li><li><strong>Execution:</strong> The query is run against an external, black-box database engine — a non-differentiable environment where standard backpropagation cannot be used.</li><li><strong>Evaluation:</strong> The database execution fails and returns an error message (ERROR: column &quot;revenue&quot; does not exist), resulting in the system assigning the attempt a scalar reward of 0 (failure).</li><li><strong>Textual Credit Assignment:</strong> A verifier model generates a “textual gradient” to explain the failure and suggest a targeted repair: <em>“Your query failed because the database column is named ‘total_sales’, not ‘revenue’, and you must add ‘DESC’ to sort by the highest spenders.”</em></li><li><strong>Optimization:</strong> The agent uses this natural language feedback to update its approach, generating a new, successful query (SELECT name FROM customers ORDER BY total_sales DESC LIMIT 5;) and earning a reward of 1.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SP69hMz3z5v_tunRVje2kQ.png" /><figcaption>TextGrad + RL</figcaption></figure><h3>5. A different Paradigm for Optimization</h3><p>Next token prediction is incredibly powerful, but this approach is inherently limited when we ask AI to step outside of text generation and interact with external systems. As we shift toward autonomous, agentic workflows, a new framework has emerged to bridge this gap: the <strong>TextGrad-powered Reinforcement Learning (RL) loop</strong>.</p><p>Here is how these two paradigms fundamentally differ, and why this shift is so critical.</p><ol><li><strong>From Guessing to Achieving (The Objective)</strong></li></ol><p>Instead of optimizing for statistical likelihood, Textgrad + RL is explicitly designed to <strong>maximize outcome-based rewards</strong>, ensuring the agent’s outputs actually achieve a tangible goal.</p><p><strong>2. Text as an Action, Not Just an Output (The Interface)</strong></p><p>In standard models, the interface is simply natural language strings; you provide text, and the model returns text. In a TextGrad RL loop, text transforms into executable actions and states. A generated string isn’t just an essay or a poem; it’s a piece of code to be compiled, a database query to run, or an actionable step in a larger plan.</p><p><strong>3. Language as the Gradient (The Feedback Mechanism)</strong></p><p>Standard models learn through mathematical backpropagation, adjusting numerical weights against ground-truth training data. However, you cannot backpropagate through a black-box API or a live software environment. TextGrad solves this by replacing mathematical gradients with <strong>verifier rewards and textual gradients</strong>. When an action fails, the system doesn’t rely on a simple numerical penalty; instead, a verifier model uses natural language to explain exactly <em>why</em> it failed and <em>how</em> to fix it on the next attempt.</p><p><strong>4. Navigating Complexity (The Problem Horizon)</strong></p><p>Next-token prediction excels in short horizons, perfectly suited for handling isolated, single-turn prompts and responses. Conversely, TextGrad-RL is built for the <strong>long game</strong>. It enables AI agents to navigate complex, multi-step trajectories, retaining context, processing feedback, and adjusting strategies over numerous iterations until the overarching task is complete.</p><p>Ultimately, traditional next-token models remain the undisputed champions of <strong>knowledge retrieval and drafting</strong>. But when you need a system capable of reliable <strong>execution, iterative debugging, and autonomous solving</strong>, the TextGrad + RL loop provides the necessary architecture, giving AI the feedback mechanisms it needs to interact successfully with the real world.</p><blockquote><strong><em>The Takeaway:</em></strong><em> </em>By marrying the flexible substrate of Transformers with the goal-directed optimization of RL and the interpretability of TextGrad, we are laying the foundational architecture for the next generation of autonomous problem solvers.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7720ada7d5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/language-as-the-gradient-from-text-generation-to-autonomous-execution-d7720ada7d5e">Language as the Gradient: From text generation to autonomous execution</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Retrieval Divergence Problem: Why Rank Fusion Matters More in the LLM Era ?]]></title>
            <link>https://medium.com/better-ml/the-retrieval-divergence-problem-why-rank-fusion-matters-more-in-the-llm-era-315eeceb9cb8?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/315eeceb9cb8</guid>
            <category><![CDATA[rankings]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[recsys]]></category>
            <category><![CDATA[inference]]></category>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 22:16:21 GMT</pubDate>
            <atom:updated>2026-07-06T22:16:42.332Z</atom:updated>
            <content:encoded><![CDATA[<h4>1. The Widening Gap in retrievers</h4><p>In traditional search architecture, using multiple retrievers often meant getting slightly different flavors of the same results. A keyword retriever might find a document based on its title, while a graph retriever might find the exact same document because it was heavily cited. There was usually a significant overlap in the retrieved lists.</p><p>However, as Small / Large Language Models (SLMs / LLMs) and advanced neural retrieval systems have entered the stack, this overlap is shrinking rapidly. The documents retrieved by different sources are becoming <strong>fundamentally different</strong>, and this divergence is increasing as LLMs unlock deep semantic connections. Here is why different retrieval sources diverge, and why LLMs are accelerating this trend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrk0nGEh_Mn3WrGtjQuijw.png" /><figcaption>LLMs widening gap in retrievers</figcaption></figure><h4>2. The Baseline: Mechanical Differences in Retrieval</h4><p>Even before LLMs, different systems naturally pulled different documents because they looked for entirely different signals:</p><ul><li><strong>Lexical Retrievers (BM25):</strong> Look for exact vocabulary matches and term frequency. They are highly literal.</li><li><strong>Knowledge Graphs:</strong> Look for structured relationships (e.g., “Company X is owned by Parent Y”).</li><li><strong>Collaborative Filtering:</strong> Looks at human behavioral signals (e.g., “Users who clicked this also clicked that”).</li></ul><p>A lexical search for “fixing a leaking pipe” will heavily bias toward DIY articles that repeat the words “fix,” “leak,” and “pipe.”</p><h4>3. The LLM Shift: From Vocabulary to Deep Intent</h4><p>The introduction of LLM-based retrieval: such as advanced cross-encoders, late-interaction models with LM (language models), and GR (generative retrieval): shifted search from matching <em>text</em> to matching <em>intent</em>.</p><p>As LLMs develop a deeper understanding of semantic connections, the lists they generate look increasingly alien compared to traditional keyword lists.</p><p>This happens in three distinct ways:</p><p><strong>1. The Zero-Overlap Phenomenon</strong> LLMs can identify perfect answers that share absolutely no keywords with the user’s query. If a user searches for <em>“why is my coffee tasting excessively bitter and metallic,”</em> a lexical search will look for “bitter” and “metallic.” An LLM understands the underlying chemical process of over-extraction or burr grinder friction. It might retrieve a highly technical barista manual about “adjusting extraction yield and grind uniformity.” The lexical and semantic retrieval lists will have near-zero overlap, yet both might be useful.</p><p><strong>2. Domain specialization of embeddings: </strong>Traditional dense embeddings <strong><em>often struggle</em></strong> with words that have multiple meanings, relying on broad proximity. Modern LLMs process the entire sequence of a query to lock in the exact context. For a query like <em>“Python performance in tight loops,”</em> an LLM immediately discards any zoological context and retrieves highly specific software optimization guides. A weaker retriever might still pull a mix of programming and snake-related documents if the exact keyword overlaps are strong enough.</p><p><strong>3. Implicit Problem Solving:</strong> Humans often search for symptoms, but they want cures. LLMs bridge this gap through multi-hop semantic reasoning. If an employee searches the corporate intranet for <em>“can’t access HR portal 403 error,”</em> a keyword engine retrieves the IT manual page for “403 Errors.” An LLM-based retriever understands that a 403 on the HR portal usually indicates an expired VPN session, and retrieves the “How to reset your VPN token” document.</p><h4>4. The Consequence for Recsys Architecture</h4><p>As LLMs become better at uncovering these deep, non-obvious connections, the disparity between retrieval lists is expanding.</p><p>This growing gap is exactly why <strong>rank fusion</strong> has become the backbone of modern search. A system can no longer just assume that a document is highly relevant because it appears in every retriever’s list. Instead, the architecture must trust that the LLM is finding profound semantic matches, while relying on the lexical retriever to ground the search and prevent AI hallucinations.</p><p>By combining highly literal, keyword-dense documents with deep, conceptually-matched documents, systems can deliver a final ranked list that satisfies both the mechanics of the user’s query and the true intent behind it.</p><p>So, this boils down to one critical question:</p><h4><strong>How do we merge multiple ranked lists into one better ranking?</strong></h4><p>This seemingly simple problem has driven nearly three decades of research. Solutions have evolved from simple voting schemes to fully learned ranking systems that optimize business metrics directly. You can think of this evolution as five successive levels of sophistication, moving from simplicity to high-quality, data-driven complexity.</p><h4>5. Why Rank Fusion Exists ?</h4><p>Imagine searching for: <strong>“best restaurants near Stanford serving ramen.”</strong></p><ul><li><strong>Lexical retriever (BM25):</strong> Excels at exact keyword matches.</li><li><strong>Dense retriever:</strong> Understands semantic similarity and context.</li><li><strong>Location retriever:</strong> Knows geographic relevance.</li><li><strong>Popularity model:</strong> Knows user preferences and trends.</li></ul><p>Each system retrieves useful — but entirely different — documents. Rank fusion solves the problem of combining these disparate results to produce one superior ranking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpXWhXTJvPGHC4iUmpw5Tg.png" /></figure><h4>5.1 Baseline: Single Retriever</h4><p>The simplest system doesn’t fuse anything. You simply choose one retrieval method (e.g., query to BM25, or query to Dense Retriever) and return the ranked list.</p><ul><li><strong>Advantages:</strong> It features the simplest architecture, is very fast, and is easy to debug.</li><li><strong>Disadvantages:</strong> It misses complementary information from other methods, and a single retrieval failure ruins recall entirely.</li></ul><p>This was the standard for classical search engines, but modern demands quickly outgrew it.</p><h4>5.2 Level 1: Unsupervised Fusion</h4><p>The first major advance was realizing that agreement between retrievers is highly valuable. Instead of trusting raw scores — which often aren’t directly comparable across different algorithms — we combine the rankings themselves. This family of methods requires no training data.</p><p><strong>Reciprocal Rank Fusion (RRF)</strong></p><p>Instead of using scores, every document receives a value based on its position in the list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*F0oOjfVTzl3u6QeXnYn9vQ.png" /><figcaption>Reciprocal Rank Fusion</figcaption></figure><ol><li>Where <strong>r_i(d)</strong> is the rank from retriever i, and k is a constant (usually <strong>60</strong>). High-ranked documents consistently appearing across <strong>multiple retrievers</strong> naturally float upward. The beauty of RRF is that score normalization is completely unnecessary.</li><li>If a <strong>document</strong> is not retrieved by system i, its rank r_i is treated as <strong>infinity</strong>. Consequently, the fraction rrf evaluates to <strong>0</strong>. The document <strong>simply gets no points from that retriever</strong>, but it keeps whatever score it earned from the systems that <em>did</em> retrieve it.</li><li>Some implementations assign a default penalty rank. If a retriever only returns the top K documents (e.g., Top 100), any document not in that list is assumed to be at rank <strong>K + 1</strong> (e.g., Rank 101) or is given the rank of the total corpus size. This is particularly common when training Learning-to-Rank (LTR) models, where a feature column cannot simply be left blank (NaN) and requires a fixed numeric value.</li></ol><p>Unsupervised methods are production-friendly, robust, and require no labels. They are surprisingly difficult to beat, which explains why RRF remains extremely popular.</p><h4>5.3 Level 2: Query adaptive Fusion</h4><p>Modern systems recognize that one fusion strategy doesn’t fit every query. Some queries are lexical (“RTX 5090”), while others are semantic (“movies about loneliness”). Adaptive fusion changes the approach dynamically.</p><ul><li><strong>Dynamic Alpha:</strong> Predict a specific weight based on the query itself, assigning higher lexical weights for exact-match searches and higher dense weights for conceptual searches.</li><li><strong>Query Routers:</strong> Rather than combining everything, a router chooses which retrievers should even participate.</li><li><strong>Weighted RRF:</strong> Instead of equal votes, assign retriever-specific weights to the RRF calculation:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*Z85dkSgtAE_hbDsi5OzN6g.png" /><figcaption>Weighted Reciprocal Rank fusion</figcaption></figure><p>Adaptive fusion is query-aware, robust, and significantly improves long-tail performance.</p><h4>5.4 Level 3: Learned Fusion</h4><p>Eventually, we stop hand-designing fusion rules. Instead, the system learns exactly how rankings should be merged by directly optimizing for relevance.</p><ul><li><strong>Learning to Rank (LTR):</strong> The classic production solution. Features like BM25 score, dense similarity, PageRank, popularity, and click history are fed into a model (like GBDT or LambdaMART) to predict the final ranking.</li><li><strong>Neural Rerankers:</strong> A cross-encoder jointly processes the query and candidate document using a Transformer to generate a highly accurate relevance score. It is much more accurate, though significantly slower.</li><li><strong>Fusion-in-T5 (FiD):</strong> Multiple retrieved documents are encoded independently and fused inside the transformer. This architecture is highly influential in modern Retrieval-Augmented Generation (RAG).</li><li><strong>Production KPI Rankers:</strong> Large companies optimize directly for business metrics such as Click-Through Rate (CTR), dwell time, purchases, or user satisfaction <strong>(Level 4)</strong>.</li></ul><p>Most modern recsys systems don’t just pick one level of rank fusion, they stack them. A typical production pipeline starts with multiple retrievers, uses <strong>Level 1 (RRF)</strong> for a fast initial merge, applies <strong>Level 2(Adaptive Routing)</strong>, and refines the candidates using <strong>Level 3(Neural Rerankers)</strong> before making a final pass for business KPIs <strong>Level 4</strong>.</p><p>This layered approach balances robustness and relevance. The evolution of rank fusion reflects a broader industry shift from handcrafted heuristics toward data-driven AI systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=315eeceb9cb8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/the-retrieval-divergence-problem-why-rank-fusion-matters-more-in-the-llm-era-315eeceb9cb8">The Retrieval Divergence Problem: Why Rank Fusion Matters More in the LLM Era ?</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TextGrad for Self-improving Agents]]></title>
            <link>https://medium.com/better-ml/textgrad-self-learning-agents-61e5aca61757?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/61e5aca61757</guid>
            <category><![CDATA[self-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[autoresearch]]></category>
            <category><![CDATA[textgrad]]></category>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 01:43:32 GMT</pubDate>
            <atom:updated>2026-07-02T01:44:54.926Z</atom:updated>
            <content:encoded><![CDATA[<p>Tune text, not weights !</p><ol><li>Self-improving agents need a mechanism for converting experience into durable improvements. A typical agent only accumulates logs: it records failures, retries with more context, and eventually suffers from context bloat. <strong>TextGrad</strong> provides a more structured alternative. It treats parts of the agent harness as <strong>optimizable variables</strong> and uses LLM-generated feedback as a gradient-like signal for improving them.</li><li>In a typical agent, the editable variables are not model weights. They are text based parameters like <strong>system prompts, tool-use instructions, routing rules, memory-writing policies, verifier prompts, retrieval queries, retry policies, and task decomposition templates</strong>. After an agent rollout, an evaluator inspects the result and produces textual feedback. <strong>TextGrad</strong> then routes that feedback back to the relevant variable and rewrites it.</li></ol><p>For example, suppose a research agent fails because it retrieves too many irrelevant papers and then summarizes them without checking whether they match the user’s question. A normal retry loop might simply say, “be more careful.” TextGrad can produce a more targeted update:</p><p><strong><em>Failure: </em></strong><em>The retriever returned papers that matched the query keywords but were not actually relevant to the user’s research intent.</em></p><p><strong><em>Textual gradient for retrieval prompt:</em></strong><em><br>The retrieval prompt should optimize for semantic relevance rather than surface-level keyword overlap. It should prioritize papers that directly address the target mechanism, benchmark, task, or empirical claim, and filter out papers that only use similar terminology.</em></p><p><strong><em>Updated retrieval prompt:</em></strong><em><br>Retrieve papers that directly support the user’s research question. Prefer sources that match the intended task, method, benchmark, mechanism, or empirical claim. Exclude papers that only share keywords without substantive relevance.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XLmBOVz0HI6_6WTAQULzQ.png" /></figure><p><strong>Reflection vs TextGrad</strong></p><p>TextGrad is different from ordinary reflection. Reflection usually produces a generic note such as “next time, verify assumptions.” TextGrad asks for an <strong>actionable edit to a specific variable</strong>. The output is is a patch.</p><p><strong>TextGrad is especially useful for agents because most agent behavior is controlled by text, not model weights</strong>. They can be optimized without fine-tuning the base model.</p><ul><li>The system prompt defines constraints. Tool descriptions define how to call tools.</li><li>Planner prompts define decomposition behavior. Memory policies define what gets stored.</li><li>Verifier prompts define acceptance criteria.</li></ul><p><strong>TextGrad Application</strong></p><ol><li>A practical self-improving agent can apply TextGrad across several parts of its workflow. It can improve the planner prompt so the agent decomposes underspecified tasks more effectively. It can refine the tool-use policy so the agent knows when to call search, code execution, calendar, file, or other external tools. It can improve the retriever prompt to select better sources and formulate more precise queries. It can strengthen the verifier prompt to catch failures more reliably and avoid false acceptance. It can update the memory policy to decide what should be stored, revised, or discarded. It can also refine the router prompt so the right sub-agent is selected for each class of task.</li><li>The most important use case is verifier improvement. Many agent failures are not caused by generation alone. They happen because the agent accepts a weak answer too early. TextGrad can improve the verifier by turning missed failures into stricter acceptance criteria. Example:</li></ol><p><strong><em>Failure</em></strong><em>: The verifier approved an answer that relied on outdated information.</em></p><p><strong><em>Textual gradient for verifier:</em></strong><em> The verifier should explicitly determine whether the answer depends on facts that may change over time. When time-sensitive claims are present, it should require up-to-date sources and reject responses that rely only on the model’s memory.</em></p><p><strong><em>Updated verifier rule:</em></strong><em> For claims involving current prices, laws, schedules, rankings, executives, software versions, or recent events, require a current source. Reject the answer when no fresh source is available.</em></p><h4>Guardrails for TextGrad:</h4><ul><li>TextGrad alone is not sufficient. Since the textual gradient is produced by an LLM, it may be <strong>ambiguous, incorrect, or too narrowly fitted to a single failure case</strong>.</li><li>A reliable self-improving agent needs safeguards around the update loop. Each edit should be evaluated before and after it is applied. The agent should maintain a held-out validation set to detect regressions.</li><li>Updates that fix one example but reduce overall performance should be rejected. Every change should be tracked with diffs and rollback points. When possible, evaluation should use an independent verifier rather than the same model that proposed the edit. The system should also favor small, targeted changes over broad prompt rewrites.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_g1hmoo4cU12DPkCdDPsw.png" /><figcaption>Agent rollout</figcaption></figure><p>For self-improving agents, those textual control surfaces are the harness. TextGrad gives the agent a way to learn from experience without training the base model. It does not make the LLM intrinsically smarter. It makes the surrounding agent system better organized, better routed, and better verified over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61e5aca61757" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/textgrad-self-learning-agents-61e5aca61757">TextGrad for Self-improving Agents</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AlphaEvolve: a reference architecture for turning LLMs into algorithm-discovery engines]]></title>
            <link>https://medium.com/better-ml/alphaevolve-a-reference-architecture-for-turning-llms-into-algorithm-discovery-engines-c6bc6119198c?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6bc6119198c</guid>
            <category><![CDATA[agent-loop]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[evolutionary-architecture]]></category>
            <category><![CDATA[evolutionary-algorithms]]></category>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Wed, 27 May 2026 07:31:38 GMT</pubDate>
            <atom:updated>2026-05-27T13:49:40.103Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>AlphaEvolve is best understood as an agent loop.</strong></p><ol><li>The LLM proposes code changes.</li><li>A programmatic evaluator runs the code and scores it.</li><li>A database keeps the best and most diverse candidates.</li><li>The loop repeats until the system discovers a verifiable solution — better algorithm, heuristic, kernel, or mathematical construction.</li></ol><p>DeepMind describes it as an <strong>evolutionary coding agent</strong> that combines Gemini models, automated evaluators, and an evolutionary framework for general-purpose algorithm discovery and optimization.</p><blockquote>Key idea is simple: let an LLM mutate code, but let execution and scoring decide what survives.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s0jeTZ8Xa8NDCvHYfwovDQ.png" /><figcaption>0. Control loop</figcaption></figure><pre>while compute_budget_remaining:<br>    parent, inspirations = database.sample()<br>    prompt = prompt_sampler.build(parent, inspirations)<br>    diff = llm.generate(prompt)<br>    child = apply_diff(parent, diff)<br>    results = evaluator.execute(child)<br>    database.add(child, results)</pre><p>The important architectural point is that <strong>the LLM is not trusted by default</strong>. It proposes candidates. The evaluator decides whether they are valid and useful. This is why AlphaEvolve works best on problems <strong>where solutions can be automatically checked</strong>: algorithms, kernels, math constructions, schedulers, compilers, and other measurable systems.</p><h4>1. Task specification</h4><p>The user provides three things:</p><ol><li>Scaffold / Research plan / An initial program.</li><li>Constraints: Marked regions of code that AlphaEvolve is allowed to modify.</li><li>An evaluation function that returns scalar scores.</li></ol><p>In the paper, the evaluator is typically a Python evaluate function returning a dictionary of scalar metrics. The code regions to evolve are marked with comments such as # EVOLVE-BLOCK-START and # EVOLVE-BLOCK-END, so the system can modify selected parts of a larger codebase without rewriting everything blindly.</p><blockquote>AlphaEvolve starts with a scaffold. Humans define the “what”: the problem, the constraints, the scoring function, and the editable code blocks. AlphaEvolve searches for the “how”: the actual implementation that improves the score.</blockquote><pre># EVOLVE-BLOCK-START<br>def score_machine(job, machine):<br>    # initial heuristic<br>    return machine.free_cpu + machine.free_mem<br># EVOLVE-BLOCK-END</pre><pre>def evaluate(candidate_program):<br>    simulation_result = run_scheduler_simulation(candidate_program)<br>    return {<br>        &quot;jobs_placed&quot;: simulation_result.jobs_placed,<br>        &quot;stranded_resources&quot;: -simulation_result.stranded_resources,<br>    }</pre><p>AlphaEvolve would repeatedly mutate <em>score_machine</em>, run the scheduler simulation, and keep variants that place more jobs while wasting fewer resources.</p><h4>2. Prompt sampler</h4><ul><li>The prompt sampler builds the context given to the LLM. It does not simply say, “write better code.” It includes the current program, previous high-performing programs, scores, evaluation outputs, task instructions, and sometimes additional prompt-evolution hints.</li><li>This matters because AlphaEvolve is doing <strong>in-context evolutionary search</strong>. The LLM sees examples of what worked before, what failed, and what objective it is optimizing. The system can also evolve meta-prompts: instructions and context suggested by the LLM itself, stored in a separate database analogous to the solution-program database.</li></ul><blockquote>The prompt sampler is AlphaEvolve’s memory-to-language bridge. It converts the evolutionary history into a prompt that the LLM can reason over.</blockquote><h4>3. LLM ensemble for efficient explore-exploit</h4><p>AlphaEvolve uses an ensemble of Gemini models. A cheap model which contributes high-throughput exploration, while the high reasoning model contributes occasional higher-quality suggestions that can move the search forward.</p><p>This is a classic exploration-exploitation split.</p><blockquote>AlphaEvolve treats LLM calls as mutation operators. A smaller/faster model gives lots of mutations. A stronger reasoning model gives more expensive but potentially more strategic mutations.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8Mn_9Khub7OMcZMerwbUA.png" /></figure><h4>4. Code mutation format</h4><p>For larger codebases, the LLM usually outputs changes as SEARCH/REPLACE diffs. The system applies those diffs to the current program, producing a child program. For very small programs, AlphaEvolve can instead ask the model to output the full code block.</p><p>Example:</p><pre>&lt;&lt;&lt;&lt;&lt;&lt;&lt; SEARCH<br>return machine.free_cpu + machine.free_mem<br>=======<br>cpu_residual = job.cpu / machine.free_cpu<br>mem_residual = job.mem / machine.free_mem<br>return -1.0 * (<br>    cpu_residual<br>    + mem_residual<br>    + mem_residual / cpu_residual<br>    + cpu_residual / mem_residual<br>)<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt; REPLACE</pre><blockquote>This style is useful because it lets AlphaEvolve operate on real codebases with constraints instead of isolated toy functions.</blockquote><h4>5. Evaluation cascades</h4><ol><li>The evaluator is the system’s source of truth. It executes the child program and returns scores. AlphaEvolve supports evaluation cascades, where cheap tests run first and expensive tests only run on promising candidates. It can also use LLM-generated feedback for softer properties such as simplicity, and it can parallelize expensive evaluations across clusters.</li><li>It also supports multiple objectives. For example, a candidate can be scored on correctness, runtime, memory use, simplicity, robustness, and generalization.</li><li>Multi-metric optimization can improve even a single target metric because different objectives surface structurally different programs.</li></ol><blockquote>The evaluator turns subjective coding into measurable search. Without it, AlphaEvolve would just be sampling plausible code. With it, every proposal becomes an experiment.</blockquote><h4>6. Long term Memory</h4><p>Every candidate program is stored with its scores and outputs. The database is not just a leaderboard. Its job is to resurface useful previous ideas while balancing exploration and exploitation.</p><blockquote>That is important because many algorithmic discoveries are not monotonic. A candidate that is not globally best may contain a useful trick that later combines with another idea.</blockquote><h4>7. Distributed async executor</h4><p>AlphaEvolve is built as an asynchronous pipeline with a controller, LLM samplers, and evaluation nodes. The system optimizes for total throughput, not the latency of one candidate, because discovery depends on evaluating many ideas under a fixed compute budget.</p><blockquote>AlphaEvolve is like a research lab running thousands of code experiments in parallel.</blockquote><h4>Application 1: faster matrix multiplication</h4><p>Matrix multiplication can be represented as a tensor decomposition problem. The fewer rank-one terms in the decomposition, the fewer scalar multiplications are required.</p><p>AlphaEvolve improved the state of the art for 14 matrix multiplication targets. Most notably, it found a rank-48 algorithm for multiplying two 4 × 4 complex-valued matrices, improving over the 49 multiplications obtained by recursively applying Strassen’s 1969 algorithm in the characteristic-zero setting.</p><blockquote>AlphaEvolve modified a search algorithm that looked for better tensor decompositions. The evaluator checked the rank and exactness. Over many iterations, the system discovered a lower-rank construction.</blockquote><h4>Application 2: Training kernel speedup</h4><p>AlphaEvolve optimized tiling heuristics for an important matrix multiplication kernel used to train Gemini. The objective was actual runtime on TPU accelerators. Google reported an average 23% kernel speedup over an expert-designed heuristic and a 1% reduction in Gemini’s overall training time. The optimization time dropped from months of engineering work to days of automated experimentation.</p><blockquote>This is recursive infrastructure optimization: Gemini powers AlphaEvolve, and AlphaEvolve finds code that makes Gemini training faster.</blockquote><h4>What makes the architecture powerful</h4><p>The useful mental model is:</p><blockquote><strong>LLM creativity + program execution + Evolutionary memory = Scalable search</strong></blockquote><p>The LLM supplies semantic mutations. The evaluator supplies ground truth. The database supplies memory and diversity. The distributed pipeline supplies scale.</p><blockquote>This avoids a common failure mode of LLM agents: plausible but unverified output. AlphaEvolve does not need the model to be right in one shot. It only needs the model to generate enough useful variation that the evaluator can select from.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6bc6119198c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/alphaevolve-a-reference-architecture-for-turning-llms-into-algorithm-discovery-engines-c6bc6119198c">AlphaEvolve: a reference architecture for turning LLMs into algorithm-discovery engines</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Differentiable Top-k Routing]]></title>
            <link>https://medium.com/better-ml/differentiable-top-k-routing-6f7432f1b2c7?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f7432f1b2c7</guid>
            <category><![CDATA[recsys]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai-training]]></category>
            <category><![CDATA[top-k]]></category>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Sun, 03 May 2026 21:40:03 GMT</pubDate>
            <atom:updated>2026-05-03T21:41:27.925Z</atom:updated>
            <content:encoded><![CDATA[<p>Most large-scale ML systems make a hard top-k decision: scores → pick k winners → discard the rest. Hard top-k breaks gradient flow at exactly the selection boundary.</p><ul><li>Differentiable top-k restores end-to-end learning by smoothing that boundary.</li><li>Best practice: <strong>train with soft top-k, serve with hard top-k</strong>. Tradeoff is clear: <strong>optimization quality vs serving efficiency</strong>.</li><li>This applies broadly across <strong>MoE routing, retrieval, and recommender cascades</strong>.</li></ul><h4>The problem: top-k as a broken interface</h4><p>Most large-scale ML systems make a hard top-k decision: scores → pick k winners → discard the rest.</p><p>This is efficient at serving time. But during training, it is a poor interface for gradient-based optimization. The selected set changes discontinuously when scores cross, so gradients do not reflect what happens at the boundary.</p><p><em>Result: the model learns scores, but not the consequences of selection.</em></p><h4>The idea: smooth the boundary</h4><p>Differentiable top-k replaces the hard selection with a smooth approximation: scores → soft k-hot mask → weighted combination.</p><p>This allows gradients to flow through the selection step. At serving time, you revert to exact top-k for efficiency.</p><p>Core pattern:</p><ul><li><strong>Training:</strong> scores → differentiable top-k → gradients flow</li><li><strong>Serving:</strong> scores → exact top-k → sparse execution</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4j2UPZZbumWxWJ1fAzlJA.png" /><figcaption>Soft top-k</figcaption></figure><h4>Where this shows up ?</h4><p>This is the same problem across systems:</p><p><strong>Retrieval / ranking</strong></p><ul><li>top-k defines the candidate shortlist</li><li>downstream model only sees this subset</li></ul><p><strong>Recommender cascades</strong></p><ul><li>Multiple selection boundaries (retrieval, filtering, reranking)</li><li>Each can break gradient flow</li></ul><p><strong>MoE (experts)</strong></p><ul><li>Top-k decides which experts run</li><li>Hard routing → efficient but unstable optimization</li></ul><p>Unifying view: Selection under a budget is a learnable operator, not just a systems constraint.</p><h4>Tradeoffs</h4><ol><li><strong>Optimization vs efficiency</strong></li></ol><p>Hard top-k is a systems-optimal operator. It enforces strict sparsity, which directly translates to bounded latency and predictable resource usage. However, from an optimization standpoint it is sub-optimal.</p><p>The selection boundary is discontinuous, so gradients do not reflect how close a losing candidate was to being selected. This prevents proper credit assignment and slows or destabilizes learning.</p><p>Differentiable top-k fixes this by smoothing the boundary and allowing gradients to flow through near-miss candidates. The cost is that sparsity becomes approximate during training, which increases compute and memory footprint. In practice, this is handled by restricting the relaxation to training only and reverting to exact sparsity at serving.</p><p><strong>2. Stability vs bias</strong></p><p>Hard top-k preserves the exact combinatorial decision rule. There is no approximation, so the selected set is unbiased with respect to the scoring function. However, because gradients are either zero or undefined at the boundary, optimization behaves like a high-variance estimator with poor signal.</p><p>Differentiable top-k introduces a continuous relaxation, which produces stable gradients and significantly improves convergence behavior. The tradeoff is bias. The model is trained under a softened selection rule that does not exactly match the true top-k operator. This bias can lead to slight mis-calibration, especially when score gaps are small, and typically requires temperature annealing or sharpening during training.</p><p><strong>3. Train-serve mismatch</strong></p><p>The standard pattern trains with a soft approximation and serves with hard top-k. This creates an inherent mismatch: the model is optimized under a relaxed operator but deployed under a discrete one.</p><p>In most cases this works well because the relaxation is designed to approximate the true operator closely. However, edge cases appear when the score distribution is flat or highly competitive. Small differences that matter under hard top-k can be washed out during training. This results in minor distribution shift at inference. Mitigations include temperature annealing, straight-through estimators, or hybrid objectives that explicitly penalize discrepancies between soft and hard selections.</p><p><strong>4. Systems complexity</strong></p><p>Hard top-k is trivial to implement and heavily optimized across hardware and frameworks. It integrates cleanly with sparse execution engines such as MoE dispatch or retrieval systems. Differentiable top-k, in contrast, requires non-trivial operators such as Gumbel-softmax sampling or differentiable sorting relaxations.</p><p>These introduce additional numerical considerations, memory overhead, and scaling challenges, especially in distributed settings.</p><p>Efficient implementations often rely on approximations or low-rank tricks, and care must be taken to avoid turning the routing step into the dominant cost. As a result, differentiable top-k is best viewed as a training-time construct rather than a systems primitive for serving.</p><h4>Industrial applications/tests</h4><ul><li>DSelect-k: large recommender testing → significant offline gains</li><li>Differentiable top-k ranking: measurable online revenue lift.</li><li>Switch Transformer: confirms why hard sparsity is operationally critical.</li></ul><p>Takeaway: <strong>There is real business value in learning through the selection boundary.</strong></p><h4>Takeaway</h4><p>Routing is not just scheduling. It is model behavior. MoE gates, retrieval shortlists, and recommender filters all collapse into the same problem:</p><p><strong>Learn the boundary, then enforce it efficiently.</strong></p><ul><li><strong>Training:</strong> differentiable approximation</li><li><strong>Serving:</strong> exact sparse top-k</li></ul><p>This gives: better optimization at same serving cost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f7432f1b2c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/differentiable-top-k-routing-6f7432f1b2c7">Differentiable Top-k Routing</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Big Is an LLM? Count the Facts It Remembers]]></title>
            <link>https://medium.com/better-ml/how-big-is-an-llm-count-the-facts-it-remembers-f8e3017cc1ff?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8e3017cc1ff</guid>
            <category><![CDATA[sysml]]></category>
            <category><![CDATA[ai-training]]></category>
            <category><![CDATA[mlsys]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Sun, 03 May 2026 01:15:20 GMT</pubDate>
            <atom:updated>2026-05-03T01:17:01.605Z</atom:updated>
            <content:encoded><![CDATA[<p>Frontier labs rarely disclose parameter counts. As a result, practitioners rely on indirect proxies such as API latency, pricing, and benchmark performance. These signals are noisy because they reflect system-level optimizations like quantization, batching, routing, and hardware efficiency rather than the model’s intrinsic capacity.</p><p>The paper <em>Incompressible Knowledge Probes: Estimating Black-Box LLM Parameter Counts via Factual Capacity</em> proposes a different approach. Instead of estimating model size from serving cost, it estimates size from how much long-tail factual knowledge a model appears to store.</p><p>Some facts cannot be derived through reasoning. They must be memorized. <strong><em>If a model reliably recalls more rare facts, it likely has higher effective parametric capacity</em></strong>. The paper validates this idea on 89 open-weight models ranging from 135M to 1.6T parameters and reports a strong log-linear relationship between factual recall and parameter count. These facts are evaluated using <em>Incompressible Knowledge Probes</em> (IKPs), a 1,400-question benchmark spanning seven tiers (T1–T7) of increasing obscurity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pucJrWw3oEiFBraX3ffauQ.png" /></figure><h4>The Problem: We Do Not Know How Big Closed Models Are</h4><p>A common workaround is to estimate model size from inference economics: serving cost, throughput, latency, and hardware assumptions. These signals are not intrinsic. A small model served inefficiently can appear large, while a large model with aggressive optimizations can appear smaller.</p><p>IKP reframes the question. Instead of asking <em>“How expensive is this model to run?”</em>, it asks <em>“How far into the factual long tail can this model recall?”</em>.</p><p>This shifts the focus from cost to stored factual knowledge.</p><p><strong>Compressible vs. Incompressible Knowledge</strong></p><ul><li><strong>Compressible skills</strong>: reasoning, coding style, instruction-following. These can be improved through better training procedures and synthetic data.</li><li><strong>Incompressible facts</strong>: long-tail associations such as obscure founding years or researcher subfields. These must be stored in the parameters.</li></ul><p>IKP targets the second category.</p><h4>Methodology: Build Facts That Models Cannot Fake by Reasoning</h4><p>The benchmark contains 1,400 probes, with 200 questions per tier (T1–T7).</p><ul><li>T1 contains common facts.</li><li>T7 contains extreme long-tail facts.</li></ul><p>The dataset spans 16 domains, including geography, history, science, and researcher metadata.</p><p><strong>Probe construction has two stages:</strong></p><ol><li><strong>LLM-generated probes (easy tiers)</strong><br>Used primarily for T1–T2. LLMs can generate common factual questions but struggle beyond their own knowledge horizon. This stage contributes 401 probes.</li><li><strong>External corpora (hard tiers)</strong></li></ol><ul><li>Wikidata: 557 probes (entity attributes, founding years)</li><li>DBLP / arXiv / OpenAlex: 345 researcher probes</li></ul><p>Researcher probes require both the correct subfield and a verifiable artifact such as a paper or co-author. This discourages plausible but fabricated answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0tN0oNpvowSxXW0e3oViQ.png" /><figcaption>LLM parameter estimation</figcaption></figure><p><strong>Filtering removes probes that measure the wrong capability:</strong></p><ul><li>Computable answers</li><li>Ambiguous entities</li><li>Name collisions</li><li>Overrepresented ML/AI entities</li><li>Non-monotonic difficulty</li></ul><p><strong>Tiering is empirical.</strong><br>Six landmark models define boundaries. A probe belongs to tier <em>k</em> if the model for tier <em>k</em> answers correctly and the previous model does not. Non-monotonic probes are discarded. This improves consistency but biases the benchmark toward the landmark models.</p><p><strong>Scoring</strong></p><p>The scoring system penalizes hallucination:</p><ul><li>Correct: +1</li><li>Weak (researcher probes): +0.5</li><li>Refusal: 0</li><li>Wrong: −1</li></ul><p>This explicitly rewards calibrated uncertainty. A model that says “I don’t know” is preferred over one that fabricates.</p><h4>Scaling Law: Factual Recall vs. Parameters</h4><p>The relationship between penalized IKP accuracy and parameter count follows a tight log-linear fit:</p><pre>accuracy = α · log10(parameter_count_in_billions) + β<br>parameter_count_in_billions = 10 ^ ((accuracy - β) / α)<br>[By fitting to open weights model]<br><br>log10(parameter_count_in_billions) = 6.790 · accuracy − 0.899</pre><p>Unlike reasoning or coding style, which can be boosted by high-quality post-training, rare factual recall relies on raw parametric capacity.The relationship between penalized IKP accuracy and parameter count follows a tight log-linear fit as shown above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuIdvssNH2hV-cyK-BYMlw.png" /></figure><h4>MoE Insight: Total Parameters Matter</h4><p>For Mixture-of-Experts models, inference cost depends on active parameters, but factual capacity depends on total parameters.</p><p>Knowledge appears distributed across experts. Therefore, IKP correlates with the full parameter pool, not the subset activated per token. This is an important distinction when comparing dense and MoE models.</p><h4>Why IKP Matters</h4><ul><li><strong>Zero-box access</strong>: Requires only API queries</li><li><strong>Infrastructure-agnostic</strong>: Avoids confounding from serving optimizations</li><li><strong>Calibrated</strong>: Anchored to open-weight models</li></ul><p>This provides a practical way to estimate the scale of closed models.</p><h4><strong>Where IKP Breaks (and Why It Matters)</strong></h4><ol><li>IKP measures factual recall, not true representation capacity. This distinction matters. A model can achieve high IKP scores by memorizing sparse associations without learning compact, generalizable structure. Conversely, a model trained with strong deduplication or compression objectives may store fewer raw facts but encode richer abstractions. IKP will systematically underestimate such models.</li><li>The method also assumes knowledge is stored purely in parameters. This breaks for systems with retrieval augmentation or tool use, where factual recall is externalized. In these cases, IKP conflates system design with model capacity and can overestimate size.</li><li>Finally, RLHF and safety tuning introduce asymmetric bias. Refusals are scored as neutral, but selective refusals on long-tail or sensitive probes can depress IKP accuracy independent of underlying knowledge. This creates a systematic downward bias for heavily aligned models.</li></ol><p>In short, IKP is a measure of <strong>accessible memorized knowledge under a specific interface</strong>, not a pure measure of model size.</p><h4>Takeaway</h4><p>IKP provides a noisy but principled proxy for model scale. It replaces indirect system-level signals with a direct measurement of stored knowledge. <strong><em>While imperfect, it offers an approximate estimation ofmodel capacity and complements existing scaling heuristics.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8e3017cc1ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/how-big-is-an-llm-count-the-facts-it-remembers-f8e3017cc1ff">How Big Is an LLM? Count the Facts It Remembers</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Over optimization & Reward hacking in Autoresearch]]></title>
            <link>https://medium.com/better-ml/over-optimization-reward-hacking-in-autoresearch-9da3f0d62994?source=rss-288e3faeb21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9da3f0d62994</guid>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Jaideep Ray]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 07:31:07 GMT</pubDate>
            <atom:updated>2026-04-12T07:31:29.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuYjOESbatdw-Bc4zi6ygg.png" /><figcaption>Over optimization</figcaption></figure><p><strong>Autoresearch failures</strong></p><ol><li>Autoresearch systems optimize whatever their loop can measure: benchmark lift, judge-model score, paper-style novelty score, pass rate, latency-adjusted reward, or some aggregate leaderboard.</li><li>This creates a vulnerability similar to proxy-objective failure seen in RLHF. Over-optimization happens when the tracked score keeps improving, but the real objective, such as scientific validity, robustness, or deployment usefulness, stops improving and may even get worse.</li><li>Reward hacking is the sharper version of the same problem. It is not just “pushing too hard” on a proxy. It is exploiting loopholes in the evaluator so the agent gets a high score without achieving the intended outcome. Reward hacking is improving a proxy reward in ways that can reduce the true reward the designer actually cares about.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BS1sb16ltoFPXP-OIKr-Aw.png" /></figure><h4>Framework design</h4><p>Because A strong optimizer will always expose a weak evaluator, you cannot rely on a single benchmark score. A robust autoresearch framework requires these core defenses:</p><p><strong>Diversify the Target:</strong></p><ul><li>Never use just one metric. Rely on hidden test sets, a variety of evaluators, and strict limits on how hard the system is allowed to optimize.</li><li>Example<em>:</em> Instead of optimizing solely for <strong>Top-1 Accuracy</strong>, use a multi-objective reward that includes <strong>Expected Calibration Error (ECE)</strong> and <strong>Inference Latency</strong>. This prevents the agent from “winning” via overconfident, computationally bloated models that fail in production.</li></ul><p><strong>Grade the Process:</strong></p><ul><li>Shift from only rewarding the final outcome to rewarding the <em>method</em>. Give credit for a sound hypothesis, proper controls, and logical reasoning — just like grading a student’s scratchpad.</li><li>Example<em>:</em> Reward the agent for performing a <strong>Sensitivity Analysis</strong> on its findings. If the agent proposes a new hyperparameter set but cannot demonstrate how those parameters behave under minor perturbations, the “process score” is penalized, regardless of the final lift.</li></ul><p><strong>Mandate Strict Testing:</strong></p><ul><li>Require proven, standard checks to ensure results aren’t just “lucky.” This means testing multiple random seeds, using cross-validation, and picking the final result based on an outside test rather than the internal validation score.</li><li>Example<em>:</em> Implement <strong>N-seed Validation</strong> as a hard gate. A configuration is only considered a “discovery” if it maintains a statistically significant improvement across 10+ different random seeds, effectively filtering out results that simply exploit stochastic noise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*MSykyNHgNf7EIHrKWI38cQ.png" /></figure><h3>Examples: The HPO Trap</h3><p>In practice, an agent running Hyperparameter Optimization (HPO) will exploit an evaluator in two common ways:</p><ul><li><strong>Over-tuning (Over-optimization):</strong> The agent runs thousands of trials against a single validation split until it memorizes the noise. Research (Schneider et al.) shows that in roughly 10% of cases, this results in an “optimized” model that actually performs <em>worse</em> than the default setting in the real world.</li><li><strong>Seed Hacking (Reward Hacking):</strong> The agent exploits the inherent randomness of the benchmark. As demonstrated by Henderson et al., algorithms can produce drastically different results using the exact same hyper-parameters but different random seeds. The system simply hunts for a “lucky” seed instead of discovering genuinely robust configurations.</li></ul><p><strong>tl;dr:</strong> Don’t let the system chase a single number. Build frameworks that evaluate the whole research method using multiple, hidden tests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9da3f0d62994" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-ml/over-optimization-reward-hacking-in-autoresearch-9da3f0d62994">Over optimization &amp; Reward hacking in Autoresearch</a> was originally published in <a href="https://medium.com/better-ml">Better ML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>