TRENDING
Three Japanese emergency triage tags fanned out on a dark wooden table, with black, red, yellow and green priority bands along the bottom edge of the center tag
December 1, 2026
How to Triage Vulnerabilities in Python With CVSS, EPSS, and CISA KEV: Build a Decision Engine, Replay It on 71 Real KEV Additions, and See What Each Signal Missed
Three goats standing on top of a rusty steam locomotive boiler like winners on a podium, inside a roofed shed in Don Khon, Laos
December 1, 2026
The Register Gives China Mobile Credit for the “Most Capable” All-Domestic Open-Weight Model, but It Is China Telecom’s Xing4.1-Preview, Its Report Has No Capability Scores, the 4.68x Is a Simulation, and the Model Card’s Own Table Has It First or Tied for First on 2 of 18 Rows
A glass sugar dispenser with a steel lid beside a salt shaker and a pepper shaker with brass caps on a diner table
December 1, 2026
easyDNS Says Customer Records, Stored AWS Keys and Unsalted Mailbox Password Hashes Were Exposed, but the Public Notice Gives No Counts, the Entry Point Appears Only in the CEO’s Comments to a Reporter, and It Is the Second Security Incident Its Blog Has Posted This Year
Brass combination lock with three number wheels and a hinged latch on a black case
December 1, 2026
How to Lock Python Dependencies With Hashes So pip Refuses a Swapped File: Run a Tamper Test, Read pip’s Hash Errors, Build a Lock That Works on Windows and Linux, and Lint It in CI
A pair of unfinished pale wooden clogs, called sabots, on a clogmaker's workbench among wood shavings and hand tools.
December 1, 2026
Anthropic Denies Claude Is Trained to Sabotage Work, and Its Documents Fit the Denial but Show a Silent Safeguard Retired After About Two Days in June, a Training Cap on Kernel and LLM-Architecture Skills With No Released-Model Score, and Viral Evidence That Cannot Tell Them Apart
01 Dec 2026
SXZ.io SXZ.io
  • Home
Search the Site
Popular Searches:
Technology Amazon AI
Recent Posts
A bicycle chain with a missing link lying on an open palm beside the loose pin and clip that should have joined it
How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
November 30, 2026
Pale church wall with an arched window filled with a star-pattern stone lattice screen
The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519
November 30, 2026
A tall cardon cactus with many upright arms stands in front of a field of cardon cacti under a blue sky with white clouds in the Sonoran Desert
Cacti’s 4HTTP2SHELL Chain Drew 1,793 Attack Attempts on One Honeypot Sensor in Four Days, but the Fix Is Still Only Source Patches With No 1.2.32 Release or CVE ID, the Advisory Calls It “Authenticated,” and on Our Reading of the Code the Guest Route Hinges on One Setting That Ships as “No User”
November 30, 2026
SXZ.io SXZ.io
  • Home

Categories

Articles 325 Posts
News 331 Posts
Learning Hub 297 Posts
Home/Learning Hub/How to Tell Whether a Team of AI Agents Beats Simple Retries: Build a Matched-Budget Test in Python With Pass@k, Majority Vote, and a Paired Bootstrap
Learning Hub

How to Tell Whether a Team of AI Agents Beats Simple Retries: Build a Matched-Budget Test in Python With Pass@k, Majority Vote, and a Paired Bootstrap

Test the claim that a team of AI agents beats one agent by building a matched-budget comparison in Python with pass@k, majority vote and paired statistics, then see why a debate team and a...

November 27, 2026 50 Min Read
34

Teams of AI agents are everywhere in this month’s news, and the claim that comes with them is nearly always the same: several agents working together did better than one. In this tutorial you will learn to test that claim yourself. You will build a small Python test that takes a team of language-model agents and asks whether it beats the cheapest alternative that costs the same, which is simply trying again.

Table Of Content

  • What you will build and why it matters
  • What you need before you begin
  • Step 1: Learn the arithmetic of retries
  • Independence predicts more than the post measured
  • The average success rate hides which problems are easy
  • The estimator that uses the recorded attempts
  • Step 2: Build a checker that needs no model
  • Step 3: Add a cost ledger and make one real call
  • Step 4: Write the three protocols
  • One attempt
  • The debate team
  • The shard-and-merge team
  • Step 5: Run every protocol on every problem
  • A repeatability check: a seed is not a promise
  • Step 6: Read the retry curve, and meet majority vote
  • Step 7: Compare each team with retries that cost the same
  • Decide what “the same cost” means
  • Compare like with like
  • Be honest about uncertainty
  • How to read it
  • Look inside the team that lost
  • Step 8: Test the test with a simulation
  • Step 9: Plant bugs and make sure the tests notice
  • Common mistakes, and how this lab guards against each
  • Confirm the whole thing works end to end
  • Where to go next
  • Sources and further reading

The question comes from a Hugging Face post published on November 26, 2026, “Swarms, Flocks, Gangs: How to build, train, and evaluate multi-agent systems” by Ben Burtenshaw and Kashif Rasul. It says: “A big swarm isn’t, by itself, evidence that cooperation helped.” It then states the fair test: “So the fairer comparison is at an equal budget: if each of four agents gets a quarter of the total tokens, can they still beat one agent that spends all of them?” The post’s own task is one that no single agent can solve, so it cannot run that test yet. It promises “a task that a single agent can solve alone, where the matched-budget comparison is meaningful” for a later post. This tutorial builds that kind of comparison now, at laptop scale, on a task a single small model can attempt alone. The post’s own example takes about five hours on two H200 GPUs and roughly $50, so I did not run it, and none of its results are reproduced here. I use it as the source of the question, not of the numbers.

What you will build and why it matters

You will build a test harness in about 900 lines of standard-library Python, tests included. It runs three ways of spending a language model’s tokens on the same problems: one attempt, many independent retries, and two different four-agent teams. It then compares each team with the retries that cost the same, with an honest margin of error. The habit this teaches is the one that keeps you from publishing, or buying, a “multi-agent improvement” that was really just more tries.

Here are the words this tutorial uses, defined once so that you can rely on them later.

  • Attempt: one model call that answers the problem once.
  • Checker: ordinary code that decides, without any model, whether an answer is right. Tasks with a checker are called verifiable. Unit tests, a compiler and a schema validator are checkers in real work.
  • Episode: one run of a team on one problem, from the first message to the final answer. The Hugging Face post uses the same unit.
  • Protocol: the rules that say who sees what and who answers when. “One attempt”, “debate” and “shard and merge” are protocols.
  • Budget: what a protocol spends, counted in tokens, the small pieces of text a model reads and writes. Two protocols are matched when their budgets are about equal.
  • Best of k (also written pass@k): the chance that at least one of k attempts is right, which is worth something only when a checker can pick the right one out.
  • Majority vote: take k attempts and keep the most common answer. It needs no checker, which makes it the honest baseline when you have none.

A caution before you start. Everything below runs one small model (Qwen2.5 with 1.5 billion parameters) on one task with 60 problems. The lab teaches the method. It does not rank debate against shard-and-merge for models in general, and nothing in it should be read as a verdict on the Hugging Face experiment.

What I found, in one sentence: neither team beat retries that cost the same. The debate team was about 8 points behind retries that can use a checker and indistinguishable from retries that vote, and the shard-and-merge team lost even to a single attempt. Steps 6 and 7 show how the numbers say that, and where the stage that failed was.

What you need before you begin

  • Python 3.13 (I used 3.13.14) and pytest (pip install pytest, I used 9.1.1). The lab code uses only the standard library.
  • Ollama (I used 0.32.9) with the model pulled by ollama pull qwen2.5:1.5b. A GPU with 4 GB of memory was enough for me; a CPU also works but will be slower.
  • Time: the full 60-problem run took about 18 minutes on an RTX A400 with four parallel requests. A 20-problem run takes about 6 minutes and shows the same pattern with wider error bars. Steps 1 and 2 need no model at all.
  • No statistics background. Every statistic below is introduced with a plain-language reason before its code.

Create an empty folder, open a terminal in it, and save each code block below under the file name on its first line. Every file begins with a comment such as # passk.py for that purpose.

Step 1: Learn the arithmetic of retries

Start with a question you can answer on paper. Suppose one attempt succeeds with probability p, and attempts are independent. The only way to fail all k attempts is to fail each one, so the chance that at least one succeeds is 1 − (1 − p)k. Save this as passk.py, along with its more careful sibling, which you will meet in a moment.

# passk.py
"""Retry arithmetic. Standard library only."""
from math import comb


def independent_best_of(p, k):
    """Chance that at least one of k independent tries succeeds when every try succeeds with probability p."""
    return 1 - (1 - p) ** k


def pass_at_k(n, c, k):
    """Estimate best-of-k success from n recorded tries of which c were correct.

    It is 1 minus the chance that k tries drawn without replacement from the n recorded
    ones are all wrong, so it works problem by problem and needs no assumption that all problems are equally hard.
    """
    if not 0 <= c <= n:
        raise ValueError("c must be between 0 and n")
    if not 1 <= k <= n:
        raise ValueError("k must be between 1 and n")
    return 1 - comb(n - c, k) / comb(n, k)


def mean(values):
    return sum(values) / len(values)

Now run the arithmetic on real numbers. The Hugging Face post reports that the untrained team’s success rate over the first five training updates was 6.56%, and that counting a problem as solved when any of eight attempts succeeded gave 37.5%. What would independence predict? Save and run this script.

# step01_arithmetic.py
"""The arithmetic of retries, and why the average success rate is not enough."""
from passk import independent_best_of, pass_at_k

print("Independent retries at 6.56 percent per try, the first-update team success rate in the Hugging Face post:")
for k in (1, 2, 4, 8):
    print(f"  best of {k}: {100 * independent_best_of(0.0656, k):.1f}%")

print("\nSame 50 percent average, best of 8 tries, two different worlds:")
print(f"  every problem has a 50% chance on every try: {100 * independent_best_of(0.5, 8):.1f}%")
half_and_half = [pass_at_k(16, correct, 8) for correct in [0, 16] * 10]
print(f"  half the problems always fail and half always succeed: {100 * sum(half_and_half) / len(half_and_half):.1f}%")

print("\nOne problem with 4 right answers in 16 recorded tries:")
print(f"  chance that 8 tries drawn from them include a right one: {pass_at_k(16, 4, 8):.4f}")
print(f"  the same by hand, 1 - C(12,8)/C(16,8) = 1 - 495/12870 = {1 - 495 / 12870:.4f}")
python step01_arithmetic.py
Independent retries at 6.56 percent per try, the first-update team success rate in the Hugging Face post:
  best of 1: 6.6%
  best of 2: 12.7%
  best of 4: 23.8%
  best of 8: 41.9%

Same 50 percent average, best of 8 tries, two different worlds:
  every problem has a 50% chance on every try: 99.6%
  half the problems always fail and half always succeed: 50.0%

One problem with 4 right answers in 16 recorded tries:
  chance that 8 tries drawn from them include a right one: 0.9615
  the same by hand, 1 - C(12,8)/C(16,8) = 1 - 495/12870 = 0.9615

