levelup.gitconnected.com 48 min read Original Source

Fusing Tiny 3B LLMs to Rival Claude Opus 5.5 Quality

Read this story for free: link

Anthropic’s Claude models are among the best at agentic tasks and complex reasoning, but every call is billed by the token and your data leaves your network. A technique called Mixture-of-Agents showed that open models answering together can beat a single frontier model. I test it on four open models of about 3B parameters, one per GPU, which alone miss too many questions. A cheap probe routes each question by difficulty, and hard ones fan out into parallel samples. An aggregator, a weighted vote and a verifier pick the answer, and each night I retrain the weakest models with DPO:

Each part of that picture is a file in the repository, tiny-llm-fusion, and one question passes through them in this order:

serve_app/orchestrator.py one OpenAI-compatible name, fusion-4x3b
-> tools/retrieval.py Wikipedia passages, for knowledge questions
-> engine/router.py a cheap Qwen probe picks one of three tiers
-> engine/sampler.py up to 16 samples, with programs for math
-> platform/gateway.py lanes, prefix routing, retries, a breaker
-> platform/governor.py no new stage once a task reaches its cap
-> engine/moa.py Qwen reads the replies and writes one more
-> engine/vote.py equal answers merged, weighed by track record
-> engine/verifier.py split votes and code: tests, then the reward model
-> engine/calibrate.py a confidence that can send the least sure to Opus
answer learn/improve.py -> LoRA adapters on two GPUs
beneath platform/fleet.py and serve.py rent the L40S VMs and boot vLLM
offline data.py seals the exam, and eval/harness.py grades every arm on it” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

request -> serve_app/orchestrator.py   one OpenAI-compatible name, fusion-4x3b
        -> tools/retrieval.py          Wikipedia passages, for knowledge questions
        -> engine/router.py            a cheap Qwen probe picks one of three tiers
        -> engine/sampler.py           up to 16 samples, with programs for math
        -> platform/gateway.py         lanes, prefix routing, retries, a breaker
        -> platform/governor.py        no new stage once a task reaches its cap
        -> engine/moa.py               Qwen reads the replies and writes one more
        -> engine/vote.py              equal answers merged, weighed by track record
        -> engine/verifier.py          split votes and code: tests, then the reward model
        -> engine/calibrate.py         a confidence that can send the least sure to Opus
answer  <- serve_app/orchestrator.py
nightly    platform/episodes.py -> learn/improve.py -> LoRA adapters on two GPUs
beneath    platform/fleet.py and serve.py rent the L40S VMs and boot vLLM
offline    data.py seals the exam, and eval/harness.py grades every arm on it
request -> serve_app/orchestrator.py   one OpenAI-compatible name, fusion-4x3b
        -> tools/retrieval.py          Wikipedia passages, for knowledge questions
        -> engine/router.py            a cheap Qwen probe picks one of three tiers
        -> engine/sampler.py           up to 16 samples, with programs for math
        -> platform/gateway.py         lanes, prefix routing, retries, a breaker
        -> platform/governor.py        no new stage once a task reaches its cap
        -> engine/moa.py               Qwen reads the replies and writes one more
        -> engine/vote.py              equal answers merged, weighed by track record
        -> engine/verifier.py          split votes and code: tests, then the reward model
        -> engine/calibrate.py         a confidence that can send the least sure to Opus
answer  <- serve_app/orchestrator.py
nightly    platform/episodes.py -> learn/improve.py -> LoRA adapters on two GPUs
beneath    platform/fleet.py and serve.py rent the L40S VMs and boot vLLM
offline    data.py seals the exam, and eval/harness.py grades every arm on it

Measured on 2,142 sealed tasks from six public benchmarks, the team finished 1.8 points behind Claude Opus 5.5 at 21.8x lower cost per task.

All the code is available in my repository:

GitHub – FareedKhan-dev/tiny-llm-fusion: Four small open LLMs fused into one self-improving engine…
Four small open LLMs fused into one self-improving engine, measured against Claude Opus 5.5 …

Environment Setup

Two kinds of machine run this project: a small CPU box for everything we write in Python, and GPU VMs that our control plane rents for the models:

We start an empty project on the CPU box with uv:

uv init tiny-llm-fusion --python 3.12 && cd tiny-llm-fusion && mkdir -p fusion data results
uv add httpx fastapi uvicorn anthropic openai math-verify bm25s scikit-learn numpy pandas datasets trl peft jupyterlab
export GPU_CLOUD_URL="https://your-gpu-cloud/v1"   # any VM API that can create, read and delete
export GPU_CLOUD_KEY="your key"                    # read once, never printed
export GATEWAY_KEY="a long random string"          # every model call carries it
export HF_TOKEN="your token"                       # Llama 3.2 is a gated download
export ANTHROPIC_API_KEY="your key"                # only the frontier yardstick calls Claude
uv init tiny-llm-fusion --python 3.12 && cd tiny-llm-fusion && mkdir -p fusion data results
uv add httpx fastapi uvicorn anthropic openai math-verify bm25s scikit-learn numpy pandas datasets trl peft jupyterlab
export GPU_CLOUD_URL="https://your-gpu-cloud/v1"   # any VM API that can create, read and delete
export GPU_CLOUD_KEY="your key"                    # read once, never printed
export GATEWAY_KEY="a long random string"          # every model call carries it
export HF_TOKEN="your token"                       # Llama 3.2 is a gated download
export ANTHROPIC_API_KEY="your key"                # only the frontier yardstick calls Claude

The drivers in this post are cells of one Jupyter notebook on that box, so objects such as dev live from one section to the next and a cell can await directly. The other files read their settings from config.py. Each model gets a spec: the id we serve, its role in the team, the temperature for its samples and its context length. Two of them have LoRA slots, because the self-improvement loop will train adapters for them later:

"""config.py: the models, prices, budgets and addresses every other file reads."""
import os
from dataclasses import dataclass
from pathlib import Path

@dataclass(frozen=True)
class Spec:
    id: str                 # the Hugging Face id we serve
    lab: str                # who trained it
    role: str               # what the system asks of it
    temperature: float      # sampling temperature for its candidates
    max_len: int            # vLLM --max-model-len
    lora: bool = False      # keeps LoRA slots for adapters

MODELS = {
    "qwen": Spec("Qwen/Qwen3.5-4B", "Qwen", "proposer, aggregator", 0.7, 16384),
    "llama": Spec("meta-llama/Llama-3.2-3B-Instruct", "Meta", "proposer", 0.8, 8192, lora=True),
    "gemma": Spec("google/gemma-4-E2B-it", "Google", "proposer", 0.8, 8192, lora=True),
    "phi": Spec("microsoft/Phi-4-mini-instruct", "Microsoft", "proposer", 0.7, 8192),
    "reward": Spec("Skywork/Skywork-Reward-V2-Llama-3.2-3B", "Skywork", "verifier", 0.0, 8192),
}
FRONTIER = "claude-opus-5-5"                        # the yardstick, called through the Anthropic SDK
"""config.py: the models, prices, budgets and addresses every other file reads."""
import os
from dataclasses import dataclass
from pathlib import Path

@dataclass(frozen=True)
class Spec:
    id: str                 # the Hugging Face id we serve
    lab: str                # who trained it
    role: str               # what the system asks of it
    temperature: float      # sampling temperature for its candidates
    max_len: int            # vLLM --max-model-len
    lora: bool = False      # keeps LoRA slots for adapters

MODELS = {
    "qwen": Spec("Qwen/Qwen3.5-4B", "Qwen", "proposer, aggregator", 0.7, 16384),
    "llama": Spec("meta-llama/Llama-3.2-3B-Instruct", "Meta", "proposer", 0.8, 8192, lora=True),
    "gemma": Spec("google/gemma-4-E2B-it", "Google", "proposer", 0.8, 8192, lora=True),
    "phi": Spec("microsoft/Phi-4-mini-instruct", "Microsoft", "proposer", 0.7, 8192),
    "reward": Spec("Skywork/Skywork-Reward-V2-Llama-3.2-3B", "Skywork", "verifier", 0.0, 8192),
}
FRONTIER = "claude-opus-5-5"                        # the yardstick, called through the Anthropic SDK

Qwen gets the longest context because it also aggregates, reading every other model’s answer at once.

The rest of the file is money and addresses. Prices are in credits, budgets follow the router’s three tiers, and the API keys come from the environment:

# config.py
CREDITS = {"l40s_hour": 0.86, "opus_in_mtok": 4.0, "opus_out_mtok": 20.0}   # one VM hour, a million tokens
BUDGET = {   # per task, by router tier
    1: {"tokens": 2_000, "gpu_s": 4.0, "credits": 0.002},
    2: {"tokens": 12_000, "gpu_s": 18.0, "credits": 0.006},
    3: {"tokens": 40_000, "gpu_s": 60.0, "credits": 0.02},
}
RUN_CREDITS = 400.0                                 # a hard ceiling for one whole evaluation run
SEED = 2026                                         # every split and sample draws from this seed
DATA, RESULTS = Path("data"), Path("results")
GATEWAY = os.environ.get("GATEWAY_URL", "http://127.0.0.1:9000/v1")   # every model call goes through it
GATEWAY_KEY = os.environ.get("GATEWAY_KEY", "")     # read once, never printed
CLOUD = {"url": os.environ.get("GPU_CLOUD_URL", ""), "key": os.environ.get("GPU_CLOUD_KEY", ""),
         "flavor": "1x-l40s-48g", "region": os.environ.get("GPU_REGION", "region-b")}
# config.py
CREDITS = {"l40s_hour": 0.86, "opus_in_mtok": 4.0, "opus_out_mtok": 20.0}   # one VM hour, a million tokens
BUDGET = {   # per task, by router tier
    1: {"tokens": 2_000, "gpu_s": 4.0, "credits": 0.002},
    2: {"tokens": 12_000, "gpu_s": 18.0, "credits": 0.006},
    3: {"tokens": 40_000, "gpu_s": 60.0, "credits": 0.02},
}
RUN_CREDITS = 400.0                                 # a hard ceiling for one whole evaluation run
SEED = 2026                                         # every split and sample draws from this seed
DATA, RESULTS = Path("data"), Path("results")
GATEWAY = os.environ.get("GATEWAY_URL", "http://127.0.0.1:9000/v1")   # every model call goes through it
GATEWAY_KEY = os.environ.get("GATEWAY_KEY", "")     # read once, never printed
CLOUD = {"url": os.environ.get("GPU_CLOUD_URL", ""), "key": os.environ.get("GPU_CLOUD_KEY", ""),
         "flavor": "1x-l40s-48g", "region": os.environ.get("GPU_REGION", "region-b")}

The box’s heaviest jobs, BM25 retrieval and sandboxed tests, need no GPU.

  • left out: container images (build it when a team shares the fleet)

Sealed Benchmark Splits

We have to download our data first. Six public benchmarks cover four kinds of work: GSM8K and MATH-500 for math, MMLU for knowledge, HumanEval+ and MBPP+ for code, and BBH for multi-step reasoning. Other splits of the same benchmarks feed the pools we may tune and train on.

Each row becomes one Task record, whatever its benchmark calls the fields:

"""data.py: the benchmarks, the sealed test slices and the pools we may tune and train on."""
import hashlib
import json
import random
from dataclasses import dataclass, field

from datasets import get_dataset_config_names, load_dataset

from fusion.config import DATA, SEED

@dataclass
class Task:
    id: str                  # "gsm8k/test/2", the same in every run
    bench: str               # gsm8k, math500, mmlu, humaneval_plus, mbpp_plus or bbh
    family: str              # math, knowledge, code or reasoning
    prompt: str              # the question exactly as the benchmark wrote it
    gold: str                # the reference answer, or the tests for code
    meta: dict = field(default_factory=dict)   # its subject or BBH task, and MBPP id
"""data.py: the benchmarks, the sealed test slices and the pools we may tune and train on."""
import hashlib
import json
import random
from dataclasses import dataclass, field

from datasets import get_dataset_config_names, load_dataset

from fusion.config import DATA, SEED

@dataclass
class Task:
    id: str                  # "gsm8k/test/2", the same in every run
    bench: str               # gsm8k, math500, mmlu, humaneval_plus, mbpp_plus or bbh
    family: str              # math, knowledge, code or reasoning
    prompt: str              # the question exactly as the benchmark wrote it
    gold: str                # the reference answer, or the tests for code
    meta: dict = field(default_factory=dict)   # its subject or BBH task, and MBPP id

SOURCES says where each split lives and which benchmark it serves, and only the first six get sealed:

(repo, configs, split, benchmark, reader)
"gsm8k": ("openai/gsm8k", ["main"], "test", "gsm8k", "gsm8k"),
"math500": ("HuggingFaceH4/MATH-500", [None], "test", "math500", "math500"),
"mmlu": ("cais/mmlu", ["all"], "test", "mmlu", "mmlu"),
"humaneval_plus": ("evalplus/humanevalplus", [None], "test", "humaneval_plus", "heplus"),
"mbpp_plus": ("evalplus/mbppplus", [None], "test", "mbpp_plus", "mbppplus"),
"bbh": ("lukaemon/bbh", "*", "test", "bbh", "bbh"), # 27 tasks, one config each
"gsm8k_train": ("openai/gsm8k", ["main"], "train", "gsm8k", "gsm8k"),
"math_full": ("EleutherAI/hendrycks_math", "*", "test", "math500", "math"), # 7 subjects
"math_train": ("EleutherAI/hendrycks_math", "*", "train", "math500", "math"),
"mmlu_val": ("cais/mmlu", ["all"], "validation", "mmlu", "mmlu"),
"mmlu_aux": ("cais/mmlu", ["all"], "auxiliary_train", "mmlu", "mmlu"),
"mbpp_train": ("google-research-datasets/mbpp", ["full"], "train", "mbpp_plus", "mbpp"),
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# data.py
FAMILY = {"gsm8k": "math", "math500": "math", "mmlu": "knowledge", "humaneval_plus": "code", "mbpp_plus": "code",
          "bbh": "reasoning"}
SOURCES = {   # name -> (repo, configs, split, benchmark, reader)
    "gsm8k": ("openai/gsm8k", ["main"], "test", "gsm8k", "gsm8k"),
    "math500": ("HuggingFaceH4/MATH-500", [None], "test", "math500", "math500"),
    "mmlu": ("cais/mmlu", ["all"], "test", "mmlu", "mmlu"),
    "humaneval_plus": ("evalplus/humanevalplus", [None], "test", "humaneval_plus", "heplus"),
    "mbpp_plus": ("evalplus/mbppplus", [None], "test", "mbpp_plus", "mbppplus"),
    "bbh": ("lukaemon/bbh", "*", "test", "bbh", "bbh"),                 # 27 tasks, one config each
    "gsm8k_train": ("openai/gsm8k", ["main"], "train", "gsm8k", "gsm8k"),
    "math_full": ("EleutherAI/hendrycks_math", "*", "test", "math500", "math"),   # 7 subjects
    "math_train": ("EleutherAI/hendrycks_math", "*", "train", "math500", "math"),
    "mmlu_val": ("cais/mmlu", ["all"], "validation", "mmlu", "mmlu"),
    "mmlu_aux": ("cais/mmlu", ["all"], "auxiliary_train", "mmlu", "mmlu"),
    "mbpp_train": ("google-research-datasets/mbpp", ["full"], "train", "mbpp_plus", "mbpp"),
}
# data.py
FAMILY = {"gsm8k": "math", "math500": "math", "mmlu": "knowledge", "humaneval_plus": "code", "mbpp_plus": "code",
          "bbh": "reasoning"}
SOURCES = {   # name -> (repo, configs, split, benchmark, reader)
    "gsm8k": ("openai/gsm8k", ["main"], "test", "gsm8k", "gsm8k"),
    "math500": ("HuggingFaceH4/MATH-500", [None], "test", "math500", "math500"),
    "mmlu": ("cais/mmlu", ["all"], "test", "mmlu", "mmlu"),
    "humaneval_plus": ("evalplus/humanevalplus", [None], "test", "humaneval_plus", "heplus"),
    "mbpp_plus": ("evalplus/mbppplus", [None], "test", "mbpp_plus", "mbppplus"),
    "bbh": ("lukaemon/bbh", "*", "test", "bbh", "bbh"),                 # 27 tasks, one config each
    "gsm8k_train": ("openai/gsm8k", ["main"], "train", "gsm8k", "gsm8k"),
    "math_full": ("EleutherAI/hendrycks_math", "*", "test", "math500", "math"),   # 7 subjects
    "math_train": ("EleutherAI/hendrycks_math", "*", "train", "math500", "math"),
    "mmlu_val": ("cais/mmlu", ["all"], "validation", "mmlu", "mmlu"),
    "mmlu_aux": ("cais/mmlu", ["all"], "auxiliary_train", "mmlu", "mmlu"),
    "mbpp_train": ("google-research-datasets/mbpp", ["full"], "train", "mbpp_plus", "mbpp"),
}

READ turns a raw row into a prompt, a gold answer and a group:

(prompt, gold, group) from one row
"gsm8k": lambda r, c: (r["question"], r["answer"].split("####")[-1].strip(), "gsm8k"), # it ends "#### 70000"
"math500": lambda r, c: (r["problem"], r["answer"], r["subject"]),
"math": lambda r, c: (r["problem"], r["solution"], c), # the grader reads the answer out of boxed{}
"mmlu": lambda r, c: (r["question"] + "".join(f"n({'ABCD'[k]}) {x}" for k, x in enumerate(r["choices"])),
"ABCD"[r["answer"]], r["subject"]),
"heplus": lambda r, c: (r["prompt"], f"{r['test']}ncheck({r['entry_point']})n", "code"), # tests, then the call
"mbppplus": lambda r, c: (f"{r['prompt']}n{r['test_list'][0]}", r["test"], "code"), # one assert shows the name
"mbpp": lambda r, c: (f"{r['text']}n{r['test_list'][0]}", "n".join(r["test_list"]), "code"),
"bbh": lambda r, c: (r["input"], r["target"], c),
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# data.py
READ = {   # reader -> (prompt, gold, group) from one row
    "gsm8k": lambda r, c: (r["question"], r["answer"].split("####")[-1].strip(), "gsm8k"),   # it ends "#### 70000"
    "math500": lambda r, c: (r["problem"], r["answer"], r["subject"]),
    "math": lambda r, c: (r["problem"], r["solution"], c),        # the grader reads the answer out of boxed{}
    "mmlu": lambda r, c: (r["question"] + "".join(f"n({'ABCD'[k]}) {x}" for k, x in enumerate(r["choices"])),
                          "ABCD"[r["answer"]], r["subject"]),
    "heplus": lambda r, c: (r["prompt"], f"{r['test']}ncheck({r['entry_point']})n", "code"),     # tests, then the call
    "mbppplus": lambda r, c: (f"{r['prompt']}n{r['test_list'][0]}", r["test"], "code"),     # one assert shows the name
    "mbpp": lambda r, c: (f"{r['text']}n{r['test_list'][0]}", "n".join(r["test_list"]), "code"),
    "bbh": lambda r, c: (r["input"], r["target"], c),
}
# data.py
READ = {   # reader -> (prompt, gold, group) from one row
    "gsm8k": lambda r, c: (r["question"], r["answer"].split("####")[-1].strip(), "gsm8k"),   # it ends "#### 70000"
    "math500": lambda r, c: (r["problem"], r["answer"], r["subject"]),
    "math": lambda r, c: (r["problem"], r["solution"], c),        # the grader reads the answer out of boxed{}
    "mmlu": lambda r, c: (r["question"] + "".join(f"n({'ABCD'[k]}) {x}" for k, x in enumerate(r["choices"])),
                          "ABCD"[r["answer"]], r["subject"]),
    "heplus": lambda r, c: (r["prompt"], f"{r['test']}ncheck({r['entry_point']})n", "code"),     # tests, then the call
    "mbppplus": lambda r, c: (f"{r['prompt']}n{r['test_list'][0]}", r["test"], "code"),     # one assert shows the name
    "mbpp": lambda r, c: (f"{r['text']}n{r['test_list'][0]}", "n".join(r["test_list"]), "code"),
    "bbh": lambda r, c: (r["input"], r["target"], c),
}

load walks every config of a source:

1 else split
tasks.append(Task(f"{name}/{where}/{i}", bench, FAMILY[bench], prompt, gold, {"group": group, "mbpp_id": mbpp}))
return tasks” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# data.py
def load(name):
    """Every row of one source as Tasks, tagged with the benchmark it serves."""
    repo, configs, split, bench, reader = SOURCES[name]
    configs = get_dataset_config_names(repo) if configs == "*" else configs
    tasks = []
    for c in configs:
        for i, r in enumerate(load_dataset(repo, c, split=split)):
            prompt, gold, group = READ[reader](r, c)
            mbpp = int(str(r["task_id"]).split("/")[-1]) if bench == "mbpp_plus" else None   # "Mbpp/2" and MBPP's 2 alike
            where = c if len(configs) > 1 else split
            tasks.append(Task(f"{name}/{where}/{i}", bench, FAMILY[bench], prompt, gold, {"group": group, "mbpp_id": mbpp}))
    return tasks
# data.py
def load(name):
    """Every row of one source as Tasks, tagged with the benchmark it serves."""
    repo, configs, split, bench, reader = SOURCES[name]
    configs = get_dataset_config_names(repo) if configs == "*" else configs
    tasks = []
    for c in configs:
        for i, r in enumerate(load_dataset(repo, c, split=split)):
            prompt, gold, group = READ[reader](r, c)
            mbpp = int(str(r["task_id"]).split("/")[-1]) if bench == "mbpp_plus" else None   # "Mbpp/2" and MBPP's 2 alike
            where = c if len(configs) > 1 else split
            tasks.append(Task(f"{name}/{where}/{i}", bench, FAMILY[bench], prompt, gold, {"group": group, "mbpp_id": mbpp}))
    return tasks

Pulling every source once shows how much we downloaded, and the first training question:

