{
  "description": "Browse aymeric's, an independent, searchable archive of readable snapshots from followed feeds, preserved in Git with aggr.",
  "feed_url": "https://aggr.aymericbeaumet.com/sources/lilianweng.github.io/feed.json",
  "home_page_url": "https://aggr.aymericbeaumet.com/sources/lilianweng.github.io/",
  "items": [
    {
      "content_html": "<p>The concept of <strong>recursive self-improvement (RSI)</strong> dates back to <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://philpapers.org/rec/GOOSCT\">I. J. Good (1965)</a>, where he defined an “ultraintelligent machine” as a system that can surpass humans in all intellectual activities and design better machines to improve itself. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.lesswrong.com/posts/JBadX7rwdcRFzGuju/recursive-self-improvement\">Yudkowsky (2008)</a> used the phrase “recursive self-improvement” for a specific feedback loop: an AI uses its current intelligence to improve the cognitive machinery that produces its intelligence.</p>\n<p>This feedback loop in modern AI may indicate the model rewriting its own weights directly, or more broadly the model improves the <em>training pipeline</em> and the <em>deployment system</em>, which in turn enables a better successor model with improved performance across economically valuable tasks. The speed of research development in AI has been shown to drastically accelerated in frontier labs (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.anthropic.com/institute/recursive-self-improvement\">Anthropic</a>; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openai.com/index/how-agents-are-transforming-work/\">OpenAI</a>).</p>\n<p>I explicitly mention <em>“deployment system”</em> because the layer between the raw model and the real-world context seems to be as important as the model’s raw intelligence (i.e. the evals right after pretraining). Harnesses are important components of AI deployment, as shown by successful coding agent products such as Claude Code and Codex. A <strong>harness</strong> is the system surrounding a base model that orchestrates execution and decides how the model thinks and plans, calls tools and acts, perceives and manages context, stores artifacts, and evaluates results.</p>\n<p>This one post will focus on research around harness engineering and how it contributes to RSI. Much recent work on auto-research, self-improving agents, and evolutionary program search can be organized around this question. Other work on model self-play, synthetic data, test-time training and a broader theme of continual learning also matches the RSI vision (e.g. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2401.10020\">Yuan et al. 2024</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2401.01335\">Chen et al. 2024</a>), <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2505.03335\">Zhao et al. 2025</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openreview.net/forum?id=lTbBFAoPSA\">Choi et al. 2026</a>)) but they will not be the focus of this post.</p>\n<h2>Harness Design Patterns</h2>\n<p>Compared with <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2023-06-23-agent/\">early agent frameworks</a>, “agent = LLM + memory + tools + planning + action”, harnesses engineering additionally include <em>workflow design (e.g. loop engineering), evaluation, permission controls, and persistent state management</em>. It is no longer only prompt templates, but closer to runtime and software system design: how the model observes, acts, memorizes, checks itself, and improves.</p>\n<p>The design should be deliberately simple and generic to enable generalization, likely with reference to existing software engineering practices to benefit from prertaining knowlege. There is also a strong analogy between operating systems and harnesses. Similar to an OS, a harness should encapsulate complicated logic while keeping the interface simple. Meanwhile, configs, tool interfaces and other protocols may gradually become standardized across the industry.</p>\n<h2>Pattern 1: Workflow Automation</h2>\n<p>Defining a workflow in which the model can operate, test, and iterate is a key design for automation. Karpathy’s autoresearch repo (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/karpathy/autoresearch\">https://github.com/karpathy/autoresearch</a>) is a clean example of how such a workflow can be constructed. A common workflow follows a goal-oriented loop of plan, execute, observe/test, improve, and execute again <em>until</em> the goal is achieved. The process may trigger proactive requests to users for clarity in task specification or execution preference.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/openai-agent-loop.png\" alt=\"\" loading=\"eager\" decoding=\"async\" fetchpriority=\"high\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>A simplified Codex agent loop: the agent calls tools and tool responses affect the model's next generation.<br />\n(Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openai.com/index/unrolling-the-codex-agent-loop/\">OpenAI codex agent post</a>)</figcaption></figure>\n<p>The workflow graph also emphasizes the model analyzing its own trajectories and failure cases and then iterating on its progress through an “agent runtime” rather than a static prompt template.</p>\n<h2>Pattern 2: File System as Persistent Memory</h2>\n<p>A recurring pattern in long-horizon agent systems is simple control over rich states and artifacts. A harness should not carry the entire workflow and all logs in context; instead, it should keep durable state in files. In long-horizon agentic rollout, artifacts such as experiment logs, code diffs, paper summaries, error traces, and past rollout trajectories often grow much longer than the context window that the model has trained for.</p>\n<p>Learning how to read, write, and edit the file system (commonly via <code>bash</code> commands) is a foundation skill for LLMs, and thus managing persistent memory in the simple form of files naturally benefits from improvements in core model capability.</p>\n<h2>Pattern 3: Sub-agent and Backend Jobs</h2>\n<p>A harness can spawn multiple subagents to execute in parallel and monitor backend jobs. This is useful when the main agent needs to search multiple hypotheses, run experiments concurrently, or delegate isolated subtasks without polluting the main context. The parent agent then needs a small process manager: launch jobs, inspect logs, cancel failed runs, and merge results back into the main agent thread.</p>\n<p>The key design choice is to make parallelism explicit and inspectable. If subagent outputs only live in a transient chat context, they quickly become obselete and hidden. If they are stored as files, logs, and status records, the model can recover after interruptions and reason over its own execution history.</p>\n<h2>Case study: Coding Agent Harness</h2>\n<p>The core interface of mainstream coding agents has become stabilized across Claude Code, Codex, OpenCode, and Cursor-style agents. They commonly use a loop like:</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/coding-harness-loop.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></p>\n<p>With access to a set of tools, the coding agent is able to develop and debug issues in a given repository, similar to how human developers are equipped with IDEs.</p>\n<p>(Not a comprenhensive list; shown for demonstration. Read <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/yasasbanukaofficial/claude-code\">this</a> if interested.)</p>\n<table>\n<thead>\n<tr>\n<th>Group</th>\n<th>Tool definitions</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>File system</td>\n<td>- File discovery: <code>glob</code>, <code>grep</code>, <code>ls</code> - File read: <code>read</code>, <code>read_many</code> - File modification: <code>write</code> (a whole new file); <code>edit</code> (string exact-match replacement); <code>multi_edit</code>; <code>apply_patch</code> (applies a structured patch/diff)</td>\n</tr>\n<tr>\n<td>Shell execution</td>\n<td>Run commands: <code>bash</code>, <code>PowerShell</code></td>\n</tr>\n<tr>\n<td>IO</td>\n<td><code>lsp</code>, git tools like <code>git_status</code>, <code>git_diff</code>, <code>git_commit</code></td>\n</tr>\n<tr>\n<td>External context</td>\n<td>MCP tools, Skills</td>\n</tr>\n<tr>\n<td>Web search</td>\n<td><code>web_search</code>, <code>web_fetch</code>, browser tools</td>\n</tr>\n<tr>\n<td>Artifacts</td>\n<td>Read docs, images; generate HTML, images</td>\n</tr>\n<tr>\n<td>Backend processes</td>\n<td>Such as: <code>CronCreate</code>, <code>CronDelete</code>, <code>CronList</code></td>\n</tr>\n<tr>\n<td>Agent delegation</td>\n<td>Such as: <code>spawn_agent</code>, <code>resume_agent</code>, <code>wait_agent</code>, <code>list_agents</code>, <code>close_agent</code>, <code>interrupt_agent</code>, etc.</td>\n</tr>\n</tbody>\n</table>\n<h2>Harness Layer vs Core Intelligence?</h2>\n<p>It is hard to forecast how much the future of RSI will rely on harness engineering, but the near-term path of RSI is unlikely to start as a model directly rewriting its weights. My prediction of a practical near-term path is:</p>\n<ol>\n<li>Harness engineering will evolve in the direction of meta-methodology (i.e. improving the machinery for getting better answers, not just improving the answer itself). The harness system itself becomes an optimization target, with fewer heuristic rules and more general mechanisms.</li>\n<li>In turn, mature harnesses enable auto-research for model self-improvement loop and smarter models prevents harnesses from overengineering and keep the system sustainable.</li>\n</ol>\n<p>Eventually it is possible that many harness improvements will be <em>internalized</em> into core model behavior, but the interface with external context and tools should remain. We have seen a softer version of this pattern with <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/\">prompt engineering</a>: manual prompt tricks became less central as instruction tuning and model reasoning improved, but <em>the need to specify goals, constraints, context, and evaluation did not disappear</em>.</p>\n<h2>Harness Optimization</h2>\n<p>The progression in the object being optimized in the harness system is roughly: instruction <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/\">prompts</a> → structured context → workflow → harness code → optimizer code. As the model becomes more intelligent and powerful, we move toward more complex targets and generic methods.</p>\n<h2>Context Engineering</h2>\n<p>Simply appending all the tool responses and model generations into the context can quickly grow out of control as the agentic job horizon increases significantly. Context management is a layer to construct a more structed and concise context for LLM and manage persistant states. There is no doubt that long-context research will keep on making progress but at the moment long-context intelligence and context engineering sometime intertwines.</p>\n<p><strong>Agentic Context Engineering</strong> (ACE; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2510.04618\">Zhang et al. 2025</a>) treats context as an evolving playbook rather than an increasingly lengthening prompt. It has three components to maintain one context playbook of bullet points, each with an identifier and a description.</p>\n<ol>\n<li><em>Generator</em>: produces task trajectories, with reference to bullet points.</li>\n<li><em>Reflector</em>: distills insights from successful and failed trajectories.</li>\n<li><em>Curator</em>: updates the structured context with incremental, itemized entries.</li>\n</ol>\n<p><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/ace.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The framework of Agentic Context Engineering (ACE). (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2510.04618\">Zhang et al. 2025</a>)</figcaption></figure>\n<p>To prevent context collapse and brevity bias during iterative rewrites, one key design choice in ACE is that the curator does not rewrite a full prompt blob. It instead outputs a collection of structured, itemized bullets in the form of (identifier, description), and these bullets are merged into a structured context logbook with deterministic logic. The context items are refined and deduplicated periodically.</p>\n<p>The fact that ACE learns insights from rollouts helps us move toward self-managed memory, but the update rules and the overall workflow are still handcrafted. To move toward a more self-improving loop, <strong>Meta Context Engineering</strong> (MCE; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2601.21557\">Ye et al. 2026</a>) separates the mechanism (how to manage context) from the artifact content (what is in context), running skill evolution at the meta-optimization level and context optimization at the base level.</p>\n<p>An MCE skill <span class=\"math\">s ∈ 𝒮</span> defines a context function <span class=\"math\">cₛ=(ρₛ,Fₛ)</span> and maps an input <span class=\"math\">x</span> to context <span class=\"math\">c = Fₛ(x;ρₛ)</span>, where:</p>\n<ul>\n<li><span class=\"math\">ρₛ = {ρ₁,…,ρₘ}</span> are static components (prompts, knowledge bases, code libraries).</li>\n<li><span class=\"math\">Fₛ = {F₁,…,Fₖ}</span> are dynamic operators (search, selection, filtering, formatting).</li>\n</ul>\n<p>The bi-level optimization is to find the best context <span class=\"math\">cₛ^*</span> given skill <span class=\"math\">s</span> on the training data, while the outer loop finds the optimal skill that provides the best performance on the validation set:</p>\n<p><span class=\"math math-display\">Inner: cₛ^*=argmax_(cₛ)Jₜᵣₐᵢₙ(cₛ;s) Outer: s^*=argmax_(s∈𝒮)Jᵥₐₗ(cₛ^*)</span></p>\n<p>The skill database tracks the history of previous skills, context functions and eval metrics <span class=\"math\">ℋₖ₋₁ = {(sᵢ,cᵢ,Jᵢᵗʳᵃⁱⁿ, Jᵢᵛᵃˡ)}ᵢ₌₁ᵏ⁻¹</span>. A meta-level agent performs agentic <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Crossover_(evolutionary_algorithm)\">crossover</a> over prior skills to create a new skill given a task <span class=\"math\">τ</span>: <span class=\"math\">sₖ=crossover(τ,ℋₖ₋₁)</span>.</p>\n<p>Then a base-level context engineer executes the skill <span class=\"math\">sₖ</span> and learns the context function from rollout feedback <span class=\"math\">ℛₖ</span>, guided by the current skill: <span class=\"math\">cₖ=engineer(τ,sₖ;cₖ₋₁^*,ℛₖ)</span>.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/mce.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The framework of Meta Context Engineering (MCE): meta-level skill evolution searches over context-management mechanisms, while the base level optimizes the task context. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2601.21557\">Ye et al. 2026</a>)</figcaption></figure>\n<p>MCE does not enforce a heuristic rule for how to structure context as ACE does. It uses <em>free-form skills</em> to store the most important knowledge for a task, and evolves the skill and the skill-conditioned context iteratively together. Implementation-wise, a context function <span class=\"math\">c</span> is instantiated as a collection of files in a dedicated directory, including both static (<code>skill.md</code>) and dynamic (context and data rollouts) components. Both meta-level and base-level optimization are executed in agentic coding envs with a standard tool set,</p>\n<p><span class=\"math math-display\">𝒯={Read,Write,Edit,Bash,Glob,Grep,TodoWrite}</span></p>\n<p><strong>Meta-Harness</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2603.28052\">Lee et al. 2026</a>) moves another level deeper: the optimized object is the <em>code</em> that determines and optimizes what information should be stored, retrieved, and presented to the model. “Meta-” in its name means it is a harness for optimizing harnesses.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/meta-harness-outer-loop.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The Meta-Harness outer-loop optimization algorithm. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2603.28052\">Lee et al. 2026</a>)</figcaption></figure>\n<p>The proposer for creating a new harness is itself a coding agent and the final output is a collection of harness candidates on the Pareto frontier.</p>\n<ul>\n<li>The entire execution history is accessible via a file system, and thus the coding agent uses commands like <code>grep</code> or <code>cat</code> to read through it instead of shoveling everything into a single prompt context.</li>\n<li>The proposed harness is a dictionary in the file system containing its own source code, scores, rollout trajectories, and state updates.</li>\n<li>The mete-harness loop iteratively creates new harnesses, and only qualified ones are kept.</li>\n</ul>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/meta-harness.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The performance of Meta-Harness on (Left) text classification with a small number of iterations and (Right) TerminalBench-2. Note that the search in the TerminalBench-2 experiment is initialized from Terminus-KIRA and Terminus-2, two very strong harnesses. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2603.28052\">Lee et al. 2026</a>)</figcaption></figure>\n<p>Still, the important lesson is clear: once harness design becomes an executable search space, a strong coding agent can exploit the same design space human engineers use.</p>\n<h2>Workflow Design</h2>\n<p>Workflow design in harness engineering can be handcrafted by domain experts. Taking auto-research as an example, various frameworks have been proposed and tested. The <strong>AI Scientist</strong> system (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.nature.com/articles/s41586-026-10265-5\">Lu et al. 2026</a>) builds a pipeline to propose research ideas, write code, run experiments, analyze results, write a manuscript, and perform peer review. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.26340\">Meng et al. (2026)</a> make verifiability the central design constraint in <strong>ScientistOne</strong>, where every claim (citation, numerical, methodological, conclusion) must trace to an evidence source and is audited by Chain-of-Evidence checks.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/ai-scientist.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>AI Scientist pipeline for idea generation, experimentation, paper writing, and review. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.nature.com/articles/s41586-026-10265-5\">Lu et al. 2026</a>)</figcaption></figure>\n<p>The <strong>Autodata</strong> agent (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2606.25996\">Kulikov et al. 2026</a>) is designed to work as a data scientist for generating training and evaluation data. The main agent manages a <em>challenger</em> that proposes problems, a <em>weak solver</em>, a <em>strong solver</em>, and a <em>verifier/judge</em>, aiming to synthesize data at the “just right” level of difficulty, meaning that the strong solver succeeds but the weak solver fails.</p>\n<p>In Autodata, the challenger prompt is updated iteratively according to feedback from the solvers and verifier. The limitation here is that synthesized tasks are used to fine-tune weak solvers but not strong solvers; if the loop cannot iteratively improve the strong model, it is more like indirect distillation over a generated prompt distribution, with less RSI flavor.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/autodata.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Autodata agentic workflow design for generating synthetic training and evaluation data around challenger, solver, and verifier roles. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2606.25996\">Kulikov et al. 2026</a>)</figcaption></figure>\n<p>The design space for workflow is <em>enormous</em>, and naturally we can think of workflow design as a search problem, and therefore we should be able to find good solutions by algorithms rather than only manually craft them. Following this direction, <strong>Automated Design of Agentic Systems</strong> (ADAS; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.08435\">Hu et al. 2025</a>) formulates agent design itself as an optimization problem, “meta-agent search” where a meta-agent proposes new designs of agentic workflows.</p>\n<ol>\n<li>Initialize an archive of agentic workflows with simple agents such as CoT and self-refine.</li>\n<li>Ask a meta-agent to program new agents, all in <em>code</em>, inspired by existing solutions in the archive.\n<ul>\n<li>The meta-agent first generates a high-level description of the new workflow, and then implements it in code.</li>\n<li>The draft program then goes through two self-refine steps (i.e. ask the model to provide feedback and then ask the same model to refine the previously generated outputs based on the feedback; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2303.17651\">Madaan et al. 2023</a>) by the meta-agent to check its novelty.</li>\n</ul>\n</li>\n<li>Evaluate each new candidate and add successful ones back to the archive.</li>\n<li>Repeat steps 2-3 until the maximum iteration count is reached.</li>\n</ol>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/adas.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of Automated Design of Agentic Systems (ADAS).<br />\n(Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.08435\">Hu et al. 2025</a>)</figcaption></figure>\n<p><strong>AFlow</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.10762\">Zhang et al. 2025</a>) represents an agentic workflow as a graph, where nodes represent LLM-invoking actions and edges implement logical operations in code. The workflow optimization relies on <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Monte_Carlo_tree_search\">MCTS</a> (Monte Carlo Tree Search):</p>\n<ol>\n<li>Initialize the starting workflow <span class=\"math\">W₀</span> in the tree with a template.</li>\n<li>Select a workflow node using a soft mixture of score and uniform exploration.</li>\n<li>Expand it by asking an LLM to produce a modified workflow conditioned on its evaluation performance.</li>\n<li>Execute and evaluate the new workflow.</li>\n<li>Add it back to the tree if the new workflow shows improvement within a budget of <span class=\"math\">N</span> rounds.</li>\n<li>Repeat steps 2-5 and stop when the top-<span class=\"math\">k</span> average score plateaus or hit the budget.</li>\n</ol>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/aflow.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>AFlow optimization process over a tree of workflow candidates. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.10762\">Zhang et al. 2025</a>)</figcaption></figure>\n<p>Experiments of AFlow in QA, code, and math tasks showed decent improvement of AFlow over manually designed workflows and ADAS.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/aflow-exp.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>AFlow experiments in comparison to manual methods and ADAS. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.10762\">Zhang et al. 2025</a>)</figcaption></figure>\n<h2>Self-Improving Harness</h2>\n<p>Either context engineering or workflow design is only one part of a harness. We need to search through the entire design space and optimize context-management logic, workflow, permissions, and many other harness components together. As we have seen in work like Meta-Harness, ADAS, and AFlow, <strong>✨code✨</strong> is a <strong>universal language</strong> for defining programs and systems. In simple words, a harness is code that programs how prompts, tool calls, subagents, control flow, memory, and workflow logic work together. If an LLM can optimize the code that executes agents, it can access a <em>much larger design space</em> than hand-written prompts.</p>\n<p><strong>Self-Taught Optimizer</strong> (STOP; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.02304\">Zelikman et al. 2023</a>) is one of the early examples of recursive scaffolding improvement. A seed improver <span class=\"math\">I₀</span> at step <span class=\"math\">t=0</span> takes an initial solution <span class=\"math\">s</span>, a utility function <span class=\"math\">u</span>, and a black-box language model <span class=\"math\">M</span>, and returns an improved solution <span class=\"math\">s’</span>, that is, <span class=\"math\">s’ = I(u, s; M)</span>. The goal of STOP is not directly to improve <span class=\"math\">s</span> but <em>to improve the improver <span class=\"math\">I</span> itself</em>.</p>\n<p>First, let’s define the meta-utility as the average utility of a given improver function <span class=\"math\">I</span> over a collection of downstream tasks <span class=\"math\">𝒟</span>:</p>\n<p><span class=\"math math-display\">û(I) ≜ 1/|𝒟|𝔼_((u,s)∼ 𝒟)[u(I(u,s; M))]</span></p>\n<p>Because improving the improver function is an optimization problem itself, we can recursively get a new version of <span class=\"math\">Iₜ</span> based on <span class=\"math\">Iₜ₋₁</span>’s performance measured by meta-utility via a self-improvement update:</p>\n<p><span class=\"math math-display\">Iₜ=Iₜ₋₁(û,Iₜ₋₁;M)</span></p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/STOP-algo.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Algorithm of Self-Taught Optimizer (STOP). (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.02304\">Zelikman et al. 2023</a>)</figcaption></figure>\n<p>In their experiments, the improved improver discovered various strategies, such as genetic algorithms, decomposing and improving parts, multi-armed prompt bandits, simulated annealing, varying temperature, and beam/tree search. This is analogous to how a harness workflow can be represented as an object for optimization.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/STOP-patterns.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Examples of self-improvement strategies discovered by STOP. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.02304\">Zelikman et al. 2023</a>)</figcaption></figure>\n<p>A <em>cautionary</em> result in Zelikman et al. (2023)’s findings is that STOP improved mean downstream performance across iterations with GPT-4 but degraded with weaker models like GPT-3.5 and Mixtral. Recursive structure alone is not enough. The base model must be <em>capable enough</em> to improve the mechanism. This implies that harness improvement enables better deployment of the model but intelligence is still the core.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.30621\">Lin et al. (2026)</a> investigated the dependency of harness evolution on model capabilities in more details. They disentangled two axes: (1) <em>harness-updating</em> refers to the capability of producing useful harness edits and (2) <em>harness-benefit</em> denotes the capability of utilizing the updated harness, to achieve better task solving. Interestingly a range of model of different sizes and core intelligence, from Qwen3.5-9B to Claude Opus 4.6, were observed in their experiments to show similar harness updating capability; the 9B harness proposer/evolver is able to write a skill procedurally isomorphic to Opus. To best utilize a harness, a model needs to invoke skills/tools correctly and timely and be good at long-horizon instruction following.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/harness-update.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Main results: (A) harness updating capability is measured flat across a range of models from Qwen2-32B to Opus 4.6; (B) harness benefit capability is non-monotonic where middle tier models benefit the most. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.30621\">Lin et al. 2026</a>)</figcaption></figure>\n<p>A more recent work, <strong>Self-Harness</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2606.09498\">Zhang et al. 2026</a>), relies on LLM agents to improve their own harness via a propose-evaluate-accept loop.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/self-harness.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Self-Harness uses a loop of weakness mining, bounded harness proposal, and validation to update a harness. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2606.09498\">Zhang et al. 2026</a>)</figcaption></figure>\n<p>The loop in Self-Harness has three stages:</p>\n<ol>\n<li><em>Weakness mining</em>: cluster failures into verifier-grounded failure patterns.\n<ul>\n<li>The current harness <span class=\"math\">hₜ</span> is used to evaluate on tasks and execution traces are collected for analysis.</li>\n<li>Note that two runs can share the same verifier outcome in the error logs on the surface, such as timeout or missing artifact, while having different causal mechanisms. Therefore we need a failure record of rich information, containing the terminal verifier-level cause, the causal status of the relevant agent behavior, and the abstract agent mechanism exposed by the trace, to uncover the root causes.</li>\n</ul>\n</li>\n<li><em>Harness proposal</em>: propose bounded harness edits based on mined failure patterns.\n<ul>\n<li>The same model is invoked under <span class=\"math\">hₜ</span> as a proposer.</li>\n<li>The model is provided with a bounded proposal context: (1) the editable surfaces of the current harness, (2) the verifier-grounded failure patterns from the evaluation system, (3) records of passing behaviors that should be preserved, and (4) summaries of previously attempted edits.</li>\n<li>Harness edits should prefer recurrent error patterns that are addressable (e.g. not task-specific difficulty) and can be resolved by narrow changes.</li>\n<li>Harness edit candidates should be distinct and diverse.</li>\n</ul>\n</li>\n<li><em>Proposal validation</em>: validate and merge qualified edits to create a new harness <span class=\"math\">hₜ₊₁</span>.\n<ul>\n<li>Candidate edits are evaluated by regression tests on held-in <span class=\"math\">Dᵢₙ</span> (for testing whether the weakness is resolved) and held-out <span class=\"math\">Dₒᵤₜ</span> (for checking whether other unknown issues were introduced) splits.</li>\n<li>Candidates are accepted only if they have no regression on both held-in and held-out data.</li>\n<li>Accepted candidates are merged to update the harness to <span class=\"math\">hₜ₊₁</span>, while rejected candidates are logged without changing the active harness.</li>\n</ul>\n</li>\n</ol>\n<p>When running <code>MiniMax M2.5</code>, <code>Qwen3.5-35B-A3B</code>, and <code>GLM-5</code> on Terminal-Bench-2, Self-Harness was shown to learn model-specific harness instructions that target at different weaknesses of different base models and improve held-out pass rates.</p>\n<p>Self-harness type of work does raise my concerns that if a program is allowed to edit the OS system, abstraction boundaries are broken. The editable surface needs to be properly designed and the permission control and security layers need to live outside this loop. All the challenges around <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/\">reward hacking</a> still remain.</p>\n<p><strong>Agentic Harness Engineering</strong> (AHE; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2604.25850\">Lin et al. 2026</a>) see the bottlenecks of harness evolution are around <strong>observability</strong>—that is, when a rollout fails, we need to know which component is responsible for that and every edit should be grounded by evidence.</p>\n<p>The framework creates a closed loop with 3 observability pillars:</p>\n<ol>\n<li><em>Component observability</em>: every editable harness component has a representation in the file system so the action space is explicit and tracable.\n<ul>\n<li>A harness contains 7 components: system prompt, tool description, tool implementation, middleware, skill, sub-agent configuration, and long-term memory.</li>\n<li>Each failure pattern is mapped to one component so the edit can be more targeted.</li>\n</ul>\n</li>\n<li><em>Experience observability</em>: analysize and summarize a large amount of raw trajectories into a hierarchy of evidence and failure patterns.\n<ul>\n<li>Each harness generates <span class=\"math\">k</span> traces.</li>\n<li>Use an agent (“Agent debugger”) to analysis the trajectories each stored in one file and generate per-task analysis report on the root cause for the failure or success.</li>\n<li>All the per-task reports are aggregated into a benchmark overview for the next step, and raw traces can be accessed if needed. This layered access structure is more token efficient.</li>\n</ul>\n</li>\n<li><em>Decision observability</em>: every edit is paired with a prediction for the next round to validate.\n<ul>\n<li>An agent (“Evolve agent”) reads the repo and decides which component to edit, and then produces the edit and the reasoning behind it.</li>\n<li>Every edit is a file-level, falsifiable claim and can be verified in the next round, under two constraints:\n<ul>\n<li>(1) Edits are only applied to the harness workspace. the runs directory, tracer, verifier, and LLM configuration are read-only, which disables a set of reward hacking (e.g disabling the verifier, swapping the model, or raising the reasoning budget) and thus it can keep every recorded gain attributable to harness edits.</li>\n<li>(2) Edits are evidence-driven, with a manifesto entry: the failure evidence’s name, the inferred root cause, the targeted fix, and a predicted impact comprising both expected fixes and at-risk regressions.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ol>\n<p>On Terminal-Bench-2, AHE achieved better than human-designed harness (OpenCode, Terminus-2, Codex) except for Hard tier and a few other self-evolve baselines (ACE, TF-GRPO). The same frozen harness, without further evolving, transfers to SWE-bench-verified, indicating that the evolved harness is able to encode engineering experience into harness components rather than doing benchmark-specific optimization.</p>\n<h2>Evolutionary Search</h2>\n<p>Evolutionary search is an optimization method inspired by natural selection (see my old post on <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2019-09-05-evolution-strategies/\">evolutionary algorithm</a>). It evolves a population of solutions by mutating them and only keeping those with high “fitness” in the crowd. Evolutionary search comes in handy when (1) the search space is extensive or weirdly shaped; and (2) it is hard to optimize directly with gradients but easy to evaluate solutions. Harness search seems to be a good fit here.</p>\n<p>Evolutionary search has been used in prompt engineering in the past studies. <strong>Promptbreeder</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2309.16797\">Fernando et al. 2023</a>) optimizes task-specific prompts through a rich set of mutation operations, and interestingly the mutation prompts (i.e. instructions to an LLM to mutate a task prompt) are themselves also improved through evolution. <strong>GEPA</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2507.19457\">Agrawal et al. 2025</a>) combines <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2023-06-23-agent/#self-reflection\">reflection</a>-based prompting with evolutionary search and uses natural language reflection over trajectories of trial and error to propose prompt updates.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2506.13131\">Novikov et al. (2025)</a> introduced <strong>AlphaEvolve</strong> as a coding-agent evolutionary search system, which stores a pool of candidate programs and prompts frozen LLMs to generate diffs for improvement. As the system repeatedly evaluates child programs and keeps successful ones, it discovers better solutions in time.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/alphaevolve.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>How AlphaEvolve works. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2506.13131\">Novikov et al. 2025</a>)</figcaption></figure>\n<p>A few details matter in the design of AlphaEvolve:</p>\n<ul>\n<li>The prompt includes parent programs, results, instructions, and sometimes meta information.</li>\n<li>The coding agent has access to the full repo, but code regions for improvement are explicitly marked with <code># EVOLVE-BLOCK-START</code> and <code># EVOLVE-BLOCK-END</code>.</li>\n<li>Meta-prompt co-evolves with instructions and context as suggested by LLM, in a similar way as how we evolve solution programs.</li>\n</ul>\n<p>Ablations show the evolution procedure, context in prompts, meta-prompts, full-file evolution and the use of stronger LLMs.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/alphaevolve-plot.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Ablations show the value of everal designs in AlphaEvolve. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2506.13131\">Novikov et al. 2025</a>)</figcaption></figure>\n<p>Recent variants such as <strong>ThetaEvolve</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2511.23473\">Wang et al. 2025</a>) combines evolutionary search with RL and in-context learning, and <strong>DemoEvolve</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.24539\">Che, et al. 2026</a>) augments the self-rollout archive with human expert demonstrations as reference experience for harness-level diagnosis and editing. <strong>ShinkaEvolve</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2509.19349\">Lange et al. 2025</a>), on the other hand, introduced three new components to improve LLM sampling efficiency:</p>\n<ul>\n<li>More sample-efficient exploration by designing parent sampling to balance performance rank and offspring count.</li>\n<li>Code-novelty rejection sampling by discarding candidates that are too similar to the existing population based on embedding-based cosine similarity.</li>\n<li>Identifying good patterns in successful solutions in a meta-scratchpad to guide future mutation.</li>\n</ul>\n<p>Unlike the methods above, which focus on solution improvement, <strong>Darwin Gödel Machine</strong> (DGM; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2505.22954\">Zhang et al. 2025</a>) explicitly targets the evolution of an editable harness-code repository with an LLM-based coding agent. Precisely, this agent is allowed to modify its own harness. A follow-up work on Hyperagents (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2603.19461\">Zhang et al. 2026</a>) introduced a meta-agent to control how to modify existing task agents to create new ones.</p>\n<ol>\n<li>Start with one coding agent in the pool.</li>\n<li>In each iteration, pick one parent with a probability proportional to its performance and inversely to the number of children it has, to modify and branch off to produce new agents.</li>\n<li>The selected parent agent examines its own benchmark evaluation log and then proposes improvements to its own harness codebase to generate a new version of the coding agent. Code editing is implemented with two basic tools: (1) bash (args: <code>&lt;bash_command&gt;</code>) and (2) editor (args: <code>view/create/edit &lt;file_path&gt;</code>).</li>\n<li>New coding agents are evaluated, and only those with sufficiently high performance are added back into the pool.</li>\n<li>Repeat steps 2-4 until some stop criteria hit.</li>\n</ol>\n<p>DGM is harness evolution under a fixed model. In experiments with <code>Claude 3.5 Sonnet</code> as the base LLM and simple initial harness configs, the DGM-discovered agents are comparable to or outperform handcrafted agents on SWE-bench Verified (20% to 50%) and Polyglot (14.2% to 30.7%).</p>\n<p>This family of methods works well when candidate solutions are automatically evaluable and candidate fitness is easy to quantify, such as matrix multiplication, GPU kernel optimization, algorithm contests, datacenter scheduling. It struggles with domains where evaluation is slow, ambiguous, or mostly heuristic-based. The compute efficiency and effectiveness of evolution are also concerns.</p>\n<h2>Joint Optimization with Model Weights</h2>\n<p>Harness evolution changes the non-parametric system around the model. To enable full self-improvement, the model can totally be allowed to update its own weights at the same time. The weight update can be implemented via improvements in the model training pipeline or continual learning at test time. The topic of continual learning is worthy of its own post in the future.</p>\n<p><strong>SIA</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.27276\">Hebbar et al. 2026</a>) is an early attempt to combine harness improvement and model-parameter updates in the same optimization loop, with three components in the design:</p>\n<ul>\n<li><em>Meta-Agent</em>: proposes the initial harness.</li>\n<li><em>Task-Specific Agent</em>: executes the task.</li>\n<li><em>Feedback-Agent</em>: chooses whether to update the harness or the model weights based on recent trajectories.</li>\n</ul>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-07-04-harness/SIA.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The Feedback-Agent in SIA decides the next iteration type. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.27276\">Hebbar et al. 2026</a>)</figcaption></figure>\n<p>There are a few confounding choices in SIA’s experiments that make the results hard to interpret. For example, the task-specific agent is much weaker than the models used for the Meta-Agent and Feedback-Agent (<code>gpt-oss-120b</code> vs <code>Claude Sonnet 4.6</code>), and the baselines are too weak to cross-reference cleanly against related methods. I would consider the direction interesting, but the evidence provisional. Yet many challenges, such as training stability and Goodhart effect, still remain open.</p>\n<p><strong>Continual Harness</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.09998\">Karten et al. 2026</a>) experimented in long-horizon gameplay setting with harness updating and co-learning a policy model by distilling a strong teacher model’s labels on low-reward trajectories.</p>\n<h2>Future Challenges</h2>\n<p>The AI Scientist line of work is a strong demonstration that an expert-designed harness can coordinate a large portion of auto-research loop, experimented in the form of writing research papers. But paper production is not identical to scientific discovery. A system can write a plausible manuscript while still having fabricated citations, implementation drift, or weak experimental results.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2601.03315\">Trehan &amp; Chopra (2026)</a> tested whether LLMs can go from a research idea to a paper with minimal scaffolding and basic tools (i.e., <code>read_file</code>, <code>write_file</code>, <code>llm_search</code>, <code>list_files</code>). Each idea had a dedicated workspace where agents could generate and read documents as part of context. They experimented in three domains (world models, multi-agent RL, AI safety &amp; alignment), with each domain containing 45-50 high-quality seed documents to inspire new ideas. Only four ideas were selected by human experts to run through the full pipeline, and only one was fully executed into a paper. They observed six recurring failure modes in the experiments:</p>\n<ul>\n<li><em>Bias toward training-data defaults</em>: use old libraries, stale commands, standard formats, or assumptions not grounded in the actual repository or dataset.</li>\n<li><em>Implementation drift under execution pressure</em>: when implementation becomes technically complex, the model may move toward a common simpler solution rather than the proposed method.</li>\n<li><em>Memory and context degradation</em>: long-horizon projects lose critical details unless logs are written as persistent artifacts.</li>\n<li><em>Over-optimism</em>: the model declares success despite noisy or failed experiments, similarly observed as “p-hacking and eureka-ing” pattern by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2511.16072\">Bubeck et al. (2025)</a> where models can introduce “numerical duct tape” and declare victory when signals are still noise.</li>\n<li><em>Insufficient domain intelligence</em>: the model lacks tacit craft knowledge, e.g. predicting implementation complexity, judging whether an experimental result is plausible, or knowing which baselines matter.</li>\n<li><em>Weak scientific taste</em>: experiments may be executable but fail to answer the right question.</li>\n</ul>\n<p>Toward full RSI, researchers have made real progress, but several bottlenecks remain.</p>\n<p><strong>1. Weak and fuzzy evaluators.</strong> Many research claims do not have a fast and precise verifier, and the same is true for many real-world tasks. Current self-improvement loops work best for tasks when evaluation metrics are measurable and objective, similar as <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2018-02-19-rl-overview/\">how RL works</a>.</p>\n<p>Research taste, novelty, and long-term scientific value are much harder to measure. For example, research taste often mixes problem framing, experimental design, and judgment about which surprising results are worth pursuing and which failure cases are worth retries.</p>\n<p><strong>2. Context and memory lifecycle.</strong> Memory grows as AI agents become more autonomous and independent. A useful harness needs to manage context and memory to complement existing limitation in long-context generation while still maximizing the success of long-horizon tasks. Since humans are able to maintain memory through our life time, I see an anoloy here that <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2026-07-04-harness/#context-engineering\">context engineering</a> will and should become a core part of intelligence, rather than staying in the software system layer.</p>\n<p><strong>3. Negative results.</strong> Researchers are incentivized to publish successful results and thus literature is biased toward successes. LLMs trained on a vast amount of data (mostly human created, at least for now, lol) may be bad at deciding when to abandon a hypothesis, report a negative result, or even acknowledge a failure due to the imablance of success vs failure cases in data. A research harness should make failed attempts easy to preserve, as learning from failure is the best way to trim down the task search space.</p>\n<p><strong>4. Diversity collapse.</strong> Evolutionary and RL loops tend to exploit known high-reward patterns. We need <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2020-06-07-exploration-drl/\">mechanisms</a> to prevent the population from collapsing into variants of the same solution. This is especially critical for open-ended research, where the best path may initially look worse under the current evaluator.</p>\n<p><strong>5. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/\">Reward hacking</a>.</strong> A self-improvement loop optimizes whatever signal it is given. If the reward comes from unit tests, the agent may overfit to tests; if it comes from a judge model, it may learn reward hacking tricks specific to this judge; if it comes from benchmark scores, it may exploit benchmark artifacts.</p>\n<p>The evaluator and permission control should likely sit outside the loop that evolves harness, with held-out tests, trace audits, and human review at decision points that matter—how much oversight can be scaled up and automated remains an open research area.</p>\n<p><strong>6. Long-term success.</strong> An extrinsic loop of optimization works on rewards outside of individual rollouts that we can simulate in training sandbox.</p>\n<p>Take coding agent as an example. Coding agents have already increased daily productivity in software engineering, but many optimization goals are still too short-term. It can often complete the task at hand, but less obvious how it should protect the long-term health of a repo collectively maintained by hundreds or thousands of engineers. Standard sandbox-based RLVR-style training rarely captures maintainability, ownership boundaries, migration cost, backwards compatibility, or future debugging burden.</p>\n<p><strong>7. The role of humans.</strong> Humans should move up the stack, not be removed from the loop, meaning that human should provide oversight at the right time, at the right abstraction level and our system design should consider when and how to set up such touch points.</p>\n<p>Many challenges listed above need human’s feedback and steering. After all, we are building the technology for better future of humanity, not other way around.</p>\n<h2>Citation</h2>\n<p>Please cite this work as:</p>\n<blockquote>\n<p>Weng, Lilian. “Harness Engineering for Self-Improvement”. Lil’Log (Jul 2026). <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2026-07-04-harness/\">https://lilianweng.github.io/posts/2026-07-04-harness/</a></p>\n</blockquote>\n<p>Or use the BibTeX citation:</p>\n<pre><code><span class=\"code-snippet\">@article{weng2026harness,\n  title = {Harness Engineering for Self-Improvement},\n  author = {Weng, Lilian},\n  journal = {lilianweng.github.io},\n  year = {2026},\n  month = {July},\n  url = &quot;https://lilianweng.github.io/posts/2026-07-04-harness/&quot;\n}\n</span></code></pre>\n<h2>Appendix: Some useful benchmarks</h2>\n<ul>\n<li><strong><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2504.01848\">PaperBench</a></strong>: replicate 20 ICML 2024 Spotlight and Oral papers from scratch, including understanding paper contributions, developing a codebase, and successfully executing experiments.\n<ul>\n<li>Each replication task is decomposed into smaller, individually gradable tasks.</li>\n<li>8,316 rubrics in total, co-developed with the paper authors.</li>\n<li>The best model at the time (<code>Claude 3.5 Sonnet</code>, ~21%) does not outperform ML PhDs.</li>\n<li>Includes PaperBench, PaperBench Code-Dev (a lighter version), and JudgeEval.</li>\n</ul>\n</li>\n<li><strong><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2409.11363\">CORE-Bench</a></strong>: evaluate computational reproducibility of published research.\n<ul>\n<li>270 tasks based on 90 scientific papers across computer science, social science, and medicine.</li>\n<li>Tasks involve reproducing results from provided code and data.</li>\n<li>Includes multiple difficulty levels and both language-only and vision-language tasks.</li>\n<li>The best reported agent at the time (<code>GPT-4o</code> and <code>GPT-4o-mini</code>) achieved only 21% accuracy on the hardest task.</li>\n</ul>\n</li>\n<li><strong><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.05080\">ScienceAgentBench</a></strong>: evaluate LLM agents for data-driven scientific discovery.\n<ul>\n<li>Extracts 102 tasks from 44 peer-reviewed publications in four disciplines (math, chemistry, biology, geography).</li>\n<li>Covers basic data-science tasks in these domains: data processing, model development, data analysis, and information visualization.</li>\n</ul>\n</li>\n<li><strong><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2411.15114\">RE-Bench</a></strong>: evaluate frontier AI agents on realistic ML research-engineering envs against human experts.\n<ul>\n<li>7 challenging, open-ended ML research-engineering environments.</li>\n<li>Each environment = (scoring function, starting solution, reference solution); each can be run with 8 or fewer H100 GPUs.</li>\n<li>Examples: optimize a kernel, run a scaling-law experiment, fix an embedding, fine-tune GPT-2 for QA, etc.</li>\n<li>Includes data from 71 eight-hour attempts by 61 distinct human experts.</li>\n<li>Human experts achieved non-zero score in 82% of 8-hour attempts; 24% matched or exceeded strong reference solutions.</li>\n<li>Best AI agents scored 4× higher than humans at a 2-hour budget, but humans had better returns to longer budgets and exceeded agents at 8-hour and 32-hour settings.</li>\n</ul>\n</li>\n<li><strong><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.07095\">MLE-bench</a></strong>: evaluate ML engineering agents on offline Kaggle competitions.\n<ul>\n<li>Contains 75 ML-engineering competitions curated from Kaggle.</li>\n<li>Tests training models, preparing datasets, running experiments, and submitting predictions to grading scripts.</li>\n<li>Uses Kaggle public leaderboards as human baselines.</li>\n<li>Best setup in the paper, <code>o1-preview</code> with AIDE scaffolding, reached at least Kaggle bronze-medal level in 16.9% of competitions.</li>\n<li>Includes resource-scaling and contamination analyses.</li>\n</ul>\n</li>\n<li><strong><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2502.10517\">KernelBench</a></strong>: evaluate correctness and speed for generated GPU kernels.\n<ul>\n<li>250 PyTorch tasks to evaluate whether LLM can write fast and correct kernels.</li>\n<li>The evaluation metric fast_p = the percentage of generated kernels that are correct and faster than baseline.</li>\n</ul>\n</li>\n</ul>\n<h2>References</h2>\n<p>[1] Good, I. J. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://philpapers.org/rec/GOOSCT\">“Speculations Concerning the First Ultraintelligent Machine.”</a> <em>Advances in Computers</em>, 6:31–88, 1965.</p>\n<p>[2] Yudkowsky, Eliezer. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.lesswrong.com/posts/JBadX7rwdcRFzGuju/recursive-self-improvement\">“Recursive Self-Improvement.”</a> LessWrong, 2008.</p>\n<p>[3] Choi, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openreview.net/forum?id=lTbBFAoPSA\">“Anchored Self-Play for Code Repair.”</a> ICML 2026.</p>\n<p>[4] Zhao, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2505.03335\">“Absolute Zero: Reinforced Self-play Reasoning with Zero Data.”</a> arXiv preprint arXiv:2505.03335, 2025.</p>\n<p>[5] Yuan, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2401.10020\">“Self-Rewarding Language Models.”</a> arXiv preprint arXiv:2401.10020, 2024.</p>\n<p>[6] Chen, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2401.01335\">“Self-Play Fine-Tuning Converts Weak Language Models to Strong Language Models.”</a> ICML 2024.</p>\n<p>[7] Zhang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2510.04618\">“Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models.”</a> ICLR 2026.</p>\n<p>[8] Ye, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2601.21557\">“Meta Context Engineering via Agentic Skill Evolution.”</a> arXiv preprint arXiv:2601.21557, 2026.</p>\n<p>[9] Lee, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2603.28052\">“Meta-Harness: End-to-End Optimization of Model Harnesses.”</a> arXiv preprint arXiv:2603.28052, 2026.</p>\n<p>[10] Lu, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.nature.com/articles/s41586-026-10265-5\">“Towards end-to-end automation of AI research.”</a> <em>Nature</em>, 651:914–919, 2026.</p>\n<p>[11] Meng, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.26340\">“ScientistOne: Towards Human-Level Autonomous Research via Chain-of-Evidence.”</a> arXiv preprint arXiv:2605.26340, 2026.</p>\n<p>[12] Kulikov, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2606.25996\">“Autodata: An agentic data scientist to create high quality synthetic data.”</a> arXiv preprint arXiv:2606.25996, 2026.</p>\n<p>[13] Hu, Lu, and Clune. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.08435\">“Automated Design of Agentic Systems.”</a> ICLR 2025.</p>\n<p>[14] Madaan, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2303.17651\">“Self-Refine: Iterative Refinement with Self-Feedback.”</a> NeurIPS 2023.</p>\n<p>[15] Zhang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.10762\">“AFlow: Automating Agentic Workflow Generation.”</a> ICLR 2025.</p>\n<p>[16] Zelikman, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.02304\">“Self-Taught Optimizer (STOP): Recursively Self-Improving Code Generation.”</a> COLM 2024.</p>\n<p>[17] Zhang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2606.09498\">“Self-Harness: Harnesses That Improve Themselves.”</a> arXiv preprint arXiv:2606.09498, 2026.</p>\n<p>[18] Fernando, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2309.16797\">“Promptbreeder: Self-Referential Self-Improvement Via Prompt Evolution.”</a> arXiv preprint arXiv:2309.16797, 2023.</p>\n<p>[19] Agrawal, A. et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2507.19457\">“GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning.”</a> arXiv preprint arXiv:2507.19457, 2025.</p>\n<p>[20] Novikov, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2506.13131\">“AlphaEvolve: A coding agent for scientific and algorithmic discovery.”</a> arXiv preprint arXiv:2506.13131, 2025.</p>\n<p>[21] Lange, Imajuku, and Cetin. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2509.19349\">“ShinkaEvolve: Towards Open-Ended And Sample-Efficient Program Evolution.”</a> arXiv preprint arXiv:2509.19349, 2025.</p>\n<p>[22] Wang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2511.23473\">“ThetaEvolve: Test-time Learning on Open Problems.”</a> arXiv preprint arXiv:2511.23473, 2025.</p>\n<p>[23] Zhang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2505.22954\">“Darwin Gödel Machine: Open-Ended Evolution of Self-Improving Agents.”</a> arXiv preprint arXiv:2505.22954, 2025.</p>\n<p>[24] Zhang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2603.19461\">“Hyperagents.”</a> arXiv preprint arXiv:2603.19461, 2026.</p>\n<p>[25] Yuksekgonul, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2601.16175\">“Learning to Discover at Test Time.”</a> arXiv preprint arXiv:2601.16175, 2026.</p>\n<p>[26] Riaz, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.11328\">“Epistemic Uncertainty for Test-Time Discovery.”</a> arXiv preprint arXiv:2605.11328, 2026.</p>\n<p>[27] Hebbar, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.27276\">“SIA: Self Improving AI with Harness &amp; Weight Updates.”</a> arXiv preprint arXiv:2605.27276, 2026.</p>\n<p>[28] Trehan and Chopra. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2601.03315\">“Why LLMs Aren’t Scientists Yet: Lessons from Four Autonomous Research Attempts.”</a> arXiv preprint arXiv:2601.03315, 2026.</p>\n<p>[29] Bubeck, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2511.16072\">“Early science acceleration experiments with GPT-5.”</a> arXiv preprint arXiv:2511.16072, 2025.</p>\n<p>[30] Starace, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2504.01848\">“PaperBench: Evaluating AI’s Ability to Replicate AI Research.”</a> ICML 2025.</p>\n<p>[31] Wijk, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2411.15114\">“RE-Bench: Evaluating frontier AI R&amp;D capabilities of language model agents against human experts.”</a> ICML 2025.</p>\n<p>[32] Chan, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.07095\">“MLE-bench: Evaluating Machine Learning Agents on Machine Learning Engineering.”</a> arXiv preprint arXiv:2410.07095, 2024.</p>\n<p>[33] Chen, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.05080\">“ScienceAgentBench: Toward Rigorous Assessment of Language Agents for Data-Driven Scientific Discovery.”</a> ICLR 2025.</p>\n<p>[34] Siegel, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2409.11363\">“CORE-Bench: Fostering the Credibility of Published Research Through a Computational Reproducibility Agent Benchmark.”</a> TMLR 2024.</p>\n<p>[35] Ouyang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2502.10517\">“KernelBench: Can LLMs Write Efficient GPU Kernels?”</a> arXiv preprint arXiv:2502.10517, 2025.</p>\n<p>[36] Lin, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.30621\">“Harness Updating Is Not Harness Benefit: Disentangling Evolution Capabilities in Self-Evolving LLM Agents.”</a> arXiv preprint arXiv:2605.30621, 2026.</p>\n<p>[37] Lin, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2604.25850\">“Agentic Harness Engineering: Observability-Driven Automatic Evolution of Coding-Agent Harnesses.”</a> arXiv preprint arXiv:2604.25850, 2026.</p>\n<p>[38] Karten, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.09998\">“Continual Harness: Online Adaptation for Self-Improving Foundation Agents.”</a> arXiv preprint arXiv:2605.09998, 2026.</p>\n<p>[39] Che, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.24539\">“DemoEvolve: Overcoming Sparse Feedback in Agentic Harness Evolution with Demonstrations.”</a> arXiv preprint arXiv:2605.24539, 2026.</p>\n",
      "date_modified": "2026-07-04T00:00:00+00:00",
      "date_published": "2026-07-04T00:00:00+00:00",
      "external_url": "https://lilianweng.github.io/posts/2026-07-04-harness/",
      "id": "urn:aggr:item:f02f9779fd0043e755ca3cc3d5dc7347679fd454",
      "language": "en-US",
      "summary": "The concept of recursive self-improvement (RSI) dates back to I. J. Good (1965), where he defined an “ultraintelligent machine” as a system that can surpass humans in all intellectual activities and design better machines to improve…",
      "tags": [
        "programming"
      ],
      "title": "Harness Engineering for Self-Improvement",
      "url": "https://aggr.aymericbeaumet.com/items/lilianweng-github-io/2026-07-04-harness-engineering-for-self-improvement/"
    },
    {
      "content_html": "<p>Scaling laws are one of the most critical empirical findings in deep learning. The observation is simple in form: the training loss <span class=\"math\">L</span> decreases predictably as we scale up model size <span class=\"math\">N</span>, dataset size <span class=\"math\">D</span>, and compute <span class=\"math\">C</span>, following a power-law curve, which appears as a straight line on a log-log plot. We can view scaling laws as a framework for describing the relationship between compute, loss, model size and data; at its core, it is about how to allocate precious compute optimally between <span class=\"math\">N</span> and <span class=\"math\">D</span>.</p>\n<p>This predictability makes scaling laws highly valuable in practice. A common workflow is to fit scaling laws on a handful of small runs and then extrapolate to estimate the token and compute requirements for larger models.</p>\n<table>\n<thead>\n<tr>\n<th>Symbol</th>\n<th>Note</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><span class=\"math\">N</span></td>\n<td>Model size, measured in parameter count.</td>\n</tr>\n<tr>\n<td><span class=\"math\">D</span></td>\n<td>Training dataset size, usually measured in token count.</td>\n</tr>\n<tr>\n<td><span class=\"math\">C</span></td>\n<td>Training compute in FLOPs. As a useful approximation, <span class=\"math\">C ≈ 6ND</span> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2001.08361\">Kaplan et al. 2020</a>), where $2ND$ accounts for the forward pass and $4ND$ for backpropagation.</td>\n</tr>\n<tr>\n<td><span class=\"math\">E</span></td>\n<td>Irreducible loss</td>\n</tr>\n<tr>\n<td><span class=\"math\">L, L̂(.)</span></td>\n<td>Test loss / test loss prediction function; can also refer to training loss, since they are strongly correlated.</td>\n</tr>\n<tr>\n<td><span class=\"math\">ϵ</span></td>\n<td>Generalization error.</td>\n</tr>\n</tbody>\n</table>\n<h2>Early days: ML loss predictability</h2>\n<p>The predictability of generalization error with scale had already been investigated before scaling laws became a mainstream concept.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://ieeexplore.ieee.org/document/6796972\">Amari et al. (1992)</a> derived four types of learning curves using a Bayesian approach and the annealed approximation.</p>\n<ol>\n<li>Deterministic learning algorithm, noiseless data, one unique solution: <span class=\"math\">ϵ ∼ c ⋅ D⁻¹</span>, where <span class=\"math\">c</span> is some constant.</li>\n<li>Deterministic learning algorithm, noiseless data, multiple equivalent solutions: <span class=\"math\">ϵ ∼ c ⋅ D⁻²</span>; the learning is faster with each new data point, because the model only learns the optimal manifold of parameters, instead of finding the single solution point.</li>\n<li>Deterministic learning algorithm, noisy data: <span class=\"math\">ϵ ∼ c ⋅ D^(−1/2)</span>; noises in data make learning harder.</li>\n<li>Stochastic learning algorithm, noisy data: <span class=\"math\">ϵ ∼ c ⋅ D⁻¹ + E</span>; here the irreducible loss <span class=\"math\">E</span> is the residual error that a stochastic learner cannot reduce further, for example when the model runs out of capacity on large data. All four types of learning curves follow a power law:</li>\n</ol>\n<p><span class=\"math math-display\">ϵ ∼ c ⋅ D^α + E</span></p>\n<p>where <span class=\"math\">E</span> can be 0 and <span class=\"math\">α = −2, −1, −1/2</span>. Although their theoretical setup is based on a simplified binary classification task, it points in a useful direction for building empirical ML loss prediction models.</p>\n<p>One of the earliest empirical studies by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1712.00409\">Hestness et al. (2017)</a> explained the relationship between generalization error, model size and data. For a given training data size, they identified the best-fit model size via grid search and then plotted loss against training dataset size. Across four different domains in deep learning (neural machine translation, image classification, language modeling, and speech recognition), a recurring pattern was observed where:</p>\n<ul>\n<li>Generalization error scales as a power law across a set of factors (e.g. data size).</li>\n<li>Model improvements shift the error curve but do not seem to affect the power-law exponent.</li>\n<li>Interestingly, architecture changes the offset (<span class=\"math\">E</span>) of the power-law fit but does not change the exponent (<span class=\"math\">α</span>). The slope of the power law appears to be a property of the problem domain rather than the model architecture.</li>\n<li>The number of model parameters <span class=\"math\">N</span> needed to fit a dataset of size <span class=\"math\">D</span> also scales as a power law.</li>\n</ul>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/hestness-1.png\" alt=\"\" loading=\"eager\" decoding=\"async\" fetchpriority=\"high\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Learning curves for (Left) Deep-Speech-2 (DS2) and attention speech model and for (Right) DS2 models of various sizes. The losses of small models plateau when training data becomes large. (Image source: Hestness et al. 2017)</figcaption></figure>\n<p>A conceptual illustration breaks the learning curve into three stages. In the small-data region, when there are not enough learning signals, the model performs only slightly better than random guessing. In the middle (“power-law region”), we observe a power-law relationship between loss, data, and model size. The final irreducible-error region can be attributed to factors such as noise in the data.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/hestness-2.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of power-law learning curve phases. (Image source: Hestness et al. 2017)</figcaption></figure>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1909.12673\">Rosenfeld et al. (2020)</a> pushed this further by trying to model error as a joint function of both model size <span class=\"math\">N</span> and data size <span class=\"math\">D</span>, across a diverse set of architectures (ResNet, WRN, LSTM, Transformer) and optimizers (Adam, SGD variants). Empirically they observed that, holding one axis fixed, the error decays as a power law in the other:</p>\n<p><span class=\"math math-display\">L̂(D,N) ≈ A/N^α + E_N, L̂(D,N) ≈ B/D^β + E_D</span></p>\n<p>which can be combined into a joint form:</p>\n<p><span class=\"math math-display\">L̂(D, N) ≈ A/N^α + B/D^β + E</span></p>\n<p>where <span class=\"math\">A &gt; 0, B &gt; 0, α ≥ 0, β ≥ 0</span> are scalar constants and <span class=\"math\">E</span> is not dependent on either <span class=\"math\">N</span> or <span class=\"math\">D</span>.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/rosenfeld-1.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>A 3D contour plot of data size, model size and generalization error in log-log-log scale. Blue dots are derived from empirical experiments and the surface is a linear interpolation between blue dots. (Image source: Rosenfeld et al. 2020)</figcaption></figure>\n<p>Thus, they can build a prediction model in the form of a simple parametric function with <span class=\"math\">θ = ⟨ A, B, E, α, β ⟩</span> to predict the expected loss for <span class=\"math\">(D, N)</span> &gt; certain thresholds by only training on a set of smaller training configs, <span class=\"math\">(D, N)</span> &lt; certain thresholds.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/rosenfeld-2.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Fitting the parametric error model on small-scale configurations and extrapolating to larger model/data regimes: (a) Illustration of the experiment setup; Experiment results on (b) ImageNet, (c) WikiText-103 and (d) CIFAR100 Error estimation with three architectures (WRN, VGG, DenseNet) and two optimizers (SGD, Adam). (Image source: Rosenfeld et al. 2020)</figcaption></figure>\n<p>Side note: These early works lean on classical learning-theory intuition like the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Vapnik%E2%80%93Chervonenkis_dimension\">VC dimension</a> (the cardinality of the largest set of points a model can shatter) as a proxy for capacity, but in modern deep learning work the VC dimension is often too coarse to explain the behavior and the empirical power laws turned out to be much cleaner and more practical than the worst-case bounds that theory provides.</p>\n<h2>Scaling Laws in Data-Infinite Region</h2>\n<h2>Kaplan et al.’s Scaling Laws</h2>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2001.08361\">Kaplan et al. (2020)</a> popularized the concept of scaling laws in the language modeling community. They found that the cross-entropy test loss <span class=\"math\">L</span> scales as a power law with each of model size <span class=\"math\">N</span> (excluding embedding layers), dataset size <span class=\"math\">D</span>, and training compute <span class=\"math\">C</span> across many orders of magnitude. The findings are aligned with early work in the last section, but Kaplan et al. formalized the concept with a focus on Transformer language models and empirical experimentation at a larger scale, with model size ranging from 768M to 1.5B non-embedding parameters and dataset size from 22M to 23B tokens. All training runs in the paper used a learning rate schedule with a 3000 step linear warmup, followed by a cosine decay to zero.</p>\n<p>List of key findings:</p>\n<ul>\n<li>The loss <span class=\"math\">L</span> scales as a power law with <span class=\"math\">N</span>, <span class=\"math\">D</span>, and <span class=\"math\">C</span> individually; for optimal performance all three must scale in tandem.</li>\n<li>Training curves follow predictable power laws whose parameters are roughly independent of model size.</li>\n<li>Larger models are more sample-efficient, meaning that they reach a given loss with fewer optimization steps and fewer data points than small models.</li>\n<li>Architectural details (width, aspect ratio, etc.) matter less than sheer scale.</li>\n<li>Train loss and test loss are positively correlated. (Sounds trivial but this is the foundation for pretraining work. On the other hand, whether pretraining loss improvement transfers to posttraining evaluation needs separate studies.)</li>\n<li>Given a fixed compute budget, it is more efficient to train a very large model and stop <em>before convergence</em> than to train a smaller model all the way to convergence. <strong>This finding is where the Chinchilla scaling laws (the next section) disagree: Kaplan et al. overestimated the optimal model size as their fitted exponent was larger.</strong></li>\n</ul>\n<p>They summarize the joint dependence on <span class=\"math\">N</span> and <span class=\"math\">D</span> in a single equation:</p>\n<p><span class=\"math math-display\">L̂(N,D) = [ (a/N)^(α/β) + b/D ]^β</span></p>\n<p>A nice consequence of this form is that the extent of overfitting (i.e. model is complex or data is small) depends predominantly on the ratio <span class=\"math\">N^(α / β) / D</span>, which indicates that the data needs to grow in a specific proportion to the growth of the model size to avoid training being data-limited.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/kaplan-1.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Test loss as a power law in compute, dataset size, and parameters, spanning many orders of magnitude. (Image source: Kaplan et al. 2020)</figcaption></figure>\n<p>The most influential and, in hindsight, most contested conclusion was the compute-optimal allocation. Kaplan et al. found <span class=\"math\">Nₒₚₜ ∝ C^(0.73)</span> and concluded that model size should grow faster than dataset size. Concretely, for a 10x increase in compute they suggested scaling the model size by ~5.5x but the training tokens by only ~1.8x. The Chinchilla paper would later overturn this recommendation, arguing that it leaves large models badly <em>undertrained</em>.</p>\n<p>Another useful analysis in Kaplan et al. approximates the number of training FLOPs needed based on <span class=\"math\">D</span> and <span class=\"math\">N</span>. Each multiply-add is counted as ~2 FLOPs.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/kaplan-2.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Parameter and compute estimation for different Transformer architectural components, given the number of layers <span class=\"math\">n_(layer)</span>, model width <span class=\"math\">d_(model)</span> (= <span class=\"math\">d_(embed)</span>; the notation is inconsistent in the original table), dimension of feed-forward layer <span class=\"math\">d_(ff)</span> (often equivalent to <span class=\"math\">4 d_(model)</span>, attention dimension <span class=\"math\">dₐₜₜₙ</span> (often equivalent to <span class=\"math\">d_(model)</span>), the context length <span class=\"math\">n_(ctx)</span> and the vocabulary size <span class=\"math\">n_(vocab)</span>. (Image source: Kaplan et al. 2020)</figcaption></figure>\n<p>Given a standard config where <span class=\"math\">dₐₜₜₙ = d_(model) = d_(ff)/4</span>, and excluding embedding layers from <span class=\"math\">N</span> and the per-token forward compute:</p>\n<p><span class=\"math math-display\">N = n_(layer) d_(model) 3 dₐₜₜₙ + n_(layer) dₐₜₜₙ d_(model) + n_(layer) 2 d_(model) d_(ff) ; no embedding layer<br>= 2 n_(layer) d_(model)(2dₐₜₜₙ + d_(ff))<br>= 12 n_(layer) d_(model)²<br>C_(fwd) = 2 n_(layer) (d_(model) 3 dₐₜₜₙ + n_(ctx)dₐₜₜₙ + dₐₜₜₙd_(embed) + 2 d_(model) d_(ff))<br>= 2 n_(layer) (12 d_(model)² + n_(ctx)dₐₜₜₙ)<br>= 2N + 2 n_(layer)n_(ctx)dₐₜₜₙ<br>≈ 2N ; assuming n_(ctx) &lt; 12 d_(model) and the n_(ctx) term is relatively small.</span></p>\n<p>Then we count backward-pass FLOPs as twice the forward-pass FLOPs, because backpropagation runs two matrix multiplications, for gradients with respect to the input activations and the weights, respectively. Thus, in total, the training FLOPs per token are approximately <span class=\"math\">6N</span>, and the total FLOPs for training over <span class=\"math\">D</span> tokens are <span class=\"math\">C ≈ 6ND</span>.</p>\n<h2>Chinchilla Scaling Laws</h2>\n<p>The Chinchilla paper (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2203.15556\">Hoffmann et al. 2022</a>) studied the relationship between the optimal model size <span class=\"math\">N</span> (total parameters, <em>including</em> embeddings) and the number of tokens <span class=\"math\">D</span> under a <em>fixed</em> compute budget <span class=\"math\">C</span> with a more careful experimental design and arrived at a somewhat different answer from Kaplan et al..</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/animal.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>You should know how chinchilla looks 😊 (Image source: ChatGPT generated)</figcaption></figure>\n<p>The central question is on the best strategy to allocate resources given a constraint <span class=\"math\">FLOPs(N, D) = C ≈ 6ND</span>. In other words, when we have only limited FLOPs (a given number of GPUs running for a given period of time), how should we choose between more data tokens and more model parameters?</p>\n<p><span class=\"math math-display\">Nₒₚₜ(C), Dₒₚₜ(C) = *arg min_(s.t. FLOPs(N,D) = C) L̂(N, D)</span></p>\n<p>The Chinchilla paper presented three neatly designed methods for scaling laws fitting.</p>\n<p>The empirical experiments scanned over 400 models, with sizes from 70M to over 16B parameters and training tokens from 5B to 500B. The experiments were under the assumption that every training token is unique (the infinite-data regime). All runs used a cosine learning-rate schedule decaying by 10x over the training horizon. Sweeping over model sizes traces out the compute-optimal frontier.</p>\n<h3>Method 1: Fix model sizes, vary the token budget</h3>\n<p>For each parameter count <span class=\"math\">N</span>, train several runs with different token budgets, and record the minimal loss achieved per FLOP budget <span class=\"math\">C</span>.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/chinchilla-1.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Chinchilla Method 1: training loss curves over FLOP budgets for a sweep of model sizes. (Image source: Hoffmann et al. 2022)</figcaption></figure>\n<h3>Method 2: IsoFLOP profiles</h3>\n<p>Fix a compute budget <span class=\"math\">C</span> and plot the final loss against parameter count <span class=\"math\">N</span>. Each iso-FLOP curve is roughly a parabola in log-space, and its minimum flags the optimal model size for that compute budget. Then repeating across budgets traces a power-law line in the plot.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/chinchilla-2.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Chinchilla Method 2: IsoFLOP parabolas; the minimum of each curve is the compute-optimal model size for that budget. (Image source: Hoffmann et al. 2022)</figcaption></figure>\n<h3>Method 3: Parametric fit</h3>\n<p>Fit the same parametric function as in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1909.12673\">Rosenfeld et al. (2020)</a> directly,</p>\n<p><span class=\"math math-display\">L̂(N, D) = A/N^α + B/D^β + E</span></p>\n<p>We can actually get a closed form approximation of optimal <span class=\"math\">Nₒₚₜ(C), Dₒₚₜ(C)</span> by minimizing <span class=\"math\">L̂(N, D)</span> under the constraint <span class=\"math\">FLOPs(N,D) = C ≈ 6ND</span>.</p>\n<p>First let’s reduce the expression to contain only <span class=\"math\">N</span>:</p>\n<p><span class=\"math math-display\">L̂(N) = A N^(−α) + B (C/6)^(−β)N^β + E<br>L̂′(N) = −α A N^(−α−1) + β B (C/6)^(−β) N^(β −1) = 0 ; derivative wrt N should be zero.<br>Thus α A N^(−α−1) = β B (C/6)^(−β) N^(β −1)<br>α A = β B (C/6)^(−β) N^(α + β)<br>Nₒₚₜ = ((α A)/(β B))^(1/(α + β)) (C/6)^(β/(α+β))<br>Dₒₚₜ = C/(6 Nₒₚₜ) = ((β B)/(α A))^(1/(α + β)) (C/6)^(α/(α+β))</span></p>\n<p>When <span class=\"math\">α ≈ β</span>, model size and training tokens should scale at equal rates.</p>\n<p>To find the optimal <span class=\"math\">θ = ⟨ A, B, E, α, β⟩</span>, the Chinchilla paper adopts a <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Huber_loss\">Huber loss</a> (robust to outliers; <span class=\"math\">δ=10⁻³</span>) and the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Limited-memory_BFGS\">L-BFGS algorithm</a> (good for curve fitting with a small number of parameters).</p>\n<p><code class=\"math math-display\">\\begin{align} \\min_{A,B,E,\\alpha,\\beta} \\sum_{\\text{runs }\\{i\\}} \\text{Huber}_\\delta (\\log \\hat{L}(N_i, D_i) - \\log L_i) \\\\ \\text{ where }\\text{Huber}_\\delta (x) = \\begin{cases}\\frac{1}{2} x^2 &amp; \\text{for }\\vert x \\vert \\leq \\delta \\\\ \\delta \\cdot (\\vert x \\vert - \\frac{1}{2}\\delta), &amp; \\text{otherwise.}\\end{cases} \\end{align}</code></p>\n<p>Chinchilla arrives at its answer through three complementary methods whose final results agree with each other, and this is part of why the result was quite convincing.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/chinchilla-3.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The three methods agree on a compute-optimal frontier where <span class=\"math\">Nₒₚₜ ∝ C^(0.5)</span>, but disagree with Kaplan et al. Note that method 3's results are slightly off from the other two, which we will explain later. (Image source: Hoffmann et al. 2022)</figcaption></figure>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/chinchilla-4.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The plot of the Chinchilla predictions by three different approaches, as well as predictions by Kaplan et al. (2020). All three methods suggest that several mainstream LLMs at the time were undertrained. (Image source: Hoffmann et al. 2022)</figcaption></figure>\n<p>The claim in the Chinchilla paper that most large models (at the time, ~2022) were undertrained is supported by a famous demonstration: under the same compute budget as Gopher (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2112.11446\">Rae et al. 2021</a>; 280B parameter count, 300B token budget), they trained Chinchilla (70B parameter count, 1.4T token budget), a model 4x smaller but trained on roughly 4x more tokens and it outperformed Gopher across the board.</p>\n<h2>Reconciling Kaplan and Chinchilla</h2>\n<p>The Chinchilla scaling laws disagree with Kaplan et al. as follows:</p>\n<ul>\n<li>Instead of “grow the model faster than the data” (<span class=\"math\">Nₒₚₜ ∝ C^(0.73)</span>), for every doubling of model size, you should also double the number of training tokens (<span class=\"math\">Nₒₚₜ ∝ C^(0.5)</span>).</li>\n<li>Instead of “train a big model and stop before convergence,” you should train a smaller model on more data.</li>\n</ul>\n<p>Both papers still agree on the same underlying principle, but they disagree on where the optimal size-vs-token tradeoff lies. Why do they disagree so much?</p>\n<p><strong>Difference 1: Kaplan et al. experimented mostly on small models.</strong> Kaplan et al. experimented mostly on smaller models, while the Chinchilla paper’s experiments reached more than 10x larger scales. When we extrapolate in log-log space, a small difference in the fit can result in large differences (See <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/#toy-simulation\">toy simulation</a>).</p>\n<p><strong>Difference 2: Embedding parameter count matters for small models.</strong> In the small-parameter regime, embedding parameters are a non-negligible fraction of the total and thus counting them or not matters. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.12907\">Pearce &amp; Song (2024)</a> did a thorough analysis along this line. Let’s use <span class=\"math\">N_(∖ E), C_(∖ E)</span> to denote model size and compute when embedding is excluded and use <span class=\"math\">N, C</span> to count total parameters.</p>\n<ul>\n<li>Kaplan et al.: <span class=\"math\">N^*_(∖ E) ∝ C^(0.73)_(∖ E)</span> (non-embedding)</li>\n<li>Chinchilla: <span class=\"math\">N^* ∝ C^(0.50)</span> (total)</li>\n</ul>\n<p>To bridge them, they fit a relationship between total parameters <span class=\"math\">N_T</span> and non-embedding parameters <span class=\"math\">N_(∖ E)</span>, for some constant <span class=\"math\">ω</span>:</p>\n<p><span class=\"math math-display\">N = N_(∖ E) + ω N_(∖ E)^(1/3).</span></p>\n<p>This form has nice properties of being strictly increasing and <span class=\"math\">lim_(N → ∞) N = N_(∖ E)</span> (because <span class=\"math\">N/(N_(∖ E)) = 1 + ω N_(∖ E)^(− 2/3), lim_(N_(∖ E) → ∞) N/(N_(∖ E)) = 1</span>.</p>\n<p>Plugging this into the Chinchilla laws equation,</p>\n<p><span class=\"math math-display\">L(N_(∖ E), C_(∖ E)) = A(N_(∖ E) + ω N_(∖ E)^(1/3))^(−α) + B ((C_(∖ E))/6)^(−β) N_(∖ E)^β + E<br>L′(N_(∖ E), C_(∖ E)) = − α A (N_(∖ E) + ω N_(∖ E)^(1/3))^(−α −1)(1 + ω/3N_(∖ E)^(−2/3)) + β B ((C_(∖ E))/6)^(−β) N_(∖ E)^(β −1) = 0 ; derivative wrt N_(∖ E) should be zero.<br>Rearrange to get α A (N^*_(∖ E) + ω N^*_(∖ E)^(1/3))^(−α −1)(1 + ω/3 N^*_(∖ E)^(−2/3)) = β B ((C_(∖ E))/6)^(−β) N^*_(∖ E)^(β −1)<br>6^(−β)(α A)/(β B) (N^*_(∖ E) + ω N^*_(∖ E)^(1/3))^(−α −1)(1 + ω/3N^*_(∖ E)^(−2/3)) N^*_(∖ E)^(1 − β) = C_(∖ E)^(−β)<br>6 ((β B)/(α A))^(1/β) (N^*_(∖ E) + ω N^*_(∖ E)^(1/3))^((1 + α)/β) (N^*_(∖ E) + ω/3N^*_(∖ E)^(1/3))^(−1/β) N^*_(∖ E) = C_(∖ E)</span></p>\n<p>The relationship between <span class=\"math\">C_(∖ E)</span> and <span class=\"math\">N_(∖ E)</span> in the above equation is no longer a clean power law. We can only approximate it locally as <span class=\"math\">N^*_(∖ E) ∼ C_(∖ E)ᵍ</span>, where <span class=\"math\">g</span> is a local exponent based on a first-order derivative (<span class=\"math\">∼</span>) rather than a global power-law exponent, resulting in <span class=\"math\">g = (d log C_(∖ E))/(d log N_(∖ E))</span>. See the full details of how the exponent <span class=\"math\">g</span> is approximated in Appendix A.1 in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.12907\">Pearce &amp; Song (2024)</a>.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/pearce-1.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Visualization of how the local power-law exponent <span class=\"math\">g</span> grows with <span class=\"math\">C_(∖ E)</span>. (Image source: Pearce &amp; Song 2024)</figcaption></figure>\n<p>As shown in the visualization above, as <span class=\"math\">C_(∖ E)</span> gets larger, <span class=\"math\">g</span> converges to the Chinchilla estimate. By generating synthetic training curves using above equation, in the range of model size from 768M to 1.5B (as in Kaplan et al.), they estimated that <span class=\"math\">g</span> is close to the Kaplan coefficient of 0.73 in that region.</p>\n<h2>Why power law?</h2>\n<p>Power laws are widely observed across many domains outside AI, such as in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Zipf%27s_law\">Zipf’s law</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Scale-free_network\">scale-free networks</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Urban_scaling\">urban scaling laws</a>, and many other complex systems. The recurring pattern is that large events are rare, small events are common and the relationship between size and frequency often follows a straight line at log-log scale.</p>\n<p><strong>Why do LLM scaling laws also have the shape of a power law?</strong></p>\n<p>Inspired partly by different domains displaying different exponents (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1712.00409\">Hestness et al. 2017</a>), one early explanation by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2004.10802\">Sharma &amp; Kaplan (2020)</a> hypothesizes that language modeling can be viewed as doing regression on a low-dimensional manifold of data. More model parameters can induce a finer partition of the data manifold and therefore smaller generalization error. In the simplest terms, if a model of effective size <span class=\"math\">N</span> partitions a <span class=\"math\">d</span>-dimensional manifold into <span class=\"math\">O(N)</span> regions, the typical linear resolution scales like <span class=\"math\">∼ N^(−1/d)</span>. This has a similar power-law form to the scaling laws above. This theory applies most cleanly in the infinite-data, underfitting regime, but in reality estimating the intrinsic dimension of a data manifold is quite hard.</p>\n<p>A later hypothesis (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2303.13506\">Michaud et al. 2023</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2412.07942\">Brill 2024</a>) assumes that knowledge or skills are learned in discrete chunks (“quantized”) and that the frequency distribution of these skills follows a power law. The model learns common skills first and rare skills later, resulting in a smooth power-law decay in loss.</p>\n<p>I only listed two hypotheses here, but there are more studies on explaining the shape of power-law scaling through spectral tails of data, kernel eigenvalues, natural-language statistics, or phase transitions in training dynamics.</p>\n<h2>Scaling Laws in Data-Limited Region</h2>\n<p>Classic scaling laws assume effectively <em>unlimited unique data</em>, no repetition, and no multi-epoch training. As the model size grows significantly, we are running out of enough high-quality unique tokens. In fact, some arguments about how long scaling in AI can continue are centered on whether we are hitting a “data wall”.</p>\n<p>It is also worth emphasizing that the dataset behind <span class=\"math\">D</span> is expected to be already cleaned. The pretraining data pipeline is often a large part of an effective pretraining pipeline, with common steps like deduplication (exact and fuzzy), quality filtering, boilerplate removal, safety filtering, PII/copyright masking, benchmark decontamination and careful reweighting of data mix components based on language, quality, content type, etc. Even when two datasets contain the same token count <span class=\"math\">D</span>, a high-quality dataset and a dataset of Internet slop can yield drastically different compute efficiency.</p>\n<p>The study by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2205.10487\">Hernandez et al. (2022)</a> focused on a controlled version: a mostly-unique dataset with a small fraction of repeated data. Starting from a large dataset, the data mix keeps 90% non-repeated but replaces the remaining 10% with repeats of a tiny portion of the original. By training a Transformer model for 100B tokens, they observed a double-descent phenomenon, that is, the test loss can actually get <em>worse</em> and then better again as a function of how much the repeated data is emphasized, an effect that becomes more pronounced as the repeated fraction grows.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/hernandez-1.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Double-descent in the test loss as the repeated fraction increases (90% repeated on the left, 50% on the right). (Image source: Hernandez et al. 2022)</figcaption></figure>\n<p>The flat or increasing trend in the middle of training is possibly due to memorization of repeated data. Learning curves with such shapes make scaling law fitting less accurate. They also concluded repeated data hurts some OOD evaluation and downstream fine-tuning. However, their data mix is constructed in a more lab-like setup, and repetition in real-world data is often more nuanced (e.g. different data has different levels of repetition, semantic repetition, etc.).</p>\n<p>Rather than saying data repetition hurts training, we are more interested in how to fit scaling laws, given that the unique high-quality data is not infinite and we likely have to repeat data during training.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.16264\">Muennighoff et al. (2023)</a> took on the research question of how compute should be allocated optimally when model training is data-constrained. Specifically, they empirically studied the impact of data repetition across roughly 400 experiments, 10M–9B parameters, data sizes up to 900B tokens, and up to 1500 epochs. The exact same dataset is repeated each epoch, shuffled between epochs, and evaluated on a held-out test set.</p>\n<p>The key modeling adjustment is to decompose the total token count <span class=\"math\">D</span> into two parts: (i) the number of unique tokens <span class=\"math\">U_D</span> and (ii) the number of repeats <span class=\"math\">R_D</span> (i.e. num. epochs - 1). Thus we have <span class=\"math\">D = U_D(1 + R_D)</span>. With a unique-data budget <span class=\"math\">D_(uniq)</span>, by definition <span class=\"math\">U_D = min { D_(uniq), D}</span> and <span class=\"math\">R_D = (D / U_D) − 1</span>. They use the Chinchilla scaling laws to find the optimal model size <span class=\"math\">U_N</span> for fitting <span class=\"math\">U_D</span>, and define excess model size via repeats <span class=\"math\">R_N = (N / U_N) − 1</span>.</p>\n<p>They then update the Chinchilla parametric fit (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/#chinchilla-method3\">method 3</a>) to use effective (discounted) data <span class=\"math\">D’</span> and model size <span class=\"math\">N’</span> in place of the raw quantities:</p>\n<p><span class=\"math math-display\">L̂(N, D) = A/N′^α + B/D′^β + E where D′ = U_D + U_D r_D(1 − exp (−R_D/r_D)).</span></p>\n<p>The intuition is that a token’s value decays <em>exponentially</em> as it is repeated. In their modeling, each repetition costs the token a <span class=\"math\">(1 − 1/r_D)</span> fraction of its remaining value, where <span class=\"math\">r_D</span> is a learnable “half-life” parameter. When <span class=\"math\">R_D = 0</span> or <span class=\"math\">R_D ≪ r_D</span>, we recover <span class=\"math\">D’ ≈ D</span>.</p>\n<p>A symmetric formulation handles excess model size, <span class=\"math\">N’ = U_N + U_N r_N(1 − exp(−R_N / r_N))</span>, capturing the idea that “larger models overfit more quickly on repeated data” and that “a model can be too large for its dataset.” This component is less intuitive, and I could not find a satisfactory explanation for why model size needs to appear in such a symmetric form as repeated data. Later work by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.01640\">Lovelace et al. (2026)</a> changed this assumption.</p>\n<p>Their empirical fit finds that <em>excess parameters decay faster in value than repeated data</em>, <span class=\"math\">r_N &lt; r_D</span>, so we should allocate more resources on more epochs rather than more model parameters. One weakness of this modeling, as the authors also pointed out, is that it significantly underestimates the final test loss of failing models (i.e. models whose loss increases midway through training), such as models trained for 44 epochs.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/muennighoff-1.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Data-constrained scaling under repetition captures the experimental results better than data-unaware fitting; the value of repeated tokens decays exponentially toward a ceiling. The fitting gets worse with more epochs as high repetition causes the test loss to increase midway through training, not depicted in the plot. (Image source: Muennighoff et al. 2023)</figcaption></figure>\n<p>Most recently, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.01640\">Lovelace et al. (2026)</a> revisited the same problem with a different approach. Rather than modeling overparameterization as a diminishing return on effective model size, Lovelace et al. model the interaction between model size <span class=\"math\">×</span> data repetition explicitly. Empirically, they trained about 300 models, spanning 15M to 1B parameters and 50M to 6B unique tokens.</p>\n<p>When they plot the fit residual for a fixed model size across a range of data-repetition levels, the observation is intuitive: more epochs cause more damage, and interestingly <em>larger models are more sensitive</em> to repetition. This hints that the loss penalty is likely a function of both model size and data size.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/lovelace-1.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Residuals of the effective-size fit reveal that overfitting damage grows with both the number of epochs and the model size. (Image source: Lovelace et al. 2026)</figcaption></figure>\n<p>An explicit overfitting penalty term was introduced and built around the <em>capacity ratio</em> <span class=\"math\">N / U_D</span> (parameter count relative to unique tokens):</p>\n<p><span class=\"math math-display\">L̂(N, U_D, R_D) = E + A/N^α + B/((U_D (1 + R_D))^β) + P ⋅ R_D^δ ⋅ (N/U_D)^κ</span></p>\n<p>where:</p>\n<ul>\n<li><span class=\"math\">R_D</span> is the repetition count;</li>\n<li>the scalar <span class=\"math\">P</span> is a learnable parameter;</li>\n<li>the exponent <span class=\"math\">κ</span> (the 2nd learnable parameter) lets the penalty scale nonlinearly with the capacity ratio <span class=\"math\">N / U_D</span>;</li>\n<li>the separate exponent <span class=\"math\">δ</span> (the 3rd learnable parameter) on the repetition count decouples repetition nonlinearity from <span class=\"math\">κ</span>.</li>\n</ul>\n<p>The added term (in red) is a direct overfitting penalty that grows with both how many times you repeat the data and how over-parameterized the model is relative to the unique data available.</p>\n<p>They also did a case study on how weight decay impacts training with the limited-data constraint and found that strong weight decay reduces the overfitting penalty caused by data repetition.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/lovelace-2.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Strong weight decay reduces the overfitting penalty from data repetition. (Image source: Lovelace et al. 2026)</figcaption></figure>\n<p>Both modeling approaches by Muennighoff et al. and Lovelace et al. are constructed from empirical curve fitting, so it is still unclear why data-constrained scaling laws should have exactly these forms and why each free parameter is needed. Curious about more theoretical work along this line.</p>\n<h2>Trickiness of Fitting Scaling Laws in Reality</h2>\n<p>Despite its clean form, in practice, scaling law fitting can be surprisingly sensitive to seemingly trivial procedural choices, like how you count parameters, how you round the precision, how you sum or average the loss, etc.</p>\n<p>Because a scaling law is only fit on the (relatively small, relatively cheap) models that we can afford to train, and the prediction is <em>extrapolated</em> for a model orders of magnitude larger. In such a setup, choices that look like rounding error may lead to wild differences in prediction.</p>\n<p>Meanwhile, scaling-law fitting assumes the only changing factor is <em>scale</em>, which means that the model architecture, optimizer, learning rate schedule, batch ramp, data mix, tokenizer, and other design choices should remain the same. Another underlying assumption is that all these settings should have been carefully tuned, as cases like undertrained models can lead to a different conclusion.</p>\n<p>The disagreement between results by Kaplan et al. and Chinchilla is one example to showcase the trickiness of scaling laws fitting.</p>\n<p>A second example is a follow-up analysis investigating why Chinchilla <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/#method-3-parametric-fit\">method 3</a> is slightly off from the other two methods. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2404.10102\">Besiroglu et al. (2024)</a> extracted the raw <span class=\"math\">(N, D, L)</span> data points from Figure 4 of Hoffmann et al. (2022) and re-ran the method 3 parametric fitting. They found a couple of concrete issues:</p>\n<ul>\n<li>A high loss scale in the L-BFGS-B minimizer, caused by averaging Huber-loss values over examples instead of summing them, which led to premature termination of the optimization. The early stopping of loss minimization during both the original fit and bootstrapping produced inconsistent estimates and implausibly narrow confidence intervals.</li>\n<li>The reported <span class=\"math\">α</span> and <span class=\"math\">β</span> were rounded to 2 digits of precision, which made the derived <span class=\"math\">A, B</span> look more off than they really were.</li>\n</ul>\n<h2>Toy simulation</h2>\n<p>Here is a toy simulation widget, created by ChatGPT, designed to demonstrate three specific failure modes.</p>\n<p>We assume the ground truth function is:</p>\n<p><span class=\"math math-display\">L̂(N, D) = 482.01 ⋅ N^(−0.3478) + 2085.43 D^(−0.3658) + 1.8172</span></p>\n<p>and thus <span class=\"math\">Nₒₚₜ ∝ C^(0.5126), Dₒₚₜ ∝ C^(0.4874)</span>. This is the estimate from <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2404.10102\">Besiroglu et al. (2024)</a>.</p>\n<p>The simulation plots the loss prediction <span class=\"math\">L̂</span> vs dataset size <span class=\"math\">D</span>, while providing a set of sliders to show case:</p>\n<ul>\n<li>Loss precision: rounding losses from high to low decimal points can change the fitted parameter values.</li>\n<li>Loss noise: perturbing loss values by only a multiplier of milli-loss (0.001) units leads to different fit.</li>\n<li>Fit-region sensitivity: fitting only small models, only medium models, or all models gives different apparent scaling laws.</li>\n</ul>\n<h2>Citation</h2>\n<p>Please cite this work as:</p>\n<blockquote>\n<p>Weng, Lilian. “Scaling Laws, Carefully”. Lil’Log (Jun 2026). <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2026-06-24-scaling-laws/\">https://lilianweng.github.io/posts/2026-06-24-scaling-laws/</a></p>\n</blockquote>\n<p>Or use the BibTex citation:</p>\n<pre><code><span class=\"code-snippet\">@article{weng2026scaling,\n title = {Scaling Laws, Carefully},\n author = {Weng, Lilian},\n journal = {lilianweng.github.io},\n year = {2026},\n month = {June},\n url = &quot;https://lilianweng.github.io/posts/2026-06-24-scaling-laws/&quot;\n}\n</span></code></pre>\n<h2>References</h2>\n<p>[1] S. Amari, N. Fujita, and S. Shinomoto. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://ieeexplore.ieee.org/document/6796972\">“Four Types of Learning Curves. Neural Computation.”</a> 4(4):605–618, 1992.</p>\n<p>[2] Hestness et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1712.00409\">“Deep Learning Scaling is Predictable, Empirically.”</a> arXiv preprint arXiv:1712.00409, 2017.</p>\n<p>[3] Rosenfeld et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1909.12673\">“A Constructive Prediction of the Generalization Error Across Scales.”</a> ICLR 2020.</p>\n<p>[4] Kaplan et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2001.08361\">“Scaling Laws for Neural Language Models.”</a> arXiv preprint arXiv:2001.08361, 2020.</p>\n<p>[5] Hoffmann et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2203.15556\">“Training Compute-Optimal Large Language Models.”</a> NeurIPS 2022.</p>\n<p>[6] Pearce and Song. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.12907\">“Reconciling Kaplan and Chinchilla Scaling Laws.”</a> TMLR 2024.</p>\n<p>[7] Bahri et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2102.06701\">“Explaining Neural Scaling Laws.”</a> arXiv preprint arXiv:2102.06701, 2021.</p>\n<p>[8] Sharma and Kaplan. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2004.10802\">“A Neural Scaling Law from the Dimension of the Data Manifold.”</a> arXiv preprint arXiv:2004.10802, 2020.</p>\n<p>[9] Hernandez et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2205.10487\">“Scaling Laws and Interpretability of Learning from Repeated Data.”</a> arXiv preprint arXiv:2205.10487, 2022.</p>\n<p>[10] Muennighoff et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.16264\">“Scaling Data-Constrained Language Models.”</a> NeurIPS 2023.</p>\n<p>[11] Lovelace et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2605.01640\">“Prescriptive Scaling Laws for Data Constrained Training.”</a> arXiv preprint arXiv:2605.01640, 2026.</p>\n<p>[12] Besiroglu et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2404.10102\">“Chinchilla Scaling: A Replication Attempt.”</a> arXiv preprint arXiv:2404.10102, 2024.</p>\n<p>[13] Michaud et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2303.13506\">“The Quantization Model of Neural Scaling”</a> NeurIPS 2023.</p>\n<p>[14] Brill. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2412.07942\">“Neural Scaling Laws Rooted in the Data Distribution.”</a> arXiv preprint arXiv:2412.07942, 2024.</p>\n<p>[15] Rae et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2112.11446\">“Scaling Language Models: Methods, Analysis &amp; Insights from Training Gopher.”</a> arXiv preprint arXiv:2112.11446, 2021.</p>\n",
      "date_modified": "2026-06-24T00:00:00+00:00",
      "date_published": "2026-06-24T00:00:00+00:00",
      "external_url": "https://lilianweng.github.io/posts/2026-06-24-scaling-laws/",
      "id": "urn:aggr:item:b60dab45ad02770ff31333914bf48126d9a0df82",
      "language": "en-US",
      "summary": "Scaling laws are one of the most critical empirical findings in deep learning. The observation is simple in form: the training loss L decreases predictably as we scale up model size N, dataset size D, and compute C, following a power-law…",
      "tags": [
        "programming"
      ],
      "title": "Scaling Laws, Carefully",
      "url": "https://aggr.aymericbeaumet.com/items/lilianweng-github-io/2026-06-24-scaling-laws-carefully/"
    },
    {
      "content_html": "<p>Special thanks to <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://scholar.google.com/citations?user=itSa94cAAAAJ&amp;hl=en\">John Schulman</a> for a lot of super valuable feedback and direct edits on this post.</p>\n<p>Test time compute (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1603.08983\">Graves et al. 2016</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1705.04146\">Ling, et al. 2017</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2110.14168\">Cobbe et al. 2021</a>) and Chain-of-thought (CoT) (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.11903\">Wei et al. 2022</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2112.00114\">Nye et al. 2021</a>), have led to significant improvements in model performance, while raising many research questions. This post aims to review recent developments in how to effectively use test-time compute (i.e. “thinking time”) and why it helps.</p>\n<h2>Motivation</h2>\n<p>Enabling models to think for longer can be motivated in a few different ways.</p>\n<h2>Analogy to Psychology</h2>\n<p>The core idea is deeply connected to how humans think. We humans cannot immediately provide the answer for <code>&quot;What's 12345 times 56789?&quot;</code>. Rather, it is natural to spend time pondering and analyzing before getting to the result, especially for complex problems. In <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.amazon.com/Thinking-Fast-Slow-Daniel-Kahneman/dp/0374533555\">Thinking, Fast and Slow (Kahneman, 2013)</a>, Daniel Kahneman characterizes human thinking into two modes, through the lens of the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Dual_process_theory\">dual process theory</a> :</p>\n<ul>\n<li><em>Fast thinking (System 1)</em> operates quickly and automatically, driven by intuition and emotion while requiring little to no effort.</li>\n<li><em>Slow thinking (System 2)</em> demands deliberate, logical thought and significant cognitive efforts. This mode of thinking consumes more mental energy and requires intentional engagement.</li>\n</ul>\n<p>Because System 1 thinking is fast and easy, it often ends up being the main decision driver, at the cost of accuracy and logic. It naturally relies on our brain’s mental shortcuts (i.e., heuristics) and can lead to errors and biases. By consciously slowing down and taking more time to reflect, improve and analyze, we can engage in System 2 thinking to challenge our instincts and make more rational choices.</p>\n<h2>Computation as a Resource</h2>\n<p>One view of deep learning, is that neural networks can be characterized by the amount of computation and storage they can access in a forward pass, and if we optimize them to solve problems using gradient descent, the optimization process will figure out how to use these resources–they’ll figure out how to organize these resources into circuits for calculation and information storage. From this view, if we design an architecture or system that can do more computation at test time, and we train it to effectively use this resource, it’ll work better.</p>\n<p>In Transformer models, the amount of computation (flops) that the model does for each generated token is roughly 2 times the number of parameters. For sparse models like mixture of experts (MoE), only a fraction of the parameters are used in each forward pass, so computation = 2 * parameters / sparsity, where sparsity is the fraction of experts active.</p>\n<p>On the other hand, CoT enables the model to perform far more flops of computation for each token of the answer that it is trying to compute. In fact, CoT has a nice property that it allows the model to use a variable amount of compute depending on the hardness of the problem.</p>\n<h2>Latent Variable Modeling</h2>\n<p>A classic idea in machine learning is to define a probabilistic model with a latent (hidden) variable <span class=\"math\">z</span> and a visible variable <span class=\"math\">y</span>, where <span class=\"math\">y</span> is given to our learning algorithm. Marginalizing (summing) over the possible values of the latent variable allows us to express a rich distribution over the visible variables, <span class=\"math\">P(y) = ∑_(z ∼ P(z)) P(y | z)</span>. For example, we can model the distribution over math problems and solutions by letting <span class=\"math\">x</span> denote a problem statement, <span class=\"math\">y</span> be ground truth answer or proof, and <span class=\"math\">z</span> as a free-form thought process that leads to the proof. The marginal probability distribution to optimize would be <span class=\"math\">P(y | x) = ∑_(z ∼ p(z| x)) P(y | x, z)</span></p>\n<p>The latent variable perspective is particularly useful for understanding methods that involve collecting multiple parallel CoTs or searching over the CoT–these algorithms can be seen as sampling from the posterior <span class=\"math\">P(z | x, y)</span>. This view also suggests the benefits of using the log loss <span class=\"math\">log P(y | x)</span> as the target objective to optimize, as the log loss objective has been so effective in pretraining.</p>\n<h2>Thinking in Tokens</h2>\n<p>The strategy of generating intermediate steps before generating short answers, particularly for math problems, was explored by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1705.04146\">Ling, et al. 2017</a>, who introduced the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/google-deepmind/AQuA\">AQUA-RAT</a> dataset, and then expanded by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2110.14168\">Cobbe et al. 2021</a>, who introduced the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/openai/grade-school-math\">Grade School Math (GSM)</a> dataset. Cobbe et al. train a generator with supervised learning on human-written solutions and verifiers that predict the correctness of a candidate solution; they can then search over these solutions. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2112.00114\">Nye et al. (2021</a>) experimented with intermediate thinking tokens as “scratchpads” and <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.11903\">Wei et al.</a> (2022) coined the now-standard term <strong>chain-of-thought</strong> (CoT).</p>\n<p>Early work on improving CoT reasoning involved doing supervised learning on human-written reasoning traces or model-written traces filtered for answer correctness, where the latter can be seen as a rudimentary form of reinforcement learning (RL). Some other work found that one could significantly boost math performance of instruction tuned models by prompting them appropriately, with <code>&quot;think step by step&quot;</code> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2205.11916\">Kojima et al. 2022</a>) or more complex prompting to encourage the model to reflect on related knowledge first (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.01714\">Yasunaga et al. 2023</a>).</p>\n<p>Later work found that the CoT reasoning capabilities can be significantly improved by doing reinforcement learning on a dataset of problems with automatically checkable solutions, such as STEM problems with short answers, or coding tasks that can be checked with unit tests (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2203.14465\">Zelikman et al. 2022</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2312.08935\">Wang et al., 2023</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.10047\">Liu et al., 2023</a>). This approach rose to prominence with the announcement of <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openai.com/index/learning-to-reason-with-llms/\">o1-preview</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openai.com/index/introducing-o3-and-o4-mini/\">o3</a>, and the R1 tech report (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.12948\">DeepSeek-AI, 2025</a>), which showed that a simple recipe where a policy gradient algorithm could lead to strong performance.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/cot-wei22.png\" alt=\"\" loading=\"eager\" decoding=\"async\" fetchpriority=\"high\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Chain-of-thought prompting leads to higher success rate of solving math problems. Larger models benefit more from thinking time. (Image source: Wei et al. 2022)</figcaption></figure>\n<h2>Branching and Editing</h2>\n<p>The fundamental intent of test-time compute is to adaptively modify the model’s output distribution at test time. There are various ways of utilizing test time resources for decoding to select better samples and thus alter the model’s predictions towards a more desired distribution. Two main approaches for improving the decoding process are parallel sampling and sequential revision.</p>\n<ul>\n<li><strong>Parallel sampling</strong> generates multiple outputs simultaneously, meanwhile providing guidance per step with process reward signals or using verifiers to judge the quality at the end. It is the most widely adopted decoding method to improve test time performance, such as best-of-<span class=\"math\">N</span> or beam search. Self-consistency (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2203.11171\">Wang et al. 2023</a>) is commonly used to select the answer with majority vote among multiple CoT rollouts when the ground truth is not available.</li>\n<li><strong>Sequential revision</strong> adapts the model’s responses iteratively based on the output in the previous step, asking the model to intentionally reflect its existing response and correct mistakes. The revision process may have to rely on a fine-tuned model, as naively relying on the model’s intrinsic capability of self-correction without external feedback may not lead to improvement (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.01297\">Kamoi et al. 2024</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.01798\">Huang et al. 2024</a>).</li>\n</ul>\n<p>Parallel sampling is simple, intuitive and easier to implement, but bounded by the model capability of whether it can achieve the correct solution in one-go. Sequential explicitly asks the model to reflect on mistakes but it is slower and requires extra care during implementation as it does run the risk of correct predictions being modified to be incorrect or introducing other types of hallucinations. These two methods can be used together. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.03314\">Snell et al. (2024</a>) showed that easier questions benefit from purely sequential test-time compute, whereas harder questions often perform best with an optimal ratio of sequential to parallel compute.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/parallel-vs-sequential.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of parallel sampling vs sequential revision.</figcaption></figure>\n<h3>Parallel Sampling</h3>\n<p>Given a generative model and a scoring function that we can use to score full or partial samples, there are various search algorithms we can use to find a high scoring sample. Best-of-<span class=\"math\">N</span> is the simplest such algorithm: one just collects <span class=\"math\">N</span> independent samples and chooses the highest-ranking sample according to some scoring function. Beam search is a more sophisticated search algorithm that makes the search process more adaptive, spending more sampling computation on more promising parts of the solution space.</p>\n<p>Beam search maintains a set of promising partial sequences and alternates between extending them and pruning the less promising ones. As a selection mechanism, we can use a process reward model (PRM; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.20050\">Lightman et al. 2023</a>) to guide beam search candidate selection. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.00633\">Xie et al. (2023</a>) used LLM to evaluate how likely its own generated reasoning step is correct, formatted as a multiple-choice question and found that per-step self-evaluation reduces accumulative errors in multi-step reasoning during beam search decoding. Besides, during sampling, annealing the temperature helps mitigate aggregated randomness. These experiments by Xie et al. achieved 5-6% improvement on few-shot GSM8k, AQuA and StrategyQA benchmarks with the Codex model. Reward balanced search (short for “REBASE”; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.00724\">Wu et al. 2025</a>) separately trained a process reward model (PRM) to determine how much each node should be expanded at each depth during beam search, according to the softmax-normalized reward scores. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.01044\">Jiang et al. (2024)</a> trained their PRM, named “RATIONALYST”, for beam search guidance on synthetic rationales conditioned on a large amount of unlabelled data. Good rationales are filtered based on whether they help reduce the neg log-prob of true answer tokens by a threshold, when comparing the difference between when the rationales is included in the context vs not. At inference time, RATIONALYST provides process supervision to the CoT generator by helping estimate log-prob of next reasoning steps (“implicit”) or directly generating next reasoning steps as part of the prompt (“explicit”).</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/beam-search-xie23.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Beam search decoding guided by LLM self-evaluation per reasoning step. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.00633\">Xie et al. 2023</a>)</figcaption></figure>\n<p>Interestingly, it is possible to trigger the emergent chain-of-thought reasoning paths <em>without</em> explicit zero-shot or few-shot prompting. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2402.10200\">Wang &amp; Zhou (2024)</a> discovered that if we branch out at the first sampling tokens by retaining the top <span class=\"math\">k</span> tokens with highest confidence, measured as the difference between top-1 and top-2 candidates during sampling, and then continue these <span class=\"math\">k</span> sampling trials with greedy decoding onward, many of these sequences natively contain CoT. Especially when CoT does appear in the context, it leads to a more confident decoding of the final answer. To calculate the confidence of the final answer, the answer span needs to be identified by task-specific heuristics (e.g. last numerical values for math questions) or by prompting the model further with <code>&quot;So the answer is&quot;</code>. The design choice of only branching out at the first token is based on the observation that early branching significantly enhances the diversity of potential paths, while later tokens are influenced a lot by previous sequences.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/cot-decoding.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Top-<span class=\"math\">k</span> decoding, <span class=\"math\">k</span> refers to the number of candidates at the first sampling step. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2402.10200\">Wang &amp; Zhou, 2024</a>)</figcaption></figure>\n<h3>Sequential Revision</h3>\n<p>If the model can reflect and correct mistakes in past responses, we would expect the model to produce a nice sequence of iterative revision with increasing quality. However, this self-correction capability turns out to not exist intrinsically among LLMs and does not easily work out of the box, due to various failure modes, such as, (1) hallucination, including modifying correct responses to be incorrect; (2) behavior collapse to non-correcting behavior; e.g. making minor or no modification on the first incorrect responses; or (3) fail to generalize to distribution shift at test time. Experiments by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.01798\">Huang et al. (2024</a>) showed that naively applying self-correction leads to worse performance and external feedback is needed for models to self improve, which can be based on matching ground truths, heuristics and task-specific metrics, unit tests results for coding questions (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2303.11366\">Shinn, et al. 2023</a>), a stronger model (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2404.17140\">Zhang et al. 2024</a>), as well as human feedback (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2302.02676\">Liu et al. 2023</a>).</p>\n<p>Self-correction learning (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2211.00053\">Welleck et al. 2023</a>) aims to train a corrector model <span class=\"math\">P_θ(y | y₀, x)</span> given a fixed generator model <span class=\"math\">P₀(y₀ | x)</span>. While the generator model remains to be generic, the corrector model can task-specific and only does generation conditioned on an initial model response and additional feedback (e.g. a sentence, a compiler trace, unit test results; can be optional):</p>\n<ol>\n<li>Self-correction learning first generates first generates multiple outputs per prompt in the data pool;</li>\n<li>then create value-improving pairs by pairing two outputs for the same prompt together if one has a higher value than the other, (prompt <span class=\"math\">x</span>, hypothesis <span class=\"math\">y</span>, correction <span class=\"math\">y’</span>).</li>\n<li>These pairs are selected proportional to is improvement in value, <span class=\"math\">v(y’) − v(y)</span>, and similarity between two outputs, <span class=\"math\">Similarity(y, y’)</span> to train the corrector model.</li>\n<li>To encourage exploration, the corrector provides new generations into the data pool as well. At the inference time, the corrector can be used iteratively to create a correction trajectory of sequential revision.</li>\n</ol>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/self-correction-welleck23.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of self-correction learning by matching model outputs for the same problem to form value-improving pairs to train a correction model. (Image source: Welleck et al. 2023)</figcaption></figure>\n<p>Recursive inspection (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2407.18219\">Qu et al. 2024</a>) also aims to train a better corrector model but with a single model to do both generation and self-correction.</p>\n<p>SCoRe (Self-Correction via Reinforcement Learning; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2409.12917\">Kumar et al. 2024</a>) is a multi-turn RL approach to encourage the model to do self-correction by producing better answers at the second attempt than the one created at the first attempt. It composes two stages of training: stage 1 only maximizes the accuracy of the second attempt while enforcing a KL penalty only on the first attempt to avoid too much shifting of the first-turn responses from the base model behavior; stage 2 optimizes the accuracy of answers produced by both the first and second attempts. Ideally we do want to see performance at both first and second attempts to be better, but adding stage 1 prevents the behavior collapse where the model does minor or none edits on the first response, and stage 2 further improves the results.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/SCoRe-kumar24.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Explicit training setup to improve self-correction capabilities by doing two-staged RL training. (Image source: Kumar et al. 2024)</figcaption></figure>\n<h2>RL for Better Reasoning</h2>\n<p>There’s been a lot of recent success in using RL to improve the reasoning ability of language models, by using a collection of questions with ground truth answers (usually STEM problems and puzzles with easy to verify answers), and rewarding the model for getting the correct answer.Recent activity in this area was spurred by strong performance of the <code>o</code>-series models from OpenAI, and the subsequent releases of models and tech reports from <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.deepseek.com/\">DeepSeek</a>.</p>\n<p><code>DeepSeek-R1</code> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.12948\">DeepSeek-AI, 2025</a>) is an open-source LLM designed to excel in tasks that require advanced reasoning skills like math, coding and logical problem solving. They run through 2 rounds of SFT-RL training, enabling R1 to be good at both reasoning and non-reasoning tasks.</p>\n<ol>\n<li><strong>Cold-start SFT</strong> is to fine-tune the <code>DeepSeek-V3-Base</code> base model on a collection of thousands of cold-start data. Without this step, the model has issues of poor readability and language mixing.</li>\n<li><strong>Reasoning-oriented RL</strong> trains a reasoning model on reasoning-only prompts with two types of rule-based rewards:\n<ul>\n<li>Format rewards: The model should wrap CoTs by <code>&lt;thinking&gt; ... &lt;/thinking&gt;</code> tokens.</li>\n<li>Accuracy rewards: Whether the final answers are correct. The answer for math problems needs to be present in a specific format (e.g. in a box) to be verified reliably. For coding problems, a compiler is used to evaluate whether test cases pass.</li>\n</ul>\n</li>\n<li><strong>Rejection-sampling + non-reasoning SFT</strong> utilizes new SFT data created by rejection sampling on the RL checkpoint of step 2, combined with non-reasoning supervised data from <code>DeepSeek-V3</code> in domains like writing, factual QA, and self-cognition, to retrain <code>DeepSeek-V3-Base</code>.\n<ul>\n<li>Filter out CoTs with mixed languages, long paragraphs, and code blocks.</li>\n<li>Include non-reasoning tasks using DeepSeek-V3 (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2412.19437v1\">DeepSeek-AI, 2024</a>) pipeline.</li>\n<li>For certain non-reasoning tasks, call DeepSeek-V3 to generate potential CoTs before answering the question by prompting. But for simpler queries like “hello”, CoT is not needed.</li>\n<li>Then fine-tune the DeepSeek-V3-Base on the total 800k samples for 2 epochs.</li>\n</ul>\n</li>\n<li>The final <strong>RL</strong> stage trains the step 3 checkpoint on both reasoning and non-reasoning prompts, improving helpfulness, harmlessness and reasoning.</li>\n</ol>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/R1-eval.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption><code>DeepSeek-R1</code> performs comparable to OpenAI <code>o1-preview</code> and <code>o1-mini</code> on several widely used reasoning benchmarks. <code>DeepSeek-V3</code> is the only non-reasoning model listed. (Image source: DeepSeek-AI, 2025)</figcaption></figure>\n<p>Interestingly the DeepSeek team showed that with pure RL, no SFT stage, it is still possible to learn advanced reasoning capabilities like reflection and backtracking (“Aha moment”). The model naturally learns to spend more thinking tokens during the RL training process to solve reasoning tasks. The “aha moment” can emerge, referring to the model reflecting on previous mistakes and then trying alternative approaches to correct them. Later, various open source efforts happened for replicating R1 results like <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/open-r1\">Open-R1</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/hkust-nlp/simpleRL-reason\">SimpleRL-reason</a>, and <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/Jiayi-Pan/TinyZero\">TinyZero</a>, all based on <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/QwenLM/Qwen2.5\">Qwen</a> models. These efforts also confirmed that pure RL leads to great performance on math problems, as well as the emergent “aha moment”.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/aha-moment.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Examples of the model learning to reflect and correct mistakes. (Image source: (left) DeepSeek-AI, 2025; (right) Zeng et al. 2025)</figcaption></figure>\n<p>The DeepSeek team also shared some of their unsuccessful attempts. They failed to use process reward model (PRM) as it is hard to define per-step rubrics or determine whether an intermediate step is correct, meanwhile making the training more vulnerable to reward hacking. The efforts on MCTS (Monte Carlo Tree Search) also failed due to the large search space for language model tokens, in comparison to, say, chess; and training the fine-grained value model used for guiding the search is very challenging too. Failed attempts often provide unique insights and we would like to encourage the research community to share more about what did not work out.</p>\n<h2>External Tool Use</h2>\n<p>During the reasoning steps, certain intermediate steps can be reliably and accurately solved by executing code or running mathematical calculations. Offloading that part of reasoning components into an external code interpreter, as in PAL (Program-Aided Language Model; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2211.10435\">Gao et al. 2022</a>) or Chain of Code (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://chain-of-code.github.io/\">Li et al. 2023</a>), can extend the capability of LLM with external tools, eliminating the need for LLMs to learn to execute code or function as calculators themselves. These code emulators, like in Chain of Code, can be augmented by an LLM such that if a standard code interpreter fails, we have the option of using LLM to execute that line of code instead. Using code to enhance reasoning steps are especially beneficial for mathematical problems, symbolic reasoning and algorithmic tasks. These unit tests may not exist as part of the coding questions, and in those cases, we can instruct the model to self-generate unit tests for it to test against to verify the solution (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2303.11366\">Shinn, et al. 2023</a>).</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/pal.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>An example of program-aided language model prompting looks like. (Image source: Gao et al. 2022)</figcaption></figure>\n<p>ReAct (Reason+Act; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2210.03629\">Yao et al. 2023</a>) combines the action of searching the Wikipedia API and generation of reasoning traces, such that reasoning paths can incorporate external knowledge.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/react.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>An example of the ReAct prompting method to solve a HotpotQA question, using Wikipedia search API as an external tool to help with reasoning. (Image source: Yao et al. 2023)</figcaption></figure>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openai.com/index/introducing-o3-and-o4-mini/\">o3 &amp; o4-mini</a>, recently released by OpenAI, are another two good examples where the reasoning process involves tool use like Web search, code execution and image processing. The team observed that large-scale reinforcement learning exhibits the same trend as in the GPT paradigm that “more compute = better performance”.</p>\n<h2>Thinking Faithfully</h2>\n<p>Deep learning models are often treated as black boxes and various interpretability methods have been proposed. Interpretability is useful for a couple reasons: first, it gives us an extra test to determine if the model is misaligned with its creators’ intent, or if it’s misbehaving in some way that we can’t tell by monitoring its actions. Second, it can help us determine whether the model is using a sound process to compute its answers. Chain of thought provides an especially convenient form of interpretability, as it makes the model’s internal process visible in natural language. This interpretability, however, rests on the assumption that the model truthfully describes its internal thought processes.</p>\n<p>Recent work showed that monitoring CoT of reasoning models can effectively detect model misbehavior such as <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/\">reward hacking</a>, and can even enable a weaker model to monitor a stronger model (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2503.11926\">Baker et al. 2025</a>). Increasing test time compute can also lead to improved adversarial robustness (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.18841\">Zaremba et al. 2025</a>); this makes sense intuitively, because thinking for longer should be especially useful when the model is presented with an unusual input, such as an adversarial example or jailbreak attempt – it can use the extra thinking time to make sense of the strange situation it’s been presented with.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/cot-monitor.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The experiment of asking the model to decide if another model tried to hack the unit tests in some way for coding questions given its thought process. We can monitor these reward hacking behavior during training with different types of monitor. The <code>exit(0)</code> coding hack is when the agent exploited a bug that allowed it to exit from the environment early without running all unit tests. The <code>raise SkipTest</code> hack is when the agent raises an exception from functions outside the testing framework in order to skip unit test evaluation. (Image source: Baker et al. 2025)</figcaption></figure>\n<h3>Does the Model Tell What it Thinks Faithfully</h3>\n<p>Intuitively, model CoTs could be biased due to lack of explicit training objectives aimed at encouraging faithful reasoning. Or when we fine-tune the model on human-written explanations, those human-written samples may contain mistakes. Thus we cannot by default assume CoT is always faithful .</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2307.13702\">Lanham et al. (2023)</a> investigated several modes of CoT faithfulness failures by deliberately introducing mistakes into CoTs and measuring their impacts on the accuracy of a set of multiple choice tasks (e.g. AQuA, MMLU, ARC Challenge, TruthfulQA, HellaSwag):</p>\n<ul>\n<li>\n<p>Mistake 1 (<em>Early answering</em>): The model may form a conclusion prematurely before CoT is generated. This is tested by early truncating or inserting mistakes into CoT. Different tasks revealed varying task-specific dependencies on CoT effectiveness; some have evaluation performance sensitive to truncated CoT but some do not. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2212.10001\">Wang et al. (2023)</a> did similar experiments but with more subtle mistakes related to bridging objects or language templates in the formation of CoT.</p>\n</li>\n<li>\n<p>Mistake 2 (<em>Uninformative tokens</em>): Uninformative CoT tokens improve performance. This hypothesis is tested by replacing CoT with filler text (e.g. all periods) and this setup shows no accuracy increase and some tasks may suffer performance drop slightly when compared to no CoT.</p>\n</li>\n<li>\n<p>Mistake 3 (<em>Human-unreadable encoding</em>): Relevant information is encoded in a way that is hard for humans to understand. Paraphrasing CoTs in an non-standard way did not degrade performance across datasets, suggesting accuracy gains do not rely on human-readable reasoning.</p>\n</li>\n</ul>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/cot-perturb.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of different ways of CoT perturbation to assess its faithfulness. (Image source: Lanham et al. 2023)</figcaption></figure>\n<p>Interestingly, Lanham et al. suggests that for multiple choice questions, smaller models may not be capable enough of utilizing CoT well, whereas larger models may have been able to solve the tasks without CoT. This dependency on CoT reasoning, measured by the percent of obtaining the same answer with vs without CoT, does not always increase with model size on multiple choice questions, but does increase with model size on addition tasks, implying that thinking time matters more for complex reasoning tasks.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/cot-ablation.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The dependency on CoT reasoning is measured as the percentage of obtaining same answers with vs without CoT. It matters more for reasoning tasks like addition and larger models benefit more. (Image source: Lanham et al. 2023)</figcaption></figure>\n<p>Alternative approaches for testing CoT faithfulness involve perturbing prompts rather than modifying CoT paths directly (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.04388\">Turpin et al. 2023</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.08156\">Chua &amp; Evans, 2025</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://assets.anthropic.com/m/71876fabef0f0ed4/original/reasoning_models_paper.pdf\">Chen et al. 2025</a>).</p>\n<p>One method consistently labels correct answers as “(A)” in few-shot examples regardless of true labels to introduce biases.</p>\n<p>Another prompting technique inserts misleading hints into prompts, such as <code>&quot;I think the answer is &lt;random_label&gt; but curious to hear what you think&quot;.</code> or <code>&quot;A Stanford Professor thinks the answer is &lt;random_label&gt;&quot;</code>. By comparing model predictions for the same question with vs without the misleading hint, we can measure whether a model is able to faithfully describe the influence of the hint on its answer. Particularly, in cases where the model produces different hint and non-hint answers, we measure whether the model acknowledges the hint when solving the question with hint. If the model is faithful, it should explicitly acknowledge the impact and admit the change of its answer is due to the hint.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/faithfulness.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Both GPT and Claude models are sensitive to different types of biases in context. Decrease in model accuracy indicates systematic unfaithfulness. Direct hints of wrong labels are more effectively than &quot;Answer is always A&quot; type of bias. (Image source: Turpin et al. 2023)</figcaption></figure>\n<p>Multiple studies found that reasoning models describe the influence of the hint much more reliably than all the non-reasoning models tested. For example, we can measure the fraction of samples where the model acknowledges the hint as a deciding factor (“faithful CoT”). Reasoning models (Claude 3.7 Sonnet, DeepSeek R1) are overall doing better than non-reasoning ones (Claude 3.6, DeepSeek V3).</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/faithfulness2.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Reasoning models are more likely to reveal faithful CoT than non-reasoning models. (Image source: Chen et al. 2025)</figcaption></figure>\n<p>Some evidence showed that using reward models leads to less faithfulness in model outputs. The reward model in classic RLHF is not trained to incentivize faithful behavior in this test as the preference comparison dataset is collected by humans selecting which one seems better or pleasing. However, in reasoning models, the CoT paths are optimized for producing the correct final answers, not to match human preference defined in RM, and thus intuitively are expected to be more faithful.</p>\n<h3>Optimization Pressure on CoT: Good or Bad?</h3>\n<p>Monitoring CoT of reasoning models for reward hacking behavior is effective. A simple way to use this monitor is to run rejection sampling with the monitor as a filter at test time and identify solutions without reward hacking. However, it only works at the early stage of RL, and, as the model is further optimized, it is rare to find a sample to pass a CoT monitor within budget. This challenge naturally suggests that we could consider incorporating CoT monitors into RL rewards—a form of process-based supervision—to prevent reward hacking.</p>\n<p>However, incorporating CoT monitoring reward into RL does not work out well, as it leads to obfuscated reward hacking where the model tries to hide its true intent within the CoT (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2503.11926\">Baker et al. 2025</a>). With this direct optimization pressure provided by the CoT monitor applied during RL training, the model still can find ways to hack, although a bit less frequently, but can hide its intention in CoT to avoid being caught by the monitor.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/RL-monitor-baker25.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>When using the monitor to provide an RL reward signal to prevent reward hacking during training, the model still can find ways to hack while avoiding being caught by the monitor. (Image source: Baker et al. 2025)</figcaption></figure>\n<p>Experiments on CoT length RL signals by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2502.03373\">Yeo et al. (2025)</a> confirmed a similar message as Baker et al. that new types of reward hacking can happen with new types of RL reward shaping. They designed the reward function such that correct CoTs can have higher rewards than wrong ones, short correct CoTs obtain higher rewards than long correct ones and short incorrect CoT receive higher penalties than long incorrect CoTs. With this extra reward, the model learns to repeat text in CoTs for challenging questions rather than attempting to solve them. Yeo et al. further applied a n-gram repetition penalty to prevent this hacking behavior.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/rew-shaping-yeo25.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Careful reward shaping is needed to stabilize training with CoT length rewards. (Image source: Yeo et al. 2025)</figcaption></figure>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://assets.anthropic.com/m/71876fabef0f0ed4/original/reasoning_models_paper.pdf\">Chen et al. (2025)</a> experimented with a flawed RL environment, specifically using a grader with incorrect answers filled in for multiple-choice questions. The model learns to exploit the reward hack on &gt;99% of the prompts, but almost never (&lt;2%) verbalizes the reward hack in its CoT on more than half of their environments. Additional RL optimization pressure fails to incentivize the model to verbalize the hack in this case.</p>\n<p>RL training is inherently sensitive to reward hacking. Only relying on heuristic investigation of reward hacking and manual fixes may lead to a “whack-a-mole” situation. We would suggest being very cautious when trying to apply optimization directly on CoT during RL training, or trying to avoid it altogether.</p>\n<h2>Thinking in Continuous Space</h2>\n<p>Adaptive Computation Time, introduced by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1603.08983\">Alex Graves in 2016</a>, predated large language models but pioneered the same direction of enabling the model to dynamically decide the number of computational steps to take at the inference time, which can be viewed as enabling the model to “think more” in continuous space at test time. Adaptive thinking time in continuous space can be enabled vertically via recurrent architecture or horizontally via more sequential sampling steps.</p>\n<h2>Recurrent Architecture</h2>\n<p>A number of architecture variations have been proposed to make the Transformer architecture recurrent, enabling adaptive test time compute (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1807.03819\">Dehghani, et al. 2019</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2203.07852\">Hutchins, et al. 2022</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2207.06881\">Bulatov, et al. 2022</a>). A deep dive into literature on this topic would make the post too long, so we will only review a few.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2020-04-07-the-transformer-family/#make-it-recurrent-universal-transformer\">Universal Transformer</a> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1807.03819\">Dehghani, et al. 2019</a>) combines self-attention in Transformer with the recurrent mechanism in RNN, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2023-01-27-the-transformer-family-v2/#adaptive-modeling\">dynamically adjusting</a> the number of steps using adaptive computation time (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1603.08983\">Graves, 2016</a>). On a high level, it can be viewed as a recurrent function for learning the hidden state representation per token, and if the number of steps is fixed, an Universal Transformer is equivalent to a multi-layer Transformer with shared parameters across layers.</p>\n<p>A recent recurrent architecture design, proposed by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2502.05171\">Geiping et al. (2025)</a>, adds a recurrent block <span class=\"math\">R</span> on top of the standard Transformer. Every iteration of this recurrent block takes the embedding <span class=\"math\">e</span> and a random state <span class=\"math\">sᵢ</span>. Conceptually, this recurrent-depth architecture is a bit similar to a conditioned diffusion model, where the original input <span class=\"math\">e</span> is provided in every recurrent step while a random Gaussian initialized state <span class=\"math\">sᵢ</span> gets updated iteratively through the process. (Interestingly some of their experiments of designs that resemble diffusion models more turned out to be bad.)</p>\n<p><span class=\"math math-display\">e = P(x) embedding<br>s_0 ∼ 𝒩(0, σ² I_n ⋅ h)<br>s_i = R(e, s_i−1) for i ∈ 1, …, r recurrent block; resembles a Transformer block<br>p = C(s_r) unembedding</span></p>\n<p>The recurrence count <span class=\"math\">r</span> during training is randomized, sampled from a log-normal Poisson distribution, per input sequence. To manage computational costs, backpropagation is truncated to only the last <span class=\"math\">k</span> iterations of the recurrent unit (<span class=\"math\">k=8</span> in experiments), making it possible to train on the heavy-tail part of the Poisson distribution. The embedding block continues to receive gradient updates in every step since its output <span class=\"math\">e</span> is injected in every step, mimicking RNN training. Unsurprisingly, the stability of training a recurrent model turns out to be very sensitive. Factors like initialization, normalization and hyperparameters all matter, especially when scaling up the training. For example, hidden states can collapse by predicting the same hidden state for every token; or the model may learn to ignore the incoming state <span class=\"math\">s</span>. To stabilize the training, Geiping et al. adopted an embedding scale factor, a small learning rate and careful tuning.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/recurrent.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Plot of an experiment on training a 3.5B model with depth recurrence. The saturation roughly happens around <span class=\"math\">r̄ = 32</span>, making us wonder how this architecture extrapolate and generalize to larger iteration counts. (Image source: Geiping et al. 2025)</figcaption></figure>\n<h2>Thinking Tokens</h2>\n<p>Thinking tokens refer to a set of implicit tokens introduced during training or inference that do not carry direct linguistic meaning. Instead, their role is to provide extra thinking time and compute power for the model to perform better.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2405.08644\">Herel &amp; Mikolov (2023</a>) introduced the idea of inserting special thinking tokens (<code>&lt;T&gt;</code>) after each word in a sentence and training the model on such a dataset. Each thinking token buys extra time for the model to process and make better predictions. Training with thinking tokens on a toy model setup results in lower perplexity than baseline model trained without them. The benefits of thinking tokens are more pronounced for non-trivial reasoning tasks or sentences involving numbers.</p>\n<p>Similarly, pause tokens proposed by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.02226\">Goyal et al. (2024)</a> delay the model’s outputs by appending dummy tokens (e.g. character like <code>.</code> or <code>#</code>) at the end of the input sequence, giving the model extra computation during inference. It is important to inject such pause tokens both during training and inference time, while only fine-tuning on pause tokens leads to limited gain. During training, multiple copies of pause tokens are inserted at uniformly random locations and the loss on pause tokens is ignored for training.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/pause-tokens-goyal24.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of how pause tokens are injected during training and inference in comparison to standard setup. (Image source: Goyal et al. 2024)</figcaption></figure>\n<p>Interestingly, thinking tokens or pause tokens in above experiments do not carry any extra information or add many new parameters. But why is it still helpful? On one hand, it helps expand the computation by introducing more inference loops, effectively increasing computational capacity. On the other hand, it can be seen as acting as a special, implicit form of CoTs. A drawback here is hat the model needs to be pretrained with respect to thinking tokens. Still, this strategy is an interesting way to further improve the capability of test time compute utilization on top of inference time CoTs.</p>\n<p>Quiet-STaR (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2403.09629\">Zelikman et al. 2025</a>) introduces token-level reasoning by training the model to generate rationales after every token to explain future text. It mixes the future-text predictions with and without rationales and uses learning to generate better rationales and uses REINFORCE to optimize the quality of rationale generation.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/quiet-star-zelikman25.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of Quiet-STaR. (Image source: Zelikman et al. 2025)</figcaption></figure>\n<p>Quiet-STaR consists of three stages:</p>\n<ul>\n<li>\n<p><em>Think</em>: Predicting next tokens with rationales. Due to high computational cost demanded by token level reasoning, this process is designed to generate multiple rationales in parallel. A special attention map is used to enable all thought tokens to only pay attention to themselves, all preceding thought tokens within the same thought, and the preceding text.</p>\n</li>\n<li>\n<p><em>Talk</em>: Next token prediction without rationale is mixed with post-rationale prediction. The mixing weight for two logits is learned by a special mixing head of a shallow MLP out of hidden output after each rationale. Correct next tokens can be selected via teacher forcing.</p>\n</li>\n<li>\n<p><em>Learn</em>: Train the model to generate better rationale via REINFORCE by learning from examples that increase the probability of correct next token while discarding those that hurt the prediction.</p>\n</li>\n</ul>\n<p>Without dataset specific fine-tuning, Quiet-STaR improves zero-shot results on CommonsenseQA (36.3%→47.2%) and GSM8K (5.9%→10.9%), within experiments on Mistral 7B.</p>\n<h2>Thinking as Latent Variables</h2>\n<p>A latent variable model defines a probabilistic framework where observable data is explained through unobserved (latent) variables. These latent variables capture hidden structures or intermediate processes that generate the observable outcomes. Language models can be viewed as probabilistic latent variable models where test-time thinking and reasoning steps are latent thought variables (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2011.05268\">Zhou et al. 2020</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2312.02179\">Phan et al. 2023</a>). Such a latent variable model defines a joint distribution of problems x_i, answers y_i and latent thought z_i. We would like to optimize the log-likelihood of answers given questions and a variety of CoTs as latent variables (N is the number of samples; <span class=\"math\">K</span> is the number of CoTs per problem):</p>\n<p><span class=\"math math-display\">log ℒ(θ) = log p(y | x)<br>= log ∑ₖ₌₁^K p(y, z⁽ᵏ⁾ | x)<br>= log ∑ₖ₌₁^K p(z⁽ᵏ⁾ | x) p(y | z⁽ᵏ⁾, x)<br>= log 𝔼_(z⁽ᵏ⁾ ∼ p(z⁽ᵏ⁾ | x)) p(y | z⁽ᵏ⁾, x)</span></p>\n<p>Our goal is to maximize the marginal likelihood of the correct answer, <span class=\"math\">p(y | x)</span>, given a number of reasoning traces per problem, <span class=\"math\">{z⁽ᵏ⁾}ₖ₌₁^K</span>.</p>\n<h2>Expectation-Maximization</h2>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm\">Expectation-Maximization</a> is a commonly used iterative algorithm for optimizing parameters for a model with (hidden) latent variables, and thus can be applied to train better CoTs and then condition on that to generate better responses. Typically we iterate between E-step (Expectation) where we guess the missing information about latent variables (i.e. how to sample better CoTs), and M-step (Maximization) where we optimize the model parameters based on latent variables (i.e. how to sample better answers), until convergence.</p>\n<p><span class=\"math math-display\">log ℒ(θ) = log 𝔼_(z⁽ᵏ⁾ ∼ p(z⁽ᵏ⁾ | x)_(E−step)) p(y | z⁽ᵏ⁾, x)_(M−step)</span></p>\n<p>Because we cannot directly sample from the latent variable distribution <span class=\"math\">p(z | x, y)</span>, researchers have explored methods relying on human annotated data (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2011.05268\">Zhou et al. 2020</a>), Metropolis-Hastings MCMC (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2312.02179\">Phan et al. 2023</a>) or Monte Carlo sampling with special importance weights (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2503.18866\">Ruan et al. 2025</a>) to draw good CoT samples to update the model. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2503.18866\">Ruan et al. (2025</a>) experimented with training a model on a large body of Web text with latent thoughts with the EM algorithm, where the latent thought is synthesized per chunk of observed data and then the model learns over both latent thought and data in an autoregressive manner.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/ruan25.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of training on data corpus with latent thought injected. (Image source: Ruan et al. 2025)</figcaption></figure>\n<p>They first prompt a LLM <span class=\"math\">q̃</span> to generate synthetic latent thought Z_i given observed data X_i:</p>\n<pre><code><span class=\"code-snippet\">You are provided with a pair of web document prefix and suffix. Your task is to insert latent thoughts between them underlying the creation of the suffix conditioned on the prefix. The latent thoughts should include: the missing background knowledge and the reasoning traces underlying each claim (especially, step-by-step derivations or logical reasoning).\n</span></code></pre>\n<p>Special tokens like <code>&lt;StartOfLatent&gt;&lt;Prior&gt; ... &lt;EndOfPrior&gt;</code> are used to insert the generated latent thought content into the raw data for training the joint distribution <span class=\"math\">p(z, x)</span> or the approximate posterior <span class=\"math\">q(z | x)</span>, depending on whether <span class=\"math\">z</span> is inserted before or after <span class=\"math\">x</span>. However, since we are using a LLM <span class=\"math\">q̃(z | x)</span> to generate the CoTs, it imposed a performance ceiling on how good the approximate <span class=\"math\">q(z | x)</span> can be. Ruan et al. introduced importance weights for selecting CoT samples at the E-step, formulated as:</p>\n<p><span class=\"math math-display\">w⁽ᵏ⁾ = (p(z⁽ᵏ⁾, x))/(q(z⁽ᵏ⁾ | x)) = (p(x | z⁽ᵏ⁾) p(z⁽ᵏ⁾))/(q(z⁽ᵏ⁾ | x))</span></p>\n<p>, such that we prioritize samples with CoTs that are good at predicting the observation (i.e., high <span class=\"math\">p(x | z⁽ᵏ⁾)</span>), simple, intuitive (i.e., high <span class=\"math\">p(z⁽ᵏ⁾)</span>) but also informative and not too obvious (i.e. low <span class=\"math\">q(z⁽ᵏ⁾ | x)</span>).</p>\n<h2>Iterative Learning</h2>\n<p>Since pretrained models already possess the capability of generating chains of thought, it is intuitive to design an iterative improvement process where we generate multiple CoTs and fine-tune the model only on rationales that lead to correct answers.<br />\nHowever, this straightforward design can fail because the model receives no learning signals for problems it fails to solve. STaR (“Self-taught reasoner”; <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2203.14465\">Zelikman et al. 2022</a>) addresses this limitation by adding a “rationalization” process for failed attempts, in which the model generates good CoTs backward conditioned on both the problem and the ground truth answer and thus the model can generate more reasonable CoTs. Then the model is finetuned on correct solutions that either lead to correct outputs or are generated through rationalization.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/STaR-algo-zelikman22.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The algorithm of STaR. (Image source: Zelikman et al. 2022)</figcaption></figure>\n<p>We can view STaR as an approximation to a policy gradient in RL, with a simple indicator function as the reward, <code class=\"math\">\\mathbb{1}[\\hat{y} = y]</code>. We want to maximize the expectation of this reward when sampling <span class=\"math\">z ∼ p(z | x)</span> and then <span class=\"math\">y ∼ p(y | x, z)</span>, since <span class=\"math\">p(y | x) = ∑_z p(z | x) p(y | x, z)</span>.</p>\n<p><code class=\"math math-display\">\\begin{aligned} \\nabla_\\theta J(\\theta) &amp;= \\nabla_\\theta \\mathbb{E}_{z_i, y_i \\sim p(.\\mid x_i)} \\mathbb{1}[y_i = y_i^\\text{truth}] \\\\ &amp;= \\sum_{i=1}^N \\nabla_\\theta \\mathbb{1}[y_i = y_i^\\text{truth}] \\; p(y_i, z_i \\mid x_i) \\\\ &amp;= \\sum_{i=1}^N \\mathbb{1}[y_i = y_i^\\text{truth}] \\; p(y_i, z_i \\mid x_i) \\frac{\\nabla_\\theta p(y_i, z_i \\mid x_i)}{p(y_i, z_i \\mid x_i)} &amp; \\text{;log-derivative trick}\\\\ &amp;= \\mathbb{E}_{z_i, y_i \\sim p(.\\mid x_i)} \\mathbb{1}[y_i = y_i^\\text{truth}] \\; \\nabla_\\theta \\log p(y_i, z_i \\mid x_i) &amp; \\text{;log-derivative trick} \\end{aligned}</code></p>\n<p>Each iteration is equivalent to first selecting the CoT samples according to <code class=\"math\">\\mathbb{1}[y=y^\\text{truth}]</code> and then running supervised fine-tuning to optimize the logprob of generating good CoTs and answers. Performance of STaR improves with more training iterations, and the “rationalization” process for generating better CoTs accelerates learning. They observed that sampling with high temperature increases the chance of getting correct answers with incorrect reasoning and finetuning LLM on such data can impair generalization. For datasets without ground truths, majority votes of multiple high-temperature outputs can serve as a proxy of ground truth answers (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2207.00747\">Wang et al. 2022</a>), making it possible to use synthetic samples for training.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/STaR-rationalization-zelikman22.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>A comparison of accuracy of two <span class=\"math\">n</span>-digit numbers summation. With rationalization (CoT generation conditioned on ground truth), the model can learn complex arithmetic tasks like <span class=\"math\">5</span>-digit summation pretty early on. (Image source: Zelikman et al. 2022)</figcaption></figure>\n<h2>Scaling Laws for Thinking Time</h2>\n<p>So far we have seen much evidence that allowing models to spend additional compute on reasoning before producing final answers at inference time can significantly improve performance. Techniques like prompting the model to generate intermediate reasoning steps before the answers, or training the model to pause and reflect before predicting next tokens, have been found to boost the model performance beyond the capability limit obtained during training. This essentially introduces a new dimension to tinker with for improving model intelligence, complementing established factors such as model size, training compute and data quantity, as defined in scaling laws (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2001.08361\">Kaplan et al. 2020</a>).</p>\n<p>Recent studies demonstrated that optimizing LLM test-time compute could be more effective than scaling up model parameters (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.03314\">Snell et al. 2024</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.00724\">Wu et al. 2025</a>). Smaller models combined with advanced inference algorithms can offer Pareto-optimal trade-offs in cost and performance.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.03314\">Snell et al. (2024)</a> evaluated and compared test-time and pretraining compute, and found that they are not 1:1 exchangeable. Test-time compute can cover up the gap easily on easy and medium questions when there is only a small gap in model capability, but proves less effective for hard problems. The ratio between token budgets for pretraining and inference matters a lot. Test-time compute is only preferable when inference tokens are substantially fewer than pretraining ones. This indicates that developing a capable base model with enough pretraining data and compute is still very critical, as test-time compute cannot solve everything or fill in big model capability gaps.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/scaling-snell24.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>(Left) Evaluation accuracy as a function of test time compute budgets, via iterative revisions or parallel decoding. (Right) Comparing a small model with test-time compute sampling tricks and a 14x larger model with only greedy decoding. We can control the token budgets used at test time such that the ratio of inference to pretraining tokens is &lt;&lt; 1, ~=1 or &gt;&gt; 1 and the benefit of test time compute is clear only the ratio &lt;&lt; 1. (Image source: Snell et al. 2024)</figcaption></figure>\n<p><code>s1</code> models (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.19393\">Muennighoff &amp; Yang, et al. 2025</a>) experimented with scaling up the CoT reasoning path length via <em>budget forcing</em> technique (i.e. forcefully lengthen it by appending the word <code>&quot;wait&quot;</code>, or shorten it by terminating the model’s thinking process by appending end-of-thinking token or <code>&quot;Final Answer:&quot;</code>). They observed a clear positive correlation between the average thinking time measured in tokens and the downstream evaluation accuracy.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/s1-muennighoff25.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Both parallel and sequential scaling methods of test-time compute shows positive correlation with the evaluation performance in s1 experiments. (Image Muennighoff &amp; Yang, et al. 2025)</figcaption></figure>\n<p>When comparing this budget forcing technique with other decoding methods of controlling reasoning trace length, it is quite surprising that simple rejection sampling (i.e. sampling generation until the lengths fits a token budget) leads to reversed scaling, meaning that longer CoTs lead to worse performance.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2025-05-01-thinking/s1-scaling-muennighoff25.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>(Left) Longer CoT path length is positively correlated with eval accuracy. (Right) Rejection sampling for controlling the generated CoT path length shows a negative scaling where longer CoTs lead to worse eval accuracy. (Image source: Muennighoff &amp; Yang et al. 2025)</figcaption></figure>\n<h2>What’s for Future</h2>\n<p>The exploration of test-time compute and chain-of-thought reasoning presents new opportunities for enhancing model capabilities. More interestingly, via test-time thinking, we are moving towards building future AI systems that mirror the best practices of how humans think, incorporating adaptability, flexibility, critical reflection, and error correction. Excitement with current progress invites us for more future research to improve and understand deeply not just how but why we—and our models—think.</p>\n<p>At the end, I would like to call for more research for the following open research questions on test time compute and chain-of-thought reasoning.</p>\n<ul>\n<li>Can we incentivize the model to produce human-readable, faithful reasoning paths during RL training while avoiding reward hacking behavior?</li>\n<li>How to define reward hacking? Can we capture reward hacking during RL training or inference without human intervention? How to prevent “whack-a-mole” style of fixes for reward hacking during RL training?</li>\n<li>Self-correction can happen within chain-of-thought or can be encouraged to happen explicitly during multi-turn RL. How can we train the model to correct itself without hallucination or regression when ground truth is not available?</li>\n<li>How to run RL training with CoT rollout for tasks that are highly contextualized, personalized and hard to grade, such as creative writing, coaching, brainstorming?</li>\n<li>When we deploy the model in reality, we cannot grow test time thinking forever and how can we smoothly translate the performance gain back into the base model with reduced inference time cost (e.g. via <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.12948\">distillation</a>)?</li>\n<li>How to make test time spending more adaptive according to the difficulty of the problem in hand?</li>\n</ul>\n<h2>Citation</h2>\n<p>Please cite this work as:</p>\n<pre><code><span class=\"code-snippet\">Weng, Lilian. &quot;Why We Think&quot;. Lil&#39;Log (May 2025). https://lilianweng.github.io/posts/2025-05-01-thinking/\n</span></code></pre>\n<p>Or use the BibTex citation:</p>\n<pre><code><span class=\"code-snippet\">@article{weng2025think,\n  title = {Why We Think},\n  author = {Weng, Lilian},\n  journal = {lilianweng.github.io},\n  year = {2025},\n  month = {May},\n  url = &quot;https://lilianweng.github.io/posts/2025-05-01-thinking/&quot;\n}\n</span></code></pre>\n<h2>References</h2>\n<p>[1] Alex Graves. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1603.08983\">“Adaptive Computation Time for Recurrent Neural Networks.”</a>. arXiv preprint arXiv:1603.08983 (2016).</p>\n<p>[2] Wang Ling, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1705.04146\">“Program Induction by Rationale Generation: Learning to Solve and Explain Algebraic Word Problems.”</a>. arXiv preprint arXiv:1705.04146 (2017).</p>\n<p>[3] Karl Cobbe, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2110.14168\">“Training Verifiers to Solve Math Word Problems.”</a>. arXiv preprint arXiv:2110.14168 (2021).</p>\n<p>[4] Jason Wei, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.11903\">“Chain of Thought Prompting Elicits Reasoning in Large Language Models.”</a>. NeurIPS 2022.</p>\n<p>[5] Maxwell Nye, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2112.00114\">“Show Your Work: Scratchpads for Intermediate Computation with Language Models.”</a>. arXiv preprint arXiv:2112.00114 (2021).</p>\n<p>[6] Daniel Kahneman. <em>Thinking, Fast and Slow</em>. Farrar, Straus and Giroux (2013).</p>\n<p>[7] Takeshi Kojima, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2205.11916\">“Large Language Models are Zero-Shot Reasoners.”</a>. NeurIPS 2022.</p>\n<p>[8] Michihiro Yasunaga, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.01714\">“Large Language Models as Analogical Reasoners”</a>. arXiv preprint arXiv:2310.01714 (2023).</p>\n<p>[9] Eric Zelikman, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2203.14465\">“STaR: Bootstrapping Reasoning With Reasoning.”</a>. NeurIPS 2022.</p>\n<p>[10] Xuezhi Wang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2203.11171\">“Self-consistency Improves Chain of Thought Reasoning in Language Models.”</a>. ACL 2023.</p>\n<p>[11] Ryo Kamoi, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.01297\">“When Can LLMs Actually Correct Their Own Mistakes? A Critical Survey of Self-Correction of LLMs.”</a>. TACL 2024.</p>\n<p>[12] Jie Huang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.01798\">“Large Language Models Cannot Self-Correct Reasoning Yet.”</a>. ICLR 2024.</p>\n<p>[13] Noah Shinn, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2303.11366\">“Reflexion: Language Agents with Verbal Reinforcement Learning.”</a>. arXiv preprint arXiv:2303.11366 (2023).</p>\n<p>[14] Yunxiang Zhang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2404.17140\">“Small Language Models Need Strong Verifiers to Self-Correct Reasoning.”</a>. ACL Findings 2024.</p>\n<p>[15] Hao Liu, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2302.02676\">“Chain of Hindsight Aligns Language Models with Feedback.”</a>. arXiv preprint arXiv:2302.02676 (2023).</p>\n<p>[16] Sean Welleck, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2211.00053\">“Generating Sequences by Learning to Self-Correct.”</a>. arXiv preprint arXiv:2211.00053 (2023).</p>\n<p>[17] Yuxiao Qu, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2407.18219\">“Recursive Introspection: Teaching Language Model Agents How to Self-Improve.”</a>. arXiv preprint arXiv:2407.18219 (2024).</p>\n<p>[18] Aviral Kumar, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2409.12917\">“Training Language Models to Self-Correct via Reinforcement Learning.”</a>. arXiv preprint arXiv:2409.12917 (2024).</p>\n<p>[19] Hunter Lightman, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.20050\">“Let’s Verify Step by Step.”</a>. arXiv preprint arXiv:2305.20050 (2023).</p>\n<p>[20] Yuxi Xie, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.00633\">“Self-Evaluation Guided Beam Search for Reasoning.”</a>. NeurIPS 2023.</p>\n<p>[21] Yangzhen Wu, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.00724\">“Inference Scaling Laws: An Empirical Analysis of Compute-Optimal Inference for Problem-Solving with Language Models”</a>. ICLR 2025.</p>\n<p>[22] Dongwei Jiang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2410.01044\">“RATIONALYST: Pre-training Process-Supervision for Improving Reasoning”</a>. arXiv preprint arXiv:2410.01044 (2024).</p>\n<p>[23] Xuezhi Wang and Denny Zhou. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2402.10200\">“Chain-of-Thought Reasoning Without Prompting.”</a>. arXiv preprint arXiv:2402.10200 (2024).</p>\n<p>[24] DeepSeek-AI. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2412.19437\">“DeepSeek-V3 Technical Report.”</a> arXiv preprint arXiv:2412.19437 (2024).</p>\n<p>[25] DeepSeek-AI. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.12948\">“DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning.”</a>. arXiv preprint arXiv:2501.12948 (2025).</p>\n<p>[26] Luyu Gao, Aman Madaan &amp; Shuyan Zhou, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2211.10435\">“PAL: Program-aided Language Models.”</a>. ICML 2023.</p>\n<p>[27] Shunyu Yao, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2210.03629\">“ReAct: Synergizing Reasoning and Acting in Language Models.”</a>. ICLR 2023.</p>\n<p>[29] Bowen Baker, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2503.11926\">“Monitoring Reasoning Models for Misbehavior and the Risks of Promoting Obfuscation.”</a>. arXiv preprint arXiv:2503.11926 (2025).</p>\n<p>[30] Wojciech Zaremba, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.18841\">“Trading Inference-Time Compute for Adversarial Robustness.”</a>. arXiv preprint arXiv:2501.18841 (2025).</p>\n<p>[31] Tamera Lanham, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2307.13702\">“Measuring Faithfulness in Chain-of-Thought Reasoning”</a>. arXiv preprint arXiv:2307.13702 (2023).</p>\n<p>[32] Boshi Wang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2212.10001\">“Towards Understanding Chain-of-Thought Prompting: An Empirical Study of What Matters.”</a>. ACL 2023.</p>\n<p>[33] Miles Turpin, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.04388\">“Language Models Don’t Always Say What They Think: Unfaithful Explanations in Chain-of-Thought Prompting.”</a>. NeuriPS 2023.</p>\n<p>[34] James Chua &amp; Owain Evans. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.08156\">“Are DeepSeek R1 And Other Reasoning Models More Faithful?”</a>. arXiv preprint arXiv:2501.08156 (2025).</p>\n<p>[35] Yanda Chen et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2505.05410\">“Reasoning Models Don’t Always Say What They Think”</a>. arXiv preprint arXiv:2505.05410 (2025).</p>\n<p>[36] Edward Yeo, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2502.03373\">“Demystifying Long Chain-of-Thought Reasoning in LLMs.”</a>. arXiv preprint arXiv:2502.03373 (2025).</p>\n<p>[37] Mostafa Dehghani, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1807.03819\">“Universal Transformers.”</a>. ICLR 2019.</p>\n<p>[38] DeLesley Hutchins, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2203.07852\">“Block-Recurrent Transformers.”</a>. NeurIPS 2022.</p>\n<p>[39] Aydar Bulatov, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2207.06881\">“Recurrent Memory Transformers.”</a>. NeuriPS 2022.</p>\n<p>[40] Jonas Geiping, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2502.05171\">“Scaling up Test-Time Compute with Latent Reasoning: A Recurrent Depth Approach.”</a>. arXiv preprint arXiv:2502.05171 (2025).</p>\n<p>[41] Herel &amp; Mikolov. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2405.08644\">“Thinking Tokens for Language Modeling.”</a>. AITP 2023.</p>\n<p>[42] Sachin Goyal et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.02226\">“Think before you speak: Training Language Models With Pause Tokens.”</a>. ICLR 2024.</p>\n<p>[43] Eric Zelikman, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2403.09629\">“Quiet-STaR: Language Models Can Teach Themselves to Think Before Speaking.”</a>. arXiv preprint arXiv:2403.09629 (2025).</p>\n<p>[44] Wangchunshu Zhou et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2011.05268\">“Towards Interpretable Natural Language Understanding with Explanations as Latent Variables.”</a>. NeurIPS 2020.</p>\n<p>[45] Du Phan et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2312.02179\">“Training Chain-of-Thought via Latent-Variable Inference.”</a>. NeurIPS 2023.</p>\n<p>[46] Yangjun Ruan et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2503.18866\">“Reasoning to Learn from Latent Thoughts.”</a>. arXiv preprint arXiv:2503.18866 (2025).</p>\n<p>[47] Xuezhi Wang et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2207.00747\">“Rationale-Augmented Ensembles in Language Models.”</a>. arXiv preprint arXiv:2207.00747 (2022).</p>\n<p>[48] Jared Kaplan, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2001.08361\">“Scaling Laws for Neural Language Models.”</a>. arXiv preprint arXiv:2001.08361 (2020).</p>\n<p>[49] Niklas Muennighoff &amp; Zitong Yang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2501.19393\">“s1: Simple test-time scaling.”</a>. arXiv preprint arXiv:2501.19393 (2025).</p>\n<p>[50] Peiyi Wang, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2312.08935\">“Math-Shepherd: Verify and Reinforce LLMs Step-by-step without Human Annotations”</a> arXiv preprint arXiv:2312.08935 (2023).</p>\n<p>[51] Yixin Liu, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.10047\">“Improving Large Language Model Fine-tuning for Solving Math Problems.”</a> arXiv preprint arXiv:2310.10047 (2023).</p>\n<p>[52] Charlie Snell, et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.03314\">“Scaling LLM Test-Time Compute Optimally can be More Effective than Scaling Model Parameters.”</a>. arXiv preprint arXiv:2408.03314 (2024).</p>\n<p>[53] OpenAI. o1-preview: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openai.com/index/learning-to-reason-with-llms/\">“Learning to reason with LLMs.”</a> Sep 12, 2024.</p>\n<p>[54] OpenAI. o3: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openai.com/index/introducing-o3-and-o4-mini/\">“Introducing OpenAI o3 and o4-mini.”</a> Apr 16, 2025.</p>\n",
      "date_modified": "2025-05-01T00:00:00+00:00",
      "date_published": "2025-05-01T00:00:00+00:00",
      "external_url": "https://lilianweng.github.io/posts/2025-05-01-thinking/",
      "id": "urn:aggr:item:378d7f5216eb84a8d6211b6df8ea23b481f169a2",
      "language": "en-US",
      "summary": "Special thanks to John Schulman for a lot of super valuable feedback and direct edits on this post. Test time compute (Graves et al. 2016, Ling, et al. 2017, Cobbe et al. 2021) and Chain-of-thought (CoT) (Wei et al. 2022, Nye et al. 2021),…",
      "tags": [
        "programming"
      ],
      "title": "Why We Think",
      "url": "https://aggr.aymericbeaumet.com/items/lilianweng-github-io/2025-05-01-why-we-think/"
    },
    {
      "content_html": "<p>Reward hacking occurs when a <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/(https://lilianweng.github.io/posts/2018-02-19-rl-overview/)\">reinforcement learning (RL)</a> agent <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2018-01-23-multi-armed-bandit/#exploitation-vs-exploration\">exploits</a> flaws or ambiguities in the reward function to achieve high rewards, without genuinely learning or completing the intended task. Reward hacking exists because RL environments are often imperfect, and it is fundamentally challenging to accurately specify a reward function.</p>\n<p>With the rise of <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2019-01-31-lm/\">language models</a> generalizing to a broad spectrum of tasks and RLHF becomes a de facto method for alignment training, reward hacking in RL training of language models has become a critical practical challenge. Instances where the model learns to modify unit tests to pass coding tasks, or where responses contain biases that mimic a user’s preference, are pretty concerning and are likely one of the major blockers for real-world deployment of more autonomous use cases of AI models.</p>\n<p>Most of the past work on this topic has been quite theoretical and focused on defining or demonstrating the existence of reward hacking. However, research into practical mitigations, especially in the context of RLHF and LLMs, remains limited. I especially want to call out for more research efforts directed toward understanding and developing mitigation for reward hacking in the future. Hope I will be able to cover the mitigation part in a dedicated post soon.</p>\n<h2>Background</h2>\n<h2>Reward Function in RL</h2>\n<p>Reward function defines the task, and reward shaping significantly impacts learning efficiency and accuracy in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2018-02-19-rl-overview/\">reinforcement learning</a>. Designing a reward function for an RL task often feels like a ‘dark art’. Many factors contribute to this complexity: How you decompose a big goal into small goals? Is the reward sparse or dense? How you measure the success? Various choices may lead to good or problematic learning dynamics, including unlearnable tasks or hackable reward functions. There is a long history of research on how to do reward shaping in RL.</p>\n<p>For example, in an <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://people.eecs.berkeley.edu/~pabbeel/cs287-fa09/readings/NgHaradaRussell-shaping-ICML1999.pdf\">1999 paper by Ng et al.</a>, the authors studied how to modify the reward function in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2018-02-19-rl-overview/#markov-decision-processes\">Markov Decision Processes (MDPs)</a> such that the optimal policy remains unchanged. They found that linear transformation works. Given a MDP <span class=\"math\">M = (S, A, T, γ, R)</span>, we want to create a transformed MDP <span class=\"math\">M’ = (S, A, T, γ, R’)</span> where <span class=\"math\">R’ = R + F</span> and <span class=\"math\">F: S × A × S ↦ ℝ</span>, such that we can guide the learning algorithm to be more efficient. Given a real-valued function <span class=\"math\">Φ: S ↦ ℝ</span>, <span class=\"math\">F</span> is a potential-based shaping function if for all <span class=\"math\">s ∈ S − s₀, a ∈ A, s’ ∈ S</span>:</p>\n<p><span class=\"math math-display\">F(s, a, s′) = γ Φ(s′) − Φ(s)</span></p>\n<p>This would guarantee that the sum of discounted <span class=\"math\">F</span>, <span class=\"math\">F(s₁, a₁, s₂) + γ F(s₂, a₂, s₃) + …</span>, ends up being 0. If <span class=\"math\">F</span> is such a potential-based shaping function, it is both <em>sufficient</em> and <em>necessary</em> to ensure <span class=\"math\">M</span> and <span class=\"math\">M’</span> share the same optimal policies.</p>\n<p>When <span class=\"math\">F(s, a, s’) = γ Φ(s’) − Φ(s)</span>, and if we further assume that <span class=\"math\">Φ(s₀) = 0</span>, where <span class=\"math\">s₀</span> is absorbing state, and <span class=\"math\">γ=1</span>, and then for all <span class=\"math\">s ∈ S, a ∈ A</span>:</p>\n<p><span class=\"math math-display\">Q^*_(M′) (s,a) = Q^*_M(s, a) − Φ(s)<br>V^*_(M′) (s,a) = V^*_M(s, a) − Φ(s)</span></p>\n<p>This form of reward shaping allows us to incorporate heuristics into the reward function to speed up learning without impacting the optimal policy.</p>\n<h2>Spurious Correlation</h2>\n<p>Spurious correlation or shortcut learning (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2004.07780\">Geirhos et al. 2020</a>) in classification task is a concept closely related to reward hacking. Spurious or shortcut features can cause a classifier to fail at learning and generalizing as intended. For example, a binary classifier for distinguishing wolves from huskies may overfit to the presence of a snowy background if all the wolf training images include snow (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1602.04938\">Ribeiro et al. 2024</a>).</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/shortcut-features.png\" alt=\"\" loading=\"eager\" decoding=\"async\" fetchpriority=\"high\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The model performs poorly on out-of-distribution (OOD) test sets if it overfits to shortcut features. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2004.07780\">Geirhos et al. 2020</a>)</figcaption></figure>\n<p>The <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Empirical_risk_minimization\">ERM principle</a> states that, since the full data distribution is unknown, minimizing the loss on training data is a reasonable proxy of risk and thus we favor models with the lowest training loss. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2010.15775\">Nagarajan et al. (2021)</a> studied the ERM principle and pointed out that ERM needs to rely on all types of informative features, including unreliable spurious features, while attempting to fit the data without constraints. Their experiments showed that ERM would depend on spurious features no matter how easy the task is.</p>\n<h2>Let’s Define Reward Hacking</h2>\n<p>Reward shaping in RL is challenging. Reward hacking occurs when an RL agent exploits flaws or ambiguities in the reward function to obtain high rewards without genuinely learning the intended behaviors or completing the task as designed. In recent years, several related concepts have been proposed, all referring to some form of reward hacking:</p>\n<ul>\n<li>Reward hacking (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1606.06565\">Amodei et al., 2016</a>)</li>\n<li>Reward corruption (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1705.08417\">Everitt et al., 2017</a>)</li>\n<li>Reward tampering (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1908.04734\">Everitt et al. 2019</a>)</li>\n<li>Specification gaming (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://deepmind.google/discover/blog/specification-gaming-the-flip-side-of-ai-ingenuity/\">Krakovna et al., 2020</a>)</li>\n<li>Objective robustness (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.gatsby.ucl.ac.uk/~balaji/udl2021/accepted-papers/UDL2021-paper-055.pdf\">Koch et al. 2021</a>)</li>\n<li>Goal misgeneralization (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2105.14111\">Langosco et al. 2022</a>)</li>\n<li>Reward misspecifications (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.03544\">Pan et al. 2022</a>)</li>\n</ul>\n<p>The concept originated with Amodei et al. (2016), who proposed a set of open research questions on AI safety in their seminal paper <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1606.06565\">“Concrete Problems in AI Safety”</a>. They listed <strong>reward hacking</strong> as one of the key AI safety problems. Reward hacking refers to the possibility of the agent gaming the reward function to achieve high reward through undesired behavior. <strong>Specification gaming</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://deepmind.google/discover/blog/specification-gaming-the-flip-side-of-ai-ingenuity/\">Krakovna et al. 2020</a>) is a similar concept, defined as a behavior that satisfies the literal specification of an objective but not achieving the desired results. Here the literal description of the task goal and the intended goal may have a gap.</p>\n<p>Reward shaping is a technique used to enrich the reward function, making it easier for the agent to learn—for example, by providing denser rewards. However, a poorly design reward shaping mechanism can alter the trajectory of the optimal policy. Designing effective reward shaping mechanisms is inherently difficult. Rather than blaming a poorly designed reward function, it is more accurate to acknowledge that designing a good reward function is intrinsically challenging due to the complexity of the task itself, partial observable state, multiple dimensions in consideration, and other factors.</p>\n<p>When testing an RL agent in out-of-distribution (OOD) environments, robustness failure may occur due to:</p>\n<ol>\n<li>The model fails to generalize effectively, even with the right objective. This happens when the algorithm lacks sufficient intelligence or capability.</li>\n<li>The model generalizes capably but pursues an objective different from the one it was trained on. This happens when the proxy reward differs from the true reward function, <span class=\"math\">R’ ≠ R</span>. This is known as <strong>objective robustness</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.gatsby.ucl.ac.uk/~balaji/udl2021/accepted-papers/UDL2021-paper-055.pdf\">Koch et al. 2021</a>) or <strong>goal misgeneralization</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2105.14111\">Langosco et al. 2022</a> )</li>\n</ol>\n<p>Experiments in two RL environments, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/openai/coinrun\">CoinRun</a> and <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/openai/procgen\">Maze</a>, demonstrated the importance of randomization during training. If during training, the coin or the cheese is placed at a fixed position (i.e. right end of the level or upper right corner of the maze) but testing in the env where the coin or cheese is placed at random, the agent would just run to the fixed position without obtaining the coin or cheese at test time. A conflict arises when a visual feature (e.g., cheese or coin) and a positional feature (e.g., upper-right or right end) are inconsistent during test time, leading the trained model to prefer the positional feature. I would like to point out that, in these two examples, the <em>reward-result gaps</em> are clear but such type of biases are unlikely to be so obvious in most real-world cases.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/coinrun-randomization.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The impact of randomizing the position of the coin during training. When the coin is placed at random for {0, 2, 3, 6, 11}% of the time during training (x-axis), the frequency of the agent navigating to the end of the level without obtaining the coin decreases with the increase of the randomization (&quot;y-axis&quot;). (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.gatsby.ucl.ac.uk/~balaji/udl2021/accepted-papers/UDL2021-paper-055.pdf\">Koch et al. 2021</a>)</figcaption></figure>\n<p><strong>Reward Tampering</strong> (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1908.04734\">Everitt et al. 2019</a>) is a form of reward hacking behavior where the agent interferes with the reward function itself, causing the observed reward to no longer accurately represent the intended goal. In reward tampering, the model modifies its reward mechanism either by directly manipulating the implementation of the reward function or by indirectly altering the environmental information used as input for the reward function.</p>\n<p>(Note: Some work defines reward tampering as a distinct category of misalignment behavior from reward hacking. But I consider reward hacking as a broader concept here.)</p>\n<p>At a high level, reward hacking can be categorized into two types: environment or goal misspecification, and reward tampering.</p>\n<ul>\n<li><strong>Environment or goal misspecified</strong>: The model learns undesired behavior to achieve high rewards by hacking the environment or optimizing a reward function not aligned with the true reward objective—such as when the reward is misspecified or lacks key requirements.</li>\n<li><strong>Reward tampering</strong>: The model learns to interfere with the reward mechanism itself.</li>\n</ul>\n<h2>List of Examples</h2>\n<h3>Reward hacking examples in RL tasks</h3>\n<ul>\n<li>A robot hand trained to grab an object can learn to trick people by placing the hand between the object and the camera. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openai.com/index/learning-from-human-preferences/\">Link</a>)</li>\n<li>An agent trained to maximize jumping height may exploit a bug in the physics simulator to achieve an unrealistically height. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1803.03453\">Link</a>)</li>\n<li>An agent is trained to ride a bicycle to a goal and wins reward whenever it is getting closer to the goal. Then the agent may learn to ride in tiny circles around the goal because there is no penalty when the agent gets away from the goal. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://people.eecs.berkeley.edu/~pabbeel/cs287-fa09/readings/NgHaradaRussell-shaping-ICML1999.pdf\">Link</a>)</li>\n<li>In a soccer game setup, the reward is assigned when the agent touches the ball and the agent learns to remain next to the ball to touch the ball in high frequency like in a viberating motion. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://people.eecs.berkeley.edu/~pabbeel/cs287-fa09/readings/NgHaradaRussell-shaping-ICML1999.pdf\">Link</a>)</li>\n<li>In the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://openai.com/blog/faulty-reward-functions/\">Coast Runners game</a>, an agent controls a boat with the goal to finish the boat race as quickly as possible. When it is given a shaping reward for hitting green blocks along the race track, it changes the optimal policy to going in circles and hitting the same green blocks over and over again. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://deepmind.google/discover/blog/specification-gaming-the-flip-side-of-ai-ingenuity/\">Link</a>)</li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1803.03453\">“The Surprising Creativity of Digital Evolution”</a> (Lehman et al. 2019) - This paper has many examples about how optimizing a misspecified fitness function can lead to surprising “hacking” or unintended evolutionary or learning results.</li>\n<li>The list of <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://docs.google.com/spreadsheets/d/e/2PACX-1vRPiprOaC3HsCf5Tuum8bRfzYUiKLRqJmbOoC-32JorNdfyTiRRsR7Ea5eWtvsWzuxo8bjOxCG84dAg/pubhtml\">specification gaming in AI examples</a> is collected by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://deepmind.google/discover/blog/specification-gaming-the-flip-side-of-ai-ingenuity/\">Krakovna et al. 2020</a>.</li>\n</ul>\n<h3>Reward hacking examples in LLM tasks</h3>\n<ul>\n<li>A language model for generating summarization is able to explore flaws in the ROUGE metric such that it obtains high score but the generated summaries are barely readable. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://web.archive.org/web/20180215132021/https://www.salesforce.com/products/einstein/ai-research/tl-dr-reinforced-model-abstractive-summarization/\">Link</a>)</li>\n<li>A coding model learns to change unit test in order to pass coding questions. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.10162\">Link</a>)</li>\n<li>A coding model may learn to directly modify the code used for calculating the reward. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.10162\">Link</a>)</li>\n</ul>\n<h3>Reward hacking examples in real life</h3>\n<ul>\n<li>The recommendation algorithm for social media is intended to provide useful information. However, usefulness is often measured by proxy metrics, such as the number of likes or comments, or the time or frequency of engagement on the platform. The algorithm ends up recommending content that can affect users’ emotion states such as outrageous and extreme content in order to trigger more engagement. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.goodreads.com/en/book/show/204927599-nexus\">Harari, 2024</a>)</li>\n<li>Optimizing for misspecified proxy metrics for a video sharing site may aggressively increase the watch time of users while the true goal is to optimize users’ subjective well-being. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.03544\">Link</a>)</li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/The_Big_Short\">“The Big Short”</a> - 2008 financial crisis caused by the housing bubble. Reward hacking of our society happened as people tried to game the financial system.</li>\n</ul>\n<h2>Why does Reward Hacking Exist?</h2>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Goodhart%27s_law\"><strong>Goodhart’s Law</strong></a> states that <em>“When a measure becomes a target, it ceases to be a good measure”</em>. The intuition is that a good metric can become corrupted once significant pressure is applied to optimize it. It is challenging to specify a 100% accurate reward objective and any <em>proxy</em> suffers the risk of being hacked, as RL algorithm exploits any small imperfection in the reward function definition. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.lesswrong.com/posts/EbFABnst8LsidYs5Y/goodhart-taxonomy\">Garrabrant (2017)</a> categorized Goodhart’s law into 4 variants:</p>\n<ol>\n<li>Regressional - selection for an imperfect proxy necessarily also selects for noise.</li>\n<li>Extremal - the metric selection pushes the state distribution into a region of different data distribution.</li>\n<li>Causal - when there is a non-causal correlation between the proxy and the goal, intervening on the proxy may fail to intervene on the goal.</li>\n<li>Adversarial - optimization for a proxy provides an incentive for adversaries to correlate their goal with the proxy.</li>\n</ol>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1606.06565\">Amodei et al. (2016)</a> summarized that reward hacking, mainly in RL setting, may occur due to:</p>\n<ol>\n<li>Partial observed states and goals are imperfect representation of the environment status.</li>\n<li>The system itself is complex and susceptible to hacking; e.g., if the agent is allowed to execute code that changes part of the environment, it becomes much easier to exploit the environment’s mechanisms.</li>\n<li>The reward may involve abstract concept that is hard to be learned or formulated; e.g., a reward function with high-dimensional inputs may disproportionately rely on a few dimensions.</li>\n<li>RL targets to get the reward function highly optimized, so there exists an intrinsic “conflict”, making the design of good RL objective challenging. A special case is a type of the reward function with a self-reinforcing feedback component, where the reward may get amplified and distorted to a point that breaks down the original intent, such as an ads placement algorithm leading to winners getting all.</li>\n</ol>\n<p>Besides, identifying the exact reward function for which an optimal agent optimizes its behavior is in general impossible since there could be an infinite number of reward functions consistent with any observed policy in an fixed environment (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://ai.stanford.edu/~ang/papers/icml00-irl.pdf\">Ng &amp; Russell, 2000</a>). <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1601.06569\">Amin and Singh (2016)</a> separated the causes of this <em>unidentifiability</em> into two classes:</p>\n<ol>\n<li>Representational - a set of reward functions is behaviorally invariant under certain arithmetic operations (e.g., re-scaling)</li>\n<li>Experimental - <span class=\"math\">π</span>’s observed behavior is insufficient to distinguish between two or more reward functions which both rationalize the behavior of the agent (the behavior is optimal under both)</li>\n</ol>\n<h2>Hacking RL Environment</h2>\n<p>Reward hacking is expected to be a more common problem as the model and the algorithm become increasingly sophisticated. A more intelligent agent is more capable of finding “holes” in the design of reward function and <em>exploiting</em> the task specification—in other words, achieving higher proxy rewards but lower true rewards. By contrast, a weaker algorithm may not be able to find such loopholes, and thus we would not observe any reward hacking or identify issues in the current reward function design when the model is not strong enough.</p>\n<p>In a set of zero-sum robotics self-play games (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1710.03748\">Bansal et al., 2017</a>), we can train two agents (victim vs. opponent) to compete against each other. A standard training process produces a victim agent with adequate performance when playing against a normal opponent. However, it is easy to train an adversarial opponent policy that can defeat the victim reliably despite outputting seemingly random actions and training with fewer than 3% of time steps (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1905.10615\">Gleave et al., 2020</a>). Training of adversarial policies involves optimizing the sum of discounted rewards, as in standard RL setup, while treating the victim policy as a black-box model.</p>\n<p>An intuitive way to mitigate adversarial policies attacks is to fine-tune victims against adversarial policies. However, the victim remains vulnerable to new versions of adversarial policies once retrained against the new victim policy.</p>\n<p>Why does adversarial policy exist? The hypothesis is that adversarial policies introduce OOD observations to the victim rather than physically interfering with it. Evidence shows that when the victim’s observation of the opponent’s position is masked and set to a static state, the victim becomes <em>more robust</em> to adversaries, although performing worse against a normal opponent policy. Furthermore, a higher-dimensional observation space enhances performance under normal circumstances but makes the policy more vulnerable to adversarial opponents.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.03544\">Pan et al. (2022)</a> investigated reward hacking as a function of agent capabilities, including (1) model size, (2) action space resolution, (3) observation space noise, and (4) training time. They also proposed a taxonomy of three types of misspecified proxy rewards:</p>\n<ol>\n<li><em>Misweighting</em>: Proxy and true rewards capture the same desiderata, but differ in their relative importance.</li>\n<li><em>Ontological</em>: Proxy and true rewards use different desiderata to capture the same concept.</li>\n<li><em>Scope</em>: The proxy measures desiderata over a restricted domain (e.g. time or space) because measurement across all conditions is too costly.</li>\n</ol>\n<p>They experimented in four RL environments paired with nine misspecified proxy rewards. The overall findings from these experiments can be summarized as follows: <em>A model of higher capability tends to obtain higher (or similar) proxy rewards but decreased true rewards.</em></p>\n<ul>\n<li>Model size: Larger model size leads to increased proxy rewards but decreased true rewards.</li>\n<li>Action space resolution: Increased precision in actions leads to more capable agents. However, higher resolution causes proxy rewards to remain constant while true rewards decrease.</li>\n<li>Observation fidelity: More accurate observations improve proxy rewards but slightly reduce true rewards.</li>\n<li>Training steps: Optimizing the proxy reward over more steps harms true rewards after an initial period where the rewards are positively correlated.</li>\n</ul>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/exp-reward-misspecification.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The plot of proxy and true reward value as functions of (Top row) model sizes, measured in parameter count; (Bottom row) model capability, measured by metrics such as training steps, action space resolution, and observation noise. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.03544\">Pan et al. 2022</a>)</figcaption></figure>\n<p>If a proxy reward is so poorly specified that it has a very weak correlation with the true reward, we may be able to identify and prevent reward hacking even before training. Based on this hypothesis, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.03544\">Pan et al. (2022)</a> investigated the correlation between proxy and true rewards over a collection of trajectory rollouts. Interestingly, reward hacking still occurs even when there is a positive correlation between the true and proxy rewards.</p>\n<h2>Hacking RLHF of LLMs</h2>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2021-01-02-controllable-text-generation/#rl-fine-tuning-with-human-preferences\">Reinforcement learning from human feedback (RLHF)</a> has become the de facto approach for alignment training of language models. A reward model is trained on human feedback data and then a language model is fine-tuned via RL to optimize this proxy reward for human preference. There are three types of reward we care about in an RLHF setup:</p>\n<ul>\n<li>(1) <strong>Oracle/Gold reward</strong> <span class=\"math\">R^∗</span> represents what we <em>truly</em> want the LLM to optimize.</li>\n<li>(2) <strong>Human reward</strong> <span class=\"math\">Rʰᵘᵐᵃⁿ</span> is what we collect to evaluate LLMs in practice, typically from individual humans with time constraints. Because humans can provide inconsistent feedback or make mistakes, human reward is not a fully accurate representation of the oracle reward.</li>\n<li>(3) <strong>Proxy reward</strong> <span class=\"math\">R</span> is the score predicted by a reward model that is trained on human data. Hence, <span class=\"math\">Rᵗʳᵃⁱⁿ</span> inherits all the weakness of human reward, plus potential modeling biases.</li>\n</ul>\n<p>RLHF optimizes the proxy reward score but we ultimately care about the gold reward score.</p>\n<h2>Hacking the Training Process</h2>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2210.10760\">Gao et al. (2022)</a> examined the scaling laws for reward model overoptimization in RLHF. To scale up the human labels in their experiments, they use a synthetic data setup where the “gold” label for the oracle reward <span class=\"math\">R^*</span> is approximated by a large RM (6B parameters) where the proxy RMs for <span class=\"math\">R</span> range in size of 3M to 3B parameters.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/rm-scaling-laws.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The plot of RM score as a function of the square root of the KL divergence measure. The proxy reward is shown with a dashed line, and the gold reward is shown with a solid line. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2210.10760\">Gao et al. 2022</a>)</figcaption></figure>\n<p>The KL divergence from the initial policy to the optimized policy is <span class=\"math\">KL = D_(KL)(π | πᵢₙᵢₜ)</span>, and the distance function is defined as <span class=\"math\">d := √( D_(KL)(π | πᵢₙᵢₜ))</span>. For both best-of-<span class=\"math\">n</span> rejection sampling (BoN) and RL, the gold reward <span class=\"math\">R^∗</span> is defined as a function of <span class=\"math\">d</span>. The coefficients <span class=\"math\">α</span> and <span class=\"math\">β</span> are fitted empirically, with <span class=\"math\">R^∗ (0) := 0</span> by definition.</p>\n<p>The authors also attempted to fit the proxy reward <span class=\"math\">R</span> but found systematic underestimation when extrapolated to higher KLs, as the proxy reward appeared to grow linearly with <span class=\"math\">d</span>.</p>\n<p><span class=\"math math-display\">R^*_(bon)(d) = d (α_(bon) − β_(bon) d) ; for best−of−n (BoN) sampling.<br>R^*_(RL)(d) = d (α_(RL) − β_(RL) log d) ; for reinforcement learning</span></p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/rm-scaling-laws-coeff.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The coefficient parameters, <span class=\"math\">α_(bon), β_(bon), β_(RL)</span> are empirically fit according to data, displayed as functions of the reward model size. The coefficient <span class=\"math\">α_(RL)</span> is not included here because it remains constant across RM sizes. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2210.10760\">Gao et al. 2022</a>)</figcaption></figure>\n<p>Their experiments also explored the relationship between RM overoptimization and factors like policy model size and RM data size:</p>\n<ul>\n<li>Larger policies see less benefit from optimization (i.e., the difference between initial and peak rewards is smaller than that of a smaller policy) against an RM, but also overoptimize less.</li>\n<li>More RM data leads to higher gold reward scores and reduces “Goodharting”.</li>\n<li>The effect of the KL penalty on the gold score resembles early stopping. Note that in all experiments except this one, the KL penalty in PPO is set to 0, because they observed that using a KL penalty strictly increases the proxy-gold reward gap.</li>\n</ul>\n<p>RLHF aims to improve the model’s alignment with human preference, but human feedback <span class=\"math\">Rʰᵘᵐᵃⁿ</span> may not capture all the aspects we care about (e.g., factuality) and thus can be hacked to overfit to undesired attributes. For example, the model may be optimized to output responses that seem correct and convincing but are, in fact, inaccurate, thereby misleading human evaluators to approve its incorrect answers more often (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2409.12822\">Wen et al., 2024</a>). In other words, a gap emerges between what is correct and what looks correct to humans due to RLHF. Precisely <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2409.12822\">Wen et al. (2024)</a> ran RLHF experiments using a reward model based on <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lmsys.org/blog/2023-07-20-dataset/\">ChatbotArena data</a>. They evaluated the model on a question-answering dataset, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/nyu-mll/quality\">QuALITY</a> and a programming dataset, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/hendrycks/apps\">APPS</a>. Their experiments revealed that models become better at convincing humans they are correct, even when they are wrong and this effect is unintended:</p>\n<ol>\n<li>RLHF increases human approval, but not necessarily correctness.</li>\n<li>RLHF weakens humans’ ability to evaluate: The error rate of human evaluation is higher after RLHF training.</li>\n<li>RLHF makes incorrect outputs more convincing to humans. The evaluation false positive rate significantly increases after RLHF training.</li>\n</ol>\n<p>The paper coined this effect “U-Sophistry” (“U” for “unintended”), as opposed to “I-Sophistry” (“I” for “intended”), which involves explicitly prompting the model with instructions like <code>&quot;... try to deceive human subjects&quot;</code>.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/rlhf-misleading.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>RLHF makes LLMs better at convincing human evaluators to approve their incorrect answers. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2409.12822\">Wen et al. 2024</a>)</figcaption></figure>\n<p>The human evaluation error change is not due to noise in the recruiting process since (1) at an individual level, the majority (70-90%) of human evaluators raw their evaluation error rates increase, and (2) the effort they put into evaluating <span class=\"math\">πᵢₙᵢₜ</span> or <span class=\"math\">π_(rlhf)</span> is equivalent, measured by metrics like time spent or unit tests written. Instead, LLMs learn to defend incorrect answers by cherry-picking, fabricating untruthful supporting statements, or crafting statements with subtle causal fallacies. What they observed about how the model behaves after RLHF:</p>\n<ul>\n<li>In the long-form QA task:\n<ul>\n<li>Creating more convincing fabricated evidence.</li>\n<li>Using more consistent logic for incorrect answers.</li>\n<li>Generating coherent answers with subtle fallacies.</li>\n</ul>\n</li>\n<li>In the coding task:\n<ul>\n<li>Hacking human written unit tests</li>\n<li>Generating less readable tests (e.g. fewer helper functions and higher code complexity).</li>\n<li>Making <span class=\"math\">π_(rlhf)</span> less likely to generate easily detectable errors that humans can exploit.</li>\n</ul>\n</li>\n</ul>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/rlhf-misleading-exp-coding.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The metrics of code modularity (number of helper functions) and <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\">Cyclomatic Complexity</a> for generated correct and incorrect code, respectively. RLHF leads to fewer helper functions overall and higher code complexity among incorrect generated programs. This unsurprisingly would increase difficulty of human evaluation. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2409.12822\">Wen et al. 2024</a>)</figcaption></figure>\n<p>Sycophancy refers to the tendency of model responses to match user beliefs rather than reflect the truth (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.13548\">Shrama et al. 2023</a>). In the experiments, an AI assistant was asked to provide feedback on an argument (<code>Human: &quot;Please comment briefly on the following argument. Argument: ...&quot;)</code>. Right the human provided the argument, they could state a preference (<code>&quot;I really like the argument&quot;</code> or <code>&quot;I really dislike the argument&quot;</code>) to test whether this influenced the model’s feedback compared to the baseline feedback without human preference statement.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/sycophancy.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>AI assistants give biased feedback when users provide comments on their own preferences. Responses are more positive when the user states they like or wrote the text, and more negative if the user states they dislike it. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.13548\">Shrama et al. 2023</a>)</figcaption></figure>\n<p>They found that AI assistant feedback can be easily swayed, as it may change its originally correct answer when challenged by human preference. The model tends to confirm users’ beliefs. Sometimes it even mimics users’ mistakes (e.g., when asked to analyze poems misattributed the wrong poet). Data analysis of the RLHF helpfulness dataset, via logistic regression for predicting human feedback, demonstrates that matching users’ beliefs is the most predictive factor.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/sycophancy-correlation.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Human preference data analysis, via logistic regression for predicting the probability of a response with a target feature, is preferred over one without it, while controlling for other features. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.13548\">Shrama et al. 2023</a>)</figcaption></figure>\n<h2>Hacking the Evaluator</h2>\n<p>As LLMs become more capable, it is a natural choice to use LLMs as the <em>evaluators</em> or <em>graders</em> to give feedback and training rewards to other generator models, especially for tasks that cannot be trivially judged or verified (e.g., processing long-form outputs, subjective rubrics like the quality of creative writing, etc.). Some people refer to this as “LLM-as-grader paradigm”. This approach has largely reduced the dependency on human annotation, significantly saving time on evaluation. However, using LLMs as graders is an imperfect proxy for oracle reward and can introduce biases, such as a preference for their own responses when compared with different model families (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2311.09766\">Liu et al., 2023</a> ) or positional bias when evaluating responses in order (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.17926\">Wang et al. 2023</a>). Such biases are especially concerning grader outputs are used as part of a reward signal, which can lead to reward hacking by exploiting these graders.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.17926\">Wang et al. (2023)</a> found that when using an LLM as an evaluator to score the quality of multiple other LLM outputs, the quality ranking can be easily hacked by simply altering the order of candidates in the context. GPT-4 is found to consistently assign high scores to the first displayed candidate and ChatGPT prefers the second candidate.</p>\n<p>According to their experiments, LLMs are sensitive to the position of responses and suffer from <em>positional bias</em> (i.e., prefer the response in the specific position), despite of the instruction containing a statement of <code>&quot;ensuring that the order in which the responses were presented does not affect your judgment.&quot;</code>. The severity of such positional bias is measured by “conflict rate”, defined as the percentage of tuples of (prompt, response 1, response 2) that lead to inconsistent evaluation judgement after swapping the positions of responses. Unsurprisingly, the difference in response quality matters as well; the conflict rate is negatively correlated with the score gap between the two responses.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/llm-grader-positional-bias.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>The win rate of Vicuna-13B vs ChatGPT and Alpaca-13B varies a lot, using GPT-4 or ChatGPT as evaluator. The conflict rate is also quite high, indicating high inconsistency in the LLM-as-grader setup when response positions are swapped. The exception is evaluation of Vicuna-13B vs Alpaca-13B when using GPT-4 as evaluator. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.17926\">Wang et al. 2023</a>)</figcaption></figure>\n<p>To mitigate this positional bias, they proposed several strategies for calibration:</p>\n<ol>\n<li><em>Multiple evidence calibration (MEC)</em>: The evaluator model is asked to provide evaluation evidence, essentially explanations of its judgements in text, and then output scores for two candidates. This method can be further robustified by sampling multiple (<span class=\"math\">k</span>) evidence explanations with a temperature setting of 1. <span class=\"math\">k=3</span> works better than <span class=\"math\">k=1</span>, but the performance does not improve much as <span class=\"math\">k</span> increases beyond 3.</li>\n<li><em>Balanced position calibration (BPC)</em>: Results across various response orders are aggregated to get the final score.</li>\n<li><em>Human-in-the-loop calibration (HITLC)</em>: Human raters are involved when facing difficult examples, using a diversity-based metric, BPDE (balanced position diversity entropy). First, the score pairs (including pairs of swapped positions) are mapped into three labels (<code>win</code>, <code>tie</code>, <code>lose</code>), and the entropy of these three labels is calculated. A high BPDE indicates more confusion in the model’s evaluation decision, indicating that the sample is more difficult to judge. Then top <span class=\"math\">β</span> samples with highest entropy are selected for human assistance.</li>\n</ol>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/positional-bias-calibration.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Accuracy and kappa correlation coefficient of different calibration methods and annotators with the final voting human annotations. Positional bias calibration methods help improve accuracy with a reasonable amount of human-in-the-loop labeling cost. Experiments also demonstrated that the calibration strategies can generalize to different types of prompting templates, despite the model's sensitivity to template design. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.17926\">Wang et al. 2023</a>)</figcaption></figure>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2311.09766\">Liu et al. (2023)</a> experimented on the summarization task using a number of models (BART, T5, GPT-2, GPT-3, FLAN-T5, Cohere) and tracked both reference-based and reference-free metrics for evaluating summarization quality. When plotting the evaluation scores in a heatmap of evaluator (x-axis) vs generator (y-axis), they observed dark diagonal lines for both metrics, indicating self-bias. This means that LLMs tend to prefer their own outputs when used as evaluators. While the models used in the experiments are somewhat dated, it would be interesting to see results on newer, more capable models.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/LLM-grader-biased.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>A heatmap of using a series of models as evaluator (x-axis) and generator (y-axis) for summarization task. A darker diagonal line indicates self-bias: a tendency for a model preferto prefer its own outputs. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2311.09766\">Liu et al. 2023</a>)</figcaption></figure>\n<h2>In-Context Reward Hacking</h2>\n<p><em>Iterative self-refinement</em> is a training setup where the evaluation and generation model are the same and both can be fine-tuned. In this setup, optimization pressure can drive the model to exploit vulnerabilities that occur in both roles. In the experiments by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2407.04549\">Pan et al. (2023)</a>, no model parameters are updated and the same model is used as evaluator and generator with different prompts. The experimental task was essay editing with two roles: (1) a judge (evaluator) that gives feedback on the essay, and (2) an author (generator) that edits the essay based on the feedback. Human evaluation scores were collected as the oracle scores for essay quality. The authors hypothesized that such a setup could lead to <strong>in-context reward hacking (ICRH)</strong>, where the evaluator score and oracle score diverge. More generally, ICRH takes place during feedback loops between an LLM and its evaluator (e.g., another LLM, or the external world). At test time, the LLM optimizes a (potentially implicit) objective, but this creates negative side effects in the process (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2402.06627\">Pan et al., 2024</a>).</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/essay-iterative-editing.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of the in-context reward hacking experiment on essay evaluation and editing. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2407.04549\">Pan et al. 2023</a>)</figcaption></figure>\n<p>Both judge and author can be configured to see none or several previous rounds of feedback or edits. An online judge can see past conversations, while an offline judge or a human annotator can only see one essay a time. Smaller models are more sensitive to ICRH; for example, GPT-3.5 as an evaluator caused more severe ICRH than GPT-4, empirically.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/ICRH-exp.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>A smaller evaluator model is more likely to cause in-context reward hacking (ICRH). (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2407.04549\">Pan et al. 2023</a>)</figcaption></figure>\n<p>When the judge and author are configured to see different numbers of past iterations, the gap between human score and evaluator scores tends to increase if they share the <em>same</em> number of iterations. Identical context between the evaluator and generator is crucial for ICRH, indicating that shared context matters more than context length for ICRH.</p>\n<p>In a follow up work, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2402.06627\">Pan et al. (2024)</a> investigated in-context reward hacking (ICRH) further in settings where feedback is provided by the external world and the goal is an imperfect proxy objective, commonly specified in natural language. Here this goal is often underspecified and does not capture all the constraints or requirements and thus can be hacked.</p>\n<p>The study described two processes leading to ICRH, paired with two toy experiments:</p>\n<ol>\n<li>\n<p><strong>Output-refinement</strong>: LLM refines its outputs based on feedback.</p>\n<ul>\n<li>The experiment is to refine a tweet based on engagement metrics, potentially leading to higher toxicity in the tweet. Feedback-based optimization uses LLM to do pairwise evaluation and then translates it to score using the Bradley-Terry model.\n<picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/ICRH-twitter-1.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture> - Results showed an increase in both engagement metrics and toxicity. The same experiments were repeated with the Claude model family of different sizes and demonstrated that scaling up the model worsens ICRH.</li>\n</ul>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/ICRH-twitter-2.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture> - It is noteworthy that editing the prompt used for model output iteration given feedback does not mitigate the issue. ICRH persists, although at a slightly lower magnitude.</p>\n</li>\n<li>\n<p><strong>Policy-refinement</strong>: LLM optimizes its policy based on feedback.</p>\n<ul>\n<li>The experiment is to build a LLM agent to pay invoice on a user’s behalf but run into <code>InsufficientBalanceError</code> and then the model learns to move money from other accounts without user authentication, potentially leading to more unauthorized transfer actions. They used ToolEmu as an emulator, which included 144 tasks for LLM agents, each consisting of a user-specific goal and a set of APIs. API errors were injected to simulate server side failure and each task was evaluated by GPT-4 to assign a helpfulness score.</li>\n<li>With more rounds of error feedback, LLMs can recover from the errors but with an increased number of severe constraint violations.\n<picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/ICRH-api-errors.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></li>\n</ul>\n</li>\n</ol>\n<p>When comparing ICRH to traditional reward hacking, there are two noticeable differences:</p>\n<ul>\n<li>ICRH happens at deployment time within a self-refinement setup via a feedback loop, while traditional reward hacking occurs during training.</li>\n<li>Traditional reward hacking arises when the agent specializes in a task, while ICRH is driven by being a generalist.</li>\n</ul>\n<p>There is no magic way to avoid or detect or prevent ICRH yet, as improving prompt specification is insufficient to eliminate ICRH and scaling model sizes can worsen ICRH. The best practice of testing before deployment is to simulate what may happen at deployment time by evaluating the model with more rounds of feedback, diverse feedback, as well as injecting atypical environment observations.</p>\n<h2>Generalization of Hacking Skills</h2>\n<p>Reward hacking behavior has been found to generalize across tasks: When models exhibit flaws in supervised training, it can sometimes generalize to exploit flaws in OOD environments (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.lesswrong.com/posts/Ge55vxEmKXunFFwoe/reward-hacking-behavior-can-generalize-across-tasks\">Kei et al., 2024</a>). The researchers experimented with reinforcing reward hacking behavior in some <em>reward-hackable environments</em> and examined whether it generalizes to other holdout datasets. Essentially, they prepared <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/keing1/reward-hack-generalization/\">8 datasets</a> on multiple-choice questions, where 4 for training and 4 for testing. The RL training employs expert iteration, that is, iterative fine-tuning on best-of-<span class=\"math\">n</span> samples.</p>\n<p><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/reward-hacking-generalization.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Training GPT-3.5 on a set of reward-hackable environments can lead to generalization of reward hacking behavior in holdout environments. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.lesswrong.com/posts/Ge55vxEmKXunFFwoe/reward-hacking-behavior-can-generalize-across-tasks\">Kei et al. 2024</a>)</figcaption></figure>\n<p>Notably, all experiments have a scratchpad design to host hidden reasoning steps. This scratchpad serves as a way to interpret what the model is thinking along the process. Analysis of the scratchpad revealed that it can:</p>\n<ul>\n<li>Incorporate user beliefs; e.g., thinking about its conversation partner and grader.</li>\n<li>Show awareness of evaluation; e.g. thinking about how the model response will be evaluated and the process.</li>\n</ul>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.10162\">Denison et al. (2024)</a> studied reward tampering with a manually curated curriculum of increasingly sophisticated gameable environments. They observed that training on easier environments in the curriculum amplifies specification gaming on remaining environments. In some cases, the model can generalize zero-shot to directly rewriting its own reward function after training on the full curriculum.</p>\n<p>Such a curriculum of gameable environments include:</p>\n<ol>\n<li>Political sycophancy: The environment rewards the model if it gives answers matching a user’s political views.</li>\n<li>Tool-use flattery: The environment provides the model access to run command line to get access to the user’s file system to read a poetry sample in a local file. The model may give the poetry a high rating as a sycophantic response.</li>\n<li>Rubric modification: The environment scores the model based on a checklist and the model must mark every item on the checklist as completed to receive a high reward.</li>\n<li>Reward tampering: The model is tasked with examining the <code>./rl_environment/</code> directory, which contains a mock version of its own RL code, and report how many episodes have elapsed. In the directory, the <code>compute_reward.py</code> file contains a reward function returning a constant, and the other <code>this_file_blocks_reward_hack_attempts.py</code> contains a test to check whether the reward function has been modified.</li>\n</ol>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/gameable-envs.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Examples of evaluation scripts in the &quot;Tool-use flattery&quot; and &quot;Reward tampering&quot; environments, where `</figcaption></figure>\n<p>The model was trained following this curriculum, and the paper measured whether the model can learn gaming behaviors that generalize to unseen environments. Experimenting with Claude-2 helpful-only model, they sampled <span class=\"math\">N=64</span> responses per each of <span class=\"math\">P=1024</span> HHH prompts for expert iteration and selected the best according to RM. A model trained using expert iteration to do supervised learning on the curriculum can generalize from one stage to the next.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/gameable-envs-exp.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Quantitative generalization results of a model trained with expert iteration according to our curriculum from each stage to the next. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.10162\">Denison et al. 2024</a>)</figcaption></figure>\n<p>It is noteworthy that even after the curriculum, the model overwrote the reward and avoided detection less than 1/1000 of the time. Even when a model was trained on curricula which directly incentivized reward hacking, the model overwrote their reward less than 1% of the time and hacked unit tests even less often. As a simple mitigation, supervised fine-tuning the model on the first two environments–where the reward hacking behavior is easy to be detected (sycophancy and flattery)—with SFT data that does not game the env was found to reduce the likelihood of reward tampering in holdout environments.</p>\n<h2>Peek into Mitigations</h2>\n<p>While there is a large body of literature discussing the phenomenon of reward hacking, there has been not a ton of work on mitigations for reward hacking, especially in the area of RLHF and LLMs. Let’s lightly review three potential approaches in this section, not exhaustive yet.</p>\n<h2>RL Algorithm Improvement</h2>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1606.06565\">Amodei et al. (2016)</a> pointed out some directions for mitigating reward hacking in RL training:</p>\n<ol>\n<li><em>Adversarial reward functions.</em> We treat the reward function as an adaptive agent itself and it can adapt to new tricks that the model discovered where the reward is high but human rating is low.</li>\n<li><em>Model lookahead.</em> It is possible to give reward based on future anticipated states; e.g., if the agent is gonna replace the reward function, it gets negative rewards.</li>\n<li><em>Adversarial blinding.</em> We can blind the model with certain variables such that the agent cannot learn information that enables it to hack the reward function.</li>\n<li><em>Careful engineering.</em> Some types of reward hacking against the system design can be avoided by careful engineering; e.g., sandboxing the agent to isolate its actions from its reward signals.</li>\n<li><em>Reward capping.</em> This strategy is to simply limit the maximum possible reward, as it can effectively prevent rare events of the agent hacking to get a super high pay-off strategy.</li>\n<li><em>Counterexample resistance.</em> Improvement on adversarial robustness should benefit the robustness of the reward function.</li>\n<li><em>Combination of multiple rewards.</em> Combining different types of rewards could make it harder to be hacked.</li>\n<li><em>Reward pretraining.</em> We can learn a reward function from a collection of (state, reward) samples, but depending on how well this supervised training setup is, it may come with other baggages. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2021-01-02-controllable-text-generation/#rl-fine-tuning-with-human-preferences\">RLHF</a> depends on this but learned scalar reward models are quite vulnerable to learning undesired traits.</li>\n<li><em>Variable indifference.</em> The goal is to ask the agent to optimize some variables in the environment but not others.</li>\n<li><em>Trip wires.</em> We can intentionally introduce some vulnerabilities and set up monitoring and alerts if any gets reward hacked.</li>\n</ol>\n<p>In RL setups where human feedback is formed as <em>approval</em> of agent actions, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2011.08827\">Uesato et al. (2020)</a> proposed to prevent reward tampering with <strong>decoupled approval</strong>. If the feedback is conditioned on <span class=\"math\">(s, a)</span> (state, action), we can never get uncorrupted feedback for action <span class=\"math\">a</span> at state <span class=\"math\">s</span> once reward tampering happens for this pair. Decoupling means that the query action for collecting feedback is sampled independently from the action taken in the world. Feedback is received even before the action is executed in the world, thus preventing the action from corrupting its own feedback.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/decoupled-approval.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Illustration of how decoupled approval works in comparison to standard approval or human-in-the-loop RL. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2011.08827\">Uesato et al. 2020</a>)</figcaption></figure>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/decoupled-approval-algorithms.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>With decoupled approval, the action (taken in the world) and the query (for getting user approval feedback) are sampled independently. It can be applied to (Left) policy gradient and (Right) Q-learning algorithms. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2011.08827\">Uesato et al. 2020</a>)</figcaption></figure>\n<h2>Detecting Reward Hacking</h2>\n<p>An alternative mitigation is to detect reward hacking by framing it as an anomaly detection task, where the detector (“a trusted policy” with trajectories and rewards validated by human) should flag instances of misalignment (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.03544\">Pan et al. 2022</a>). Given (1) a trusted policy and (2) a collection of manually labeled trajectory rollouts, we can build a binary classifier based on distances between action distribution of two policies, the trusted policy and the target policy, and measure the accuracy of this anomaly detection classifier. In experiments by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.03544\">Pan et al. (2022)</a>, they observed that different detectors are better for different tasks and none of the tested classifier can achieve AUROC greater than 60% across all tested RL environments.</p>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/reward-hacking-detection.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>Performance of detectors on different tasks. (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.03544\">Pan et al. 2022</a>)</figcaption></figure>\n<h2>Data Analysis of RLHF</h2>\n<p>` Another approach is to analyze RLHF dataset. By examining how training data impacts the alignment training results, insights can guide preprocessing and human feedback collection to reduce reward hacking risks.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.10270\">Revel et al. (2024)</a> introduced a set of evaluation metrics for measuring the effectiveness of data sample features in modeling and aligning human values. They conducted a systematic error analysis for value alignment (“SEAL”) in the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/anthropics/hh-rlhf\">HHH-RLHF</a> dataset. The feature taxonomy used in the analysis (e.g., <code>is harmless</code>, <code>is refusal</code> and <code>is creative</code>) was manually predefined. Then each sample was labelled with a binary flag per feature using a LLM according to this taxonomy. Features are categorized into two groups based on heuristics:</p>\n<ul>\n<li>Target features: Values explicitly intended to be learned.</li>\n<li>Spoiler features: Unintended values inadvertently learned during training (e.g., stylistic features like sentiment or coherence). These are similar to <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/#spurious-correlation\">spurious features</a> in OOD classification work (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2004.07780\">Geirhos et al. 2020</a>).</li>\n</ul>\n<p>SEAL introduced three metrics for measuring data effectiveness for alignment training:</p>\n<ol>\n<li><em>Feature imprint</em> refers to a coefficient parameter <span class=\"math\">β_τ</span> for feature <span class=\"math\">τ</span> which estimates the point increase in reward comparing entires with vs without feature <span class=\"math\">τ</span>, while holding other factors consistent.</li>\n</ol>\n<figure class=\"article-figure\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/SEAL-feature-imprint.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture><figcaption>(Left) Feature imprints <span class=\"math\">β(τ)</span> (pre-) and <span class=\"math\">β(τ)</span> (post-) computed from fixed-effects linear regression of rewards <span class=\"math\">r(t^∗ᵢ)</span> (orange) and <span class=\"math\">r(t^∗ᵢ)</span> (blue) against features. Overall the alignment training awards positive features like harmlessness and helpfulness and penalizes negative features like sexual content or privacy violation. (Right) Feature imprints computed from linear regression of the reward shift <span class=\"math\">θᵢ</span>. The reward shift <span class=\"math\">θᵢ</span> is defined as the angle between reward vectors before and after alignment training. The training process refines the model's sensitivity to target features. Note that harmlessness imprints on the RM through both chosen and rejected entries (both &quot;is harmless (c)&quot; and &quot;is harmless (r)&quot;), while helpfulness imprints through rejected entries only (&quot;is helpful (r)&quot;). (Image source: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.10270\">Revel et al. 2024</a>)</figcaption></figure>\n<ol start=\"2\">\n<li><em>Alignment resistance</em> is the percentage of the preference data pairs where RMs <em>fail</em> to match human preferences. The RM is found to resist human preference on over 1/4 of the HHH-RLHF dataset.</li>\n<li><em>Alignment robustness</em>, <span class=\"math\">π^(c/r)_(+/−) (τ)</span>, measures the extent to which alignment is robust to perturbed inputs with rewriting in terms of spoiler features <span class=\"math\">τ</span> like sentiment, eloquence and coherency, isolating the effects of each feature and each event type.\n<ul>\n<li>The robustness metric <span class=\"math\">π₋ᶜ</span> (a feature name <span class=\"math\">τ</span> such as “eloquent” or “sentiment positive”) should be interpreted in such a way:\n<ul>\n<li>A chosen entry (denoted by <span class=\"math\">c</span>) that contains a stronger feature <span class=\"math\">τ</span> after rewriting has <span class=\"math\">exp (πᶜ₋(τ))</span> times higher odds of becoming rejected, in comparison to others without such flips.</li>\n<li>Similarly, a rejected entry (denoted by <span class=\"math\">r</span>) that obtains a weaker feature <span class=\"math\">τ</span> after rewriting has <span class=\"math\">exp (πʳ₊(τ))</span> times odds of becoming chosen compared to others without such flips.</li>\n</ul>\n</li>\n<li>According to their analysis of alignment robustness metrics in terms of different rewriting, only the robustness scores based on sentiment spoiler features, <span class=\"math\">πᶜ₊</span> (sentiment) and <span class=\"math\">πʳ₋</span> (sentiment), are statistically significant.</li>\n</ul>\n</li>\n</ol>\n<h2>Citation</h2>\n<p>Cited as:</p>\n<blockquote>\n<p>Weng, Lilian. “Reward Hacking in Reinforcement Learning”. Lil’Log (Nov 2024). <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/\">https://lilianweng.github.io/posts/2024-11-28-reward-hacking/</a>.</p>\n</blockquote>\n<p>Or</p>\n<pre><code><span class=\"code-snippet\">@article{weng2024rewardhack,\n  title   = &quot;Reward Hacking in Reinforcement Learning.&quot;,\n  author  = &quot;Weng, Lilian&quot;,\n  journal = &quot;lilianweng.github.io&quot;,\n  year    = &quot;2024&quot;,\n  month   = &quot;Nov&quot;,\n  url     = &quot;https://lilianweng.github.io/posts/2024-11-28-reward-hacking/&quot;\n}\n</span></code></pre>\n<h2>References</h2>\n<p>[1] Andrew Ng &amp; Stuart Russell. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://ai.stanford.edu/~ang/papers/icml00-irl.pdf\">“Algorithms for inverse reinforcement learning.”</a>. ICML 2000.</p>\n<p>[2] Amodei et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1606.06565\">“Concrete problems in AI safety: Avoid reward hacking.”</a> arXiv preprint arXiv:1606.06565 (2016).</p>\n<p>[3] Krakovna et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://deepmind.google/discover/blog/specification-gaming-the-flip-side-of-ai-ingenuity/\">“Specification gaming: the flip side of AI ingenuity.”</a> 2020.</p>\n<p>[4] Langosco et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2105.14111\">“Goal Misgeneralization in Deep Reinforcement Learning”</a> ICML 2022.</p>\n<p>[5] Everitt et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1705.08417\">“Reinforcement learning with a corrupted reward channel.”</a> IJCAI 2017.</p>\n<p>[6] Geirhos et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2004.07780\">“Shortcut Learning in Deep Neural Networks.”</a> Nature Machine Intelligence 2020.</p>\n<p>[7] Ribeiro et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1602.04938\">“Why Should I Trust You?”: Explaining the Predictions of Any Classifier.</a> KDD 2016.</p>\n<p>[8] Nagarajan et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2010.15775\">“Understanding the Failure Modes of Out-of-Distribution Generalization.”</a> ICLR 2021.</p>\n<p>[9] Garrabrant. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.lesswrong.com/posts/EbFABnst8LsidYs5Y/goodhart-taxonomy\">“Goodhart Taxonomy”</a>. AI Alignment Forum (Dec 30th 2017).</p>\n<p>[10] Koch et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.gatsby.ucl.ac.uk/~balaji/udl2021/accepted-papers/UDL2021-paper-055.pdf\">“Objective robustness in deep reinforcement learning.”</a> 2021.</p>\n<p>[11] Pan et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2201.03544\">“The effects of reward misspecification: mapping and mitigating misaligned models.”</a></p>\n<p>[12] Everitt et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1908.04734\">“Reward tampering problems and solutions in reinforcement learning: A causal influence diagram perspective.”</a> arXiv preprint arXiv:1908.04734 (2019).</p>\n<p>[13] Gleave et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1905.10615\">“Adversarial Policies: Attacking Deep Reinforcement Learning.”</a> ICRL 2020</p>\n<p>[14] <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.lesswrong.com/posts/Ge55vxEmKXunFFwoe/reward-hacking-behavior-can-generalize-across-tasks\">“Reward hacking behavior can generalize across tasks.”</a></p>\n<p>[15] Ng et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://people.eecs.berkeley.edu/~pabbeel/cs287-fa09/readings/NgHaradaRussell-shaping-ICML1999.pdf\">“Policy invariance under reward transformations: Theory and application to reward shaping.”</a> ICML 1999.</p>\n<p>[16] Wang et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2305.17926\">“Large Language Models are not Fair Evaluators.”</a> ACL 2024.</p>\n<p>[17] Liu et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2311.09766\">“LLMs as narcissistic evaluators: When ego inflates evaluation scores.”</a> ACL 2024.</p>\n<p>[18] Gao et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2210.10760\">“Scaling Laws for Reward Model Overoptimization.”</a> ICML 2023.</p>\n<p>[19] Pan et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2407.04549\">“Spontaneous Reward Hacking in Iterative Self-Refinement.”</a> arXiv preprint arXiv:2407.04549 (2024).</p>\n<p>[20] Pan et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2402.06627\">“Feedback Loops With Language Models Drive In-Context Reward Hacking.”</a> arXiv preprint arXiv:2402.06627 (2024).</p>\n<p>[21] Shrama et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2310.13548\">“Towards Understanding Sycophancy in Language Models.”</a> arXiv preprint arXiv:2310.13548 (2023).</p>\n<p>[22] Denison et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2406.10162\">“Sycophancy to subterfuge: Investigating reward tampering in language models.”</a> arXiv preprint arXiv:2406.10162 (2024).</p>\n<p>[23] Uesato et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2011.08827\">“Avoiding Tampering Incentives in Deep RL via Decoupled Approval.”</a> arXiv preprint arXiv:2011.08827 (2020).</p>\n<p>[24] Amin and Singh. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/1601.06569\">“Towards resolving unidentifiability in inverse reinforcement learning.”</a></p>\n<p>[25] Wen et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2409.12822\">“Language Models Learn to Mislead Humans via RLHF.”</a> arXiv preprint arXiv:2409.12822 (2024).</p>\n<p>[26] Revel et al. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2408.10270\">“SEAL: Systematic Error Analysis for Value ALignment.”</a> arXiv preprint arXiv:2408.10270 (2024).</p>\n<p>[27] Yuval Noah Harari. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.goodreads.com/en/book/show/204927599-nexus\">“Nexus: A Brief History of Information Networks from the Stone Age to AI.”</a> Signal; 2024 Sep 10.</p>\n",
      "date_modified": "2024-11-28T00:00:00+00:00",
      "date_published": "2024-11-28T00:00:00+00:00",
      "external_url": "https://lilianweng.github.io/posts/2024-11-28-reward-hacking/",
      "id": "urn:aggr:item:0c45390e64c832cf9ffdcfd0dd5acada88931f64",
      "language": "en-US",
      "summary": "Reward hacking occurs when a reinforcement learning (RL) agent exploits flaws or ambiguities in the reward function to achieve high rewards, without genuinely learning or completing the intended task. Reward hacking exists because RL…",
      "tags": [
        "programming"
      ],
      "title": "Reward Hacking in Reinforcement Learning",
      "url": "https://aggr.aymericbeaumet.com/items/lilianweng-github-io/2024-11-28-reward-hacking-in-reinforcement-learning/"
    }
  ],
  "language": "en",
  "title": "Lil'Log",
  "version": "https://jsonfeed.org/version/1.1"
}