Three things in that output deserve a slow read.

Independence predicts more than the post measured

At 6.56% per try, eight independent tries should succeed 41.9% of the time (my arithmetic). The post measured 37.5% on its training problems. The post itself says to “read this as an estimate”, because both rows use training problems rather than held-out ones and the later updates in that window already sample from a slightly trained policy, so I do not treat the gap as a finding. It is, however, the pattern the second block of the output explains.

The average success rate hides which problems are easy

Two worlds can share a 50% average. In one, every problem is a coin flip, so eight tries almost always find a success (99.6%). In the other, half the problems are hopeless and half are trivial, so eight tries change nothing (50.0%). Real tasks sit between those extremes, and retries only help on problems where the model is sometimes right. That is why the lab below records many attempts per problem, instead of one overall success rate.

The estimator that uses the recorded attempts

When you have n recorded attempts at a problem and c of them were right, the chance that k attempts drawn from them include a right one is 1 − C(n − c, k) / C(n, k), where C(a, b) counts the ways to choose b items from a. Chen and colleagues, in the paper that introduced the Codex code model, describe the recipe: “we generate n ≥ k samples per task (in this paper, we use n = 200 and k ≤ 100), count the number of correct samples c ≤ n which pass unit tests, and calculate the unbiased estimator”. The function pass_at_k is that estimator. The last block of the output checks it by hand for 4 right answers in 16: choosing 8 of the 16 recorded attempts at random includes a right one with probability 0.9615.

Two notes on the code. First, Python’s math.comb “evaluates to zero when k > n”, so when fewer than k attempts are wrong, the failure chance is 0 and the function returns 1 without a special case; the tests in Step 9 pin that behavior. Second, Chen and colleagues warn about a different shortcut: plugging each problem’s own measured success rate into the independent formula “results in a consistent underestimate”. The shortcut in the output above plugs in the average over all problems, and it errs the other way, upward. The estimator avoids both mistakes: it works one problem at a time, so problems may differ in difficulty, and it never plugs a measured rate into a formula.

Check that it worked: your output should match the block above exactly, since it contains no model calls.

Step 2: Build a checker that needs no model

A fair comparison needs one thing before any model runs: an answer key that code can apply. The Hugging Face post counts a team as successful when “at least one agent submits the complete, correctly sorted list”, which works because sorting is easy to check. This lab uses the same family of task, in a form a single agent can attempt alone: sort twelve integers between 1 and 99, with duplicates allowed.

I chose twelve numbers after a short probe on 24 throwaway problems with four tries each at temperature 0.8: the 1.5-billion-parameter model was right on 83% of tries at six numbers, 60% at eight, 33% at twelve and 18% at sixteen. At twelve it is right often enough for retries to matter and wrong often enough for them to be needed. The real run uses temperature 1.0, which samples from the model’s own distribution without sharpening it. In the probe, raising the temperature to 1.3 did not change the picture: most problems were still solved on all four tries or on none. Save the task and its checker as task.py.

# task.py
"""The task: sort a list of integers. A checker decides, with no model involved, whether an answer is right."""
import random
import re

LIST_RE = re.compile(r"\[([^\[\]]*)\]")
INT_RE = re.compile(r"-?\d+")


def make_problems(count, size, seed):
    """`count` problems; each is a list of `size` integers from 1 to 99. Duplicates are allowed."""
    rng = random.Random(seed)
    return [{"id": index, "numbers": [rng.randint(1, 99) for _ in range(size)]} for index in range(count)]


def render(numbers):
    return "[" + ", ".join(str(n) for n in numbers) + "]"


def sort_prompt(numbers):
    return (
        "Sort these numbers from smallest to largest. Duplicates stay in the list.\n"
        "Reply with the sorted list in square brackets and nothing else.\n\n"
        f"Numbers: {render(numbers)}"
    )


def parse_answer(text):
    """The last bracketed list of integers in the reply, as a tuple, or None if there is none."""
    for body in reversed(LIST_RE.findall(text)):
        parts = [part.strip() for part in body.split(",")]
        if parts and all(INT_RE.fullmatch(part) for part in parts):
            return tuple(int(part) for part in parts)
    return None


def is_correct(numbers, answer):
    """The verifier: the answer must be exactly the sorted input."""
    return answer is not None and list(answer) == sorted(numbers)

Four details in that file come from mistakes that are easy to make. parse_answer takes the last bracketed list, because models often echo the input first. It uses fullmatch, so a reply such as [1, 2x] is rejected instead of half-read. is_correct compares to the sorted list itself, so a dropped duplicate or a wrong order fails. And make_problems draws from a seeded random generator, so problem 59 never changes if you later ask for 100 problems. Try the checker on six kinds of reply.

# step02_checker.py
"""What the checker accepts and what it refuses."""
from task import is_correct, make_problems, parse_answer, render, sort_prompt

problem = make_problems(60, 12, seed=2026)[0]
numbers = problem["numbers"]
print(sort_prompt(numbers))

right = sorted(numbers)
replies = {
    "the list and nothing else": render(right),
    "the list inside chatter": "Sure! Here you go: " + render(right) + " Hope that helps.",
    "the input echoed, then the answer": render(numbers) + "\n" + render(right),
    "one number dropped": render(right[:-1]),
    "right numbers, wrong order": render(right[::-1]),
    "words instead of a list": "The smallest is " + str(right[0]) + " and the largest is " + str(right[-1]) + ".",
}
print()
for label, reply in replies.items():
    verdict = is_correct(numbers, parse_answer(reply))
    print(f"{label:<36} {'correct' if verdict else 'wrong'}")
python step02_checker.py
Sort these numbers from smallest to largest. Duplicates stay in the list.
Reply with the sorted list in square brackets and nothing else.

Numbers: [16, 41, 65, 66, 83, 14, 29, 77, 80, 72, 54, 74]

the list and nothing else            correct
the list inside chatter              correct
the input echoed, then the answer    correct
one number dropped                   wrong
right numbers, wrong order           wrong
words instead of a list              wrong

Check that it worked: the first three replies are right, because only the last list counts, and the last three are wrong.

Step 3: Add a cost ledger and make one real call

Before comparing anything at the same cost, you need a way to count cost. Ollama reports two numbers with every reply. Its API documentation describes them as “prompt_eval_count: number of tokens in the prompt” and “eval_count: number of tokens in the response”. The client below returns both next to the text, and keeps every reply in a cache folder under a hash of everything that can change it (model, prompt, seed, temperature, length limit). The cache means a re-run of the lab repeats no call you have already paid for. Save it as olc.py.

# olc.py
"""A tiny Ollama client with a disk cache and token counts. Standard library only."""
import hashlib
import json
import os
import time
import urllib.request

HOST = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434")
MODEL = "qwen2.5:1.5b"
TEMPERATURE = 1.0
CACHE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache")


def ask(model, prompt, seed, temperature=0.8, num_predict=120):
    """One non-streaming /api/generate call. Returns the text and the token counts Ollama reports.

    The answer is cached on disk under a hash of everything that can change it, so a re-run
    of the lab repeats no call that has already been paid for.
    """
    key = hashlib.sha256(json.dumps([model, prompt, seed, temperature, num_predict]).encode()).hexdigest()[:24]
    path = os.path.join(CACHE, key + ".json")
    if os.path.exists(path):
        with open(path, encoding="utf-8") as handle:
            return json.load(handle)
    body = {
        "model": model,
        "prompt": prompt,
        "stream": False,
        "keep_alive": "30m",
        "options": {"temperature": temperature, "seed": seed, "num_predict": num_predict, "num_ctx": 4096},
    }
    request = urllib.request.Request(
        HOST + "/api/generate", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}
    )
    started = time.perf_counter()
    with urllib.request.urlopen(request, timeout=600) as response:
        data = json.load(response)
    result = {
        "text": data["response"],
        "prompt_tokens": data.get("prompt_eval_count", 0),
        "gen_tokens": data.get("eval_count", 0),
        "seconds": round(time.perf_counter() - started, 3),
    }
    os.makedirs(CACHE, exist_ok=True)
    with open(path, "w", encoding="utf-8") as handle:
        json.dump(result, handle)
    return result

The ledger is the second half of the idea. It adds up calls and tokens separately, because there are two defensible ways to measure cost, and they can disagree. Generated tokens counts only what the model writes, which is what the Hugging Face post counts. Total tokens adds the prompt, which matters because a team that reads its teammates’ messages pays to read them. Save it as ledger.py.

# ledger.py
"""A cost ledger: what a protocol spent, in model calls and in tokens."""


class Ledger:
    """Adds up model calls, prompt tokens and generated tokens."""

    def __init__(self):
        self.calls = 0
        self.prompt_tokens = 0
        self.gen_tokens = 0

    def add(self, reply):
        self.calls += 1
        self.prompt_tokens += reply["prompt_tokens"]
        self.gen_tokens += reply["gen_tokens"]

    @property
    def total_tokens(self):
        return self.prompt_tokens + self.gen_tokens

Now make one call, then three more, and watch the ledger.

# step03_one_call.py
"""One real model call, and what the cost ledger records for three of them."""
import olc
from ledger import Ledger
from task import is_correct, make_problems, parse_answer, render, sort_prompt

problem = make_problems(60, 12, seed=2026)[0]
prompt = sort_prompt(problem["numbers"])
print("truth:", render(sorted(problem["numbers"])))

reply = olc.ask(olc.MODEL, prompt, seed=1000, temperature=olc.TEMPERATURE, num_predict=150)
print("raw reply:", repr(reply["text"]))
print(f"Ollama says: prompt_eval_count = {reply['prompt_tokens']}, eval_count = {reply['gen_tokens']}")

print("\nthree attempts, three seeds, one ledger:")
ledger = Ledger()
for seed in (1000, 1001, 1002):
    reply = olc.ask(olc.MODEL, prompt, seed=seed, temperature=olc.TEMPERATURE, num_predict=150)
    ledger.add(reply)
    print(f"  seed {seed}: correct = {is_correct(problem['numbers'], parse_answer(reply['text']))}")
print(f"ledger: {ledger.calls} calls, {ledger.prompt_tokens} prompt tokens, {ledger.gen_tokens} generated tokens, {ledger.total_tokens} in all")
ollama serve   # in a second terminal, if Ollama is not already running
python step03_one_call.py
truth: [14, 16, 29, 41, 54, 65, 66, 72, 74, 77, 80, 83]
raw reply: '[14, 16, 29, 41, 54, 65, 66, 72, 74, 77, 80, 83]'
Ollama says: prompt_eval_count = 106, eval_count = 49

three attempts, three seeds, one ledger:
  seed 1000: correct = True
  seed 1001: correct = True
  seed 1002: correct = True
ledger: 3 calls, 318 prompt tokens, 147 generated tokens, 465 in all