from pathlib import Path
from datasets import config
from fusion.data import SOURCES, load

tasks = {name: load(name) for name in SOURCES}
mb = sum(f.stat().st_size for f in Path(config.HF_DATASETS_CACHE).rglob("*") if f.is_file()) / 2**20
print(f"{sum(map(len, tasks.values())):,} rows from {len(tasks)} sources, {mb:,.0f} MB on disk")
t = tasks["gsm8k_train"][0]
print(t.id, "| gold", t.gold, "|", t.prompt)

#### OUTPUT ####
144,634 rows from 12 sources, 231 MB on disk
gsm8k_train/train/0 | gold 72 | Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?
from pathlib import Path
from datasets import config
from fusion.data import SOURCES, load

tasks = {name: load(name) for name in SOURCES}
mb = sum(f.stat().st_size for f in Path(config.HF_DATASETS_CACHE).rglob("*") if f.is_file()) / 2**20
print(f"{sum(map(len, tasks.values())):,} rows from {len(tasks)} sources, {mb:,.0f} MB on disk")
t = tasks["gsm8k_train"][0]
print(t.id, "| gold", t.gold, "|", t.prompt)

#### OUTPUT ####
144,634 rows from 12 sources, 231 MB on disk
gsm8k_train/train/0 | gold 72 | Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?

Most of those rows are MMLU’s auxiliary training set, which only feeds the pools. The six test sets are about one row in six.

The test slices get a seal: drawn once from a fixed seed, evenly per subject, with their ids hashed into a manifest that training checks:

# data.py
SEAL = {"gsm8k": "all", "math500": "all", "mmlu": 20, "humaneval_plus": "all", "mbpp_plus": "all", "bbh": 30}

def seal(tasks, seed=SEED):
    """The sealed test slices, drawn once, and a sha256 over their ids."""
    rng, sealed = random.Random(seed), []
    for bench, rule in SEAL.items():
        pool = [t for t in tasks if t.bench == bench]
        if rule == "all":
            sealed += pool
            continue
        groups = {}                                     # the same number from every subject
        for t in pool:
            groups.setdefault(t.meta["group"], []).append(t)
        sealed += [t for g in sorted(groups) for t in rng.sample(groups[g], rule)]
    ids = sorted(t.id for t in sealed)
    digest = hashlib.sha256("n".join(ids).encode()).hexdigest()
    (DATA / f"sealed_manifest_seed{seed}.json").write_text(json.dumps({"sha256": digest, "ids": ids}))
    return sealed, digest
# data.py
SEAL = {"gsm8k": "all", "math500": "all", "mmlu": 20, "humaneval_plus": "all", "mbpp_plus": "all", "bbh": 30}

def seal(tasks, seed=SEED):
    """The sealed test slices, drawn once, and a sha256 over their ids."""
    rng, sealed = random.Random(seed), []
    for bench, rule in SEAL.items():
        pool = [t for t in tasks if t.bench == bench]
        if rule == "all":
            sealed += pool
            continue
        groups = {}                                     # the same number from every subject
        for t in pool:
            groups.setdefault(t.meta["group"], []).append(t)
        sealed += [t for g in sorted(groups) for t in rng.sample(groups[g], rule)]
    ids = sorted(t.id for t in sealed)
    digest = hashlib.sha256("n".join(ids).encode()).hexdigest()
    (DATA / f"sealed_manifest_seed{seed}.json").write_text(json.dumps({"sha256": digest, "ids": ids}))
    return sealed, digest

pools builds everything we may tune and train on, minus any question that repeats a sealed one by text or by MBPP id. MATH’s test split, for one, contains all of MATH-500:

# data.py
def norm(text):
    return " ".join(text.lower().split())               # case and spacing never hide a repeat

def pools(sealed, candidates):
    """Rows we may tune and train on, minus repeats of a sealed question or MBPP id."""
    sealed_ids, seen_text = {t.id for t in sealed}, {norm(t.prompt) for t in sealed}
    seen_mbpp = {t.meta["mbpp_id"] for t in sealed if t.meta.get("mbpp_id")}
    keep, dropped = [], {"text": 0, "mbpp_id": 0}
    for t in candidates:
        if t.id in sealed_ids:
            continue                                    # a sealed row itself
        if norm(t.prompt) in seen_text:
            dropped["text"] += 1
        elif t.meta.get("mbpp_id") in seen_mbpp:        # MBPP+ reworded prompts but kept ids
            dropped["mbpp_id"] += 1
        else:
            keep.append(t)
    return keep, dropped
# data.py
def norm(text):
    return " ".join(text.lower().split())               # case and spacing never hide a repeat

def pools(sealed, candidates):
    """Rows we may tune and train on, minus repeats of a sealed question or MBPP id."""
    sealed_ids, seen_text = {t.id for t in sealed}, {norm(t.prompt) for t in sealed}
    seen_mbpp = {t.meta["mbpp_id"] for t in sealed if t.meta.get("mbpp_id")}
    keep, dropped = [], {"text": 0, "mbpp_id": 0}
    for t in candidates:
        if t.id in sealed_ids:
            continue                                    # a sealed row itself
        if norm(t.prompt) in seen_text:
            dropped["text"] += 1
        elif t.meta.get("mbpp_id") in seen_mbpp:        # MBPP+ reworded prompts but kept ids
            dropped["mbpp_id"] += 1
        else:
            keep.append(t)
    return keep, dropped

draw takes a dev set and a training set from the pool, with no task in both:

(dev size, train size, dev split)
"gsm8k": (400, 3000, "gsm8k_train"), "math500": (400, 2400, "math_full"), "mmlu": (400, 1800, "mmlu_val"),
"mbpp_plus": (200, 162, "mbpp_train"), "bbh": (405, 1620, "bbh"),
}

def draw(pool, seed=SEED):
"""(dev, train) from the pool, per benchmark and with no task in both."""
rng, dev, train = random.Random(seed), [], []
for bench, (d, t, source) in DRAW.items():
rows = [x for x in pool if x.bench == bench]
dev += rng.sample([x for x in rows if x.id.startswith(source + "/")], d)
taken = {x.id for x in dev}
train += rng.sample([x for x in rows if x.id not in taken], t)
return dev, train” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# data.py
DRAW = {   # benchmark -> (dev size, train size, dev split)
    "gsm8k": (400, 3000, "gsm8k_train"), "math500": (400, 2400, "math_full"), "mmlu": (400, 1800, "mmlu_val"),
    "mbpp_plus": (200, 162, "mbpp_train"), "bbh": (405, 1620, "bbh"),
}

def draw(pool, seed=SEED):
    """(dev, train) from the pool, per benchmark and with no task in both."""
    rng, dev, train = random.Random(seed), [], []
    for bench, (d, t, source) in DRAW.items():
        rows = [x for x in pool if x.bench == bench]
        dev += rng.sample([x for x in rows if x.id.startswith(source + "/")], d)
        taken = {x.id for x in dev}
        train += rng.sample([x for x in rows if x.id not in taken], t)
    return dev, train
# data.py
DRAW = {   # benchmark -> (dev size, train size, dev split)
    "gsm8k": (400, 3000, "gsm8k_train"), "math500": (400, 2400, "math_full"), "mmlu": (400, 1800, "mmlu_val"),
    "mbpp_plus": (200, 162, "mbpp_train"), "bbh": (405, 1620, "bbh"),
}

def draw(pool, seed=SEED):
    """(dev, train) from the pool, per benchmark and with no task in both."""
    rng, dev, train = random.Random(seed), [], []
    for bench, (d, t, source) in DRAW.items():
        rows = [x for x in pool if x.bench == bench]
        dev += rng.sample([x for x in rows if x.id.startswith(source + "/")], d)
        taken = {x.id for x in dev}
        train += rng.sample([x for x in rows if x.id not in taken], t)
    return dev, train

Running the seal over the six benchmarks and the pools over the other sources:

from fusion.data import draw, pools, seal

sealed, digest = seal([t for n in ("gsm8k", "math500", "mmlu", "humaneval_plus", "mbpp_plus", "bbh") for t in load(n)])
print(f"sealed {len(sealed):,} tasks, sha256 {digest[:12]}")
pool, dropped = pools(sealed, [t for n in list(SOURCES)[5:] for t in load(n)])   # from bbh on, its only split is test
print(f"pool {len(pool):,} rows, dropped {dropped['text']} repeated questions and {dropped['mbpp_id']} reused MBPP ids")
dev, train = draw(pool)
print(f"dev {len(dev):,} tasks, train {len(train):,} tasks")

#### OUTPUT ####
sealed 4,311 tasks, sha256 88286cebe1d1
pool 126,872 rows, dropped 537 repeated questions and 12 reused MBPP ids
dev 1,805 tasks, train 8,982 tasks
from fusion.data import draw, pools, seal

sealed, digest = seal([t for n in ("gsm8k", "math500", "mmlu", "humaneval_plus", "mbpp_plus", "bbh") for t in load(n)])
print(f"sealed {len(sealed):,} tasks, sha256 {digest[:12]}")
pool, dropped = pools(sealed, [t for n in list(SOURCES)[5:] for t in load(n)])   # from bbh on, its only split is test
print(f"pool {len(pool):,} rows, dropped {dropped['text']} repeated questions and {dropped['mbpp_id']} reused MBPP ids")
dev, train = draw(pool)
print(f"dev {len(dev):,} tasks, train {len(train):,} tasks")

#### OUTPUT ####
sealed 4,311 tasks, sha256 88286cebe1d1
pool 126,872 rows, dropped 537 repeated questions and 12 reused MBPP ids
dev 1,805 tasks, train 8,982 tasks

A text check alone would miss the MBPP repeats, because MBPP+ reworded those prompts and kept their ids. The dev set tunes the engine’s choices, and the training set feeds the self-improvement loop.

The final results come from the sealed slices, read only on the last day of the run.

  • left out: a date-fresh test slice (build it when your models may have seen the test)

GPU Control Plane

Six VMs left running overnight cost 61.9 credits, even if no request arrives, and a cold VM needs 418 seconds before it answers anything. The control plane trades one cost against the other: a VM per model, a warm spare, more replicas when a queue grows and nothing rented when quiet.

It runs on the CPU box, and a VM passes through seven states, from requested to gone:

API maps three cloud operations onto REST paths, and two dictionaries carry messages to and from the VMs:

its model, vm id -> the last state it reported” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

"""platform/fleet.py: the GPU control plane. It rents VMs, keeps one warm, scales them and gives them back."""
import math
import time
from dataclasses import dataclass, field

import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import PlainTextResponse

from fusion.config import CLOUD
from fusion.platform.serve import job

API = {"create": ("POST", "/vms"), "get": ("GET", "/vms/{id}"), "delete": ("DELETE", "/vms/{id}")}   # your cloud's paths
STATES = ("requested", "booting", "pulling", "ready", "serving", "draining", "gone")   # "ready": a standby, weights on disk
ASSIGN, REPORTED = {}, {}       # vm id -> its model, vm id -> the last state it reported
"""platform/fleet.py: the GPU control plane. It rents VMs, keeps one warm, scales them and gives them back."""
import math
import time
from dataclasses import dataclass, field

import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import PlainTextResponse

from fusion.config import CLOUD
from fusion.platform.serve import job

API = {"create": ("POST", "/vms"), "get": ("GET", "/vms/{id}"), "delete": ("DELETE", "/vms/{id}")}   # your cloud's paths
STATES = ("requested", "booting", "pulling", "ready", "serving", "draining", "gone")   # "ready": a standby, weights on disk
ASSIGN, REPORTED = {}, {}       # vm id -> its model, vm id -> the last state it reported

CloudClient wraps the three calls, and user_data carries the boot script for cloud-init:

# platform/fleet.py
class CloudClient:
    """A thin REST client for any GPU cloud with create, get and delete calls."""

    def __init__(self, url=CLOUD["url"], key=CLOUD["key"]):
        self.http = httpx.Client(base_url=url, headers={"Authorization": f"Bearer {key}"}, timeout=60)

    def call(self, op, body=None, **ids):
        method, path = API[op]
        r = self.http.request(method, path.format(**ids), json=body)
        r.raise_for_status()
        return r.json() if r.content else {}

    def create(self, name, user_data):
        return self.call("create", {"name": name, "flavor": CLOUD["flavor"], "region": CLOUD["region"],
                                    "image": "ubuntu-24.04-cuda-13.0", "volume_gb": 200, "user_data": user_data})
# platform/fleet.py
class CloudClient:
    """A thin REST client for any GPU cloud with create, get and delete calls."""

    def __init__(self, url=CLOUD["url"], key=CLOUD["key"]):
        self.http = httpx.Client(base_url=url, headers={"Authorization": f"Bearer {key}"}, timeout=60)

    def call(self, op, body=None, **ids):
        method, path = API[op]
        r = self.http.request(method, path.format(**ids), json=body)
        r.raise_for_status()
        return r.json() if r.content else {}

    def create(self, name, user_data):
        return self.call("create", {"name": name, "flavor": CLOUD["flavor"], "region": CLOUD["region"],
                                    "image": "ubuntu-24.04-cuda-13.0", "volume_gb": 200, "user_data": user_data})

Each VM is a record that only moves forward and times its moves:

<button data-code="# platform/fleet.py
@dataclass
class VM:
id: str
model: str # a MODELS key, or "standby"
state: str = "requested"
ip: str = "" # private address, from the cloud
events: list = field(default_factory=list) # (state, seconds since it was requested)
born: float = field(default_factory=time.time)

def move(self, state):
"""A VM only ever moves forward through STATES, and every move is timed."""
if STATES.index(state)

# platform/fleet.py
@dataclass
class VM:
    id: str
    model: str                                       # a MODELS key, or "standby"
    state: str = "requested"
    ip: str = ""                                     # private address, from the cloud
    events: list = field(default_factory=list)       # (state, seconds since it was requested)
    born: float = field(default_factory=time.time)

    def move(self, state):
        """A VM only ever moves forward through STATES, and every move is timed."""
        if STATES.index(state) <= STATES.index(self.state):
            raise ValueError(f"{self.id}: {self.state} cannot go to {state}")
        self.state = state
        self.events.append((state, round(time.time() - self.born, 1)))
# platform/fleet.py
@dataclass
class VM:
    id: str
    model: str                                       # a MODELS key, or "standby"
    state: str = "requested"
    ip: str = ""                                     # private address, from the cloud
    events: list = field(default_factory=list)       # (state, seconds since it was requested)
    born: float = field(default_factory=time.time)

    def move(self, state):
        """A VM only ever moves forward through STATES, and every move is timed."""
        if STATES.index(state) <= STATES.index(self.state):
            raise ValueError(f"{self.id}: {self.state} cannot go to {state}")
        self.state = state
        self.events.append((state, round(time.time() - self.born, 1)))

Scaling follows the Kubernetes Horizontal Pod Autoscaler on the calls waiting at the gateway:

Cooldowns of one minute up and five minutes down keep a short lull from tearing down replicas:

replicas and since >= self.up_cool) or (want = self.down_cool):
self.last[model] = now
return want
return replicas # inside a cooldown we hold what we have” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# platform/fleet.py
@dataclass
class Autoscaler:
    target: float = 24.0         # requests waiting per replica that we accept
    hi: int = 3                  # at most this many replicas of one model
    up_cool: float = 60.0        # seconds between two scale-outs of a model
    down_cool: float = 300.0     # seconds after any change before a scale-in
    last: dict = field(default_factory=dict)

    def desired(self, model, replicas, waiting, now):
        # the Kubernetes HPA rule, clamped to 1..hi
        want = max(1, min(self.hi, math.ceil(waiting / self.target)))
        since = now - self.last.get(model, float("-inf"))
        if (want > replicas and since >= self.up_cool) or (want < replicas and since >= self.down_cool):
            self.last[model] = now
            return want
        return replicas                              # inside a cooldown we hold what we have
# platform/fleet.py
@dataclass
class Autoscaler:
    target: float = 24.0         # requests waiting per replica that we accept
    hi: int = 3                  # at most this many replicas of one model
    up_cool: float = 60.0        # seconds between two scale-outs of a model
    down_cool: float = 300.0     # seconds after any change before a scale-in
    last: dict = field(default_factory=dict)

    def desired(self, model, replicas, waiting, now):
        # the Kubernetes HPA rule, clamped to 1..hi
        want = max(1, min(self.hi, math.ceil(waiting / self.target)))
        since = now - self.last.get(model, float("-inf"))
        if (want > replicas and since >= self.up_cool) or (want < replicas and since >= self.down_cool):
            self.last[model] = now
            return want
        return replicas                              # inside a cooldown we hold what we have

The reconciler turns these counts into cloud calls. The warm standby waits as ready with every model’s weights on disk, and promote hands it to a model in under a minute:

# platform/fleet.py
class Reconciler:
    """Desired replicas in, cloud calls out. It ticks every 15 seconds, like a Kubernetes controller."""

    def __init__(self, cloud, boot, max_vms=8):
        self.cloud, self.boot, self.max_vms, self.vms = cloud, boot, max_vms, []

    def rent(self, model):
        vm = VM(self.cloud.create(f"fusion-{model}", self.boot)["id"], model)
        ASSIGN[vm.id] = model                        # the VM fetches this once booted
        self.vms.append(vm)

    def promote(self, model):
        """Hand the warm standby to a model. It serves in under a minute."""
        spare = next((v for v in self.vms if v.model == "standby" and v.state == "ready"), None)
        if spare:
            spare.model, ASSIGN[spare.id] = model, model
            self.rent("standby")                     # and order the next standby straight away
        return spare is not None
# platform/fleet.py
class Reconciler:
    """Desired replicas in, cloud calls out. It ticks every 15 seconds, like a Kubernetes controller."""

    def __init__(self, cloud, boot, max_vms=8):
        self.cloud, self.boot, self.max_vms, self.vms = cloud, boot, max_vms, []

    def rent(self, model):
        vm = VM(self.cloud.create(f"fusion-{model}", self.boot)["id"], model)
        ASSIGN[vm.id] = model                        # the VM fetches this once booted
        self.vms.append(vm)

    def promote(self, model):
        """Hand the warm standby to a model. It serves in under a minute."""
        spare = next((v for v in self.vms if v.model == "standby" and v.state == "ready"), None)
        if spare:
            spare.model, ASSIGN[spare.id] = model, model
            self.rent("standby")                     # and order the next standby straight away
        return spare is not None

tick drains a VM before giving it back, and refresh moves each VM forward from what the cloud and the VM report:

<button data-code="# platform/fleet.py
def tick(self, desired, idle):
for model, n in desired.items():
live = [v for v in self.vms if v.model == model and v.state in STATES[:5]]
for _ in range(n – len(live)):
if sum(v.state != "gone" for v in self.vms) STATES.index(v.state):
v.move(seen)” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# platform/fleet.py
    def tick(self, desired, idle):
        for model, n in desired.items():
            live = [v for v in self.vms if v.model == model and v.state in STATES[:5]]
            for _ in range(n - len(live)):
                if sum(v.state != "gone" for v in self.vms) < self.max_vms and not self.promote(model):
                    self.rent(model)
            for v in live[n:]:
                v.move("draining")                   # it finishes the requests it holds, then goes
        for v in self.vms:
            if v.state == "draining" and idle(v):
                self.cloud.call("delete", id=v.id)
                v.move("gone")

    def refresh(self):
        # the cloud says up and where, the VM says the rest
        for v in [v for v in self.vms if v.state in STATES[:4]]:      # only these can still move forward here
            info = self.cloud.call("get", id=v.id)
            v.ip = info.get("ip") or v.ip
            seen = REPORTED.get(v.id) or ("booting" if info.get("status") == "active" else None)
            if seen and STATES.index(seen) > STATES.index(v.state):
                v.move(seen)
# platform/fleet.py
    def tick(self, desired, idle):
        for model, n in desired.items():
            live = [v for v in self.vms if v.model == model and v.state in STATES[:5]]
            for _ in range(n - len(live)):
                if sum(v.state != "gone" for v in self.vms) < self.max_vms and not self.promote(model):
                    self.rent(model)
            for v in live[n:]:
                v.move("draining")                   # it finishes the requests it holds, then goes
        for v in self.vms:
            if v.state == "draining" and idle(v):
                self.cloud.call("delete", id=v.id)
                v.move("gone")

    def refresh(self):
        # the cloud says up and where, the VM says the rest
        for v in [v for v in self.vms if v.state in STATES[:4]]:      # only these can still move forward here
            info = self.cloud.call("get", id=v.id)
            v.ip = info.get("ip") or v.ip
            seen = REPORTED.get(v.id) or ("booting" if info.get("status") == "active" else None)
            if seen and STATES.index(seen) > STATES.index(v.state):
                v.move(seen)

The download and the health check happen inside the VM, and its boot script reports both to two small routes. The first answers 404 until the reconciler names a model:

# platform/fleet.py
control = FastAPI()                              # the two routes a VM calls

@control.get("/control/assign/{vm_id}", response_class=PlainTextResponse)
def assignment(vm_id: str, skip: str = ""):
    model = ASSIGN.get(vm_id)
    if model in (None, skip):
        raise HTTPException(404)                 # the VM's curl retries until it gets one
    return "n".join([model, *job(model)])       # model, repos and vLLM flags

@control.post("/control/state/{vm_id}/{state}")
def report(vm_id: str, state: str):
    if state in ("pulling", "ready", "serving"):  # what a VM can see from inside
        REPORTED[vm_id] = state
    return {"ok": True}
# platform/fleet.py
control = FastAPI()                              # the two routes a VM calls

@control.get("/control/assign/{vm_id}", response_class=PlainTextResponse)
def assignment(vm_id: str, skip: str = ""):
    model = ASSIGN.get(vm_id)
    if model in (None, skip):
        raise HTTPException(404)                 # the VM's curl retries until it gets one
    return "n".join([model, *job(model)])       # model, repos and vLLM flags