The prompt is 106 tokens and the answer is 49, so one attempt costs 155 tokens by the total rule and 49 by the generated rule. Do not assume that a fixed seed makes a reply repeatable: Step 5 measures how often the same prompt and seed give a different answer on a second call. The cache, not the seed, is what makes your analysis repeatable, and your own replies in this step may differ a little from mine. Choose your accounting rule before you look at any result. Picking whichever rule flatters your favorite protocol is the quietest way to cheat, and Step 7 shows how far the rule moves the budget and a borderline verdict.

Step 4: Write the three protocols

Now give the model three ways to spend its tokens on one problem. The first is the baseline you must beat. The other two are teams of four agents that share one model but not one context: each agent is a separate call, and a teammate’s message reaches it only as text in its prompt.

One attempt

One agent sees the whole list and answers once. Retries are not a protocol of their own. They are many one-attempt runs, and you will combine them after the fact, which is the reason to record every attempt separately.

The debate team

Four agents see the whole list. In round one each answers alone. In round two each reads the other three answers, then answers again. This is the multi-agent debate idea of Du and colleagues, in which “multiple language model instances propose and debate their individual responses and reasoning processes over multiple rounds to arrive at a common final answer”. A debate team has no new information. It has extra voices and a second look, and costs eight calls with long prompts. The team succeeds when the checker accepts at least one of its four final answers, which is the Hugging Face post’s own success rule. When no checker exists, a majority of the four final answers has to be right instead, and the comparison below reports both.

The shard-and-merge team

This is the team that resembles the Hugging Face setup. Each agent holds one quarter of the list, three numbers, and sorts only those. Agent 0 then receives the four sorted parts and merges them into the final list. The team has private information and a division of labor, and costs five short calls. A single agent can still solve the whole problem alone, which is what makes a matched comparison possible.

Save both teams, and the single attempt, as protocols.py.

# protocols.py
"""Three ways to spend model calls on one problem: one attempt, a debate team, and a shard-and-merge team."""
import olc
from ledger import Ledger
from olc import MODEL, TEMPERATURE
from task import parse_answer, render, sort_prompt

TEAM_SIZE = 4


def call(prompt, seed, ledger, num_predict=150):
    reply = olc.ask(MODEL, prompt, seed, TEMPERATURE, num_predict)
    ledger.add(reply)
    return parse_answer(reply["text"])


def shown(answer):
    return render(answer) if answer else "(no valid list)"


def single_attempt(problem, seed, ledger):
    """One agent, one try."""
    return call(sort_prompt(problem["numbers"]), seed, ledger)


def debate_prompt(numbers, others):
    lines = "\n".join(f"Teammate {i + 1}: {shown(answer)}" for i, answer in enumerate(others))
    return (
        sort_prompt(numbers)
        + "\n\nYour teammates already answered this question:\n"
        + lines
        + "\n\nReply with your final sorted list in square brackets and nothing else."
    )


def debate_episode(problem, seed, ledger):
    """Four agents see the whole list. Each answers alone, then reads the other three answers and answers again."""
    first = [single_attempt(problem, seed * 10 + agent, ledger) for agent in range(TEAM_SIZE)]
    finals = []
    for agent in range(TEAM_SIZE):
        others = [first[j] for j in range(TEAM_SIZE) if j != agent]
        finals.append(call(debate_prompt(problem["numbers"], others), seed * 10 + agent, ledger))
    return first, finals


def merge_prompt(parts):
    lines = "\n".join(f"Part {i + 1}: {shown(part)}" for i, part in enumerate(parts))
    return (
        "Four agents each sorted one part of a list of numbers. Combine the four parts into one list "
        "sorted from smallest to largest. Duplicates stay in the list.\n"
        "Reply with the sorted list in square brackets and nothing else.\n\n" + lines
    )


def shard_episode(problem, seed, ledger):
    """Each agent holds one quarter of the list and sorts it; agent 0 then merges the four sorted parts."""
    numbers = problem["numbers"]
    size = len(numbers) // TEAM_SIZE
    shards = [numbers[i * size:(i + 1) * size] for i in range(TEAM_SIZE)]
    parts = [call(sort_prompt(shard), seed * 10 + agent, ledger, num_predict=100) for agent, shard in enumerate(shards)]
    return parts, call(merge_prompt(parts), seed * 10 + 9, ledger)

Three choices in this file protect the comparison. The seed for each agent is derived from the episode seed, so agents sample differently from one another. The episode seeds (500 and 900 plus the repeat number, which the protocols multiply by ten before adding the agent number) never collide with the single-attempt seeds (1000 plus the repeat number), so the team’s first-round answers are fresh samples and not copies of the attempts that serve as the baseline. And every call goes through call, which feeds the ledger, so cost is counted in one place and cannot be forgotten for a protocol.

The wording of the prompts matters less than the structure, but you should know what the agents were told. The debate prompt is the original sorting prompt followed by the three teammates’ answers and the instruction to reply with a final sorted list. The merge prompt says that four agents each sorted one part, lists the parts, and asks for one sorted list. Nothing tells any agent how to reason, because the point is to measure the protocol and not to tune a prompt.

Step 5: Run every protocol on every problem

The runner below does all the model work in one pass and writes one JSON line per attempt or episode, with the answers and the tokens each one spent. Keeping the raw record means you can change the analysis, the accounting rule or the matched budget later without paying for a single new call. For each problem it makes 16 single attempts, 2 debate episodes and 3 shard-and-merge episodes: 47 model calls per problem, 2,820 calls for 60 problems. Sixteen attempts are enough to estimate best-of-k for any k up to 16.

# run_live.py
"""Run every protocol on every problem and save one JSON line per attempt or episode to out/live.jsonl."""
import json
import os
import sys
from concurrent.futures import ThreadPoolExecutor

from protocols import Ledger, debate_episode, shard_episode, single_attempt
from task import make_problems

PROBLEMS = int(sys.argv[1]) if len(sys.argv) > 1 else 60
SIZE = 12
SINGLES, DEBATES, SHARDS = 16, 2, 3  # attempts or episodes per problem
OUT = os.path.join("out", "live.jsonl")


def spent(ledger):
    return {"calls": ledger.calls, "prompt": ledger.prompt_tokens, "gen": ledger.gen_tokens}


def job(args):
    kind, problem, rep = args
    ledger = Ledger()
    if kind == "single":
        answer = single_attempt(problem, 1000 + rep, ledger)
        record = {"answer": answer}
    elif kind == "debate":
        first, finals = debate_episode(problem, 500 + rep, ledger)
        record = {"first": first, "finals": finals}
    else:
        parts, final = shard_episode(problem, 900 + rep, ledger)
        record = {"parts": parts, "final": final}
    return {"problem": problem["id"], "kind": kind, "rep": rep, **record, **spent(ledger)}


if __name__ == "__main__":
    problems = make_problems(PROBLEMS, SIZE, seed=2026)
    jobs = [("single", p, r) for p in problems for r in range(SINGLES)]
    jobs += [("debate", p, r) for p in problems for r in range(DEBATES)]
    jobs += [("shard", p, r) for p in problems for r in range(SHARDS)]
    os.makedirs("out", exist_ok=True)
    done = 0
    with ThreadPoolExecutor(4) as pool, open(OUT, "w", encoding="utf-8") as handle:
        for record in pool.map(job, jobs):
            handle.write(json.dumps(record) + "\n")
            handle.flush()
            done += 1
            if done % 200 == 0:
                print(done, "of", len(jobs), flush=True)
    print("finished", len(jobs), "jobs")

Start the server with four parallel slots and run it. Four slots roughly halved the waiting time when I measured them in an earlier Ollama concurrency tutorial, and the runner uses four threads to match.

OLLAMA_NUM_PARALLEL=4 ollama serve   # in a second terminal
python run_live.py 60                # about 18 minutes for 60; use 20 for a quick pass

In Windows PowerShell, set the variable on its own line first: $env:OLLAMA_NUM_PARALLEL = 4, then ollama serve.

While it runs, keep reading: Steps 6 and 7 only need the file it writes. Check that it worked: for 60 problems the file ends with 1,260 lines (960 single attempts, 120 debate episodes and 180 shard-and-merge episodes). Setting the problem count to a smaller number changes only how many problems you get, because the generator is seeded. If the run stops halfway, start it again: every finished call is cached, so it picks up where it left off.

A repeatability check: a seed is not a promise

You might expect that passing a seed makes every call repeatable. Test it before you rely on it. repro_check.py asks 40 problems times 3 single attempts, 120 calls, a second time with the same prompt and the same seed, bypasses the cache with a fresh cache folder, and compares the new answers with the saved ones.

# repro_check.py
"""Does the same prompt with the same seed give the same answer again? Ask 120 single attempts a second time.

Usage: python repro_check.py [threads]   (default 4, the number of requests in flight)
"""
import json
import os
import sys
from concurrent.futures import ThreadPoolExecutor

import olc
from protocols import Ledger, single_attempt
from task import make_problems

THREADS = int(sys.argv[1]) if len(sys.argv) > 1 else 4
olc.CACHE = os.path.join(os.path.dirname(os.path.abspath(__file__)), f"cache_repro_{THREADS}")  # a fresh cache forces new calls
problems = make_problems(60, 12, seed=2026)[:40]
saved = {}
with open(os.path.join("out", "live.jsonl"), encoding="utf-8") as handle:
    for line in handle:
        row = json.loads(line)
        if row["kind"] == "single":
            saved[(row["problem"], row["rep"])] = (row["answer"], row["gen"])

problems = [p for p in problems if (p["id"], 0) in saved]  # a short run saved fewer problems


def again(job):
    problem, rep = job
    ledger = Ledger()
    answer = single_attempt(problem, 1000 + rep, ledger)
    first_answer, first_gen = saved[(problem["id"], rep)]
    same_answer = (list(answer) if answer else None) == first_answer
    return same_answer, ledger.gen_tokens == first_gen


jobs = [(problem, rep) for problem in problems for rep in range(3)]
with ThreadPoolExecutor(THREADS) as pool:
    results = list(pool.map(again, jobs))
print(f"asked {len(results)} attempts a second time, {THREADS} at once")
print(f"same parsed answer: {sum(a for a, _ in results)} of {len(results)}")
print(f"same number of generated tokens: {sum(g for _, g in results)} of {len(results)}")
python repro_check.py 4
python repro_check.py 1
asked 120 attempts a second time, 4 at once
same parsed answer: 81 of 120
same number of generated tokens: 97 of 120
asked 120 attempts a second time, 1 at once
same parsed answer: 82 of 120
same number of generated tokens: 94 of 120

With four requests in flight, 39 of the 120 repeated calls returned a different parsed answer. Even one request at a time, 38 of 120 did, about a third, and 26 of 120 generated a different number of tokens. I did not trace the cause. One untested guess is that a repeated prompt is partly served from the server’s cached prompt processing, which can change tiny numerical details and flip a borderline word choice at temperature 1.0. Whatever the cause, two consequences follow. A from-scratch re-run of this lab will not reproduce my tallies exactly. It will reproduce the pattern, within the sampling noise the intervals in Step 7 already measure. And the saved live.jsonl and the cache folder are your record of what happened, so keep them next to your analysis. The attempts are still independent samples, which is all the statistics need.

Step 6: Read the retry curve, and meet majority vote

The first thing to look at is the baseline, because every team has to beat it. If you have a checker, retries are strong: try again until the checker says yes. If you have no checker, you cannot tell which attempt is right, so the honest fallback is a majority vote: take k attempts and keep the most common answer, which is the idea behind the self-consistency decoding of Wang and colleagues. Two details need a decision. A vote can tie, and ties here are broken at random, so a tie between a right and a wrong answer is worth half a point on average. And a reply with no readable list counts as a vote for “no answer”, which can never be right. Save the vote as vote.py.

# vote.py
"""Majority vote over recorded answers, for tasks that have no checker."""
import random
from collections import Counter


def vote_winner(answers, rng):
    """The most common answer. Ties are broken at random, and None counts as a vote for 'no answer'."""
    counts = Counter(answers)
    top = max(counts.values())
    return rng.choice([answer for answer, count in counts.items() if count == top])


def vote_at_k(answers, truth, k, draws=2000, seed=0):
    """Expected success of a plurality vote over k answers drawn without replacement from the recorded ones."""
    rng = random.Random(seed)
    wins = 0
    for _ in range(draws):
        wins += vote_winner(rng.sample(answers, k), rng) == truth
    return wins / draws

Computing the vote exactly would mean trying every way to choose k of the 16 recorded answers, which is 12,870 subsets for k = 8, for each of the 60 problems. Instead vote_at_k draws 2,000 random subsets with a fixed seed. The error of that estimate is at most about one point for a single problem and about 0.15 points for the average over 60, which is far smaller than the effects below. Now print the whole curve from the single attempts you collected. Save this as curve.py.

# curve.py
"""What do retries buy? The honest best-of-k curve against the shortcut that uses only the average success rate."""
import sys

from compare import as_tuple, load, retry_scores, single_rate
from passk import independent_best_of, mean
from task import make_problems

COUNT = int(sys.argv[1]) if len(sys.argv) > 1 else 60  # how many problems the run covered
by = load("out/live.jsonl", make_problems(COUNT, 12, seed=2026))
average = single_rate(by)
print(f"one attempt succeeds {100 * average:.1f}% of the time on average over {len(by)} problems")

counts = [sum(as_tuple(row["answer"]) == entry["truth"] for row in entry["single"]) for entry in by.values()]
never = sum(c == 0 for c in counts)
always = sum(c == 16 for c in counts)
print(f"never right in 16 tries: {never} problems; always right: {always}; sometimes right: {len(counts) - never - always}")
print("\n  k   best of k (honest)   shortcut 1-(1-p)^k   majority vote of k")
for k in (1, 2, 4, 8, 16):
    best, vote = retry_scores(by, k)
    print(f"{k:3d}   {100 * mean(best):15.1f}%   {100 * independent_best_of(average, k):17.1f}%   {100 * mean(vote):17.1f}%")
python curve.py
one attempt succeeds 45.8% of the time on average over 60 problems
never right in 16 tries: 20 problems; always right: 12; sometimes right: 28

  k   best of k (honest)   shortcut 1-(1-p)^k   majority vote of k
  1              45.8%                45.8%                45.7%
  2              54.6%                70.7%                46.0%
  4              60.7%                91.4%                51.1%
  8              64.6%                99.3%                54.9%
 16              66.7%               100.0%                57.5%

This one table holds the lesson of the whole lab, so read it slowly.

  • Problems fall into three groups. A single attempt succeeds 45.8% of the time on average, but 20 of the 60 problems were never solved in 16 tries, 12 were solved every time, and only 28 were solved some of the time. Retries can only help on those 28.
  • The honest curve flattens. Best of k with a checker climbs from 45.8% to 66.7% at k = 16. That ceiling is exactly 40 of 60 problems: the 12 always-solved plus the 28 sometimes-solved. The 20 problems that never succeeded in 16 tries stay at zero, because a model that makes the same mistake every time does not fix it by trying again.
  • The shortcut is wildly optimistic. Plugging the 45.8% average into the independent formula predicts 99.3% at k = 8 against the honest 64.6%. This is the Step 1 warning made concrete.
  • A checker is worth about ten points. At k = 8, picking a right answer with the checker gives 64.6% and a majority vote gives 54.9%. Voting also barely moves at k = 2 (46.0%), because two answers that disagree are a coin flip.

Check that it worked: the k = 1 row must show the same percentage in all three columns, apart from vote noise in the third (45.8, 45.8 and 45.7 here), because with one attempt there is nothing to estimate, shortcut or vote on. If they differ by more than a point, something in the pipeline is wrong.

Step 7: Compare each team with retries that cost the same

Now the main event. Each team is compared with the retry strategy that spends the same budget, and the comparison has three parts: a rule for what “the same” means, a rule for which baseline to use, and honest uncertainty.

Decide what “the same cost” means

The team’s average cost per episode, divided by the average cost of one attempt, gives the number of attempts the team’s budget buys. It is rarely a whole number, so the report below uses both neighbors, and the verdict lines use the larger one. That gives retries the benefit of the doubt: if the team still loses to the extra attempt, rounding cannot be the reason. Do this under both accounting rules from Step 3, generated tokens and total tokens, and decide in advance which one you will headline.

Compare like with like

A team that can use the checker, “any of the four answers is right”, must be compared with retries that can use it, best of k. A team that must commit to one answer by vote must be compared with a majority vote of k attempts. Comparing a verifier-assisted team with voting retries, or the reverse, hands one side a tool the other does not have. The shard-and-merge team commits to one final list with no vote and no checker, so it is compared with both baselines.

Be honest about uncertainty

For every problem there is a team score and a retry score on the same problem. Their difference is the unit of evidence, and the 60 differences are what you analyze, not the thousands of individual attempts, because attempts at one problem are not independent of each other. bootstrap_ci redraws 60 problems with replacement thousands of times, takes the mean difference each time, and reports the middle 95%. sign_flip_p asks how often randomly flipping the sign of each problem’s difference gives a mean at least as far from zero as the one observed. A small p-value means a gap this large would be rare if the team and the retries were really equal. Neither method assumes a bell curve. Save them as stats.py.

# stats.py
"""Paired statistics over problems. Standard library only."""
import random

from passk import mean


def bootstrap_ci(values, draws=10000, seed=0):
    """95% interval for the mean of per-problem values, resampling whole problems with replacement."""
    rng = random.Random(seed)
    n = len(values)
    means = sorted(mean([values[rng.randrange(n)] for _ in range(n)]) for _ in range(draws))
    return means[int(0.025 * draws)], means[int(0.975 * draws) - 1]


def sign_flip_p(diffs, draws=20000, seed=0):
    """Two-sided p-value for 'the mean per-problem difference is zero', by randomly flipping each sign."""
    rng = random.Random(seed)
    observed = abs(sum(diffs))
    extreme = 0
    for _ in range(draws):
        flipped = sum(d if rng.random() < 0.5 else -d for d in diffs)
        extreme += abs(flipped) >= observed - 1e-12
    return (extreme + 1) / (draws + 1)

Now the comparison itself. Save this as compare.py. It loads the saved runs, scores every protocol per problem, and prints one report per accounting rule.

# compare.py
"""Turn the saved runs into per-problem scores and compare each team with retries that cost the same."""
import json
import random
import sys
from math import ceil, floor

from passk import mean, pass_at_k
from stats import bootstrap_ci, sign_flip_p
from vote import vote_at_k, vote_winner
from task import make_problems

RULES = {"generated": lambda row: row["gen"], "total": lambda row: row["gen"] + row["prompt"]}


def as_tuple(answer):
    return tuple(answer) if answer else None


def load(path, problems):
    """Group the saved JSON lines by problem and by protocol."""
    by = {p["id"]: {"truth": tuple(sorted(p["numbers"])), "single": [], "debate": [], "shard": []} for p in problems}
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            row = json.loads(line)
            by[row["problem"]][row["kind"]].append(row)
    return by


def mean_cost(by, kind, rule):
    return mean([RULES[rule](row) for entry in by.values() for row in entry[kind]])


def retry_scores(by, k):
    """Per-problem best-of-k (with a checker) and vote-of-k (without one), in problem order."""
    best, vote = [], []
    for entry in by.values():
        answers = [as_tuple(row["answer"]) for row in entry["single"]]
        correct = sum(answer == entry["truth"] for answer in answers)
        best.append(pass_at_k(len(answers), correct, k))
        vote.append(vote_at_k(answers, entry["truth"], k, seed=k))
    return best, vote


def team_scores(by, seed=0):
    """Per-problem success of each team metric, averaged over that problem's episodes."""
    rng = random.Random(seed)
    out = {"debate_round1": [], "debate_any": [], "debate_vote": [], "shard": []}
    for entry in by.values():
        truth = entry["truth"]
        firsts = [[as_tuple(a) for a in row["first"]] for row in entry["debate"]]
        finals = [[as_tuple(a) for a in row["finals"]] for row in entry["debate"]]
        out["debate_round1"].append(mean([any(a == truth for a in group) for group in firsts]))
        out["debate_any"].append(mean([any(a == truth for a in group) for group in finals]))
        out["debate_vote"].append(mean([vote_winner(group, rng) == truth for group in finals]))
        out["shard"].append(mean([as_tuple(row["final"]) == truth for row in entry["shard"]]))
    return out


def single_rate(by):
    return mean([mean([as_tuple(row["answer"]) == entry["truth"] for row in entry["single"]]) for entry in by.values()])


def line(label, scores):
    low, high = bootstrap_ci(scores, draws=4000)
    return f"  {label:<44} {100 * mean(scores):5.1f}%  [{100 * low:5.1f}, {100 * high:5.1f}]"


def versus(label, team, baseline):
    diffs = [t - b for t, b in zip(team, baseline)]
    low, high = bootstrap_ci(diffs, draws=4000)
    p = sign_flip_p(diffs, draws=10000)
    print(f"  {label:<44} {100 * mean(diffs):+6.1f} points  [{100 * low:+6.1f}, {100 * high:+6.1f}]  p = {p:.4f}")