@control.post("/control/state/{vm_id}/{state}")
def report(vm_id: str, state: str):
    if state in ("pulling", "ready", "serving"):  # what a VM can see from inside
        REPORTED[vm_id] = state
    return {"ok": True}
  • left out: spot capacity (build it when a region runs out of L40S)

Serving Layer

Each VM starts as a plain Ubuntu image with CUDA, and one boot script installs vLLM, waits for a model name, downloads the weights and starts serving:

<button data-code="#!/bin/bash
# platform/bootstrap.sh: cloud-init runs this once, as root, on every VM the control plane rents
set -euo pipefail
export HF_TOKEN=@HF_TOKEN@ HF_HOME=/opt/hf VLLM_ALLOW_RUNTIME_LORA_UPDATING=True # boot_script() fills the @ fields
CONTROL=@CONTROL@/control VM=$(cat /var/lib/cloud/data/instance-id) # cloud-init knows our id
ASK="curl -sf –retry 99999 –retry-delay 5 –retry-all-errors -o /opt/job $CONTROL/assign/$VM" # waits for a 200
SAY="curl -sf -X POST -o /dev/null $CONTROL/state/$VM"

curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/opt/uv sh
/opt/uv/uv venv /opt/venv –python 3.12
/opt/uv/uv pip install –python /opt/venv/bin/python vllm==0.21.1 huggingface_hub
$ASK # blocks until the reconciler names a model
mapfile -t JOB < /opt/job # the model, its repos and its vLLM flags
$SAY/pulling
echo "${JOB[1]}" | xargs -n1 /opt/venv/bin/hf download –quiet # one repo, or all five on the standby
[ "${JOB[0]}" = standby ] && $SAY/ready && $ASK?skip=standby && mapfile -t JOB

#!/bin/bash
# platform/bootstrap.sh: cloud-init runs this once, as root, on every VM the control plane rents
set -euo pipefail
export HF_TOKEN=@HF_TOKEN@ HF_HOME=/opt/hf VLLM_ALLOW_RUNTIME_LORA_UPDATING=True   # boot_script() fills the @ fields
CONTROL=@CONTROL@/control VM=$(cat /var/lib/cloud/data/instance-id)               # cloud-init knows our id
ASK="curl -sf --retry 99999 --retry-delay 5 --retry-all-errors -o /opt/job $CONTROL/assign/$VM"   # waits for a 200
SAY="curl -sf -X POST -o /dev/null $CONTROL/state/$VM"

curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/opt/uv sh
/opt/uv/uv venv /opt/venv --python 3.12
/opt/uv/uv pip install --python /opt/venv/bin/python vllm==0.21.1 huggingface_hub
$ASK                                                            # blocks until the reconciler names a model
mapfile -t JOB < /opt/job                                       # the model, its repos and its vLLM flags
$SAY/pulling
echo "${JOB[1]}" | xargs -n1 /opt/venv/bin/hf download --quiet  # one repo, or all five on the standby
[ "${JOB[0]}" = standby ] && $SAY/ready && $ASK?skip=standby && mapfile -t JOB < /opt/job   # wait for promotion
/opt/venv/bin/vllm serve ${JOB[2]} --api-key @GATEWAY_KEY@ --port 8000 &
curl -sf --retry 200 --retry-delay 2 --retry-all-errors -o /dev/null localhost:8000/health
$SAY/serving
wait                                                            # vLLM runs until the reconciler deletes this VM
#!/bin/bash
# platform/bootstrap.sh: cloud-init runs this once, as root, on every VM the control plane rents
set -euo pipefail
export HF_TOKEN=@HF_TOKEN@ HF_HOME=/opt/hf VLLM_ALLOW_RUNTIME_LORA_UPDATING=True   # boot_script() fills the @ fields
CONTROL=@CONTROL@/control VM=$(cat /var/lib/cloud/data/instance-id)               # cloud-init knows our id
ASK="curl -sf --retry 99999 --retry-delay 5 --retry-all-errors -o /opt/job $CONTROL/assign/$VM"   # waits for a 200
SAY="curl -sf -X POST -o /dev/null $CONTROL/state/$VM"

curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/opt/uv sh
/opt/uv/uv venv /opt/venv --python 3.12
/opt/uv/uv pip install --python /opt/venv/bin/python vllm==0.21.1 huggingface_hub
$ASK                                                            # blocks until the reconciler names a model
mapfile -t JOB < /opt/job                                       # the model, its repos and its vLLM flags
$SAY/pulling
echo "${JOB[1]}" | xargs -n1 /opt/venv/bin/hf download --quiet  # one repo, or all five on the standby
[ "${JOB[0]}" = standby ] && $SAY/ready && $ASK?skip=standby && mapfile -t JOB < /opt/job   # wait for promotion
/opt/venv/bin/vllm serve ${JOB[2]} --api-key @GATEWAY_KEY@ --port 8000 &
curl -sf --retry 200 --retry-delay 2 --retry-all-errors -o /dev/null localhost:8000/health
$SAY/serving
wait                                                            # vLLM runs until the reconciler deletes this VM

A standby branches off at one line: it downloads all five models, reports ready and waits to be promoted. The @ fields are filled in on the CPU box:

"""platform/serve.py: what each GPU VM downloads, and the vllm serve flags it starts with."""
import os
import shlex
from pathlib import Path

from fusion.config import GATEWAY, GATEWAY_KEY, MODELS

BOOT = Path(__file__).with_name("bootstrap.sh")

def boot_script():
    """bootstrap.sh with the control address and two keys written in, as every VM's user_data."""
    text = BOOT.read_text()
    fields = {"@CONTROL@": GATEWAY.removesuffix("/v1"), "@GATEWAY_KEY@": GATEWAY_KEY, "@HF_TOKEN@": os.environ["HF_TOKEN"]}
    for name, value in fields.items():
        text = text.replace(name, shlex.quote(value))
    return text
"""platform/serve.py: what each GPU VM downloads, and the vllm serve flags it starts with."""
import os
import shlex
from pathlib import Path

from fusion.config import GATEWAY, GATEWAY_KEY, MODELS

BOOT = Path(__file__).with_name("bootstrap.sh")

def boot_script():
    """bootstrap.sh with the control address and two keys written in, as every VM's user_data."""
    text = BOOT.read_text()
    fields = {"@CONTROL@": GATEWAY.removesuffix("/v1"), "@GATEWAY_KEY@": GATEWAY_KEY, "@HF_TOKEN@": os.environ["HF_TOKEN"]}
    for name, value in fields.items():
        text = text.replace(name, shlex.quote(value))
    return text

job is what the first control route sends back. launch_args builds the flags per role: an FP8 KV cache and a prefix cache everywhere, LoRA slots on Llama and Gemma, n-gram drafts on the aggregator and a pooling runner for the reward model:

# platform/serve.py
def job(model):
    """(repos, flags) for one VM. A standby downloads every model and waits to be promoted."""
    if model == "standby":
        return " ".join(s.id for s in MODELS.values()), ""
    return MODELS[model].id, " ".join(launch_args(model))

def launch_args(name):
    """The vllm serve flags for one model and its role."""
    spec = MODELS[name]
    args = [spec.id, "--served-model-name", name, "--max-model-len", str(spec.max_len), "--kv-cache-dtype", "fp8",
            "--enable-prefix-caching", "--gpu-memory-utilization", "0.90"]
    if spec.lora:                                # slots for the DPO adapters
        args += ["--enable-lora", "--max-lora-rank", "16", "--max-loras", "2"]
    if "aggregator" in spec.role:                # an aggregator copies its prompt
        args += ["--speculative-config", '{"method":"ngram","num_speculative_tokens":4,"prompt_lookup_max":4}']
    if spec.role == "verifier":                  # the reward model only scores
        args += ["--runner", "pooling"]
    return args
# platform/serve.py
def job(model):
    """(repos, flags) for one VM. A standby downloads every model and waits to be promoted."""
    if model == "standby":
        return " ".join(s.id for s in MODELS.values()), ""
    return MODELS[model].id, " ".join(launch_args(model))

def launch_args(name):
    """The vllm serve flags for one model and its role."""
    spec = MODELS[name]
    args = [spec.id, "--served-model-name", name, "--max-model-len", str(spec.max_len), "--kv-cache-dtype", "fp8",
            "--enable-prefix-caching", "--gpu-memory-utilization", "0.90"]
    if spec.lora:                                # slots for the DPO adapters
        args += ["--enable-lora", "--max-lora-rank", "16", "--max-loras", "2"]
    if "aggregator" in spec.role:                # an aggregator copies its prompt
        args += ["--speculative-config", '{"method":"ngram","num_speculative_tokens":4,"prompt_lookup_max":4}']
    if spec.role == "verifier":                  # the reward model only scores
        args += ["--runner", "pooling"]
    return args

I served the control routes and asked for one replica of each model, plus the standby:

<button data-code="import threading
import time
import uvicorn
from fusion.config import CLOUD, MODELS
from fusion.platform.fleet import CloudClient, Reconciler, control
from fusion.platform.serve import boot_script

threading.Thread(target=uvicorn.run, args=(control,), kwargs={"host": "0.0.0.0", "port": 9000}, daemon=True).start()
rec = Reconciler(CloudClient(), boot=boot_script())
rec.tick({m: 1 for m in MODELS} | {"standby": 1}, idle=lambda v: False)
while any(v.state not in ("ready", "serving") for v in rec.vms):
time.sleep(5)
rec.refresh()
for v in rec.vms:
print(f"{v.id} {CLOUD['flavor']} {v.model:9} {t:>6.1f}s" for s, t in v.events))

#### OUTPUT ####
vm-7c41e2 1x-l40s-48g qwen booting 51.2s pulling 143.7s serving 418.3s
vm-2b9f04 1x-l40s-48g llama booting 49.6s pulling 139.2s serving 377.9s
vm-e3a1c8 1x-l40s-48g gemma booting 53.4s pulling 146.1s serving 402.6s
vm-90d5f7 1x-l40s-48g phi booting 52.0s pulling 141.8s serving 391.4s
vm-4f6b2d 1x-l40s-48g reward booting 161.0s pulling 254.3s serving 497.2s
vm-b81e3a 1x-l40s-48g standby booting 50.7s pulling 142.5s ready 612.8s” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

import threading
import time
import uvicorn
from fusion.config import CLOUD, MODELS
from fusion.platform.fleet import CloudClient, Reconciler, control
from fusion.platform.serve import boot_script

threading.Thread(target=uvicorn.run, args=(control,), kwargs={"host": "0.0.0.0", "port": 9000}, daemon=True).start()
rec = Reconciler(CloudClient(), boot=boot_script())
rec.tick({m: 1 for m in MODELS} | {"standby": 1}, idle=lambda v: False)
while any(v.state not in ("ready", "serving") for v in rec.vms):
    time.sleep(5)
    rec.refresh()
for v in rec.vms:
    print(f"{v.id}  {CLOUD['flavor']}  {v.model:<8}" + "".join(f"{s:>9} {t:>6.1f}s" for s, t in v.events))

#### OUTPUT ####
vm-7c41e2  1x-l40s-48g  qwen      booting   51.2s  pulling  143.7s  serving  418.3s
vm-2b9f04  1x-l40s-48g  llama     booting   49.6s  pulling  139.2s  serving  377.9s
vm-e3a1c8  1x-l40s-48g  gemma     booting   53.4s  pulling  146.1s  serving  402.6s
vm-90d5f7  1x-l40s-48g  phi       booting   52.0s  pulling  141.8s  serving  391.4s
vm-4f6b2d  1x-l40s-48g  reward    booting  161.0s  pulling  254.3s  serving  497.2s
vm-b81e3a  1x-l40s-48g  standby   booting   50.7s  pulling  142.5s    ready  612.8s
import threading
import time
import uvicorn
from fusion.config import CLOUD, MODELS
from fusion.platform.fleet import CloudClient, Reconciler, control
from fusion.platform.serve import boot_script

threading.Thread(target=uvicorn.run, args=(control,), kwargs={"host": "0.0.0.0", "port": 9000}, daemon=True).start()
rec = Reconciler(CloudClient(), boot=boot_script())
rec.tick({m: 1 for m in MODELS} | {"standby": 1}, idle=lambda v: False)
while any(v.state not in ("ready", "serving") for v in rec.vms):
    time.sleep(5)
    rec.refresh()
for v in rec.vms:
    print(f"{v.id}  {CLOUD['flavor']}  {v.model:<8}" + "".join(f"{s:>9} {t:>6.1f}s" for s, t in v.events))

#### OUTPUT ####
vm-7c41e2  1x-l40s-48g  qwen      booting   51.2s  pulling  143.7s  serving  418.3s
vm-2b9f04  1x-l40s-48g  llama     booting   49.6s  pulling  139.2s  serving  377.9s
vm-e3a1c8  1x-l40s-48g  gemma     booting   53.4s  pulling  146.1s  serving  402.6s
vm-90d5f7  1x-l40s-48g  phi       booting   52.0s  pulling  141.8s  serving  391.4s
vm-4f6b2d  1x-l40s-48g  reward    booting  161.0s  pulling  254.3s  serving  497.2s
vm-b81e3a  1x-l40s-48g  standby   booting   50.7s  pulling  142.5s    ready  612.8s

Five hosts booted in under a minute, and the reward model’s took 161 seconds for a reason the cloud never gave. The standby was ready last because it downloaded every model, and it can now replace any of them.

The Llama VM’s console shows where its card went:

#### OUTPUT ####
INFO 11-12 09:07:03 [gpu_model_runner.py:2653] Model loading took 6.0234 GiB and 9.841237 seconds
INFO 11-12 09:07:52 [kv_cache_utils.py:1087] GPU KV cache size: 615,472 tokens
INFO 11-12 09:07:52 [kv_cache_utils.py:1091] Maximum concurrency for 8,192 tokens per request: 75.13x
INFO 11-12 09:08:27 [api_server.py:1957] Starting vLLM API server 0 on http://0.0.0.0:8000
$ nvidia-smi
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 580.95.05              Driver Version: 580.95.05      CUDA Version: 13.0     |
|-----------------------------------------+------------------------+----------------------|
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|=========================================+========================+======================|
|   0  NVIDIA L40S                    On  |   00000000:00:05.0 Off |                    0 |
| N/A   41C    P0             87W /  350W |   41452MiB /  46068MiB |      0%      Default |
+-----------------------------------------+------------------------+----------------------+
#### OUTPUT ####
INFO 11-12 09:07:03 [gpu_model_runner.py:2653] Model loading took 6.0234 GiB and 9.841237 seconds
INFO 11-12 09:07:52 [kv_cache_utils.py:1087] GPU KV cache size: 615,472 tokens
INFO 11-12 09:07:52 [kv_cache_utils.py:1091] Maximum concurrency for 8,192 tokens per request: 75.13x
INFO 11-12 09:08:27 [api_server.py:1957] Starting vLLM API server 0 on http://0.0.0.0:8000
$ nvidia-smi
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 580.95.05              Driver Version: 580.95.05      CUDA Version: 13.0     |
|-----------------------------------------+------------------------+----------------------|
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|=========================================+========================+======================|
|   0  NVIDIA L40S                    On  |   00000000:00:05.0 Off |                    0 |
| N/A   41C    P0             87W /  350W |   41452MiB /  46068MiB |      0%      Default |
+-----------------------------------------+------------------------+----------------------+

Weights take 6.0 GiB and the FP8 cache the rest, twice the tokens of BF16. vLLM reserves nine tenths of the card at start, and an idle GPU reads almost full. Each cached token costs a key and a value in every layer:

Qwen has the least room of the five, with the longest context:

A replica accepts 48 calls at once, and fan-out and batch calls may never take the last 12 of them:

its DPO adapter, once promoted” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

"""platform/gateway.py: one OpenAI-compatible door to every replica, with a reserved lane and a circuit breaker."""

import asyncio
import hashlib
import time
from contextlib import nullcontext
from dataclasses import dataclass, field
import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fusion.config import GATEWAY_KEY, MODELS
from fusion.platform.fleet import control

SLOTS, RESERVED = 48, 12 # calls per replica, and the share bulk calls never take
BULK = ("fanout", "batch") # lanes that leave RESERVED slots free

HTTP = httpx.AsyncClient(timeout=180, headers={"Authorization": f"Bearer {GATEWAY_KEY}"})

REPLICAS, WAITING = {m: [] for m in MODELS}, {m: 0 for m in MODELS} # WAITING is what the autoscaler reads

ADAPTER = {} # model -> its DPO adapter, once promoted
"""platform/gateway.py: one OpenAI-compatible door to every replica, with a reserved lane and a circuit breaker."""

import asyncio
import hashlib
import time
from contextlib import nullcontext
from dataclasses import dataclass, field
import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fusion.config import GATEWAY_KEY, MODELS
from fusion.platform.fleet import control

SLOTS, RESERVED = 48, 12 # calls per replica, and the share bulk calls never take
BULK = ("fanout", "batch") # lanes that leave RESERVED slots free

HTTP = httpx.AsyncClient(timeout=180, headers={"Authorization": f"Bearer {GATEWAY_KEY}"})

REPLICAS, WAITING = {m: [] for m in MODELS}, {m: 0 for m in MODELS} # WAITING is what the autoscaler reads

ADAPTER = {} # model -> its DPO adapter, once promoted
  • left out: tensor parallelism (build it when a model outgrows one card)

Inference Gateway

Sixteen samples each from a few hard questions can fill every slot a model has, and an easy question a second later waits behind them. The gateway, the one door to the replicas, stops that with a reserved lane for short calls. It also routes by prompt prefix, retries and trips a breaker:

A Replica has a failure count and the two semaphores that make the lanes. pick sends one prompt prefix to one replica with rendezvous hashing:

vLLM’s prefix cache only helps on a replica that has seen the prefix:

<button data-code="# platform/gateway.py
@dataclass
class Replica:
model: str
url: str # http://10.0.3.17:8000
inflight: int = 0
fails: int = 0 # failures in a row
down_until: float = 0.0 # an open breaker skips it until then
every: asyncio.Semaphore = field(default_factory=lambda: asyncio.Semaphore(SLOTS))
bulk: asyncio.Semaphore = field(default_factory=lambda: asyncio.Semaphore(SLOTS – RESERVED))

def sync(vms): # mirror the reconciler: serving VMs in, departed VMs out
for m in REPLICAS:
live = {f"http://{v.ip}:8000" for v in vms if v.model == m and v.state == "serving"}
kept = [r for r in REPLICAS[m] if r.url in live]
REPLICAS[m] = kept + [Replica(m, u) for u in sorted(live – {r.url for r in kept})]

def pick(model, prefix, tried=()): # one prefix, one home replica, unless busy
up = [r for r in REPLICAS[model] if r.down_until < time.time() and r not in tried] or REPLICAS[model]
home = max(up, key=lambda r: hashlib.sha1((r.url + prefix).encode()).digest()) # rendezvous hashing
least = min(up, key=lambda r: r.inflight)
return home if home.inflight

# platform/gateway.py
@dataclass
class Replica:
    model: str
    url: str                                         # http://10.0.3.17:8000
    inflight: int = 0
    fails: int = 0                                   # failures in a row
    down_until: float = 0.0                          # an open breaker skips it until then
    every: asyncio.Semaphore = field(default_factory=lambda: asyncio.Semaphore(SLOTS))
    bulk: asyncio.Semaphore = field(default_factory=lambda: asyncio.Semaphore(SLOTS - RESERVED))

def sync(vms):                                       # mirror the reconciler: serving VMs in, departed VMs out
    for m in REPLICAS:
        live = {f"http://{v.ip}:8000" for v in vms if v.model == m and v.state == "serving"}
        kept = [r for r in REPLICAS[m] if r.url in live]
        REPLICAS[m] = kept + [Replica(m, u) for u in sorted(live - {r.url for r in kept})]

def pick(model, prefix, tried=()):                   # one prefix, one home replica, unless busy
    up = [r for r in REPLICAS[model] if r.down_until < time.time() and r not in tried] or REPLICAS[model]
    home = max(up, key=lambda r: hashlib.sha1((r.url + prefix).encode()).digest())    # rendezvous hashing
    least = min(up, key=lambda r: r.inflight)
    return home if home.inflight < least.inflight + 8 else least
# platform/gateway.py
@dataclass
class Replica:
    model: str
    url: str                                         # http://10.0.3.17:8000
    inflight: int = 0
    fails: int = 0                                   # failures in a row
    down_until: float = 0.0                          # an open breaker skips it until then
    every: asyncio.Semaphore = field(default_factory=lambda: asyncio.Semaphore(SLOTS))
    bulk: asyncio.Semaphore = field(default_factory=lambda: asyncio.Semaphore(SLOTS - RESERVED))

def sync(vms):                                       # mirror the reconciler: serving VMs in, departed VMs out
    for m in REPLICAS:
        live = {f"http://{v.ip}:8000" for v in vms if v.model == m and v.state == "serving"}
        kept = [r for r in REPLICAS[m] if r.url in live]
        REPLICAS[m] = kept + [Replica(m, u) for u in sorted(live - {r.url for r in kept})]

def pick(model, prefix, tried=()):                   # one prefix, one home replica, unless busy
    up = [r for r in REPLICAS[model] if r.down_until < time.time() and r not in tried] or REPLICAS[model]
    home = max(up, key=lambda r: hashlib.sha1((r.url + prefix).encode()).digest())    # rendezvous hashing
    least = min(up, key=lambda r: r.inflight)
    return home if home.inflight < least.inflight + 8 else least

forward is the whole policy, and three failures in a row take a replica out for half a minute:

<button data-code="# platform/gateway.py
async def forward(path, body, lane="single"):
"""One call. Bulk lanes leave RESERVED slots free, and three failures open the breaker."""
tried = []
for _ in range(3): # retry on an untried replica
r = pick(body["model"], str(body.get("messages") or body.get("input"))[:400], tried)
tried.append(r)
WAITING[r.model] += 1
async with (r.bulk if lane in BULK else nullcontext()), r.every:
WAITING[r.model] -= 1
r.inflight += 1
try:
resp = await HTTP.post(r.url + path, json={**body, "model": ADAPTER.get(r.model, r.model)})
if resp.status_code = 3 else r.down_until # open for 30 s, then try it again
raise HTTPException(503, f"{body['model']}: every attempt failed")” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# platform/gateway.py
async def forward(path, body, lane="single"):
    """One call. Bulk lanes leave RESERVED slots free, and three failures open the breaker."""
    tried = []
    for _ in range(3):                                   # retry on an untried replica
        r = pick(body["model"], str(body.get("messages") or body.get("input"))[:400], tried)
        tried.append(r)
        WAITING[r.model] += 1
        async with (r.bulk if lane in BULK else nullcontext()), r.every:
            WAITING[r.model] -= 1
            r.inflight += 1
            try:
                resp = await HTTP.post(r.url + path, json={**body, "model": ADAPTER.get(r.model, r.model)})
                if resp.status_code < 500:               # a 4xx is our mistake, so no retry
                    r.fails = 0
                    return resp
            except httpx.TransportError:
                pass
            finally:
                r.inflight -= 1
            r.fails += 1
            r.down_until = time.time() + 30 if r.fails >= 3 else r.down_until   # open for 30 s, then try it again
    raise HTTPException(503, f"{body['model']}: every attempt failed")
# platform/gateway.py
async def forward(path, body, lane="single"):
    """One call. Bulk lanes leave RESERVED slots free, and three failures open the breaker."""
    tried = []
    for _ in range(3):                                   # retry on an untried replica
        r = pick(body["model"], str(body.get("messages") or body.get("input"))[:400], tried)
        tried.append(r)
        WAITING[r.model] += 1
        async with (r.bulk if lane in BULK else nullcontext()), r.every:
            WAITING[r.model] -= 1
            r.inflight += 1
            try:
                resp = await HTTP.post(r.url + path, json={**body, "model": ADAPTER.get(r.model, r.model)})
                if resp.status_code < 500:               # a 4xx is our mistake, so no retry
                    r.fails = 0
                    return resp
            except httpx.TransportError:
                pass
            finally:
                r.inflight -= 1
            r.fails += 1
            r.down_until = time.time() + 30 if r.fails >= 3 else r.down_until   # open for 30 s, then try it again
    raise HTTPException(503, f"{body['model']}: every attempt failed")

The door checks the key, reads the lane from a header and keeps serving the control routes for the VMs:

# platform/gateway.py
app = FastAPI()
app.include_router(control.router)                   # the VMs' control routes

@app.post("/{path:path}")
async def proxy(path: str, request: Request):
    """The OpenAI-compatible door. An X-Lane header picks the lane, and single is the default."""
    if request.headers.get("authorization") != f"Bearer {GATEWAY_KEY}":
        raise HTTPException(401)
    resp = await forward("/" + path, await request.json(), request.headers.get("x-lane", "single"))
    return JSONResponse(resp.json(), resp.status_code)
# platform/gateway.py
app = FastAPI()
app.include_router(control.router)                   # the VMs' control routes

@app.post("/{path:path}")
async def proxy(path: str, request: Request):
    """The OpenAI-compatible door. An X-Lane header picks the lane, and single is the default."""
    if request.headers.get("authorization") != f"Bearer {GATEWAY_KEY}":
        raise HTTPException(401)
    resp = await forward("/" + path, await request.json(), request.headers.get("x-lane", "single"))
    return JSONResponse(resp.json(), resp.status_code)

The gateway registers one replica for each serving VM:

from fusion.platform import gateway

gateway.sync(rec.vms)
print("registered", {m: [r.url for r in rs] for m, rs in gateway.REPLICAS.items()})

#### OUTPUT ####
registered {'qwen': ['http://10.0.3.17:8000'], 'llama': ['http://10.0.3.21:8000'], 'gemma': ['http://10.0.3.9:8000'], 'phi': ['http://10.0.3.30:8000'], 'reward': ['http://10.0.3.12:8000']}
from fusion.platform import gateway

gateway.sync(rec.vms)
print("registered", {m: [r.url for r in rs] for m, rs in gateway.REPLICAS.items()})

#### OUTPUT ####
registered {'qwen': ['http://10.0.3.17:8000'], 'llama': ['http://10.0.3.21:8000'], 'gemma': ['http://10.0.3.9:8000'], 'phi': ['http://10.0.3.30:8000'], 'reward': ['http://10.0.3.12:8000']}

The standby has no replica, since it serves nothing until promoted. All model calls now go through these five.

To measure the lane, I sent sixteen samples each of six hard questions to the one Qwen replica, then forty easy calls, once without the lane and once with it:

<button data-code="import asyncio
import time
EASY, HARD = "What is 17 times 23?", "Prove that the sum of the first n odd numbers is n squared."

async def call(prompt, lane, tokens):
body = {"model": "qwen", "messages": [{"role": "user", "content": prompt}], "max_tokens": tokens}
t0 = time.perf_counter()
await gateway.forward("/v1/chat/completions", body, lane)
return time.perf_counter() – t0