def report(by, rule):
    attempt = mean_cost(by, "single", rule)
    teams = team_scores(by)
    print(f"== accounting rule: {rule} tokens ==")
    print(f"one attempt costs {attempt:.1f}")
    for kind, name in (("debate", "debate team"), ("shard", "shard-and-merge team")):
        cost = mean_cost(by, kind, rule)
        print(f"{name} costs {cost:.1f} per episode = {cost / attempt:.2f} attempts")
    print()
    for kind, name, key_any, key_vote in (
        ("debate", "debate team", "debate_any", "debate_vote"),
        ("shard", "shard-and-merge team", "shard", "shard"),
    ):
        kstar = mean_cost(by, kind, rule) / attempt
        ks = sorted({max(1, floor(kstar)), min(16, max(1, ceil(kstar)))})
        print(f"-- {name} against retries that cost the same (k = {' or '.join(map(str, ks))})")
        for k in ks:
            best, vote = retry_scores(by, k)
            print(line(f"best of {k} with a checker", best))
            print(line(f"majority vote of {k}", vote))
        print(line("the team, any answer correct" if kind == "debate" else "the team, its one final answer", teams[key_any]))
        if kind == "debate":
            print(line("the team, majority of final answers", teams["debate_vote"]))
            print(line("the team after round one only, any answer", teams["debate_round1"]))
            best4, _ = retry_scores(by, 4)
            versus("round one minus best of 4 (should be near 0)", teams["debate_round1"], best4)
        top = max(ks)
        best, vote = retry_scores(by, top)
        versus(f"team minus best of {top} (checker)", teams[key_any], best)
        versus(f"team minus majority vote of {top}", teams[key_vote], vote)
        print()


if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else "out/live.jsonl"
    count = int(sys.argv[2]) if len(sys.argv) > 2 else 60
    by = load(path, make_problems(count, 12, seed=2026))
    print(f"{len(by)} problems; one attempt succeeds {100 * single_rate(by):.1f}% of the time\n")
    for rule in RULES:
        report(by, rule)
python compare.py
60 problems; one attempt succeeds 45.8% of the time

== accounting rule: generated tokens ==
one attempt costs 47.9
debate team costs 386.9 per episode = 8.08 attempts
shard-and-merge team costs 98.0 per episode = 2.05 attempts

-- debate team against retries that cost the same (k = 8 or 9)
  best of 8 with a checker                      64.6%  [ 52.8,  76.0]
  majority vote of 8                            54.9%  [ 43.0,  66.6]
  best of 9 with a checker                      65.1%  [ 53.3,  76.6]
  majority vote of 9                            55.6%  [ 43.6,  67.3]
  the team, any answer correct                  57.5%  [ 45.0,  70.0]
  the team, majority of final answers           52.5%  [ 40.0,  65.0]
  the team after round one only, any answer     56.7%  [ 44.2,  69.2]
  round one minus best of 4 (should be near 0)   -4.0 points  [  -8.6,   -0.0]  p = 0.0849
  team minus best of 9 (checker)                 -7.6 points  [ -15.0,   -0.8]  p = 0.0511
  team minus majority vote of 9                  -3.1 points  [  -8.8,   +2.8]  p = 0.3102

-- shard-and-merge team against retries that cost the same (k = 2 or 3)
  best of 2 with a checker                      54.6%  [ 43.0,  65.8]
  majority vote of 2                            46.0%  [ 35.2,  56.7]
  best of 3 with a checker                      58.5%  [ 46.5,  69.9]
  majority vote of 3                            49.3%  [ 38.0,  60.6]
  the team, its one final answer                21.7%  [ 12.8,  31.7]
  team minus best of 3 (checker)                -36.8 points  [ -47.6,  -26.0]  p = 0.0001
  team minus majority vote of 3                 -27.6 points  [ -38.1,  -17.1]  p = 0.0001

== accounting rule: total tokens ==
one attempt costs 152.9
debate team costs 1945.0 per episode = 12.72 attempts
shard-and-merge team costs 513.2 per episode = 3.36 attempts

-- debate team against retries that cost the same (k = 12 or 13)
  best of 12 with a checker                     66.1%  [ 54.4,  77.7]
  majority vote of 12                           56.5%  [ 44.5,  68.3]
  best of 13 with a checker                     66.3%  [ 54.6,  77.9]
  majority vote of 13                           56.8%  [ 44.8,  68.7]
  the team, any answer correct                  57.5%  [ 45.0,  70.0]
  the team, majority of final answers           52.5%  [ 40.0,  65.0]
  the team after round one only, any answer     56.7%  [ 44.2,  69.2]
  round one minus best of 4 (should be near 0)   -4.0 points  [  -8.6,   -0.0]  p = 0.0849
  team minus best of 13 (checker)                -8.8 points  [ -17.0,   -1.5]  p = 0.0467
  team minus majority vote of 13                 -4.3 points  [ -10.5,   +1.9]  p = 0.1901

-- shard-and-merge team against retries that cost the same (k = 3 or 4)
  best of 3 with a checker                      58.5%  [ 46.5,  69.9]
  majority vote of 3                            49.3%  [ 38.0,  60.6]
  best of 4 with a checker                      60.7%  [ 48.9,  72.2]
  majority vote of 4                            51.1%  [ 39.5,  62.5]
  the team, its one final answer                21.7%  [ 12.8,  31.7]
  team minus best of 4 (checker)                -39.0 points  [ -50.0,  -28.1]  p = 0.0001
  team minus majority vote of 4                 -29.5 points  [ -39.9,  -18.8]  p = 0.0001

How to read it

Each success rate in the report is followed by its 95% interval in brackets. Each difference line gives the gap in percentage points, its interval and its p-value. Start with the costs. One attempt costs 47.9 generated tokens, or 152.9 counting the prompt. The debate team costs 8.08 attempts by the first rule and 12.72 by the second, because its second round makes every agent re-read three answers. The shard-and-merge team costs 2.05 or 3.36 attempts.

Now the debate team, with its checker, against best of 9. It succeeded on 57.5% of problems, and nine retries with a checker succeeded on 65.1%. The difference is minus 7.6 points, with a 95% interval from minus 15.0 to minus 0.8 and a p-value of 0.0511. Against a majority vote of nine, which needs no checker, the gap shrinks to minus 3.1 points with an interval from minus 8.8 to plus 2.8 and a p-value of 0.31: no detectable difference. The team’s own majority of final answers, 52.5%, also sits below a vote of nine retries (55.6%), inside the noise. In plain words, the evidence says the debate team did not beat retries that cost the same, is probably worse than retries with a checker, and is indistinguishable from voting retries.

The accounting rule moves the line. Counting prompt tokens, the debate team buys 13 retries, the gap to best of 13 is minus 8.8 points, and the p-value is 0.0467, on the other side of 0.05 from the first rule’s 0.0511. The verdict word “significant” would flip with the rule, while the interval barely moved. (The interval and the p-value come from different calculations, so close to the boundary they can disagree about whether zero is excluded, as they do under the first rule.) That is why you decide the rule first, report the interval and not only the verdict, and treat anything near 0.05 as borderline, as Step 8 predicted.

Two lines are there to keep the harness honest. The first-round answers inside the debate episodes are four independent attempts, so “the team after round one” should match “best of 4” from the single attempts. It reads 56.7% against 60.7%, a difference of minus 4.0 points with an interval from minus 8.6 to 0.0, which is inside the noise but on the low side. So part of the debate team’s shortfall may simply be a weak draw in its own first round, and each problem here had only two episodes. The second round, the part that is actually the team, lifted “any answer correct” from 56.7% to 57.5%, under one point, for four more calls with long prompts. Going from best of 4 to best of 9 retries adds 4.4 points for a similar extra spend.

Finally the shard-and-merge team. Its single final list is right 21.7% of the time. A single attempt is right 45.8% of the time, and it costs less than half of what this team spends. The team loses to best of 3 by 36.8 points and to a vote of three by 27.6, with p-values of 0.0001, which is the smallest value a 10,000-draw test can print. When a team loses to a single attempt, the matched-budget question never arises: the protocol is simply worse.

Look inside the team that lost

A verdict tells you that a team lost, not why. Two short scripts open the records. groups.py splits the problems by how single attempts fare on them, which shows where a team could possibly win: it would have to crack problems that retries never solve, or beat retries on the problems they sometimes solve.

# groups.py
"""Where do a team's gains come from? Split the problems by how single attempts fare on them."""
import sys

from compare import as_tuple, load, retry_scores, team_scores
from passk import mean
from task import make_problems

K = 4  # more retries than either accounting rule buys for the shard team, so the baseline is generous
COUNT = int(sys.argv[1]) if len(sys.argv) > 1 else 60  # how many problems the run covered
by = load("out/live.jsonl", make_problems(COUNT, 12, seed=2026))
teams = team_scores(by)
best, _ = retry_scores(by, K)
right = [sum(as_tuple(row["answer"]) == entry["truth"] for row in entry["single"]) for entry in by.values()]
one_try = [count / 16 for count in right]

groups = {
    "never right in 16 tries": [i for i, count in enumerate(right) if count == 0],
    "right some of the time": [i for i, count in enumerate(right) if 0 < count < 16],
    "right in all 16 tries": [i for i, count in enumerate(right) if count == 16],
}


def share(values, indexes):
    """Mean score of one group as text, or a dash when a short run left the group empty."""
    return f"{100 * mean([values[i] for i in indexes]):.1f}%" if indexes else "-"


print(f"{'problems':<25}{'n':>3}  {'one try':>8}  {'best of ' + str(K):>9}  {'debate':>7}  {'shard':>7}")
for label, indexes in groups.items():
    print(
        f"{label:<25}{len(indexes):>3}  {share(one_try, indexes):>8}  {share(best, indexes):>9}"
        f"  {share(teams['debate_any'], indexes):>7}  {share(teams['shard'], indexes):>7}"
    )
python groups.py
problems                   n   one try  best of 4   debate    shard
never right in 16 tries   20      0.0%       0.0%     5.0%     0.0%
right some of the time    28     55.4%      87.1%    76.8%    28.6%
right in all 16 tries     12    100.0%     100.0%   100.0%    41.7%

On the 20 problems that no single attempt ever solved, the debate team scored 5.0% and the shard team 0.0%. On the 28 problems the model sometimes solves, best of four reached 87.1% and the debate team 76.8%. And on the 12 problems every single attempt solves, the shard team managed only 41.7%. Neither team found a region where it wins, and the shard team loses even on the easy problems. The second script, diagnose.py, counts what happened inside each team.

# diagnose.py
"""Look inside the teams: did the debate change minds, and which stage of shard-and-merge fails?"""
import sys
from collections import Counter

from compare import as_tuple, load
from task import make_problems

SIZE, PARTS = 12, 4
COUNT = int(sys.argv[1]) if len(sys.argv) > 1 else 60  # how many problems the run covered
by = load("out/live.jsonl", make_problems(COUNT, SIZE, seed=2026))
problems = {p["id"]: p["numbers"] for p in make_problems(COUNT, SIZE, seed=2026)}

print("== debate: does the second round change minds? ==")
agree = {"round one": 0, "round two": 0}
moves = Counter()
episodes = 0
for entry in by.values():
    truth = entry["truth"]
    for row in entry["debate"]:
        episodes += 1
        first = [as_tuple(a) for a in row["first"]]
        finals = [as_tuple(a) for a in row["finals"]]
        agree["round one"] += len(set(first)) == 1
        agree["round two"] += len(set(finals)) == 1
        for before, after in zip(first, finals):
            moves[("changed" if before != after else "kept", before == truth, after == truth)] += 1
print(f"all four agents give the same answer: round one {agree['round one']} of {episodes} episodes, round two {agree['round two']} of {episodes}")
total = sum(moves.values())
changed = sum(n for (kind, _, _), n in moves.items() if kind == "changed")
print(f"{changed} of {total} agent answers changed in round two")
print(f"  wrong to right: {moves[('changed', False, True)]}, right to wrong: {moves[('changed', True, False)]}, wrong to a different wrong: {moves[('changed', False, False)]}")

print("\n== shard and merge: which stage fails? ==")
leaves = leaves_right = episodes = all_right = merged = merged_given_right = 0
kinds = Counter()
for pid, entry in by.items():
    numbers = problems[pid]
    size = SIZE // PARTS
    for row in entry["shard"]:
        episodes += 1
        flags = []
        for i in range(PARTS):
            shard = sorted(numbers[i * size:(i + 1) * size])
            flags.append(as_tuple(row["parts"][i]) == tuple(shard))
        leaves += PARTS
        leaves_right += sum(flags)
        final = as_tuple(row["final"])
        good = final == entry["truth"]
        merged += good
        if all(flags):
            all_right += 1
            merged_given_right += good
            if not good:
                if final is None:
                    kinds["no list at all"] += 1
                elif len(final) != SIZE:
                    kinds["wrong length"] += 1
                elif sorted(final) != sorted(entry["truth"]):
                    kinds["right length, wrong numbers"] += 1
                else:
                    kinds["right numbers, wrong order"] += 1
print(f"each part sorted correctly: {leaves_right} of {leaves} ({100 * leaves_right / leaves:.1f}%)")
print(f"all four parts correct in an episode: {all_right} of {episodes}")
print(f"final list correct: {merged} of {episodes} ({100 * merged / episodes:.1f}%)")
print(f"final list correct when all four parts were correct: {merged_given_right} of {all_right} ({100 * merged_given_right / max(all_right, 1):.1f}%)")
print("what went wrong in the merge when every part was right:", dict(kinds))
python diagnose.py
== debate: does the second round change minds? ==
all four agents give the same answer: round one 58 of 120 episodes, round two 76 of 120
194 of 480 agent answers changed in round two
  wrong to right: 28, right to wrong: 17, wrong to a different wrong: 149

== shard and merge: which stage fails? ==
each part sorted correctly: 680 of 720 (94.4%)
all four parts correct in an episode: 144 of 180
final list correct: 39 of 180 (21.7%)
final list correct when all four parts were correct: 38 of 144 (26.4%)
what went wrong in the merge when every part was right: {'right length, wrong numbers': 2, 'wrong length': 92, 'right numbers, wrong order': 9, 'no list at all': 3}

The debate did what debates do: agents converged. All four agents agreed in 58 of 120 episodes after round one and in 76 after round two. But of the 194 answers that changed in round two, 149 moved from one wrong answer to another wrong answer, 28 were repaired and 17 were broken. Consensus rose without correctness rising by much. Published comparisons on other models and tasks point in the same direction: Smit and colleagues found that debate systems “in their current form, do not reliably outperform other proposed prompting strategies, such as self-consistency and ensembling using multiple reasoning paths”, and Choi and colleagues found that “Majority Voting alone accounts for most of the performance gains typically attributed to MAD”. Those studies used other models and tasks, so read them as context for this lab’s result, not as confirmation of it.

The shard team shows a different kind of failure, and the stage counts locate it. The agents sorted their three-number parts correctly 94.4% of the time, and all four parts were right in 144 of 180 episodes. But given four correct parts, the merge produced the right list in only 38 of those 144 (26.4%), and in 92 of the 106 failures the final list had the wrong length: the merging agent dropped or repeated numbers. The decomposition was sensible, and the second step was harder for this model than the first. The fix, a better merge prompt or a merge done by ordinary code, is a different experiment, and it must be evaluated on fresh problems, not on these 60, or the comparison will be tuned to its own test set.

Step 8: Test the test with a simulation

A comparison method can be wrong even when its code has no bug. It can ask the wrong question, it can have too little data, or its margin of error can be too optimistic. The cure is to invent a world where you know the truth, run the method on it hundreds of times, and ask two things: does it find a real effect, and does it stay quiet when there is none?

sim.py builds that world. Each of 60 problems gets a hidden chance of success from a U-shaped distribution, so most problems are nearly always solved or nearly never, as in the real run. A simulated team does as well as four retries plus a chosen fraction of the distance left to a perfect score. Each simulated study then records 16 attempts per problem and 3 team episodes per problem and runs the same estimator, interval and test that Step 7 uses. Three scenarios cover the cases that matter.

# sim.py
"""Test the test: invent a world where the truth is known and check that the comparison finds it, and only it."""
import random

from passk import independent_best_of, mean, pass_at_k
from stats import bootstrap_ci, sign_flip_p

PROBLEMS, ATTEMPTS, EPISODES, K = 60, 16, 3, 4


def world(rng):
    """Chance that one attempt succeeds, per problem. Most problems are nearly always solved or nearly never."""
    return [rng.betavariate(0.25, 0.45) for _ in range(PROBLEMS)]


def binomial(rng, n, p):
    return sum(rng.random() < p for _ in range(n))


def experiment(rng, gap, baseline_k):
    """One simulated study. The team does as well as K retries plus `gap` of the distance left to a perfect score."""
    p = world(rng)
    team_true = [b + gap * (1 - b) for b in (independent_best_of(x, K) for x in p)]
    baseline_true = [independent_best_of(x, baseline_k) for x in p]
    team_seen = [binomial(rng, EPISODES, q) / EPISODES for q in team_true]
    retries_seen = [pass_at_k(ATTEMPTS, binomial(rng, ATTEMPTS, x), baseline_k) for x in p]
    diffs = [t - r for t, r in zip(team_seen, retries_seen)]
    truth = mean([t - b for t, b in zip(team_true, baseline_true)])
    low, high = bootstrap_ci(diffs, draws=1000)
    return truth, low <= truth <= high, sign_flip_p(diffs, draws=2000) < 0.05


def scenario(label, gap, baseline_k, runs=400):
    rng = random.Random(2026)
    results = [experiment(rng, gap, baseline_k) for _ in range(runs)]
    truth = mean([r[0] for r in results])
    covered = mean([r[1] for r in results])
    rejected = mean([r[2] for r in results])
    print(f"{label:<44} {100 * truth:+6.1f}   {100 * covered:5.1f}%   {100 * rejected:5.1f}%")


if __name__ == "__main__":
    rng = random.Random(7)
    p = world(rng)
    shortcut = independent_best_of(mean(p), 8)
    truth = mean([independent_best_of(x, 8) for x in p])
    print(f"average chance of one success {100 * mean(p):.1f}%")
    print(f"best of 8 from that average alone {100 * shortcut:.1f}%, from the per-problem chances {100 * truth:.1f}%\n")
    print(f"{'scenario (team costs the same as 4 retries)':<44} {'truth':>6}  {'CI holds':>7}  {'p<0.05':>7}")
    scenario("A. team no better than 4 retries, compared with 4", 0.0, K)
    scenario("B. team closes 15% of the gap, compared with 4", 0.15, K)
    scenario("C. team no better than 4 retries, vs one attempt", 0.0, 1)
python sim.py
average chance of one success 34.7%
best of 8 from that average alone 96.7%, from the per-problem chances 57.9%

scenario (team costs the same as 4 retries)   truth  CI holds   p<0.05
A. team no better than 4 retries, compared with 4   +0.0    92.5%     6.5%
B. team closes 15% of the gap, compared with 4   +7.0    93.0%    63.7%
C. team no better than 4 retries, vs one attempt  +17.7    99.0%   100.0%

Read the output from top to bottom.

  • The shortcut lies. In this world the average chance of one success is 34.7%. Feeding only that average into the independent formula says eight retries succeed 96.7% of the time. The per-problem chances say 57.9%. A comparison built on the shortcut would make every retry baseline look far stronger than it is.
  • Scenario A, no real gain. The team is exactly as good as four retries, and the study compares it with four retries. The true difference is zero, the 95% interval contained it in 92.5% of 400 studies, and the test cried “difference” in 6.5% of them. Both numbers are slightly worse than the nominal 95% and 5%, which is what a percentile bootstrap does with 60 lopsided problems. Treat a p-value just under 0.05 as borderline, not as proof.
  • Scenario B, a real but modest gain. The team closes 15% of the remaining gap, worth 7.0 points. With 60 problems and 3 episodes each, the test detects it in 63.7% of studies. About one honest study in three would have missed a real 7-point gain, which is the reason to report the interval and not only the verdict.
  • Scenario C, the wrong question. The team has no skill beyond four retries, yet compared with one attempt it wins in 100% of studies, by a true 17.7 points. The statistics are right in every row. The question in this row is wrong, because the team spent four attempts’ worth of tokens and the baseline spent one.

Check that it worked: the script has its own fixed seed, so your numbers should match mine exactly, and a different seed would move them by a point or so. The pattern is what matters: a false-alarm rate near 5%, intervals near 95%, and the single-attempt comparison always “winning”.

Step 9: Plant bugs and make sure the tests notice

Statistics code fails quietly. A reversed formula or a lost tie-break still prints plausible numbers. So this lab ships with unit tests that need no model: they compare pass_at_k with a brute-force count over every subset, check the checker on awkward replies, feed the protocols a fake model that sorts correctly and assert who sees what, and run the comparison on a tiny hand-made study with answers you can verify by eye. Save them as test_lab.py.

# test_lab.py
"""Tests for the statistics, the checker, the protocols and the comparison. No model is needed."""
import itertools
import random
import re
from math import comb

import pytest

import compare
import protocols
from passk import independent_best_of, mean, pass_at_k
from stats import bootstrap_ci, sign_flip_p
from vote import vote_at_k, vote_winner
from task import is_correct, make_problems, parse_answer


# ---------- the retry arithmetic ----------
def brute_force_pass_at_k(n, c, k):
    """Try every way of choosing k of the n recorded tries and count the ways that contain a correct one."""
    flags = [True] * c + [False] * (n - c)
    hits = sum(any(flags[i] for i in subset) for subset in itertools.combinations(range(n), k))
    return hits / comb(n, k)


@pytest.mark.parametrize("c", range(0, 7))
@pytest.mark.parametrize("k", range(1, 7))
def test_pass_at_k_matches_brute_force(c, k):
    assert pass_at_k(6, c, k) == pytest.approx(brute_force_pass_at_k(6, c, k))


def test_pass_at_k_edges_and_bad_arguments():
    assert pass_at_k(16, 0, 16) == 0
    assert pass_at_k(16, 16, 1) == 1
    assert pass_at_k(16, 9, 8) == 1  # fewer than 8 wrong tries, so any 8 contain a right one
    for n, c, k in [(16, 17, 2), (16, -1, 2), (16, 4, 0), (16, 4, 17)]:
        with pytest.raises(ValueError):
            pass_at_k(n, c, k)