async def main():
for lane in ("single", "fanout"):
hard = [asyncio.create_task(call(HARD, lane, 1024)) for _ in range(16 * 6)]
await asyncio.sleep(1)
easy = sorted(await asyncio.gather(*[call(EASY, "single", 16) for _ in range(40)]))
done = max(await asyncio.gather(*hard))
print(f"lane {lane:

import asyncio
import time
EASY, HARD = "What is 17 times 23?", "Prove that the sum of the first n odd numbers is n squared."

async def call(prompt, lane, tokens):
    body = {"model": "qwen", "messages": [{"role": "user", "content": prompt}], "max_tokens": tokens}
    t0 = time.perf_counter()
    await gateway.forward("/v1/chat/completions", body, lane)
    return time.perf_counter() - t0

async def main():
    for lane in ("single", "fanout"):
        hard = [asyncio.create_task(call(HARD, lane, 1024)) for _ in range(16 * 6)]
        await asyncio.sleep(1)
        easy = sorted(await asyncio.gather(*[call(EASY, "single", 16) for _ in range(40)]))
        done = max(await asyncio.gather(*hard))
        print(f"lane {lane:<7} easy p95 {easy[37]:5.2f} s   fan-out finished {done:6.1f} s")
await main()

#### OUTPUT ####
lane single  easy p95 41.37 s   fan-out finished   83.9 s
lane fanout  easy p95  0.58 s   fan-out finished  102.7 s
import asyncio
import time
EASY, HARD = "What is 17 times 23?", "Prove that the sum of the first n odd numbers is n squared."

async def call(prompt, lane, tokens):
    body = {"model": "qwen", "messages": [{"role": "user", "content": prompt}], "max_tokens": tokens}
    t0 = time.perf_counter()
    await gateway.forward("/v1/chat/completions", body, lane)
    return time.perf_counter() - t0

async def main():
    for lane in ("single", "fanout"):
        hard = [asyncio.create_task(call(HARD, lane, 1024)) for _ in range(16 * 6)]
        await asyncio.sleep(1)
        easy = sorted(await asyncio.gather(*[call(EASY, "single", 16) for _ in range(40)]))
        done = max(await asyncio.gather(*hard))
        print(f"lane {lane:<7} easy p95 {easy[37]:5.2f} s   fan-out finished {done:6.1f} s")
await main()

#### OUTPUT ####
lane single  easy p95 41.37 s   fan-out finished   83.9 s
lane fanout  easy p95  0.58 s   fan-out finished  102.7 s

Without the lane, the easy calls waited behind a full wave of hard ones. With it they started at once, and the fan-out finished 22% later. I kept the lane, because the router’s probes must answer fast.

  • left out: hedged requests (build it when tail latency matters more than load)

Sandboxed Execution and Grading

Code nobody has read runs on the CPU box: candidate solutions, reasoning programs and the tests that grade them. Each runs in a sandbox, its own Python process that cannot start another, with caps on time and memory:

Run is everything a caller learns about one execution:

"""tools/sandbox.py: runs code nobody reviewed in its own process, with a time limit and a memory cap."""
import resource
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass

@dataclass
class Run:
    ok: bool                                     # exit code 0
    out: str
    err: str
    seconds: float
    killed: bool = False                         # True when the time limit ended it
"""tools/sandbox.py: runs code nobody reviewed in its own process, with a time limit and a memory cap."""
import resource
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass

@dataclass
class Run:
    ok: bool                                     # exit code 0
    out: str
    err: str
    seconds: float
    killed: bool = False                         # True when the time limit ended it

cap runs in the child just before Python starts:

<button data-code="# tools/sandbox.py
def run(code, stdin="", timeout=5.0, mem_mb=512):
"""python -I in an empty directory, with a memory cap and no new processes or threads."""
def cap(): # runs in the child, just before Python starts
resource.setrlimit(resource.RLIMIT_AS, (mem_mb << 20, mem_mb <

# tools/sandbox.py
def run(code, stdin="", timeout=5.0, mem_mb=512):
    """python -I in an empty directory, with a memory cap and no new processes or threads."""
    def cap():                                   # runs in the child, just before Python starts
        resource.setrlimit(resource.RLIMIT_AS, (mem_mb << 20, mem_mb << 20))
        resource.setrlimit(resource.RLIMIT_NPROC, (0, 0))
    with tempfile.TemporaryDirectory() as tmp:
        t0 = time.time()
        try:
            p = subprocess.run([sys.executable, "-I", "-c", code], input=stdin, capture_output=True, text=True,
                               timeout=timeout, cwd=tmp, env={"OMP_NUM_THREADS": "1"}, preexec_fn=cap)   # numpy, one thread
            return Run(p.returncode == 0, p.stdout, p.stderr[-2000:], round(time.time() - t0, 2))
        except subprocess.TimeoutExpired:
            return Run(False, "", "timed out", timeout, killed=True)
# tools/sandbox.py
def run(code, stdin="", timeout=5.0, mem_mb=512):
    """python -I in an empty directory, with a memory cap and no new processes or threads."""
    def cap():                                   # runs in the child, just before Python starts
        resource.setrlimit(resource.RLIMIT_AS, (mem_mb << 20, mem_mb << 20))
        resource.setrlimit(resource.RLIMIT_NPROC, (0, 0))
    with tempfile.TemporaryDirectory() as tmp:
        t0 = time.time()
        try:
            p = subprocess.run([sys.executable, "-I", "-c", code], input=stdin, capture_output=True, text=True,
                               timeout=timeout, cwd=tmp, env={"OMP_NUM_THREADS": "1"}, preexec_fn=cap)   # numpy, one thread
            return Run(p.returncode == 0, p.stdout, p.stderr[-2000:], round(time.time() - t0, 2))
        except subprocess.TimeoutExpired:
            return Run(False, "", "timed out", timeout, killed=True)

Grading pulls the final answer out of a reply first. The last match of a family’s pattern wins, and no match is a format failure that counts as wrong:

pattern, the last match wins
"math": r"\boxed{((?:[^{}]|{[^{}]*})*)}", # a boxed{} answer, one level of braces deep
"knowledge": r"answer is (?([ABCD]))?", # "The answer is (C)"
"code": FENCE + r"(?:python)?n(.*?)" + FENCE, # the last python fence
"reasoning": r"answer is (.+?).?$", # BBH: "So the answer is (B)."
}

def extract(family, text):
found = re.findall(PATTERNS[family], text.strip(), re.S | re.M)
return found[-1].strip() if found else None # None is a format failure” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

"""tools/graders.py: pulls the final answer out of a reply and checks it against the gold."""
import re

from math_verify import parse, verify

from fusion.tools.sandbox import run

FENCE = "`" * 3                                  # a code fence
PATTERNS = {                                     # family -> pattern, the last match wins
    "math": r"\boxed{((?:[^{}]|{[^{}]*})*)}",           # a boxed{} answer, one level of braces deep
    "knowledge": r"answer is (?([ABCD]))?",                  # "The answer is (C)"
    "code": FENCE + r"(?:python)?n(.*?)" + FENCE,             # the last python fence
    "reasoning": r"answer is (.+?).?$",                       # BBH: "So the answer is (B)."
}

def extract(family, text):
    found = re.findall(PATTERNS[family], text.strip(), re.S | re.M)
    return found[-1].strip() if found else None               # None is a format failure
"""tools/graders.py: pulls the final answer out of a reply and checks it against the gold."""
import re

from math_verify import parse, verify

from fusion.tools.sandbox import run

FENCE = "`" * 3                                  # a code fence
PATTERNS = {                                     # family -> pattern, the last match wins
    "math": r"\boxed{((?:[^{}]|{[^{}]*})*)}",           # a boxed{} answer, one level of braces deep
    "knowledge": r"answer is (?([ABCD]))?",                  # "The answer is (C)"
    "code": FENCE + r"(?:python)?n(.*?)" + FENCE,             # the last python fence
    "reasoning": r"answer is (.+?).?$",                       # BBH: "So the answer is (B)."
}

def extract(family, text):
    found = re.findall(PATTERNS[family], text.strip(), re.S | re.M)
    return found[-1].strip() if found else None               # None is a format failure

check compares math answers by value with ``[Math-Verify](https://github.com/huggingface/Math-Verify)``, runs code against its tests in the sandbox and compares the rest as text:

# tools/graders.py
def check(task, answer):
    """Math by value, code by running its tests in the sandbox, everything else by exact text."""
    if answer is None:
        return False
    if task.family == "math":
        return verify(parse(f"${task.gold}$"), parse(f"${answer}$"))   # 1/2, 0.5 and frac{1}{2} are one value
    if task.family == "code":
        return run(answer + "nn" + task.gold, timeout=10).ok        # a code task's gold is its test program
    return answer.lower() == task.gold.strip().lower()
# tools/graders.py
def check(task, answer):
    """Math by value, code by running its tests in the sandbox, everything else by exact text."""
    if answer is None:
        return False
    if task.family == "math":
        return verify(parse(f"${task.gold}$"), parse(f"${answer}$"))   # 1/2, 0.5 and frac{1}{2} are one value
    if task.family == "code":
        return run(answer + "nn" + task.gold, timeout=10).ok        # a code task's gold is its test program
    return answer.lower() == task.gold.strip().lower()

Four prints test both files. The last grades a wrong answer to the first HumanEval+ task that only compares neighbours in the list:

<button data-code="from fusion.data import Task, load
from fusion.tools.graders import check, extract
from fusion.tools.sandbox import run

print(run("while True: pass"))
print(run("x = bytearray(2 * 1024 ** 3)").err.splitlines()[-1])
half = Task("demo/0", "math500", "math", "", r"frac{1}{2}")
print(check(half, extract("math", r"so it is boxed{0.5}")), check(half, extract("math", "so it is 0.5")))
task = load("humaneval_plus")[0]
code = task.prompt + " return any(abs(a – b)

from fusion.data import Task, load
from fusion.tools.graders import check, extract
from fusion.tools.sandbox import run

print(run("while True: pass"))
print(run("x = bytearray(2 * 1024 ** 3)").err.splitlines()[-1])
half = Task("demo/0", "math500", "math", "", r"frac{1}{2}")
print(check(half, extract("math", r"so it is boxed{0.5}")), check(half, extract("math", "so it is 0.5")))
task = load("humaneval_plus")[0]
code = task.prompt + "    return any(abs(a - b) < threshold for a, b in zip(numbers, numbers[1:]))n"
print(run(code + "assert has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)").ok, check(task, code))

#### OUTPUT ####
Run(ok=False, out='', err='timed out', seconds=5.0, killed=True)
MemoryError
True False
True False
from fusion.data import Task, load
from fusion.tools.graders import check, extract
from fusion.tools.sandbox import run

print(run("while True: pass"))
print(run("x = bytearray(2 * 1024 ** 3)").err.splitlines()[-1])
half = Task("demo/0", "math500", "math", "", r"frac{1}{2}")
print(check(half, extract("math", r"so it is boxed{0.5}")), check(half, extract("math", "so it is 0.5")))
task = load("humaneval_plus")[0]
code = task.prompt + "    return any(abs(a - b) < threshold for a, b in zip(numbers, numbers[1:]))n"
print(run(code + "assert has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)").ok, check(task, code))

#### OUTPUT ####
Run(ok=False, out='', err='timed out', seconds=5.0, killed=True)
MemoryError
True False
True False

The endless loop died at the time limit and the two-gigabyte allocation died at the cap. The wrong has_close_elements passes its docstring example and fails the hidden tests, because two close numbers do not have to be neighbours.

  • left out: network isolation (build it when strangers submit code)

Diverse Model Pool

Those 1,805 dev tasks are where we meet the four models. Each family gets one short instruction:

<button data-code=""""engine/pool.py: the four proposers, one call to any of them, and how often they miss together."""
import math
import time
from dataclasses import dataclass
from itertools import combinations

from fusion.platform.gateway import forward
from fusion.platform.telemetry import record
from fusion.tools.graders import extract

POOL = ["qwen", "llama", "gemma", "phi"] # the reward model only scores
PROMPT = { # one instruction per family, after every question
"math": "Solve it step by step and put the final answer in \boxed{}.",
"knowledge": "Think step by step, then end with: The answer is (X).",
"reasoning": "Think step by step, then end with: So the answer is .",
"code": "Return the complete function in one python code fence.",
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

"""engine/pool.py: the four proposers, one call to any of them, and how often they miss together."""
import math
import time
from dataclasses import dataclass
from itertools import combinations

from fusion.platform.gateway import forward
from fusion.platform.telemetry import record
from fusion.tools.graders import extract

POOL = ["qwen", "llama", "gemma", "phi"]          # the reward model only scores
PROMPT = {                                        # one instruction per family, after every question
    "math": "Solve it step by step and put the final answer in \boxed{}.",
    "knowledge": "Think step by step, then end with: The answer is (X).",
    "reasoning": "Think step by step, then end with: So the answer is <answer>.",
    "code": "Return the complete function in one python code fence.",
}
"""engine/pool.py: the four proposers, one call to any of them, and how often they miss together."""
import math
import time
from dataclasses import dataclass
from itertools import combinations

from fusion.platform.gateway import forward
from fusion.platform.telemetry import record
from fusion.tools.graders import extract

POOL = ["qwen", "llama", "gemma", "phi"]          # the reward model only scores
PROMPT = {                                        # one instruction per family, after every question
    "math": "Solve it step by step and put the final answer in \boxed{}.",
    "knowledge": "Think step by step, then end with: The answer is (X).",
    "reasoning": "Think step by step, then end with: So the answer is <answer>.",
    "code": "Return the complete function in one python code fence.",
}

A candidate is one reply with its answer pulled out, and ask is the engine’s only call to a model:

# engine/pool.py
@dataclass
class Candidate:
    model: str
    text: str
    answer: str | None                           # None for a format failure
    tokens: int                                  # completion tokens, the GPU work it cost
    seconds: float

async def ask(model, task, temperature=0.0, lane="single", messages=None):
    """One reply from one model through the gateway, the engine's only model call."""
    messages = messages or [{"role": "user", "content": f"{task.prompt}nn{PROMPT[task.family]}"}]
    body = {"model": model, "messages": messages, "temperature": temperature, "max_tokens": 2048}
    t0 = time.perf_counter()
    r = (await forward("/v1/chat/completions", body, lane)).json()
    text = r["choices"][0]["message"]["content"]
    cand = Candidate(model, text, extract(task.family, text), r["usage"]["completion_tokens"], time.perf_counter() - t0)
    record(task.id, cand)                        # one span per call, for cost
    return cand
# engine/pool.py
@dataclass
class Candidate:
    model: str
    text: str
    answer: str | None                           # None for a format failure
    tokens: int                                  # completion tokens, the GPU work it cost
    seconds: float

async def ask(model, task, temperature=0.0, lane="single", messages=None):
    """One reply from one model through the gateway, the engine's only model call."""
    messages = messages or [{"role": "user", "content": f"{task.prompt}nn{PROMPT[task.family]}"}]
    body = {"model": model, "messages": messages, "temperature": temperature, "max_tokens": 2048}
    t0 = time.perf_counter()
    r = (await forward("/v1/chat/completions", body, lane)).json()
    text = r["choices"][0]["message"]["content"]
    cand = Candidate(model, text, extract(task.family, text), r["usage"]["completion_tokens"], time.perf_counter() - t0)
    record(task.id, cand)                        # one span per call, for cost
    return cand

Fusion only helps if the models miss different questions. overlap measures how their misses correlate, and effective_voters turns that into independent voters:

# engine/pool.py
def overlap(right):
    """rho for every pair of models: the correlation of their misses (right[m] is 0 or 1 per task)."""
    rho = {}
    for a, b in combinations(right, 2):
        x, y = [1 - v for v in right[a]], [1 - v for v in right[b]]
        mx, my = sum(x) / len(x), sum(y) / len(y)
        cov = sum((p - mx) * (q - my) for p, q in zip(x, y)) / len(x)
        rho[a, b] = cov / math.sqrt(mx * (1 - mx) * my * (1 - my))
    return rho

def effective_voters(n, rho):
    return n / (1 + (n - 1) * rho)               # the design effect from survey sampling
# engine/pool.py
def overlap(right):
    """rho for every pair of models: the correlation of their misses (right[m] is 0 or 1 per task)."""
    rho = {}
    for a, b in combinations(right, 2):
        x, y = [1 - v for v in right[a]], [1 - v for v in right[b]]
        mx, my = sum(x) / len(x), sum(y) / len(y)
        cov = sum((p - mx) * (q - my) for p, q in zip(x, y)) / len(x)
        rho[a, b] = cov / math.sqrt(mx * (1 - mx) * my * (1 - my))
    return rho

def effective_voters(n, rho):
    return n / (1 + (n - 1) * rho)               # the design effect from survey sampling

effective_voters divides N by the design effect from survey sampling:

Each model answered the dev tasks once, greedy and in the batch lane:

import asyncio
from fusion.engine.pool import POOL, ask, effective_voters, overlap
from fusion.tools.graders import check

out = {m: await asyncio.gather(*[ask(m, t, lane="batch") for t in dev]) for m in POOL}
right = {m: [int(check(t, c.answer)) for t, c in zip(dev, cands)] for m, cands in out.items()}
print({m: round(100 * sum(r) / len(dev), 1) for m, r in right.items()})
print(f"at least one model right: {100 * sum(map(any, zip(*right.values()))) / len(dev):.1f}%")
rho = sum(overlap(right).values()) / 6
print(f"mean rho of misses {rho:.2f}, four models vote like {effective_voters(4, rho):.2f}")

#### OUTPUT ####
{'qwen': 79.1, 'llama': 60.7, 'gemma': 64.4, 'phi': 71.3}
at least one model right: 91.5%
mean rho of misses 0.36, four models vote like 1.92
import asyncio
from fusion.engine.pool import POOL, ask, effective_voters, overlap
from fusion.tools.graders import check

out = {m: await asyncio.gather(*[ask(m, t, lane="batch") for t in dev]) for m in POOL}
right = {m: [int(check(t, c.answer)) for t, c in zip(dev, cands)] for m, cands in out.items()}
print({m: round(100 * sum(r) / len(dev), 1) for m, r in right.items()})
print(f"at least one model right: {100 * sum(map(any, zip(*right.values()))) / len(dev):.1f}%")
rho = sum(overlap(right).values()) / 6
print(f"mean rho of misses {rho:.2f}, four models vote like {effective_voters(4, rho):.2f}")

#### OUTPUT ####
{'qwen': 79.1, 'llama': 60.7, 'gemma': 64.4, 'phi': 71.3}
at least one model right: 91.5%
mean rho of misses 0.36, four models vote like 1.92

Qwen is the strongest single model, and the team has 12.4 points of headroom above it on questions some model gets right. The misses correlate enough that four models vote like two, and plain voting cannot reach most of that headroom. Qwen and Phi miss together most often:

Each model also solves questions that the other three miss, Qwen most often and Llama least:

  • left out: specialist fine-tunes (build it when one family dominates)

Frontier Gap Diagnosis

Claude Opus 5.5 is our yardstick. It gets the pool’s prompts at medium effort, with no fallbacks, because a fallback would answer with another model:

"""tools/frontier.py: the yardstick. Claude Opus 5.5 answers the same prompts, priced in credits."""
import time

import anthropic

from fusion.config import CREDITS, FRONTIER
from fusion.engine.pool import PROMPT
from fusion.tools.graders import extract

CLIENT = anthropic.Anthropic()                   # reads ANTHROPIC_API_KEY

def params(task):
    # medium effort, set explicitly. No fallbacks: a refusal scores as wrong
    return {"model": FRONTIER, "max_tokens": 16000, "output_config": {"effort": "medium"},
            "messages": [{"role": "user", "content": f"{task.prompt}nn{PROMPT[task.family]}"}]}

def score(task, msg):
    """(answer, credits, refused) for one finished message, at the live price."""
    text = "".join(b.text for b in msg.content if b.type == "text")
    usage = msg.usage.input_tokens * CREDITS["opus_in_mtok"] + msg.usage.output_tokens * CREDITS["opus_out_mtok"]
    return extract(task.family, text), round(usage / 1e6, 6), msg.stop_reason == "refusal"
"""tools/frontier.py: the yardstick. Claude Opus 5.5 answers the same prompts, priced in credits."""
import time

import anthropic

from fusion.config import CREDITS, FRONTIER
from fusion.engine.pool import PROMPT
from fusion.tools.graders import extract

CLIENT = anthropic.Anthropic()                   # reads ANTHROPIC_API_KEY

def params(task):
    # medium effort, set explicitly. No fallbacks: a refusal scores as wrong
    return {"model": FRONTIER, "max_tokens": 16000, "output_config": {"effort": "medium"},
            "messages": [{"role": "user", "content": f"{task.prompt}nn{PROMPT[task.family]}"}]}

def score(task, msg):
    """(answer, credits, refused) for one finished message, at the live price."""
    text = "".join(b.text for b in msg.content if b.type == "text")
    usage = msg.usage.input_tokens * CREDITS["opus_in_mtok"] + msg.usage.output_tokens * CREDITS["opus_out_mtok"]
    return extract(task.family, text), round(usage / 1e6, 6), msg.stop_reason == "refusal"

live times one call for the latency sample, and batch sends the paired runs through the Message Batches API at half the price:

# tools/frontier.py
def live(task):
    t0 = time.perf_counter()                     # one timed call, for the latency sample
    return CLIENT.messages.create(**params(task)), time.perf_counter() - t0

def batch(tasks, poll=60):
    """One Message Batch at half the price. Returns {task id: message}, None where it failed."""
    reqs = [{"custom_id": t.id.replace("/", "--"), "params": params(t)} for t in tasks]   # ids allow no "/"
    b = CLIENT.messages.batches.create(requests=reqs)
    while CLIENT.messages.batches.retrieve(b.id).processing_status != "ended":
        time.sleep(poll)
    return {r.custom_id.replace("--", "/"): r.result.message if r.result.type == "succeeded" else None
            for r in CLIENT.messages.batches.results(b.id)}
# tools/frontier.py
def live(task):
    t0 = time.perf_counter()                     # one timed call, for the latency sample
    return CLIENT.messages.create(**params(task)), time.perf_counter() - t0

def batch(tasks, poll=60):
    """One Message Batch at half the price. Returns {task id: message}, None where it failed."""
    reqs = [{"custom_id": t.id.replace("/", "--"), "params": params(t)} for t in tasks]   # ids allow no "/"
    b = CLIENT.messages.batches.create(requests=reqs)
    while CLIENT.messages.batches.retrieve(b.id).processing_status != "ended":
        time.sleep(poll)
    return {r.custom_id.replace("--", "/"): r.result.message if r.result.type == "succeeded" else None
            for r in CLIENT.messages.batches.results(b.id)}

One live call on the first GSM8K training question shows what comes back:

from fusion.data import load
from fusion.tools.frontier import live, score

t = load("gsm8k_train")[0]
msg, seconds = live(t)
print(msg.id, msg.stop_reason, [b.type for b in msg.content], msg.usage.input_tokens, msg.usage.output_tokens)
print(f"{seconds:.1f} s", score(t, msg))

#### OUTPUT ####
msg_01HqT7vR3kXw9GmZ2pL8sYfN end_turn ['thinking', 'text'] 64 318
4.1 s ('72', 0.006616, False)
from fusion.data import load
from fusion.tools.frontier import live, score

t = load("gsm8k_train")[0]
msg, seconds = live(t)
print(msg.id, msg.stop_reason, [b.type for b in msg.content], msg.usage.input_tokens, msg.usage.output_tokens)
print(f"{seconds:.1f} s", score(t, msg))

#### OUTPUT ####
msg_01HqT7vR3kXw9GmZ2pL8sYfN end_turn ['thinking', 'text'] 64 318
4.1 s ('72', 0.006616, False)

The thinking block is empty because Opus 5.5 keeps its reasoning private by default, though those tokens are still billed. An easy question costs under a hundredth of a credit.

The study measures the gap closed, the share of the distance from the best small model to Opus that the team recovers:

Before building anything, I sent 200 dev tasks per family to Opus in one batch:

<button data-code="from fusion.tools.frontier import batch, score

FAMILIES, pct = ("math", "knowledge", "reasoning", "code"), lambda xs: 100 * sum(xs) / len(xs)
pilot = [t for f in FAMILIES for t in [t for t in dev if t.family == f][:200]]
opus, row = batch(pilot), {t.id: i for i, t in enumerate(dev)}
for f in FAMILIES:
ts = [t for t in pilot if t.family == f]
q = [right["qwen"][row[t.id]] for t in ts]
o = [opus[t.id] is not None and check(t, score(t, opus[t.id])[0]) for t in ts]
team = [any(right[m][row[t.id]] for m in POOL) for t in ts]
print(f"{f:

from fusion.tools.frontier import batch, score

FAMILIES, pct = ("math", "knowledge", "reasoning", "code"), lambda xs: 100 * sum(xs) / len(xs)
pilot = [t for f in FAMILIES for t in [t for t in dev if t.family == f][:200]]
opus, row = batch(pilot), {t.id: i for i, t in enumerate(dev)}
for f in FAMILIES:
    ts = [t for t in pilot if t.family == f]
    q = [right["qwen"][row[t.id]] for t in ts]
    o = [opus[t.id] is not None and check(t, score(t, opus[t.id])[0]) for t in ts]
    team = [any(right[m][row[t.id]] for m in POOL) for t in ts]
    print(f"{f:<10} qwen {pct(q):5.1f}   opus {pct(o):5.1f}   any model {pct(team):5.1f}")

#### OUTPUT ####
math       qwen  85.5   opus  97.0   any model  95.0
knowledge  qwen  74.0   opus  91.5   any model  86.5
reasoning  qwen  76.5   opus  93.5   any model  94.0
code       qwen  70.5   opus  82.0   any model  89.0
from fusion.tools.frontier import batch, score

FAMILIES, pct = ("math", "knowledge", "reasoning", "code"), lambda xs: 100 * sum(xs) / len(xs)
pilot = [t for f in FAMILIES for t in [t for t in dev if t.family == f][:200]]
opus, row = batch(pilot), {t.id: i for i, t in enumerate(dev)}
for f in FAMILIES:
    ts = [t for t in pilot if t.family == f]
    q = [right["qwen"][row[t.id]] for t in ts]
    o = [opus[t.id] is not None and check(t, score(t, opus[t.id])[0]) for t in ts]
    team = [any(right[m][row[t.id]] for m in POOL) for t in ts]
    print(f"{f:<10} qwen {pct(q):5.1f}   opus {pct(o):5.1f}   any model {pct(team):5.1f}")

#### OUTPUT ####
math       qwen  85.5   opus  97.0   any model  95.0
knowledge  qwen  74.0   opus  91.5   any model  86.5
reasoning  qwen  76.5   opus  93.5   any model  94.0
code       qwen  70.5   opus  82.0   any model  89.0

On math, reasoning and code, some model in the team already reaches about as many answers as Opus, and the missing points are a selection problem. On knowledge the team stops 5 points short of Opus, because some facts are missing from every model:

I sorted 200 of Qwen’s dev misses by their first wrong step, and each kind became a hypothesis:

  • H1, arithmetic slips (31% of misses): a Python program should fix them.
  • H2, wrong method (22%): an aggregator should keep another model’s better method.
  • H3, missing facts (19%): retrieval should lift MMLU, though not in every subject.
  • H4, misread questions (14%): a weighted vote should outvote them.
  • H5, code edge cases (8%): the question’s own examples should catch them.
  • H6, format failures (6%): one follow-up call should recover them.
  • H7, cost: routing should keep the accuracy at a fraction of the cost.
  • H8, self-improvement: DPO on the team’s own answers should lift its weakest members.

Each hypothesis maps to one part of the engine:

  • left out: a second yardstick (build it when one vendor is not enough)

Program-Aided Reasoning Tool

Almost a third of Qwen’s misses were arithmetic slips: a right plan with one wrong number. Program-aided reasoning moves the arithmetic into a short program that the sandbox runs:

pal_answer asks for a program instead of an answer, then runs it:

"""tools/pal.py: program-aided reasoning. The model writes a program, and the sandbox does the arithmetic."""
from fusion.engine.pool import ask
from fusion.tools.graders import extract
from fusion.tools.sandbox import run

PAL_SYSTEM = ("Write a Python function solution() that returns the final answer as a number, in one python code "
              "fence. Use only the standard library.")

async def pal_answer(model, task, lane="single"):
    """Ask for a program, run it, and keep what it returns as the answer."""
    msgs = [{"role": "system", "content": PAL_SYSTEM}, {"role": "user", "content": task.prompt}]
    cand = await ask(model, task, 0.0, lane, msgs)
    result = run((extract("code", cand.text) or "") + "nprint(solution())", timeout=5)
    cand.answer = result.out.strip() if result.ok else None     # a crash or a timeout is a format failure
    return cand
"""tools/pal.py: program-aided reasoning. The model writes a program, and the sandbox does the arithmetic."""
from fusion.engine.pool import ask
from fusion.tools.graders import extract
from fusion.tools.sandbox import run

PAL_SYSTEM = ("Write a Python function solution() that returns the final answer as a number, in one python code "
              "fence. Use only the standard library.")

async def pal_answer(model, task, lane="single"):
    """Ask for a program, run it, and keep what it returns as the answer."""
    msgs = [{"role": "system", "content": PAL_SYSTEM}, {"role": "user", "content": task.prompt}]
    cand = await ask(model, task, 0.0, lane, msgs)
    result = run((extract("code", cand.text) or "") + "nprint(solution())", timeout=5)
    cand.answer = result.out.strip() if result.ok else None     # a crash or a timeout is a format failure
    return cand

Llama answered the fourth GSM8K training question both ways:

import asyncio
from fusion.tools.pal import pal_answer

t = load("gsm8k_train")[3]
cot, pot = await asyncio.gather(ask("llama", t), pal_answer("llama", t))
print("CoT", cot.answer, check(t, cot.answer), "| PoT", pot.answer, check(t, pot.answer))

#### OUTPUT ####
CoT 47 False | PoT 42 True
import asyncio
from fusion.tools.pal import pal_answer

t = load("gsm8k_train")[3]
cot, pot = await asyncio.gather(ask("llama", t), pal_answer("llama", t))
print("CoT", cot.answer, check(t, cot.answer), "| PoT", pot.answer, check(t, pot.answer))

#### OUTPUT ####
CoT 47 False | PoT 42 True

Chain of thought slipped on one subtraction, and the program did not. Across dev, programs fixed 71% of the arithmetic slips of all four models.

  • left out: several tool calls per answer (build it when one program is not enough)

Knowledge Retrieval Tool

No vote can recover a fact that none of the four models knows. Retrieval puts the facts in front of the model: four passages from a BM25 index over the lead of every English Wikipedia article:

BM25 ranks a passage by how often it uses the question’s rarer words:

It needs no GPU, and bm25s builds the index in minutes. SKIP lists the subjects where retrieval lowered the dev score:

"""tools/retrieval.py: BM25 over Wikipedia, for knowledge questions in the subjects where it helps."""
import bm25s

INDEX = None
SKIP = {"abstract_algebra", "college_mathematics", "elementary_mathematics", "high_school_mathematics", "formal_logic",
        "high_school_statistics", "college_physics", "econometrics", "moral_scenarios"}   # retrieval hurt these on dev

def build_index(passages):
    global INDEX                                  # built once, about two gigabytes
    INDEX = bm25s.BM25(corpus=passages)
    INDEX.index(bm25s.tokenize(passages, stopwords="en"))

def search(query, k=4):
    docs, _ = INDEX.retrieve(bm25s.tokenize(query, stopwords="en"), k=k)
    return list(docs[0])
"""tools/retrieval.py: BM25 over Wikipedia, for knowledge questions in the subjects where it helps."""
import bm25s

INDEX = None
SKIP = {"abstract_algebra", "college_mathematics", "elementary_mathematics", "high_school_mathematics", "formal_logic",
        "high_school_statistics", "college_physics", "econometrics", "moral_scenarios"}   # retrieval hurt these on dev

def build_index(passages):
    global INDEX                                  # built once, about two gigabytes
    INDEX = bm25s.BM25(corpus=passages)
    INDEX.index(bm25s.tokenize(passages, stopwords="en"))

def search(query, k=4):
    docs, _ = INDEX.retrieve(bm25s.tokenize(query, stopwords="en"), k=k)
    return list(docs[0])

augment searches with the question alone, since the choices would pull in passages about wrong answers:

# tools/retrieval.py
def augment(task):
    """The question with four passages in front, or alone in a skipped subject."""
    if task.meta.get("group") in SKIP:
        return task.prompt
    passages = "nn".join(search(task.prompt.split("n(A)")[0]))     # search with the question, not its choices
    return f"Background passages:n{passages}nnQuestion:n{task.prompt}"
# tools/retrieval.py
def augment(task):
    """The question with four passages in front, or alone in a skipped subject."""
    if task.meta.get("group") in SKIP:
        return task.prompt
    passages = "nn".join(search(task.prompt.split("n(A)")[0]))     # search with the question, not its choices
    return f"Background passages:n{passages}nnQuestion:n{task.prompt}"

Qwen took the MMLU dev questions again, this time with passages:

from datasets import load_dataset
from fusion.engine.pool import PROMPT
from fusion.tools.retrieval import SKIP, augment, build_index

wiki = load_dataset("wikimedia/wikipedia", "20231101.en", split="train")
build_index([" ".join(a["text"].split()[:120]) for a in wiki])
mmlu = [t for t in dev if t.bench == "mmlu"]
msgs = lambda t: [{"role": "user", "content": f"{augment(t)}nn{PROMPT[t.family]}"}]
rag = await asyncio.gather(*[ask("qwen", t, messages=msgs(t)) for t in mmlu])
print(f"{len(wiki):,} passages, {len(SKIP)} subjects skipped")
print(f"qwen on mmlu dev: {pct([right['qwen'][row[t.id]] for t in mmlu]):.1f} without, "
      f"{pct([check(t, c.answer) for t, c in zip(mmlu, rag)]):.1f} with")

#### OUTPUT ####
6,407,814 passages, 9 subjects skipped
qwen on mmlu dev: 73.8 without, 80.5 with
from datasets import load_dataset
from fusion.engine.pool import PROMPT
from fusion.tools.retrieval import SKIP, augment, build_index

wiki = load_dataset("wikimedia/wikipedia", "20231101.en", split="train")
build_index([" ".join(a["text"].split()[:120]) for a in wiki])
mmlu = [t for t in dev if t.bench == "mmlu"]
msgs = lambda t: [{"role": "user", "content": f"{augment(t)}nn{PROMPT[t.family]}"}]
rag = await asyncio.gather(*[ask("qwen", t, messages=msgs(t)) for t in mmlu])
print(f"{len(wiki):,} passages, {len(SKIP)} subjects skipped")
print(f"qwen on mmlu dev: {pct([right['qwen'][row[t.id]] for t in mmlu]):.1f} without, "
      f"{pct([check(t, c.answer) for t, c in zip(mmlu, rag)]):.1f} with")

#### OUTPUT ####
6,407,814 passages, 9 subjects skipped
qwen on mmlu dev: 73.8 without, 80.5 with

Four passages lift Qwen by 6.7 points on MMLU. In the skipped subjects, mostly mathematics and logic, a Wikipedia lead only added noise to a calculation.

  • left out: dense retrieval (build it when BM25 recall plateaus)

Parallel Candidate Sampling

I gave every hard question sixteen samples, four per model, because the right answer is usually somewhere in the team. The sampler sends them at once:

Samples go through a result cache. Ablations rerun most of the same calls, and replaying a stored sample keeps a rerun identical and free:

"""engine/cache.py: answers we already paid for, replayed free when a call repeats."""
import hashlib
import json
import shelve

CACHE = shelve.open("data/result_cache")          # on disk, warm after a restart

async def cached(call, model, messages, temperature, i):
    """The stored candidate for this exact call, or a fresh one, stored on the way out."""
    key = hashlib.sha256(json.dumps([model, messages, temperature, i], sort_keys=True).encode()).hexdigest()
    if key not in CACHE:
        CACHE[key] = await call()
    return CACHE[key]
"""engine/cache.py: answers we already paid for, replayed free when a call repeats."""
import hashlib
import json
import shelve

CACHE = shelve.open("data/result_cache")          # on disk, warm after a restart

async def cached(call, model, messages, temperature, i):
    """The stored candidate for this exact call, or a fresh one, stored on the way out."""
    key = hashlib.sha256(json.dumps([model, messages, temperature, i], sort_keys=True).encode()).hexdigest()
    if key not in CACHE:
        CACHE[key] = await call()
    return CACHE[key]

one draws a sample and repairs a reply that lost its answer:

"""engine/sampler.py: one question to every proposer at once, with a repair call for a lost answer."""
import asyncio
from fusion.config import MODELS
from fusion.engine.cache import cached
from fusion.engine.pool import POOL, PROMPT, ask
from fusion.platform.gateway import ADAPTER
from fusion.tools.pal import pal_answer

REPAIR = "Give only the final answer, in the required format."

async def one(model, task, i):                   # sample i of one model, cached
    first = [{"role": "user", "content": f"{task.prompt}nn{PROMPT[task.family]}"}]
    async def fresh():
        c = await ask(model, task, MODELS[model].temperature, "fanout")
        if c.answer is None:                     # a follow-up is cheaper than a lost sample
            again = first + [{"role": "assistant", "content": c.text}, {"role": "user", "content": REPAIR}]
            fix = await ask(model, task, 0.0, "fanout", again)
            c.answer, c.tokens = fix.answer, c.tokens + fix.tokens
        return c
    return await cached(fresh, ADAPTER.get(model, model), first, MODELS[model].temperature, i)   # an adapter is a new model
"""engine/sampler.py: one question to every proposer at once, with a repair call for a lost answer."""
import asyncio
from fusion.config import MODELS
from fusion.engine.cache import cached
from fusion.engine.pool import POOL, PROMPT, ask
from fusion.platform.gateway import ADAPTER
from fusion.tools.pal import pal_answer

REPAIR = "Give only the final answer, in the required format."

async def one(model, task, i):                   # sample i of one model, cached
    first = [{"role": "user", "content": f"{task.prompt}nn{PROMPT[task.family]}"}]
    async def fresh():
        c = await ask(model, task, MODELS[model].temperature, "fanout")
        if c.answer is None:                     # a follow-up is cheaper than a lost sample
            again = first + [{"role": "assistant", "content": c.text}, {"role": "user", "content": REPAIR}]
            fix = await ask(model, task, 0.0, "fanout", again)
            c.answer, c.tokens = fix.answer, c.tokens + fix.tokens
        return c
    return await cached(fresh, ADAPTER.get(model, model), first, MODELS[model].temperature, i)   # an adapter is a new model

sample fans out across the pool and adds program samples for math:

# engine/sampler.py
async def sample(task, per_model=4, pal=0, models=POOL):   # per_model samples from each model, plus pal programs
    calls = [one(m, task, k * per_model + i) for k, m in enumerate(models) for i in range(per_model)]
    return await asyncio.gather(*calls, *[pal_answer(m, task, "fanout") for m in POOL[:pal]])
# engine/sampler.py
async def sample(task, per_model=4, pal=0, models=POOL):   # per_model samples from each model, plus pal programs
    calls = [one(m, task, k * per_model + i) for k, m in enumerate(models) for i in range(per_model)]
    return await asyncio.gather(*calls, *[pal_answer(m, task, "fanout") for m in POOL[:pal]])

One MATH dev question got sixteen samples and two programs:

<button data-code="from fusion.engine.sampler import sample

t = dev[412]
cands = await sample(t, per_model=4, pal=2)
print(t.id)
for m in POOL:
mine = [c for c in cands if c.model == m]
print(f"{m:

from fusion.engine.sampler import sample

t = dev[412]
cands = await sample(t, per_model=4, pal=2)
print(t.id)
for m in POOL:
    mine = [c for c in cands if c.model == m]
    print(f"{m:<6} {[c.answer for c in mine]}")

#### OUTPUT ####
math_full/intermediate_algebra/1187
qwen   ['\frac{14}{3}', '\frac{14}{3}', '5', '\frac{14}{3}', '4.666666666666667']
llama  ['\frac{7}{3}', '14/3', '4', '\frac{14}{3}', '4.666666666666667']
gemma  ['\frac{14}{3}', '\frac{7}{3}', '\frac{14}{3}', '\frac{14}{3}']
phi    ['\frac{14}{3}', '5', '\frac{14}{3}', '\frac{7}{3}']
from fusion.engine.sampler import sample

t = dev[412]
cands = await sample(t, per_model=4, pal=2)
print(t.id)
for m in POOL:
    mine = [c for c in cands if c.model == m]
    print(f"{m:<6} {[c.answer for c in mine]}")

#### OUTPUT ####
math_full/intermediate_algebra/1187
qwen   ['\frac{14}{3}', '\frac{14}{3}', '5', '\frac{14}{3}', '4.666666666666667']
llama  ['\frac{7}{3}', '14/3', '4', '\frac{14}{3}', '4.666666666666667']
gemma  ['\frac{14}{3}', '\frac{7}{3}', '\frac{14}{3}', '\frac{14}{3}']
phi    ['\frac{14}{3}', '5', '\frac{14}{3}', '\frac{7}{3}']

All four models found fourteen thirds at least once, in three spellings: a LaTeX fraction, a plain fraction and a decimal from the programs. A vote that compares strings would split the right answer three ways.

  • left out: cancelling slow samples (build it when tail latency matters most)

Weighted Majority Voting

Eighteen answers came back, written six ways. The vote merges equal answers and weighs each model by the log odds of its dev accuracy:

same decides when two answers mean the same thing:

"""engine/vote.py: a weighted vote over candidates, after answers that mean the same thing are merged."""
from math_verify import parse, verify

WEIGHT = {"qwen": 1.33, "llama": 0.43, "gemma": 0.59, "phi": 0.91, "moa": 1.95}   # log odds of dev accuracy

def same(task, a, b):
    """Math answers match by value, so 14/3 and 4.6667 are one answer. The rest by text."""
    if task.family == "math":
        return verify(parse(f"${a}$"), parse(f"${b}$"))
    return a.strip().lower() == b.strip().lower()
"""engine/vote.py: a weighted vote over candidates, after answers that mean the same thing are merged."""
from math_verify import parse, verify

WEIGHT = {"qwen": 1.33, "llama": 0.43, "gemma": 0.59, "phi": 0.91, "moa": 1.95}   # log odds of dev accuracy

def same(task, a, b):
    """Math answers match by value, so 14/3 and 4.6667 are one answer. The rest by text."""
    if task.family == "math":
        return verify(parse(f"${a}$"), parse(f"${b}$"))
    return a.strip().lower() == b.strip().lower()

tally groups the answers, sums their weights and reports the margin, the winner’s share minus the runner-up’s:

1 else 0.0), shares” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# engine/vote.py
def tally(task, cands, weight=WEIGHT):
    """(winner, margin, shares): the heaviest answer, its lead over the runner-up, every share."""
    groups = []                                  # [answer as first seen, total weight]
    for c in (c for c in cands if c.answer is not None):
        g = next((g for g in groups if same(task, g[0], c.answer)), None)
        if g:
            g[1] += weight.get(c.model, 1.0)
        else:
            groups.append([c.answer, weight.get(c.model, 1.0)])
    if not groups:
        return None, 0.0, {}
    total, groups = sum(w for _, w in groups), sorted(groups, key=lambda g: -g[1])
    shares = {a: w / total for a, w in groups}
    return groups[0][0], shares[groups[0][0]] - (groups[1][1] / total if len(groups) > 1 else 0.0), shares
# engine/vote.py
def tally(task, cands, weight=WEIGHT):
    """(winner, margin, shares): the heaviest answer, its lead over the runner-up, every share."""
    groups = []                                  # [answer as first seen, total weight]
    for c in (c for c in cands if c.answer is not None):
        g = next((g for g in groups if same(task, g[0], c.answer)), None)
        if g:
            g[1] += weight.get(c.model, 1.0)
        else:
            groups.append([c.answer, weight.get(c.model, 1.0)])
    if not groups:
        return None, 0.0, {}
    total, groups = sum(w for _, w in groups), sorted(groups, key=lambda g: -g[1])
    shares = {a: w / total for a, w in groups}
    return groups[0][0], shares[groups[0][0]] - (groups[1][1] / total if len(groups) > 1 else 0.0), shares

tally folds the three spellings of fourteen thirds into one group:

That question’s winner and margin come first, then every dev task:

<button data-code="from fusion.engine.vote import WEIGHT, tally

winner, margin, shares = tally(t, cands)
print(winner, round(margin, 3))
every = await asyncio.gather(*[sample(t) for t in dev])
for f in FAMILIES:
ix = [i for i, t in enumerate(dev) if t.family == f]
acc = lambda w: pct([check(dev[i], tally(dev[i], every[i], w)[0]) for i in ix])
print(f"{f:

from fusion.engine.vote import WEIGHT, tally

winner, margin, shares = tally(t, cands)
print(winner, round(margin, 3))
every = await asyncio.gather(*[sample(t) for t in dev])
for f in FAMILIES:
    ix = [i for i, t in enumerate(dev) if t.family == f]
    acc = lambda w: pct([check(dev[i], tally(dev[i], every[i], w)[0]) for i in ix])
    print(f"{f:<10} qwen {pct([right['qwen'][i] for i in ix]):5.1f}   majority {acc({m: 1.0 for m in POOL}):5.1f}"
          f"   weighted {acc(WEIGHT):5.1f}")

#### OUTPUT ####
frac{14}{3} 0.538
math       qwen  85.4   majority  90.1   weighted  91.4
knowledge  qwen  73.8   majority  77.0   weighted  78.5
reasoning  qwen  76.3   majority  85.2   weighted  86.4
code       qwen  70.5   majority  72.0   weighted  72.5
from fusion.engine.vote import WEIGHT, tally

winner, margin, shares = tally(t, cands)
print(winner, round(margin, 3))
every = await asyncio.gather(*[sample(t) for t in dev])
for f in FAMILIES:
    ix = [i for i, t in enumerate(dev) if t.family == f]
    acc = lambda w: pct([check(dev[i], tally(dev[i], every[i], w)[0]) for i in ix])
    print(f"{f:<10} qwen {pct([right['qwen'][i] for i in ix]):5.1f}   majority {acc({m: 1.0 for m in POOL}):5.1f}"
          f"   weighted {acc(WEIGHT):5.1f}")

#### OUTPUT ####
frac{14}{3} 0.538
math       qwen  85.4   majority  90.1   weighted  91.4
knowledge  qwen  73.8   majority  77.0   weighted  78.5
reasoning  qwen  76.3   majority  85.2   weighted  86.4
code       qwen  70.5   majority  72.0   weighted  72.5

Weighting by track record adds 1.2 points over a plain majority, and both beat Qwen alone on every family. Code barely moves, because two correct functions rarely match as text, and the verifier decides those.

  • left out: universal self-consistency (build it when answers have no canonical form)

Mixture of Agents Aggregation

In Mixture-of-Agents, an aggregator reads the team’s replies and writes its own, which can repair a step every proposer got wrong. Qwen is our aggregator:

moa shows the aggregator the end of one reply per distinct answer, most common first:

<button data-code=""""engine/moa.py: Mixture-of-Agents. One model reads the team's answers and writes its own final one."""
from fusion.engine.pool import PROMPT, ask

AGG_SYSTEM = ("Several models answered the question below, and some of them may be wrong. Check each answer, keep "
"what is right, fix what is wrong, and give one final answer in the required format.")

async def moa(task, cands, aggregator="qwen", k=6):
"""Show the aggregator one reply per distinct answer, most common first, and return its answer."""
seen, shown = set(), []
for c in sorted(cands, key=lambda c: -sum(d.answer == c.answer for d in cands)):
if c.answer not in seen and len(shown)

"""engine/moa.py: Mixture-of-Agents. One model reads the team's answers and writes its own final one."""
from fusion.engine.pool import PROMPT, ask

AGG_SYSTEM = ("Several models answered the question below, and some of them may be wrong. Check each answer, keep "
              "what is right, fix what is wrong, and give one final answer in the required format.")

async def moa(task, cands, aggregator="qwen", k=6):
    """Show the aggregator one reply per distinct answer, most common first, and return its answer."""
    seen, shown = set(), []
    for c in sorted(cands, key=lambda c: -sum(d.answer == c.answer for d in cands)):
        if c.answer not in seen and len(shown) < k:
            seen.add(c.answer)
            shown.append(f"Answer {len(shown) + 1}:n{c.text[-1500:]}")    # the end of a reply holds its conclusion
    msgs = [{"role": "system", "content": AGG_SYSTEM},
            {"role": "user", "content": task.prompt + "nn" + "nn".join(shown) + "nn" + PROMPT[task.family]}]
    agg = await ask(aggregator, task, 0.0, "fanout", msgs)
    agg.model = "moa"                            # the aggregate gets its own vote weight
    return agg
"""engine/moa.py: Mixture-of-Agents. One model reads the team's answers and writes its own final one."""
from fusion.engine.pool import PROMPT, ask

AGG_SYSTEM = ("Several models answered the question below, and some of them may be wrong. Check each answer, keep "
              "what is right, fix what is wrong, and give one final answer in the required format.")

async def moa(task, cands, aggregator="qwen", k=6):
    """Show the aggregator one reply per distinct answer, most common first, and return its answer."""
    seen, shown = set(), []
    for c in sorted(cands, key=lambda c: -sum(d.answer == c.answer for d in cands)):
        if c.answer not in seen and len(shown) < k:
            seen.add(c.answer)
            shown.append(f"Answer {len(shown) + 1}:n{c.text[-1500:]}")    # the end of a reply holds its conclusion
    msgs = [{"role": "system", "content": AGG_SYSTEM},
            {"role": "user", "content": task.prompt + "nn" + "nn".join(shown) + "nn" + PROMPT[task.family]}]
    agg = await ask(aggregator, task, 0.0, "fanout", msgs)
    agg.model = "moa"                            # the aggregate gets its own vote weight
    return agg

All dev questions went through the aggregator, whose answer joins the vote with its own weight:

from fusion.engine.moa import moa

aggs = await asyncio.gather(*[moa(t, cs) for t, cs in zip(dev, every)])
base = pct([check(t, tally(t, cs)[0]) for t, cs in zip(dev, every)])
fused = pct([check(t, tally(t, cs + [a])[0]) for t, cs, a in zip(dev, every, aggs)])
print(f"vote {base:.1f}   vote with the aggregate {fused:.1f}")

#### OUTPUT ####
vote 85.3   vote with the aggregate 87.4
from fusion.engine.moa import moa

aggs = await asyncio.gather(*[moa(t, cs) for t, cs in zip(dev, every)])
base = pct([check(t, tally(t, cs)[0]) for t, cs in zip(dev, every)])
fused = pct([check(t, tally(t, cs + [a])[0]) for t, cs, a in zip(dev, every, aggs)])
print(f"vote {base:.1f}   vote with the aggregate {fused:.1f}")

#### OUTPUT ####
vote 85.3   vote with the aggregate 87.4

The aggregator adds 2.1 points, mostly on math and BBH, where one wrong step in a good reply is common.

A critique round on close votes, with Phi flagging wrong steps, turned 31 dev answers right and 33 wrong.

  • left out: a critique round (build it when the reviewer outclasses the proposers)

Verification and Calibration

Split votes and all code go to the verifier. A code candidate must pass the examples its question shows, and the Skywork reward model ranks what is left:

The reward model returns one logit per reply, trained on ranked pairs:

examples turns the examples a question shows into asserts:

>> (.+)ns*(.+)", task.prompt)
return [f"assert {call} == {want}" for call, want in pairs] + re.findall(r"^assert .+$", task.prompt, re.M)” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

"""engine/verifier.py: picks among candidates. Code must pass the question's own examples, then the reward model ranks."""
import asyncio
import re

from fusion.platform.gateway import forward
from fusion.tools.sandbox import run

async def reward(task, cand):
    """The reward model's logit for one candidate, from vLLM's pooling route. Higher is better."""
    msgs = [{"role": "user", "content": task.prompt}, {"role": "assistant", "content": cand.text}]
    return (await forward("/pooling", {"model": "reward", "messages": msgs}, "fanout")).json()["data"][0]["data"][0]

def examples(task):
    """A code question's shown examples as asserts: doctest lines, or MBPP's given assert."""
    pairs = re.findall(r">>> (.+)ns*(.+)", task.prompt)
    return [f"assert {call} == {want}" for call, want in pairs] + re.findall(r"^assert .+$", task.prompt, re.M)
"""engine/verifier.py: picks among candidates. Code must pass the question's own examples, then the reward model ranks."""
import asyncio
import re

from fusion.platform.gateway import forward
from fusion.tools.sandbox import run

async def reward(task, cand):
    """The reward model's logit for one candidate, from vLLM's pooling route. Higher is better."""
    msgs = [{"role": "user", "content": task.prompt}, {"role": "assistant", "content": cand.text}]
    return (await forward("/pooling", {"model": "reward", "messages": msgs}, "fanout")).json()["data"][0]["data"][0]

def examples(task):
    """A code question's shown examples as asserts: doctest lines, or MBPP's given assert."""
    pairs = re.findall(r">>> (.+)ns*(.+)", task.prompt)
    return [f"assert {call} == {want}" for call, want in pairs] + re.findall(r"^assert .+$", task.prompt, re.M)

best_of_n keeps the passing candidates and returns the one with the highest logit:

# engine/verifier.py
async def best_of_n(task, cands, tests=True):
    """(candidate, logit). Code that fails a shown example is out, unless every candidate fails."""
    pool = [c for c in cands if c.answer is not None]
    if task.family == "code" and tests:
        pool = [c for c in pool if run(c.answer + "n" + "n".join(examples(task)), timeout=10).ok] or pool
    if not pool:
        return None, float("-inf")
    logits = await asyncio.gather(*[reward(task, c) for c in pool])
    return max(zip(pool, logits), key=lambda x: x[1])
# engine/verifier.py
async def best_of_n(task, cands, tests=True):
    """(candidate, logit). Code that fails a shown example is out, unless every candidate fails."""
    pool = [c for c in cands if c.answer is not None]
    if task.family == "code" and tests:
        pool = [c for c in pool if run(c.answer + "n" + "n".join(examples(task)), timeout=10).ok] or pool
    if not pool:
        return None, float("-inf")
    logits = await asyncio.gather(*[reward(task, c) for c in pool])
    return max(zip(pool, logits), key=lambda x: x[1])

A winner’s vote share overstates how often it is right, so fit maps the share to the measured chance with isotonic regression:

"""engine/calibrate.py: turns the winner's vote share into a calibrated probability."""
import numpy as np
from sklearn.isotonic import IsotonicRegression

ESCAPE = 0.5                                     # below this probability, the question goes to Opus

def fit(share, right):
    return IsotonicRegression(y_min=0, y_max=1, out_of_bounds="clip").fit(share, right)

def ece(p, y, bins=10):
    """Expected calibration error: the gap between confidence and accuracy per bin, weighted by the bin's size."""
    p, y = np.asarray(p, float), np.asarray(y, float)
    b = np.minimum((p * bins).astype(int), bins - 1)
    return float(sum(abs(p[b == k].mean() - y[b == k].mean()) * (b == k).mean() for k in set(b)))
"""engine/calibrate.py: turns the winner's vote share into a calibrated probability."""
import numpy as np
from sklearn.isotonic import IsotonicRegression

ESCAPE = 0.5                                     # below this probability, the question goes to Opus

def fit(share, right):
    return IsotonicRegression(y_min=0, y_max=1, out_of_bounds="clip").fit(share, right)

def ece(p, y, bins=10):
    """Expected calibration error: the gap between confidence and accuracy per bin, weighted by the bin's size."""
    p, y = np.asarray(p, float), np.asarray(y, float)
    b = np.minimum((p * bins).astype(int), bins - 1)
    return float(sum(abs(p[b == k].mean() - y[b == k].mean()) * (b == k).mean() for k in set(b)))

ece averages the gap between confidence and accuracy over bins:

Both ran on dev, with calibration fit on one half and measured on the other:

<button data-code="from fusion.engine.calibrate import ESCAPE, ece, fit
from fusion.engine.verifier import best_of_n

code = [i for i, t in enumerate(dev) if t.family == "code"]
picks = await asyncio.gather(*[best_of_n(dev[i], every[i] + [aggs[i]]) for i in code])
print(f"code with the verifier {pct([check(dev[i], c.answer) for i, (c, _) in zip(code, picks)]):.1f}")
won = [tally(t, cs + [a]) for t, cs, a in zip(dev, every, aggs)]
share, ok = [s.get(w, 0.0) for w, _, s in won], [check(t, w) for t, (w, _, _) in zip(dev, won)]
p = fit(share[::2], ok[::2]).predict(share[1::2])
print(f"ece {ece(share[1::2], ok[1::2]):.3f} raw, {ece(p, ok[1::2]):.3f} calibrated, {pct(p

from fusion.engine.calibrate import ESCAPE, ece, fit
from fusion.engine.verifier import best_of_n

code = [i for i, t in enumerate(dev) if t.family == "code"]
picks = await asyncio.gather(*[best_of_n(dev[i], every[i] + [aggs[i]]) for i in code])
print(f"code with the verifier {pct([check(dev[i], c.answer) for i, (c, _) in zip(code, picks)]):.1f}")
won = [tally(t, cs + [a]) for t, cs, a in zip(dev, every, aggs)]
share, ok = [s.get(w, 0.0) for w, _, s in won], [check(t, w) for t, (w, _, _) in zip(dev, won)]
p = fit(share[::2], ok[::2]).predict(share[1::2])
print(f"ece {ece(share[1::2], ok[1::2]):.3f} raw, {ece(p, ok[1::2]):.3f} calibrated, {pct(p < ESCAPE):.1f}% below {ESCAPE}")

#### OUTPUT ####
code with the verifier 81.0
ece 0.112 raw, 0.021 calibrated, 4.1% below 0.5
from fusion.engine.calibrate import ESCAPE, ece, fit
from fusion.engine.verifier import best_of_n

code = [i for i, t in enumerate(dev) if t.family == "code"]
picks = await asyncio.gather(*[best_of_n(dev[i], every[i] + [aggs[i]]) for i in code])
print(f"code with the verifier {pct([check(dev[i], c.answer) for i, (c, _) in zip(code, picks)]):.1f}")
won = [tally(t, cs + [a]) for t, cs, a in zip(dev, every, aggs)]
share, ok = [s.get(w, 0.0) for w, _, s in won], [check(t, w) for t, (w, _, _) in zip(dev, won)]
p = fit(share[::2], ok[::2]).predict(share[1::2])
print(f"ece {ece(share[1::2], ok[1::2]):.3f} raw, {ece(p, ok[1::2]):.3f} calibrated, {pct(p < ESCAPE):.1f}% below {ESCAPE}")

#### OUTPUT ####
code with the verifier 81.0
ece 0.112 raw, 0.021 calibrated, 4.1% below 0.5

The verifier lifts code by 8.5 points, because most wrong functions fail an example the question already shows. After calibration, confidence matches accuracy within about two points, and the answers below one half are worth sending to Opus.

  • left out: a process reward model (build it when one exists at this size)

Difficulty-Aware Router

Most dev questions never needed sixteen samples. Qwen alone gets about four in five right, and the full engine costs eleven times one greedy call. The router spends that compute only where it buys accuracy:

probe is one greedy Qwen call with log probabilities, whose answer is the first tier’s and whose confidence feeds the router:

"""engine/router.py: decides how much of the engine a question gets, from one cheap probe."""
import numpy as np
from sklearn.linear_model import LogisticRegression

from fusion.engine.pool import PROMPT
from fusion.platform.gateway import forward
from fusion.tools.graders import extract

COST = {1: 0.0004, 2: 0.0021, 3: 0.0045}         # credits per task: probe, 8 samples, everything
LAMBDA = 6.0                                      # the accuracy one credit must buy, from dev

async def probe(task):
    """Qwen's greedy answer with token log probabilities: tier 1's answer and the router's evidence."""
    body = {"model": "qwen", "messages": [{"role": "user", "content": f"{task.prompt}nn{PROMPT[task.family]}"}],
            "temperature": 0.0, "max_tokens": 2048, "logprobs": True}
    choice = (await forward("/v1/chat/completions", body, "probe")).json()["choices"][0]
    lp = [t["logprob"] for t in choice["logprobs"]["content"]]
    answer = extract(task.family, choice["message"]["content"])
    x = [task.family == f for f in ("math", "knowledge", "reasoning", "code")]
    return answer, np.array(x + [len(task.prompt) / 1000, len(lp) / 1000, np.mean(lp), min(lp), answer is None], float)
"""engine/router.py: decides how much of the engine a question gets, from one cheap probe."""
import numpy as np
from sklearn.linear_model import LogisticRegression

from fusion.engine.pool import PROMPT
from fusion.platform.gateway import forward
from fusion.tools.graders import extract

COST = {1: 0.0004, 2: 0.0021, 3: 0.0045}         # credits per task: probe, 8 samples, everything
LAMBDA = 6.0                                      # the accuracy one credit must buy, from dev

async def probe(task):
    """Qwen's greedy answer with token log probabilities: tier 1's answer and the router's evidence."""
    body = {"model": "qwen", "messages": [{"role": "user", "content": f"{task.prompt}nn{PROMPT[task.family]}"}],
            "temperature": 0.0, "max_tokens": 2048, "logprobs": True}
    choice = (await forward("/v1/chat/completions", body, "probe")).json()["choices"][0]
    lp = [t["logprob"] for t in choice["logprobs"]["content"]]
    answer = extract(task.family, choice["message"]["content"])
    x = [task.family == f for f in ("math", "knowledge", "reasoning", "code")]
    return answer, np.array(x + [len(task.prompt) / 1000, len(lp) / 1000, np.mean(lp), min(lp), answer is None], float)

fit learns one logistic model per tier, and route picks the best predicted accuracy after cost:

# engine/router.py
def fit(X, right):
    """One logistic model per tier: P(tier t is right | probe features), fit on dev."""
    return {t: LogisticRegression(max_iter=1000).fit(X, right[t]) for t in COST}

def route(models, x, lam=LAMBDA):
    """The tier with the best predicted accuracy minus lam times its cost."""
    score = {t: m.predict_proba(x[None])[0, 1] - lam * COST[t] for t, m in models.items()}
    return max(score, key=score.get)
# engine/router.py
def fit(X, right):
    """One logistic model per tier: P(tier t is right | probe features), fit on dev."""
    return {t: LogisticRegression(max_iter=1000).fit(X, right[t]) for t in COST}

def route(models, x, lam=LAMBDA):
    """The tier with the best predicted accuracy minus lam times its cost."""
    score = {t: m.predict_proba(x[None])[0, 1] - lam * COST[t] for t, m in models.items()}
    return max(score, key=score.get)

With g a tier’s predicted accuracy, c its cost and lambda the price of accuracy:

Fit on the even dev rows, the router then routed the odd ones:

import numpy as np
from fusion.engine.router import COST, fit, probe, route

probes = await asyncio.gather(*[probe(t) for t in dev])
X = np.array([x for _, x in probes])
final = list(ok)
for i, (c, _) in zip(code, picks):
    final[i] = check(dev[i], c.answer)
tier = {1: right["qwen"], 2: [check(t, tally(t, cs[::2])[0]) for t, cs in zip(dev, every)], 3: final}
models = fit(X[::2], {t: np.array(v)[::2] for t, v in tier.items()})
plan, odd = [route(models, x) for x in X[1::2]], range(1, len(dev), 2)
print(f"routed {pct([tier[p][i] for p, i in zip(plan, odd)]):.1f} at {np.mean([COST[p] for p in plan]):.4f} credits, "
      f"always the full engine {pct(final[1::2]):.1f} at {COST[3]:.4f}")

#### OUTPUT ####
routed 87.9 at 0.0019 credits, always the full engine 88.6 at 0.0045
import numpy as np
from fusion.engine.router import COST, fit, probe, route

probes = await asyncio.gather(*[probe(t) for t in dev])
X = np.array([x for _, x in probes])
final = list(ok)
for i, (c, _) in zip(code, picks):
    final[i] = check(dev[i], c.answer)
tier = {1: right["qwen"], 2: [check(t, tally(t, cs[::2])[0]) for t, cs in zip(dev, every)], 3: final}
models = fit(X[::2], {t: np.array(v)[::2] for t, v in tier.items()})
plan, odd = [route(models, x) for x in X[1::2]], range(1, len(dev), 2)
print(f"routed {pct([tier[p][i] for p, i in zip(plan, odd)]):.1f} at {np.mean([COST[p] for p in plan]):.4f} credits, "
      f"always the full engine {pct(final[1::2]):.1f} at {COST[3]:.4f}")

#### OUTPUT ####
routed 87.9 at 0.0019 credits, always the full engine 88.6 at 0.0045

About half of the questions stop at the probe. The router keeps 99% of the accuracy at 42% of the cost, as H7 predicted.

  • left out: a learned router over many models (build it when traffic spans dozens)

Budget Governor and Telemetry

One runaway question can spend what a hundred easy ones do. The governor caps each task by tier: past the soft cap it starts no new stage, past the hard cap it returns its best answer, flagged:

Each tier’s budget comes from config.py, and one ceiling covers the whole run:

credits charged so far

def charge(self, task_id, tier, tokens):
"""'ok', 'soft' past the tier's budget, or 'hard' past twice that budget or the run's ceiling."""
credits = tokens * PER_TOKEN
self.tasks[task_id] = self.tasks.get(task_id, 0.0) + credits
self.spent += credits
if self.tasks[task_id] > 2 * BUDGET[tier]["credits"] or self.spent > RUN_CREDITS:
return "hard" # return the best answer so far, flagged
return "soft" if self.tasks[task_id] > BUDGET[tier]["credits"] else "ok" # soft: finish, start nothing new” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

"""platform/governor.py: soft and hard caps per task, and a ceiling for the run."""
from dataclasses import dataclass, field

from fusion.config import BUDGET, RUN_CREDITS

PER_TOKEN = 1.9e-6                               # credits per token, fully loaded, from dev

@dataclass
class Governor:
    spent: float = 0.0                           # credits charged across the whole run
    tasks: dict = field(default_factory=dict)    # task id -> credits charged so far

    def charge(self, task_id, tier, tokens):
        """'ok', 'soft' past the tier's budget, or 'hard' past twice that budget or the run's ceiling."""
        credits = tokens * PER_TOKEN
        self.tasks[task_id] = self.tasks.get(task_id, 0.0) + credits
        self.spent += credits
        if self.tasks[task_id] > 2 * BUDGET[tier]["credits"] or self.spent > RUN_CREDITS:
            return "hard"                        # return the best answer so far, flagged
        return "soft" if self.tasks[task_id] > BUDGET[tier]["credits"] else "ok"   # soft: finish, start nothing new
"""platform/governor.py: soft and hard caps per task, and a ceiling for the run."""
from dataclasses import dataclass, field

from fusion.config import BUDGET, RUN_CREDITS

PER_TOKEN = 1.9e-6                               # credits per token, fully loaded, from dev

@dataclass
class Governor:
    spent: float = 0.0                           # credits charged across the whole run
    tasks: dict = field(default_factory=dict)    # task id -> credits charged so far

    def charge(self, task_id, tier, tokens):
        """'ok', 'soft' past the tier's budget, or 'hard' past twice that budget or the run's ceiling."""
        credits = tokens * PER_TOKEN
        self.tasks[task_id] = self.tasks.get(task_id, 0.0) + credits
        self.spent += credits
        if self.tasks[task_id] > 2 * BUDGET[tier]["credits"] or self.spent > RUN_CREDITS:
            return "hard"                        # return the best answer so far, flagged
        return "soft" if self.tasks[task_id] > BUDGET[tier]["credits"] else "ok"   # soft: finish, start nothing new

Telemetry says what a call costs. A call leaves a span, and a run’s rented GPU seconds are shared out over its tasks by the tokens each used:

credits, idle time included. The shares add up to what the fleet cost."""
used = defaultdict(int)
for task_id, _, tokens, _ in SPANS:
used[task_id] += tokens
total, rate = sum(used.values()), CREDITS["l40s_hour"] / 3600
return {task_id: rented_s * rate * n / total for task_id, n in used.items()}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

"""platform/telemetry.py: who used the GPUs, by the tokens each task used."""
from collections import defaultdict

from fusion.config import CREDITS

SPANS = []                                       # (task id, model, tokens, seconds) per call

def record(task_id, cand):
    SPANS.append((task_id, cand.model, cand.tokens, cand.seconds))

def attribute(rented_s):
    """task id -> credits, idle time included. The shares add up to what the fleet cost."""
    used = defaultdict(int)
    for task_id, _, tokens, _ in SPANS:
        used[task_id] += tokens
    total, rate = sum(used.values()), CREDITS["l40s_hour"] / 3600
    return {task_id: rented_s * rate * n / total for task_id, n in used.items()}
"""platform/telemetry.py: who used the GPUs, by the tokens each task used."""
from collections import defaultdict

from fusion.config import CREDITS

SPANS = []                                       # (task id, model, tokens, seconds) per call

def record(task_id, cand):
    SPANS.append((task_id, cand.model, cand.tokens, cand.seconds))

def attribute(rented_s):
    """task id -> credits, idle time included. The shares add up to what the fleet cost."""
    used = defaultdict(int)
    for task_id, _, tokens, _ in SPANS:
        used[task_id] += tokens
    total, rate = sum(used.values()), CREDITS["l40s_hour"] / 3600
    return {task_id: rented_s * rate * n / total for task_id, n in used.items()}

These fully loaded shares always add up to what the fleet cost:

  • left out: per-team budgets (build it when other teams share the endpoint)

System Orchestrator

All of the parts meet in solve, which takes a task through the probe and the router, then samples, aggregates, votes or verifies as its tier allows:

The engine has the router, the calibrator and a governor, with the escape hatch and the episode store off by default:

"""serve_app/orchestrator.py: the whole team behind one OpenAI-compatible model name, fusion-4x3b."""
import asyncio
import time
from dataclasses import replace

from fastapi import FastAPI, Request

from fusion.data import Task
from fusion.engine.moa import moa
from fusion.engine.router import probe, route
from fusion.engine.sampler import sample
from fusion.engine.verifier import best_of_n
from fusion.engine.pool import POOL
from fusion.engine.vote import WEIGHT, tally
from fusion.platform import episodes, gateway
from fusion.platform.governor import Governor
from fusion.tools import frontier
from fusion.tools.retrieval import augment

class FusionEngine:
    def __init__(self, router, calibrator, escape=0.0, store=False, off=()):    # escape: a threshold, 0 is off
        self.router, self.cal, self.escape, self.store, self.gov = router, calibrator, escape, store, Governor()
        self.off = set(off)                      # parts switched off for one ablation row
"""serve_app/orchestrator.py: the whole team behind one OpenAI-compatible model name, fusion-4x3b."""
import asyncio
import time
from dataclasses import replace

from fastapi import FastAPI, Request

from fusion.data import Task
from fusion.engine.moa import moa
from fusion.engine.router import probe, route
from fusion.engine.sampler import sample
from fusion.engine.verifier import best_of_n
from fusion.engine.pool import POOL
from fusion.engine.vote import WEIGHT, tally
from fusion.platform import episodes, gateway
from fusion.platform.governor import Governor
from fusion.tools import frontier
from fusion.tools.retrieval import augment

class FusionEngine:
    def __init__(self, router, calibrator, escape=0.0, store=False, off=()):    # escape: a threshold, 0 is off
        self.router, self.cal, self.escape, self.store, self.gov = router, calibrator, escape, store, Governor()
        self.off = set(off)                      # parts switched off for one ablation row

solve is the whole request path:

1:
pal = 2 if tier == 3 and task.family == "math" and "pot" not in self.off else 0
cands = await sample(task, 2 if tier == 2 else 4, pal, ["qwen"] * 4 if "diversity" in self.off else POOL)
trace["governor"] = self.gov.charge(task.id, tier, sum(c.tokens for c in cands))
if tier == 3 and trace["governor"] == "ok" and "moa" not in self.off:
cands.append(await moa(task, cands))
answer, margin, shares = tally(task, cands, dict.fromkeys(WEIGHT, 1.0) if "weights" in self.off else WEIGHT)
if task.family == "code" or margin < 0.3: # split votes and all code go to the verifier
pick, _ = await best_of_n(task, cands, tests="tests" not in self.off)
answer = pick.answer if pick else answer
p = float(self.cal.predict([shares.get(answer, 0.0)])[0])
if self.store:
episodes.add(task, cands)
if p < self.escape: # the escape hatch: Opus answers instead
answer = frontier.score(task, (await asyncio.to_thread(frontier.live, task))[0])[0]
return answer, trace | {"confidence": round(p, 3), "escalated": p

# serve_app/orchestrator.py
    async def solve(self, task):
        """(answer, trace): probe, route, sample, aggregate, vote or verify, then a calibrated confidence."""
        if task.family == "knowledge" and "retrieval" not in self.off:
            task = replace(task, prompt=augment(task))
        answer, x = await probe(task)
        tier = 3 if "router" in self.off else route(self.router, x)
        p, trace = float(self.router[1].predict_proba(x[None])[0, 1]), {"tier": tier}
        if tier > 1:
            pal = 2 if tier == 3 and task.family == "math" and "pot" not in self.off else 0
            cands = await sample(task, 2 if tier == 2 else 4, pal, ["qwen"] * 4 if "diversity" in self.off else POOL)
            trace["governor"] = self.gov.charge(task.id, tier, sum(c.tokens for c in cands))
            if tier == 3 and trace["governor"] == "ok" and "moa" not in self.off:
                cands.append(await moa(task, cands))
            answer, margin, shares = tally(task, cands, dict.fromkeys(WEIGHT, 1.0) if "weights" in self.off else WEIGHT)
            if task.family == "code" or margin < 0.3:            # split votes and all code go to the verifier
                pick, _ = await best_of_n(task, cands, tests="tests" not in self.off)
                answer = pick.answer if pick else answer
            p = float(self.cal.predict([shares.get(answer, 0.0)])[0])
            if self.store:
                episodes.add(task, cands)
        if p < self.escape:                                      # the escape hatch: Opus answers instead
            answer = frontier.score(task, (await asyncio.to_thread(frontier.live, task))[0])[0]
        return answer, trace | {"confidence": round(p, 3), "escalated": p < self.escape}
# serve_app/orchestrator.py
    async def solve(self, task):
        """(answer, trace): probe, route, sample, aggregate, vote or verify, then a calibrated confidence."""
        if task.family == "knowledge" and "retrieval" not in self.off:
            task = replace(task, prompt=augment(task))
        answer, x = await probe(task)
        tier = 3 if "router" in self.off else route(self.router, x)
        p, trace = float(self.router[1].predict_proba(x[None])[0, 1]), {"tier": tier}
        if tier > 1:
            pal = 2 if tier == 3 and task.family == "math" and "pot" not in self.off else 0
            cands = await sample(task, 2 if tier == 2 else 4, pal, ["qwen"] * 4 if "diversity" in self.off else POOL)
            trace["governor"] = self.gov.charge(task.id, tier, sum(c.tokens for c in cands))
            if tier == 3 and trace["governor"] == "ok" and "moa" not in self.off:
                cands.append(await moa(task, cands))
            answer, margin, shares = tally(task, cands, dict.fromkeys(WEIGHT, 1.0) if "weights" in self.off else WEIGHT)
            if task.family == "code" or margin < 0.3:            # split votes and all code go to the verifier
                pick, _ = await best_of_n(task, cands, tests="tests" not in self.off)
                answer = pick.answer if pick else answer
            p = float(self.cal.predict([shares.get(answer, 0.0)])[0])
            if self.store:
                episodes.add(task, cands)
        if p < self.escape:                                      # the escape hatch: Opus answers instead
            answer = frontier.score(task, (await asyncio.to_thread(frontier.live, task))[0])[0]
        return answer, trace | {"confidence": round(p, 3), "escalated": p < self.escape}

run_stream caps the tasks in flight, and chat serves the team as one model on its own port:

# serve_app/orchestrator.py
    async def run_stream(self, tasks, width=64):
        """Many tasks, at most width in flight. The training pass and the sealed run use this."""
        gate = asyncio.Semaphore(width)
        async def one(t):
            async with gate:
                return await self.solve(t)
        return await asyncio.gather(*map(one, tasks))

API, ENGINE = FastAPI(), None                    # the public door, on its own port

@API.post("/v1/chat/completions")
async def chat(request: Request):
    """OpenAI-compatible: messages in, an answer and a fusion block out."""
    body = await request.json()
    task = Task(f"api/{time.time_ns()}", "api", body.get("family", "reasoning"), body["messages"][-1]["content"], "")
    answer, trace = await ENGINE.solve(task)
    return {"id": task.id, "object": "chat.completion", "created": int(time.time()), "model": "fusion-4x3b",
            "choices": [{"index": 0, "message": {"role": "assistant", "content": answer}, "finish_reason": "stop"}],
            "fusion": trace}
# serve_app/orchestrator.py
    async def run_stream(self, tasks, width=64):
        """Many tasks, at most width in flight. The training pass and the sealed run use this."""
        gate = asyncio.Semaphore(width)
        async def one(t):
            async with gate:
                return await self.solve(t)
        return await asyncio.gather(*map(one, tasks))

API, ENGINE = FastAPI(), None                    # the public door, on its own port

@API.post("/v1/chat/completions")
async def chat(request: Request):
    """OpenAI-compatible: messages in, an answer and a fusion block out."""
    body = await request.json()
    task = Task(f"api/{time.time_ns()}", "api", body.get("family", "reasoning"), body["messages"][-1]["content"], "")
    answer, trace = await ENGINE.solve(task)
    return {"id": task.id, "object": "chat.completion", "created": int(time.time()), "model": "fusion-4x3b",
            "choices": [{"index": 0, "message": {"role": "assistant", "content": answer}, "finish_reason": "stop"}],
            "fusion": trace}

lifecycle keeps the gateway in step with the fleet, scales it and releases it after ten quiet minutes:

quiet_after
rec.tick({m: 0 for m in want} | {"standby": 0} if quiet else want | {"standby": 1},
idle=lambda v: not any(r.inflight for r in gateway.REPLICAS.get(v.model, []) if v.ip in r.url))
await asyncio.sleep(every)” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# serve_app/orchestrator.py
async def lifecycle(rec, scaler, every=15, quiet_after=600):
    """The control loop: sync the gateway, scale on waiting calls, release everything after ten quiet minutes."""
    last_busy = time.time()
    while True:
        rec.refresh()
        gateway.sync(rec.vms)
        now = time.time()
        if any(gateway.WAITING.values()) or any(r.inflight for rs in gateway.REPLICAS.values() for r in rs):
            last_busy = now
        want = {m: scaler.desired(m, max(len(rs), 1), gateway.WAITING[m], now) for m, rs in gateway.REPLICAS.items()}
        quiet = now - last_busy > quiet_after
        rec.tick({m: 0 for m in want} | {"standby": 0} if quiet else want | {"standby": 1},
                 idle=lambda v: not any(r.inflight for r in gateway.REPLICAS.get(v.model, []) if v.ip in r.url))
        await asyncio.sleep(every)
# serve_app/orchestrator.py
async def lifecycle(rec, scaler, every=15, quiet_after=600):
    """The control loop: sync the gateway, scale on waiting calls, release everything after ten quiet minutes."""
    last_busy = time.time()
    while True:
        rec.refresh()
        gateway.sync(rec.vms)
        now = time.time()
        if any(gateway.WAITING.values()) or any(r.inflight for rs in gateway.REPLICAS.values() for r in rs):
            last_busy = now
        want = {m: scaler.desired(m, max(len(rs), 1), gateway.WAITING[m], now) for m, rs in gateway.REPLICAS.items()}
        quiet = now - last_busy > quiet_after
        rec.tick({m: 0 for m in want} | {"standby": 0} if quiet else want | {"standby": 1},
                 idle=lambda v: not any(r.inflight for r in gateway.REPLICAS.get(v.model, []) if v.ip in r.url))
        await asyncio.sleep(every)

The OpenAI client now calls the team like any hosted model:

import uvicorn
from openai import AsyncOpenAI
from fusion.engine.calibrate import fit as fit_calibrator
from fusion.serve_app import orchestrator

orchestrator.ENGINE = orchestrator.FusionEngine(models, fit_calibrator(share, ok))
asyncio.create_task(uvicorn.Server(uvicorn.Config(orchestrator.API, port=8080)).serve())
client = AsyncOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
r = await client.chat.completions.create(model="fusion-4x3b", extra_body={"family": "math"},
                                         messages=[{"role": "user", "content": dev[412].prompt}])
print(r.choices[0].message.content, r.model_extra["fusion"])

#### OUTPUT ####
frac{14}{3} {'tier': 3, 'governor': 'ok', 'confidence': 0.912, 'escalated': False}
import uvicorn
from openai import AsyncOpenAI
from fusion.engine.calibrate import fit as fit_calibrator
from fusion.serve_app import orchestrator

orchestrator.ENGINE = orchestrator.FusionEngine(models, fit_calibrator(share, ok))
asyncio.create_task(uvicorn.Server(uvicorn.Config(orchestrator.API, port=8080)).serve())
client = AsyncOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
r = await client.chat.completions.create(model="fusion-4x3b", extra_body={"family": "math"},
                                         messages=[{"role": "user", "content": dev[412].prompt}])
print(r.choices[0].message.content, r.model_extra["fusion"])

#### OUTPUT ####
frac{14}{3} {'tier': 3, 'governor': 'ok', 'confidence': 0.912, 'escalated': False}

The hard MATH question from the sampling section went to the third tier and came back right, confident enough to keep Opus out. The server runs in the notebook’s event loop, which owns the gateway’s connections.

  • left out: streaming answers (build it when a UI waits on the endpoint)

Self-Improvement Loop

Llama-3.2–3B and Gemma are the weakest members, and their own answers can teach them. Where a model was both right and wrong on one question, DPO learns to prefer the right reply:

The pairs come from an episode store. add keeps every graded candidate and refuses a sealed task before anything is written:

"""platform/episodes.py: every graded candidate, kept for training. A sealed task is refused at the door."""
import json
import sqlite3

from fusion.config import DATA, SEED
from fusion.tools.graders import check

SEALED = set(json.loads((DATA / f"sealed_manifest_seed{SEED}.json").read_text())["ids"])
DB = sqlite3.connect(DATA / "episodes.db")
DB.execute("CREATE TABLE IF NOT EXISTS ep (task TEXT, prompt TEXT, model TEXT, answer TEXT, ok INT, reply TEXT)")

def add(task, cands):
    if task.id in SEALED:                        # the seal guard
        raise PermissionError(f"{task.id} is sealed")
    DB.executemany("INSERT INTO ep VALUES (?, ?, ?, ?, ?, ?)",
                   [(task.id, task.prompt, c.model, c.answer, int(check(task, c.answer)), c.text) for c in cands])
    DB.commit()
"""platform/episodes.py: every graded candidate, kept for training. A sealed task is refused at the door."""
import json
import sqlite3

from fusion.config import DATA, SEED
from fusion.tools.graders import check

SEALED = set(json.loads((DATA / f"sealed_manifest_seed{SEED}.json").read_text())["ids"])
DB = sqlite3.connect(DATA / "episodes.db")
DB.execute("CREATE TABLE IF NOT EXISTS ep (task TEXT, prompt TEXT, model TEXT, answer TEXT, ok INT, reply TEXT)")

def add(task, cands):
    if task.id in SEALED:                        # the seal guard
        raise PermissionError(f"{task.id} is sealed")
    DB.executemany("INSERT INTO ep VALUES (?, ?, ?, ?, ?, ?)",
                   [(task.id, task.prompt, c.model, c.answer, int(check(task, c.answer)), c.text) for c in cands])
    DB.commit()

mine_pairs builds the pairs for one model, with its own replies on both sides:

"""learn/improve.py: DPO on the team's own answers, as a LoRA adapter hot-loaded into vLLM."""
import httpx
from datasets import Dataset
from peft import LoraConfig
from trl import DPOConfig, DPOTrainer

from fusion.config import GATEWAY_KEY, MODELS
from fusion.platform import gateway
from fusion.platform.episodes import DB

PAIRS = """SELECT a.prompt, a.reply, b.reply FROM ep a JOIN ep b ON a.task = b.task AND a.model = b.model
           WHERE a.model = ? AND a.ok = 1 AND b.ok = 0 GROUP BY a.task"""     # one right and one wrong reply per task

def mine_pairs(model):
    """Tasks where this model was both right and wrong, with its own replies on both sides."""
    turn = lambda role, text: [{"role": role, "content": text}]
    return Dataset.from_list([{"prompt": turn("user", p), "chosen": turn("assistant", c), "rejected": turn("assistant", r)}
                              for p, c, r in DB.execute(PAIRS, (model,))])
"""learn/improve.py: DPO on the team's own answers, as a LoRA adapter hot-loaded into vLLM."""
import httpx
from datasets import Dataset
from peft import LoraConfig
from trl import DPOConfig, DPOTrainer

from fusion.config import GATEWAY_KEY, MODELS
from fusion.platform import gateway
from fusion.platform.episodes import DB

PAIRS = """SELECT a.prompt, a.reply, b.reply FROM ep a JOIN ep b ON a.task = b.task AND a.model = b.model
           WHERE a.model = ? AND a.ok = 1 AND b.ok = 0 GROUP BY a.task"""     # one right and one wrong reply per task

def mine_pairs(model):
    """Tasks where this model was both right and wrong, with its own replies on both sides."""
    turn = lambda role, text: [{"role": role, "content": text}]
    return Dataset.from_list([{"prompt": turn("user", p), "chosen": turn("assistant", c), "rejected": turn("assistant", r)}
                              for p, c, r in DB.execute(PAIRS, (model,))])

train runs TRL’s DPO with an NLL term on the chosen replies, the RPO variant, as a LoRA adapter on the training VM:

# learn/improve.py
def train(model, pairs):
    """DPO plus an NLL term (rpo_alpha), LoRA rank 16, on the training VM. Returns the hub id."""
    args = DPOConfig(output_dir=f"{model}-dpo", beta=0.1, rpo_alpha=1.0, learning_rate=5e-6, num_train_epochs=2,
                     per_device_train_batch_size=4, gradient_accumulation_steps=8, bf16=True,
                     push_to_hub=True, hub_private_repo=True)
    lora = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM")
    trainer = DPOTrainer(model=MODELS[model].id, args=args, train_dataset=pairs, peft_config=lora)
    trainer.train()
    trainer.push_to_hub()
    return trainer.hub_model_id
# learn/improve.py
def train(model, pairs):
    """DPO plus an NLL term (rpo_alpha), LoRA rank 16, on the training VM. Returns the hub id."""
    args = DPOConfig(output_dir=f"{model}-dpo", beta=0.1, rpo_alpha=1.0, learning_rate=5e-6, num_train_epochs=2,
                     per_device_train_batch_size=4, gradient_accumulation_steps=8, bf16=True,
                     push_to_hub=True, hub_private_repo=True)
    lora = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM")
    trainer = DPOTrainer(model=MODELS[model].id, args=args, train_dataset=pairs, peft_config=lora)
    trainer.train()
    trainer.push_to_hub()
    return trainer.hub_model_id

The loss lifts the chosen reply’s log ratio above the rejected one’s, and the NLL term keeps the chosen reply likely:

hot_load loads an adapter into every running replica and points the gateway at it, with no restart:

# learn/improve.py
def hot_load(model, repo):
    """Load the adapter into every running replica, then point the gateway at it. Nothing restarts."""
    for r in gateway.REPLICAS[model]:
        httpx.post(f"{r.url}/v1/load_lora_adapter", json={"lora_name": f"{model}-dpo", "lora_path": repo},
                   headers={"Authorization": f"Bearer {GATEWAY_KEY}"}, timeout=300).raise_for_status()
    gateway.ADAPTER[model] = f"{model}-dpo"
# learn/improve.py
def hot_load(model, repo):
    """Load the adapter into every running replica, then point the gateway at it. Nothing restarts."""
    for r in gateway.REPLICAS[model]:
        httpx.post(f"{r.url}/v1/load_lora_adapter", json={"lora_name": f"{model}-dpo", "lora_path": repo},
                   headers={"Authorization": f"Bearer {GATEWAY_KEY}"}, timeout=300).raise_for_status()
    gateway.ADAPTER[model] = f"{model}-dpo"

On Friday night the engine answered the training tasks with the store turned on:

from fusion.platform import episodes

orchestrator.ENGINE.store = True
await orchestrator.ENGINE.run_stream(train)
print(episodes.DB.execute("SELECT COUNT(*), SUM(ok), COUNT(DISTINCT task) FROM ep").fetchone())

#### OUTPUT ####
(61744, 44187, 4412)
from fusion.platform import episodes

orchestrator.ENGINE.store = True
await orchestrator.ENGINE.run_stream(train)
print(episodes.DB.execute("SELECT COUNT(*), SUM(ok), COUNT(DISTINCT task) FROM ep").fetchone())

#### OUTPUT ####
(61744, 44187, 4412)

Only questions routed past the probe produce candidates. Seven in ten stored candidates are right, and the rest give DPO its rejected replies.

I copied the store to the training VM, ran train for both models, then loaded the adapters and asked the dev set again:

<button data-code="from fusion.learn.improve import hot_load, mine_pairs

for m in ("llama", "gemma"):
hot_load(m, f"fusion-team/{m}-dpo")
after = await asyncio.gather(*[ask(m, t, lane="batch") for t in dev])
print(f"{m: {pct([check(t, c.answer) for t, c in zip(dev, after)]):.1f}")

#### OUTPUT ####
llama 2,311 pairs dev 60.7 -> 65.8
gemma 2,047 pairs dev 64.4 -> 68.7″ data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

from fusion.learn.improve import hot_load, mine_pairs

for m in ("llama", "gemma"):
    hot_load(m, f"fusion-team/{m}-dpo")
    after = await asyncio.gather(*[ask(m, t, lane="batch") for t in dev])
    print(f"{m:<6} {len(mine_pairs(m)):,} pairs   dev {pct(right[m]):.1f} -> {pct([check(t, c.answer) for t, c in zip(dev, after)]):.1f}")

#### OUTPUT ####
llama  2,311 pairs   dev 60.7 -> 65.8
gemma  2,047 pairs   dev 64.4 -> 68.7
from fusion.learn.improve import hot_load, mine_pairs

for m in ("llama", "gemma"):
    hot_load(m, f"fusion-team/{m}-dpo")
    after = await asyncio.gather(*[ask(m, t, lane="batch") for t in dev])
    print(f"{m:<6} {len(mine_pairs(m)):,} pairs   dev {pct(right[m]):.1f} -> {pct([check(t, c.answer) for t, c in zip(dev, after)]):.1f}")

#### OUTPUT ####
llama  2,311 pairs   dev 60.7 -> 65.8
gemma  2,047 pairs   dev 64.4 -> 68.7

DPO lifted Llama by 5.1 points and Gemma by 4.3 on dev, from pairs the team made itself. Later runs use the adapters, because the gateway now answers llama and gemma with them:

  • left out: online RL such as GRPO (build it when the store stops yielding pairs)

Evaluation Harness

Nothing in the engine saw a sealed task before Saturday. The harness grades the arms on the same sealed tasks:

grade logs each read of the seal, and interval resamples whole subjects, because questions from one subject are not independent:

"""eval/harness.py: the sealed run, every arm on the same tasks, every number with an interval."""
import numpy as np
from scipy.stats import binomtest

from fusion.config import SEED
from fusion.tools.graders import check

ACCESS = []                                      # (arm, task id) per sealed read

def grade(arm, tasks, answers):
    """1 or 0 per task for one arm, with every read of the seal logged."""
    ACCESS.extend((arm, t.id) for t in tasks)
    return np.array([check(t, a) for t, a in zip(tasks, answers)], float)

def interval(right, groups, reps=10000, seed=SEED):
    """A 95% bootstrap interval that resamples whole groups, such as MMLU subjects."""
    rng, ids = np.random.default_rng(seed), sorted(set(groups))
    by = {g: right[[i for i, x in enumerate(groups) if x == g]] for g in ids}
    means = [np.concatenate([by[g] for g in rng.choice(ids, len(ids))]).mean() for _ in range(reps)]
    return np.percentile(means, [2.5, 97.5])
"""eval/harness.py: the sealed run, every arm on the same tasks, every number with an interval."""
import numpy as np
from scipy.stats import binomtest

from fusion.config import SEED
from fusion.tools.graders import check

ACCESS = []                                      # (arm, task id) per sealed read

def grade(arm, tasks, answers):
    """1 or 0 per task for one arm, with every read of the seal logged."""
    ACCESS.extend((arm, t.id) for t in tasks)
    return np.array([check(t, a) for t, a in zip(tasks, answers)], float)

def interval(right, groups, reps=10000, seed=SEED):
    """A 95% bootstrap interval that resamples whole groups, such as MMLU subjects."""
    rng, ids = np.random.default_rng(seed), sorted(set(groups))
    by = {g: right[[i for i, x in enumerate(groups) if x == g]] for g in ids}
    means = [np.concatenate([by[g] for g in rng.choice(ids, len(ids))]).mean() for _ in range(reps)]
    return np.percentile(means, [2.5, 97.5])

mcnemar compares two arms task by task, because both answered the same questions:

It is a binomial test with a fair coin, and gap_closed is the rule from the diagnosis:

# eval/harness.py
def mcnemar(a, b):
    """Exact McNemar p value for two arms, from the tasks where they disagree."""
    n01, n10 = int(((a == 1) & (b == 0)).sum()), int(((a == 0) & (b == 1)).sum())
    return binomtest(n01, n01 + n10).pvalue if n01 + n10 else 1.0

def gap_closed(single, fused, frontier):
    return (fused - single) / (frontier - single)
# eval/harness.py
def mcnemar(a, b):
    """Exact McNemar p value for two arms, from the tasks where they disagree."""
    n01, n10 = int(((a == 1) & (b == 0)).sum()), int(((a == 0) & (b == 1)).sum())
    return binomtest(n01, n01 + n10).pvalue if n01 + n10 else 1.0

def gap_closed(single, fused, frontier):
    return (fused - single) / (frontier - single)

On Saturday four arms took the paired tasks, Opus in one batch:

from fusion.eval.harness import ACCESS, gap_closed, grade, interval

BENCHES = ["gsm8k", "math500", "mmlu", "humaneval_plus", "mbpp_plus", "bbh"]
paired = [t for b in BENCHES for t in [t for t in sealed if t.bench == b][:400]]
runs = {"best_single": [a for a, _ in await asyncio.gather(*map(probe, paired))],
        "fused_dpo": [a for a, _ in await orchestrator.ENGINE.run_stream(paired)]}
gateway.ADAPTER.clear()
runs["fused"] = [a for a, _ in await orchestrator.ENGINE.run_stream(paired)]
opus = batch(paired)
runs["opus"] = [score(t, opus[t.id])[0] if opus[t.id] else None for t in paired]
graded = {arm: grade(arm, paired, answers) for arm, answers in runs.items()}
print(f"{len(paired):,} paired tasks, {len(ACCESS):,} reads logged, opus refusals "
      f"{sum(m is not None and m.stop_reason == 'refusal' for m in opus.values())}")

#### OUTPUT ####
2,142 paired tasks, 8,568 reads logged, opus refusals 0
from fusion.eval.harness import ACCESS, gap_closed, grade, interval

BENCHES = ["gsm8k", "math500", "mmlu", "humaneval_plus", "mbpp_plus", "bbh"]
paired = [t for b in BENCHES for t in [t for t in sealed if t.bench == b][:400]]
runs = {"best_single": [a for a, _ in await asyncio.gather(*map(probe, paired))],
        "fused_dpo": [a for a, _ in await orchestrator.ENGINE.run_stream(paired)]}
gateway.ADAPTER.clear()
runs["fused"] = [a for a, _ in await orchestrator.ENGINE.run_stream(paired)]
opus = batch(paired)
runs["opus"] = [score(t, opus[t.id])[0] if opus[t.id] else None for t in paired]
graded = {arm: grade(arm, paired, answers) for arm, answers in runs.items()}
print(f"{len(paired):,} paired tasks, {len(ACCESS):,} reads logged, opus refusals "
      f"{sum(m is not None and m.stop_reason == 'refusal' for m in opus.values())}")

#### OUTPUT ####
2,142 paired tasks, 8,568 reads logged, opus refusals 0

Every Opus request came back, with no refusal to score as wrong. The fleet peaked at 8 VMs and was gone ten minutes after the last call.

  • left out: human preference ratings (build it when answers are not checkable)

Accuracy Against Spend

On the paired sealed tasks, the team with its DPO adapters is 1.8 points below Opus on the six-benchmark mean and closes most of the gap from Qwen alone:

<button data-code="acc = {a: {b: 100 * r[[t.bench == b for t in paired]].mean() for b in BENCHES} for a, r in graded.items()}
for a in acc:
acc[a]["mean"] = np.mean([acc[a][b] for b in BENCHES])
ARMS = ("best_single", "fused", "fused_dpo", "opus")
print(f"{'':12}" for a in ARMS) + " gap closed")
for b in BENCHES + ["mean"]:
row = [acc[a][b] for a in ARMS]
print(f"{b:

acc = {a: {b: 100 * r[[t.bench == b for t in paired]].mean() for b in BENCHES} for a, r in graded.items()}
for a in acc:
    acc[a]["mean"] = np.mean([acc[a][b] for b in BENCHES])
ARMS = ("best_single", "fused", "fused_dpo", "opus")
print(f"{'':<15}" + "".join(f"{a:>12}" for a in ARMS) + "   gap closed")
for b in BENCHES + ["mean"]:
    row = [acc[a][b] for a in ARMS]
    print(f"{b:<15}" + "".join(f"{x:12.1f}" for x in row) + f"   {gap_closed(row[0], row[2], row[3]):10.2f}")

#### OUTPUT ####
                best_single       fused   fused_dpo        opus   gap closed
gsm8k                  92.0        96.5        96.8        97.0         0.95
math500                79.5        92.2        92.8        95.8         0.82
mmlu                   74.2        85.8        86.2        91.2         0.71
humaneval_plus         78.7        92.1        92.7        92.7         1.00
mbpp_plus              70.1        81.0        81.2        81.5         0.98
bbh                    76.8        90.5        91.0        93.5         0.85
mean                   78.5        89.7        90.1        91.9         0.86
acc = {a: {b: 100 * r[[t.bench == b for t in paired]].mean() for b in BENCHES} for a, r in graded.items()}
for a in acc:
    acc[a]["mean"] = np.mean([acc[a][b] for b in BENCHES])
ARMS = ("best_single", "fused", "fused_dpo", "opus")
print(f"{'':<15}" + "".join(f"{a:>12}" for a in ARMS) + "   gap closed")
for b in BENCHES + ["mean"]:
    row = [acc[a][b] for a in ARMS]
    print(f"{b:<15}" + "".join(f"{x:12.1f}" for x in row) + f"   {gap_closed(row[0], row[2], row[3]):10.2f}")

#### OUTPUT ####
                best_single       fused   fused_dpo        opus   gap closed
gsm8k                  92.0        96.5        96.8        97.0         0.95
math500                79.5        92.2        92.8        95.8         0.82
mmlu                   74.2        85.8        86.2        91.2         0.71
humaneval_plus         78.7        92.1        92.7        92.7         1.00
mbpp_plus              70.1        81.0        81.2        81.5         0.98
bbh                    76.8        90.5        91.0        93.5         0.85
mean                   78.5        89.7        90.1        91.9         0.86

The code gap almost closes, because tests and the reward model find a right function when one exists. MMLU keeps the widest gap, as the pilot predicted.

Each benchmark with its 95% interval from resampling whole subjects:

Leaving out MMLU, where facts are missing, the team trails Opus by 1.4 points on the other five, and the whole 90% interval of that gap is inside a 2 point margin:

By a two one-sided test the team rivals Opus, though Opus is still measurably ahead.

Per task, the team cost 0.001558 credits fully loaded against 0.03389 for Opus, 21.8x cheaper:

The team was also faster: 3.6 s against 8.7 s at the median, 19.7 s against 24.0 s at p95.

With the escape hatch on, the 4.1% of tasks with a calibrated confidence below one half went to Opus. The mean rose to 91.1, under a point from Opus, at 11.6x lower cost.

Ablation Study

Switching off one part at a time, I reran the paired tasks, with the result cache replaying every unchanged sample:

<button data-code="macro = lambda r: np.mean([r[[t.bench == b for t in paired]].mean() for b in BENCHES])
ref = orchestrator.FusionEngine(models, orchestrator.ENGINE.cal)
base = macro(grade("full", paired, [a for a, _ in await ref.run_stream(paired)]))
for row in ("router", "diversity", "pot", "retrieval", "moa", "weights", "tests", "dpo"):
if row == "dpo":
gateway.ADAPTER.clear()
engine = orchestrator.FusionEngine(models, orchestrator.ENGINE.cal, off={row})
out = macro(grade(row, paired, [a for a, _ in await engine.run_stream(paired)]))
print(f"{row:

macro = lambda r: np.mean([r[[t.bench == b for t in paired]].mean() for b in BENCHES])
ref = orchestrator.FusionEngine(models, orchestrator.ENGINE.cal)
base = macro(grade("full", paired, [a for a, _ in await ref.run_stream(paired)]))
for row in ("router", "diversity", "pot", "retrieval", "moa", "weights", "tests", "dpo"):
    if row == "dpo":
        gateway.ADAPTER.clear()
    engine = orchestrator.FusionEngine(models, orchestrator.ENGINE.cal, off={row})
    out = macro(grade(row, paired, [a for a, _ in await engine.run_stream(paired)]))
    print(f"{row:<10} {100 * (out - base):+6.2f} points {engine.gov.spent / ref.gov.spent:5.2f}x credits")

#### OUTPUT ####
router      -0.21 points  2.40x credits
diversity   -1.73 points  1.03x credits
pot         -0.88 points  1.08x credits
retrieval   -1.21 points  0.95x credits
moa         -0.59 points  0.91x credits
weights     -0.40 points  1.00x credits
tests       -1.82 points  1.05x credits
dpo         -0.44 points  1.22x credits
macro = lambda r: np.mean([r[[t.bench == b for t in paired]].mean() for b in BENCHES])
ref = orchestrator.FusionEngine(models, orchestrator.ENGINE.cal)
base = macro(grade("full", paired, [a for a, _ in await ref.run_stream(paired)]))
for row in ("router", "diversity", "pot", "retrieval", "moa", "weights", "tests", "dpo"):
    if row == "dpo":
        gateway.ADAPTER.clear()
    engine = orchestrator.FusionEngine(models, orchestrator.ENGINE.cal, off={row})
    out = macro(grade(row, paired, [a for a, _ in await engine.run_stream(paired)]))
    print(f"{row:<10} {100 * (out - base):+6.2f} points {engine.gov.spent / ref.gov.spent:5.2f}x credits")

#### OUTPUT ####
router      -0.21 points  2.40x credits
diversity   -1.73 points  1.03x credits
pot         -0.88 points  1.08x credits
retrieval   -1.21 points  0.95x credits
moa         -0.59 points  0.91x credits
weights     -0.40 points  1.00x credits
tests       -1.82 points  1.05x credits
dpo         -0.44 points  1.22x credits

The verifier’s tests and the pool’s diversity carry the most accuracy, and sixteen Qwen samples lose to four from each lab. The router costs almost no accuracy and saves more than half the spend:

Claim Verdicts and Known Limits

Five predictions held, and three held only in part: the aggregator, the weighted vote and DPO each helped, but their sealed intervals include zero:

Knowledge stays the weakest family. Escalations lift the p95 latency, and the reward model is built on Llama, which can favour Llama. Opus may have seen these benchmarks in training, the numbers come from one seed, and Opus ran at one effort level.

The whole study used 186 L40S VM hours for 160 credits and 54 credits of Opus. The code is in the repository.