def test_independent_formula_and_its_blind_spot():
    assert independent_best_of(0.0656, 8) == pytest.approx(0.4189, abs=1e-4)
    assert independent_best_of(0, 5) == 0 and independent_best_of(1, 5) == 1
    # Half the problems are never solved and half always are: the average is 0.5, yet retries add nothing.
    honest = mean([pass_at_k(16, c, 8) for c in [0, 16] * 10])
    assert honest == pytest.approx(0.5)
    assert independent_best_of(0.5, 8) > 0.99


def test_vote_winner_breaks_ties_at_random():
    winners = {vote_winner(["a", "b"], random.Random(seed)) for seed in range(40)}
    assert winners == {"a", "b"}
    assert vote_winner(["a", "b", "b"], random.Random(0)) == "b"


def test_vote_at_k_known_values():
    answers = ["a", "a", "a", "b"]
    assert vote_at_k(answers, "a", 3, draws=400) == 1.0
    assert vote_at_k(answers, "a", 1, draws=4000) == pytest.approx(0.75, abs=0.03)
    assert vote_at_k(answers, "a", 2, draws=4000) == pytest.approx(0.75, abs=0.03)  # 3 of 6 pairs tie at random


def test_bootstrap_ci_is_a_95_percent_interval_and_repeatable():
    values = [0.0, 1.0] * 30
    low, high = bootstrap_ci(values, draws=2000, seed=3)
    assert (low, high) == bootstrap_ci(values, draws=2000, seed=3)
    assert low < 0.5 < high and 0.18 < high - low < 0.30
    assert bootstrap_ci([0.7] * 10, draws=200) == (0.7, 0.7)


def test_sign_flip_p_value():
    assert sign_flip_p([0.0] * 20, draws=500) == 1.0
    p = sign_flip_p([1.0] * 20, draws=2000)
    assert 0 < p < 0.01  # never exactly zero, and small for a clear effect
    assert sign_flip_p([1.0, -1.0] * 10, draws=500) > 0.5


# ---------- the checker ----------
def test_parse_answer_takes_the_last_list_of_integers():
    assert parse_answer("Numbers [5, 1]\n[1, 5]") == (1, 5)
    assert parse_answer("Sure! Here you go: [3, 3, 9]") == (3, 3, 9)
    assert parse_answer("[1, 2x]") is None
    assert parse_answer("[1, 2") is None
    assert parse_answer("no list at all") is None
    assert parse_answer("[-4, 7]") == (-4, 7)


def test_is_correct_needs_exact_order_and_duplicates():
    assert is_correct([5, 26, 5, 78], (5, 5, 26, 78))
    assert not is_correct([5, 26, 5, 78], (5, 26, 78))  # a dropped duplicate
    assert not is_correct([5, 26, 5, 78], (78, 26, 5, 5))  # right numbers, wrong order
    assert not is_correct([5, 26], None)


def test_problems_are_repeatable_and_extendable():
    assert make_problems(10, 12, seed=2026) == make_problems(30, 12, seed=2026)[:10]
    assert all(len(p["numbers"]) == 12 for p in make_problems(5, 12, seed=1))


# ---------- the protocols, with a fake model that sorts correctly ----------
def install_fake(monkeypatch, log, echo_seed=False):
    def fake(model, prompt, seed, temperature=0.8, num_predict=120):
        log.append({"prompt": prompt, "seed": seed})
        parts = re.findall(r"Part \d: \[([^\]]*)\]", prompt)
        if parts:
            numbers = [int(x) for part in parts for x in part.split(",") if x.strip()]
            text = str(sorted(numbers))
        elif echo_seed and "Teammate" not in prompt:
            text = f"[{seed}]"
        else:
            numbers = [int(x) for x in re.search(r"Numbers: \[([^\]]*)\]", prompt).group(1).split(",")]
            text = str(sorted(numbers))
        return {"text": text, "prompt_tokens": len(prompt.split()), "gen_tokens": 7, "seconds": 0}

    monkeypatch.setattr(protocols.olc, "ask", fake)


def test_shard_agents_each_see_one_quarter(monkeypatch):
    log = []
    install_fake(monkeypatch, log)
    problem = {"id": 0, "numbers": [41, 7, 93, 12, 56, 3, 88, 20, 64, 35, 71, 9]}
    ledger = protocols.Ledger()
    parts, final = protocols.shard_episode(problem, seed=1, ledger=ledger)
    seen = [re.search(r"Numbers: \[([^\]]*)\]", entry["prompt"]).group(1) for entry in log[:4]]
    seen = [[int(x) for x in text.split(",")] for text in seen]
    assert all(len(group) == 3 for group in seen)
    assert sorted(sum(seen, [])) == sorted(problem["numbers"])  # together they cover the list, once
    assert "Part 4" in log[4]["prompt"] and ledger.calls == 5
    assert final == tuple(sorted(problem["numbers"]))


def test_debate_agent_reads_the_other_three_not_its_own(monkeypatch):
    log = []
    install_fake(monkeypatch, log, echo_seed=True)
    problem = {"id": 0, "numbers": list(range(12, 0, -1))}
    ledger = protocols.Ledger()
    protocols.debate_episode(problem, seed=7, ledger=ledger)
    assert ledger.calls == 8
    round_two = [entry["prompt"] for entry in log[4:]]
    own = [f"[{70 + agent}]" for agent in range(4)]  # what agent i answered in round one
    for agent, prompt in enumerate(round_two):
        teammates = re.findall(r"Teammate \d: (\[[^\]]*\])", prompt)
        assert len(teammates) == 3 and own[agent] not in teammates
        assert set(teammates) == set(own) - {own[agent]}


def test_ledger_adds_up_prompt_and_generated_tokens():
    ledger = protocols.Ledger()
    ledger.add({"prompt_tokens": 100, "gen_tokens": 40})
    ledger.add({"prompt_tokens": 10, "gen_tokens": 5})
    assert (ledger.calls, ledger.prompt_tokens, ledger.gen_tokens, ledger.total_tokens) == (2, 110, 45, 155)


# ---------- the comparison, on a tiny hand-made study ----------
def small_study():
    truth = (1, 2, 3)
    right, wrong = [1, 2, 3], [3, 2, 1]
    single = lambda answers: [{"answer": a, "gen": 10, "prompt": 100} for a in answers]
    by = {
        0: {"truth": truth, "single": single([right] * 8 + [wrong] * 8),
            "debate": [{"first": [wrong] * 4, "finals": [right, wrong, wrong, wrong], "gen": 80, "prompt": 900}],
            "shard": [{"final": right, "gen": 25, "prompt": 400}, {"final": wrong, "gen": 25, "prompt": 400}]},
        1: {"truth": truth, "single": single([wrong] * 16),
            "debate": [{"first": [right, wrong, wrong, wrong], "finals": [wrong] * 4, "gen": 80, "prompt": 900}],
            "shard": [{"final": wrong, "gen": 25, "prompt": 400}, {"final": wrong, "gen": 25, "prompt": 400}]},
    }
    return by


def test_retry_scores_use_the_estimator():
    best, vote = compare.retry_scores(small_study(), 2)
    assert best[0] == pytest.approx(1 - comb(8, 2) / comb(16, 2))
    assert best[1] == 0
    assert vote[1] == 0


def test_team_scores_and_costs():
    by = small_study()
    teams = compare.team_scores(by)
    assert teams["debate_any"] == [1.0, 0.0]  # one right final is enough for the team
    assert teams["debate_round1"] == [0.0, 1.0]
    assert teams["shard"] == [0.5, 0.0]
    assert compare.mean_cost(by, "single", "generated") == 10
    assert compare.mean_cost(by, "single", "total") == 110
    assert compare.mean_cost(by, "debate", "total") == 980
    assert compare.single_rate(by) == pytest.approx(0.25)
python -m pytest -q test_lab.py
........................................................  [100%]
56 passed in 0.11s

Passing tests prove little unless they can also fail. Mutation testing checks that: plant one bug at a time in the lab’s own code, run the tests, and demand a failure. A bug that no test notices is a hole in the tests. Save this as mutate.py. It edits each source file in place, restores it afterwards, and prints which test caught each bug.

# mutate.py
"""Plant one bug at a time in the lab and check that the tests notice."""
import os
import pathlib
import shutil
import subprocess
import sys

MUTANTS = [
    ("passk.py", "pass_at_k returns the failure chance", "return 1 - comb(n - c, k) / comb(n, k)", "return comb(n - c, k) / comb(n, k)"),
    ("passk.py", "pass_at_k uses the average-rate shortcut", "return 1 - comb(n - c, k) / comb(n, k)", "return 1 - (1 - c / n) ** k"),
    ("passk.py", "pass_at_k lets k exceed n", "if not 1 <= k <= n:", "if not 1 <= k <= n + 1:"),
    ("vote.py", "vote ties always go to the first answer", "return rng.choice([answer for answer, count in counts.items() if count == top])",
     "return [answer for answer, count in counts.items() if count == top][0]"),
    ("vote.py", "vote needs no plurality", "if count == top]", "if count >= 1]"),
    ("stats.py", "p-value can reach zero", "return (extreme + 1) / (draws + 1)", "return extreme / draws"),
    ("stats.py", "p-value ignores ties with the observed sum", "abs(flipped) >= observed - 1e-12", "abs(flipped) > observed"),
    ("stats.py", "interval is only 50 percent wide", "means[int(0.025 * draws)], means[int(0.975 * draws) - 1]", "means[int(0.25 * draws)], means[int(0.75 * draws) - 1]"),
    ("task.py", "checker reads the first list, not the last", "for body in reversed(LIST_RE.findall(text)):", "for body in LIST_RE.findall(text):"),
    ("task.py", "checker ignores order and duplicates", "list(answer) == sorted(numbers)", "set(answer) == set(numbers)"),
    ("task.py", "checker accepts 2x as an integer", "INT_RE.fullmatch(part)", "INT_RE.match(part)"),
    ("ledger.py", "ledger forgets prompt tokens", 'self.prompt_tokens += reply["prompt_tokens"]', "pass"),
    ("protocols.py", "debate agent also reads its own answer", "others = [first[j] for j in range(TEAM_SIZE) if j != agent]", "others = list(first)"),
    ("protocols.py", "every shard agent gets the first quarter", "shards = [numbers[i * size:(i + 1) * size] for i in range(TEAM_SIZE)]", "shards = [numbers[:size] for i in range(TEAM_SIZE)]"),
    ("compare.py", "total cost leaves out the prompts", 'lambda row: row["gen"] + row["prompt"]', 'lambda row: row["gen"]'),
    ("compare.py", "team needs every final answer right", "any(a == truth for a in group) for group in finals", "all(a == truth for a in group) for group in finals"),
]


def run_tests():
    shutil.rmtree("__pycache__", ignore_errors=True)
    env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", COLUMNS="170")
    try:
        result = subprocess.run(
            [sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider", "test_lab.py"],
            capture_output=True, text=True, env=env, timeout=300,
        )
    except subprocess.TimeoutExpired:
        return 1, "hung"
    failed = [line for line in result.stdout.splitlines() if line.startswith("FAILED")]
    return result.returncode, failed[0].split(" - ")[0].replace("FAILED test_lab.py::", "") if failed else ""


code, _ = run_tests()
print(f"clean source: tests exit code {code}")
caught = 0
for name, label, old, new in MUTANTS:
    path = pathlib.Path(name)
    original = path.read_text(encoding="utf-8")
    assert original.count(old) == 1, label
    try:
        path.write_text(original.replace(old, new), encoding="utf-8")
        code, first = run_tests()
    finally:
        path.write_text(original, encoding="utf-8")
    caught += code != 0
    print(f"{label:<44} {'caught by ' + first if code else 'SURVIVED'}")
print(f"{caught} of {len(MUTANTS)} planted bugs caught")
python mutate.py
clean source: tests exit code 0
pass_at_k returns the failure chance         caught by test_pass_at_k_matches_brute_force[1-0]
pass_at_k uses the average-rate shortcut     caught by test_pass_at_k_matches_brute_force[2-1]
pass_at_k lets k exceed n                    caught by test_pass_at_k_edges_and_bad_arguments
vote ties always go to the first answer      caught by test_vote_winner_breaks_ties_at_random
vote needs no plurality                      caught by test_vote_at_k_known_values
p-value can reach zero                       caught by test_sign_flip_p_value
p-value ignores ties with the observed sum   caught by test_sign_flip_p_value
interval is only 50 percent wide             caught by test_bootstrap_ci_is_a_95_percent_interval_and_repeatable
checker reads the first list, not the last   caught by test_parse_answer_takes_the_last_list_of_integers
checker ignores order and duplicates         caught by test_is_correct_needs_exact_order_and_duplicates
checker accepts 2x as an integer             caught by test_parse_answer_takes_the_last_list_of_integers
ledger forgets prompt tokens                 caught by test_ledger_adds_up_prompt_and_generated_tokens
debate agent also reads its own answer       caught by test_debate_agent_reads_the_other_three_not_its_own
every shard agent gets the first quarter     caught by test_shard_agents_each_see_one_quarter
total cost leaves out the prompts            caught by test_team_scores_and_costs
team needs every final answer right          caught by test_team_scores_and_costs
16 of 16 planted bugs caught

All 16 planted bugs are caught, including the two that matter most for the conclusions: the estimator that returns the failure chance, and the debate agent that also reads its own answer. One kind of mutant is deliberately absent. Deleting a special case for fewer than k wrong attempts changes nothing, because math.comb already returns zero there, so such a mutant is equivalent to the original and no test could ever catch it. When one of your own mutants survives, ask first whether it is equivalent before you write a test for it.

Common mistakes, and how this lab guards against each

Comparing the team with one attempt. It is the most common mistake and the easiest to make by accident, because “better than one agent” sounds like the point. Scenario C in Step 8 shows what it does: a team with no skill beyond its own retries wins in every simulated study. Always put the matched-retry baseline in the same table as the single attempt.

Predicting retries from the average success rate. The independent formula is a fine first sketch and a bad measurement. In the real run it promised 99.3% at eight tries where the data said 64.6%, so any team measured against the formula would look far worse than it was. Use the recorded attempts and pass_at_k.

Counting attempts instead of problems. The 16 attempts at one problem are not 16 independent pieces of evidence about the model, because they share the problem’s difficulty. Resample whole problems, as bootstrap_ci does. In the earlier shortcut-audit tutorial, resampling whole groups gave an interval 7.4 times wider than resampling rows.

Switching the accounting rule after you have seen the results. Step 7 gave p = 0.0511 under one rule and 0.0467 under the other for the same data. Fix the rule, and the rounding policy for the matched k, before the run.

Giving one side a tool the other lacks. A team that may use the checker belongs against retries that may use it, and a team that votes belongs against retries that vote. The report prints both baselines for exactly this reason.

Treating an unreadable reply as missing data. A reply with no list in it is a wrong answer. parse_answer returns None, the checker says no, and the vote counts it as a vote for nothing. Dropping such replies would quietly flatter whichever protocol produces more of them.

Tuning on the problems you report. When you improve the merge prompt, generate fresh problems with a new seed for the tuning, and keep the 60 problems of the original seed for one honest final run. Because make_problems is seeded, a new seed gives a new set of problems for tuning, and the 60 reporting problems stay exactly as they were.

Choosing the number of episodes after you have looked. I fixed two debate episodes and three shard episodes per problem before the run, and I did not add more when the debate result came out borderline. Collecting more data because a p-value is close to 0.05 raises the false-alarm rate. If you need a narrower interval, decide so in advance, or run a new study on fresh problems.

Confirm the whole thing works end to end

Run these four checks, in this order, and compare each with what this tutorial printed.

  1. python -m pytest -q test_lab.py prints 56 passed, and python mutate.py ends with 16 of 16 planted bugs caught. Neither needs a model.
  2. python sim.py prints a shortcut near 96.7%, a false-alarm rate in scenario A within a point or two of 5%, and 100% for scenario C.
  3. python run_live.py 20 (about 6 minutes) writes 420 lines: 320 single attempts, 40 debate episodes and 60 shard episodes. Then python compare.py out/live.jsonl 20, python curve.py 20, python groups.py 20 and python diagnose.py 20 print the same four reports for the shorter run.
  4. Look for the pattern, not my digits: a single attempt right between 40% and 50% of the time, an honest best-of-k curve far below the shortcut, and neither team beating the retries that cost the same. Replies are not exactly repeatable, as the check in Step 5 showed, and 20 problems give wider intervals than 60.

A finished study in your own project should report, at minimum: the accounting rule and the rounding policy, the matched k, the number of problems and episodes, both baselines with and without a checker, the paired difference with its interval and p-value, and the stage-level counts that explain any loss.

Where to go next

  • Use a task whose checker is a test suite. Code generation with unit tests is the classic setting for best of k, and everything here carries over: the checker becomes “the tests pass”.
  • Fix the merge, then test on fresh problems. Try a merge done by ordinary code, a pairwise merge, or a prompt that spells out the procedure, and measure it against retries again.
  • Give the team something retries cannot have. The 20 problems that no attempt ever solved are where a team could earn its keep. Private information, a different tool per agent, or a judge that picks among teammates are designs worth the same matched-budget test.
  • Change the unit of cost. Count dollars at a provider’s price list, or wall-clock seconds, instead of tokens. A team that runs its agents in parallel can win on time while losing on tokens.
  • Run your own agents through the same harness. The agent harness tutorial builds one with validated tools and run limits, and the pass-rate gate tutorial turns a pass-rate comparison into a CI check. When the Hugging Face series publishes its promised single-agent task, this is the test to apply to it.

Sources and further reading

  • Ben Burtenshaw and Kashif Rasul, Swarms, Flocks, Gangs: How to build, train, and evaluate multi-agent systems, Hugging Face blog, November 26, 2026: the question, the equal-budget framing and the 6.56% and 37.5% figures.
  • Mark Chen and colleagues, Evaluating Large Language Models Trained on Code, arXiv 2107.03374: the unbiased pass@k estimator and its appendix on why plug-in estimates err.
  • Xuezhi Wang and colleagues, Self-Consistency Improves Chain of Thought Reasoning in Language Models, arXiv 2203.11171: sampling many answers and keeping the most consistent one.
  • Yilun Du and colleagues, Improving Factuality and Reasoning in Language Models through Multiagent Debate, arXiv 2305.14325: the debate protocol.
  • Andries Smit and colleagues, Should we be going MAD? A Look at Multi-Agent Debate Strategies for LLMs, arXiv 2311.17371, and Hyeong Kyu Choi, Xiaojin Zhu and Sharon Li, Debate or Vote: Which Yields Better Decisions in Multi-Agent Large Language Models?, arXiv 2508.17536: tests of debate against voting and self-consistency.
  • Ollama, API documentation for prompt_eval_count and eval_count, and the Python 3.13 math module documentation for math.comb.

Tags:

AI AgentsLLM EvaluationMulti-Agent SystemsOllamaPass@kPythonStatistics

Share

A worn aluminum survey marker disk set in rough ground, its stamped digits scratched and overstamped
Previous Post

Ars Technica’s Physics Feature Turns a 98% Benchmark Score Into a Forecast, but the Answer Key Was Corrected Where Astra Disagreed, One Run Per Agent Cannot Separate Astra From Opus, the Thesis Story Is an Audit, and the Yang-Mills Group Says It Does Not Yet Fully Understand the Proof

A bank vault with its grille door open and walls of numbered safe deposit boxes on both sides
Next Post

1Password Says One Employee’s GitHub Account Let an Attacker Push Code to Its Backend and Copy Customer Records, and Gives No Customer Count or Entry Point; the Stolen SRP Data “cannot be used to access your account,” but Its Whitepaper Says a Verifier Can Be Used in Password Cracking Attempts, With the Secret Key as the Missing Piece

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest
30 Nov
How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
30 Nov
The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519
Trending
November 30, 2026
How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
November 30, 2026
The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519
November 30, 2026
Cacti’s 4HTTP2SHELL Chain Drew 1,793 Attack Attempts on One Honeypot Sensor in Four Days, but the Fix Is Still Only Source Patches With No 1.2.32 Release or CVE ID, the Advisory Calls It “Authenticated,” and on Our Reading of the Code the Guest Route Hinges on One Setting That Ships as “No User”
November 30, 2026
How to Triage Vulnerabilities in Python With CVSS, EPSS, and CISA KEV: Build a Decision Engine, Replay It on 71 Real KEV Additions, and See What Each Signal Missed
November 30, 2026
The Register Gives China Mobile Credit for the “Most Capable” All-Domestic Open-Weight Model, but It Is China Telecom’s Xing4.1-Preview, Its Report Has No Capability Scores, the 4.68x Is a Simulation, and the Model Card’s Own Table Has It First or Tied for First on 2 of 18 Rows
November 30, 2026
easyDNS Says Customer Records, Stored AWS Keys and Unsalted Mailbox Password Hashes Were Exposed, but the Public Notice Gives No Counts, the Entry Point Appears Only in the CEO’s Comments to a Reporter, and It Is the Second Security Incident Its Blog Has Posted This Year

Related Posts

A laptop wrapped in a chain and padlock, illustrating least-privilege controls for AI agents.
Learning Hub

How to Secure Tool-Using AI Agents Before They Touch Production

June 8, 2026
Colorful sticky notes arranged on an office wall, symbolizing governance checklists and planning.
Learning Hub

AI Governance for Agentic Apps: A Practical Checklist for Builders

June 8, 2026
A technician connects green fiber optic cables at a data center, representing a private production inference endpoint.
Learning Hub

How to Deploy a Fine-Tuned LLM Behind a Private Production Inference Endpoint

June 8, 2026
Narrow aisle behind black supercomputer racks in a data center
Learning Hub

Kubernetes SELinux Volume Labeling: What Cluster Operators Should Audit Before v1.37

June 8, 2026
SXZ.io SXZ.io
  • [email protected]

Categories

Articles
Learning Hub
News

All Rights Reserved by SXZ.io ©2026