> ## Documentation Index
> Fetch the complete documentation index at: https://benchgen.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# BenchGen Router Lite

> The full story of BenchGen Router Lite: a lightweight routing model that learns which language model should answer each query, instead of sending every query to the same one.

Not every query needs the same model. A frontier-class model is expensive and often overkill for
an easy question, and a cheap model quietly fails on a hard one. The usual answer is to pick one
model for everything, or to hand-write routing rules. **BenchGen Router Lite** takes a different
approach, similar in spirit to Sakana AI's work on model routing: train a small, dedicated router
that learns, from measured evidence rather than guesses, which model in a pool is the right one for
a given query.

The router itself never generates an answer. It looks at a query, picks the best pool member for
it, and that pool member's real reply is what comes back. This guide tells the complete story of
how BenchGen Router Lite was built: the dataset it learned from, how it was trained, and how it was
benchmarked. On [Router Fidelity Benchmark](https://benchgen.com/benchmarks/platform/router-fidelity-benchmark),
the trained router scored **82.6%**, more accurate than calling its own strongest pool member for
every single question, at **roughly 3.1x lower cost**. The full breakdown is in
[Benchmark](#3-benchmark) below.

![Diagram of one query moving through BenchGen Router Lite: the frozen backbone embeds it, the router head picks one pool member, here open\_mid, and only that model's real reply is returned](https://mintcdn.com/benchgen-8fc81371/cQg68q4he_kAbyyN/images/guides/router-head/architecture.svg?fit=max\&auto=format\&n=cQg68q4he_kAbyyN\&q=85\&s=6b4a73654d0bb322a87bab57ad1442a6)

One query moving through BenchGen Router Lite: the frozen backbone embeds it, the head picks one pool member (here open\_mid), and only that model's real reply comes back. No text is ever generated by the head itself.

Everything below, the dataset, the pipeline that built it, and the trained head, is open source,
hosted outside these docs. Here is all of it in one place before the story starts:

> [card] [Source and pipeline](https://github.com/benchgen-ai/benchgen-router-lite-dataset)
>
> The full five-stage generation pipeline, tests, and reports, as a runnable repository.

> [card] [Rewards dataset](https://benchgen.com/datasets/benchgen/benchgen-router-rewards-dataset)
>
> 46 tasks, 5 agents, 3 repetitions. Also on [Hugging Face](https://huggingface.co/datasets/benchgen/router-pilot).

> [card] [Task pool](https://benchgen.com/datasets/benchgen/benchgen-router-tasks)
>
> 1,110 tasks with prompt text. Also on [Hugging Face](https://huggingface.co/datasets/benchgen/router-pilot-tasks).

> [card] [Trained head](https://benchgen.com/models/benchgen/benchgen-router-lite)
>
> `benchgen-router-lite`. Also on [Hugging Face](https://huggingface.co/benchgen/benchgen-router-lite).

> [card] [Router Fidelity Benchmark](https://benchgen.com/benchmarks/platform/router-fidelity-benchmark)
>
> 46 in-distribution tasks. 82.6% accuracy, roughly 3.1x cheaper than its own strongest pool
> member called alone. Full results in [Benchmark](#3-benchmark) below.

> [!NOTE]
>
> This guide refers to the trained head by its stable model-page name, **benchgen-router-lite**. The
> platform itself registers each training run under its own generated id, which changes on every
> retrain, so an id shown on the [benchgen-router-lite model page](https://benchgen.com/models/benchgen/benchgen-router-lite)
> or on the benchmark's leaderboard may not match run to run; that page's URL is what stays stable.
> Opening an entry from the leaderboard also requires signing in, since individual evaluation pages
> aren't public.

***

## 1. Build the dataset

A router has nothing to learn from until you can prove that different models are actually better
at different things. That proof is a **reward matrix**: for every task, how well each candidate
model actually scored on it, measured rather than assumed. BenchGen Router Lite trains on two
paired datasets published from a single pilot collection run.

| Dataset | Contents | Why it is separate |
| - | - | - |
| **[Rewards dataset](https://benchgen.com/datasets/benchgen/benchgen-router-rewards-dataset)** | `task_id`, one reward column per pool member, tie and empty/error flags | Published without prompt text, since redistribution rights differ per upstream source |
| **[Tasks dataset](https://benchgen.com/datasets/benchgen/benchgen-router-tasks)** | `task_id`, `prompt`, gold answer, grader, domain, difficulty, split | Supplies the prompt text so a reward row can be embedded and joined at training time |

The join key is `task_id`, shaped `{source}/{split}/{index}`. Training the router head means
loading both datasets and matching rows on that field before anything gets embedded.

### The pipeline, end to end

Both datasets come out of one ordered pipeline of five stages, run in sequence. Each writes a
data file into `data/` and a report into `reports/`, and each refuses to run ahead of its own
gate, so a broken pool cannot quietly become a published dataset.

```bash theme={null}
python pipeline/01_verify_pool.py            # Gate 1: every agent proven to answer
python pipeline/02_build_task_dataset.py     # -> data/tasks.v1.jsonl
python pipeline/03_collect_rewards.py        # -> data/rewards.v1-pilot.jsonl
python pipeline/04_gate_and_baselines.py     # Gate 3, plus the baselines to beat
python pipeline/05_publish.py --push         # -> the two published datasets
```

Shared settings live in `configs/`, never inline in a script: the call protocol and pool in
`agents.v1.json`, the seed, repetitions and sampling plan in `collection.v1.json`, the gate
thresholds in `gates.v1.json`. Every report carries a SHA-256 digest of its inputs and no
timestamps, so stages 4 and 5 rebuild their output byte for byte from committed data with no
network access and no API key. That is the cheapest possible regression test:

```bash theme={null}
python pipeline/04_gate_and_baselines.py && git diff --stat reports/
```

> [!NOTE]
>
> Stage 3 accepts `--dry-run`, which prints the call count and an upper bound on cost and makes
> zero calls. Stage 5 accepts `--push`, and uploads privately unless `--public` is also given.

### Stage 1: prove the pool answers

Every model was reached through [OpenRouter](https://openrouter.ai), so the pool could mix
closed-style and open-weight models behind one API and one billing account. Candidates were
picked from the live OpenRouter catalogue, skipping slug variants that would make the
measurement meaningless: `:free` is rate limited and silently truncates, `:batch` is
asynchronous, and `nitro`, `floor`, `online` and `extended` all change routing. Any of those
makes a reward column measure the variant rather than the model.

A dead or misbehaving slug is worse than a weak model, because it fills a whole reward column
with silent zeros and teaches the router to avoid a model that was never actually broken. So
before a cent is spent, every active agent gets 21 live calls: 20 against a trivial prompt, plus
one prompt that cannot be satisfied inside `max_tokens`.

```python pipeline/01_verify_pool.py theme={null}
PROBE_CALLS = 20
PROBE_PROMPT = "Reply with exactly: OK"
# Deliberately unsatisfiable within max_tokens. A compliant agent stops at the cap with its
# partial text intact; silent truncation looks identical to a short answer once it reaches the
# reward matrix, so it has to be caught here.
LENGTH_PROBE_PROMPT = "Count from 1 to 5000. One number per line. Do not stop early."
MAX_EMPTY_RATE = 0.05


async def check(agent, protocol) -> tuple[str, str]:
    empties = errors = 0
    usage_seen = False

    async with OpenRouterClient(timeout_s=protocol.timeout_s) as client:
        for _ in range(PROBE_CALLS):
            result = await client.chat(
                agent, [{"role": "user", "content": PROBE_PROMPT}], protocol
            )
            errors += bool(result.error)
            empties += bool(result.empty)
            usage_seen = usage_seen or result.completion_tokens is not None
        long = await client.chat(
            agent, [{"role": "user", "content": LENGTH_PROBE_PROMPT}], protocol
        )

    detail = f"empty={empties / PROBE_CALLS:.0%} err={errors / PROBE_CALLS:.0%}"
    over_cap = (
        long.completion_tokens is not None and long.completion_tokens > protocol.max_tokens
    )
    if errors:
        return "FAIL", f"{detail} (call errors)"
    if empties / PROBE_CALLS > MAX_EMPTY_RATE:
        return "FAIL", f"{detail} (empty rate above {MAX_EMPTY_RATE:.0%})"
    if not usage_seen:
        return "FAIL", f"{detail} (no token counts, so cost cannot be tracked)"
    # A probe that errored or came back empty measured nothing, so it cannot pass: the point is
    # positive evidence that the cap is honoured.
    if long.error or over_cap or not long.text.strip():
        return "FAIL", f"{detail} (ignored the {protocol.max_tokens} token cap)"
    return "PASS", detail
```

A pass stamps `verified_at` in `configs/agents.v1.json`, and Stage 3 raises rather than start
against a slug that never got one. The five models that passed split into two roles inside the
pool:

| Role | Agent | Model | Mode |
| - | - | - | - |
| **Frontier** | `frontier_a` | `openai/gpt-oss-120b` | Reasoning |
| **Frontier** | `frontier_b` | `deepseek/deepseek-v4-flash-0731` | Reasoning |
| **Frontier** | `frontier_c` | `google/gemma-3-27b-it` | Direct |
| **Mid-tier** | `open_mid` | `mistralai/mistral-nemo` | Direct |
| **Cheap reasoning** | `open_cheap_reasoning` | `inclusionai/ling-3.0-flash` | Reasoning |

The three **Frontier** slots are the pool's strong anchors, the models a naive "always use one
model" strategy would pick, standing in for closed, proprietary frontier APIs on a budget that
favored strong open-weight models available on OpenRouter. The **Mid-tier** slot is the
deliberately weakest agent in the pool, included specifically to see if it is ever uniquely best on
cheap questions, and the **cheap reasoning** slot is the cheapest reasoning-capable model in the
catalogue, from a different vendor family so its failures do not correlate with the frontier slots.

This composition mirrors the coordinator design in Sakana AI's Trinity paper
([arXiv:2512.04695](https://arxiv.org/abs/2512.04695)): a router only has something to learn if no
single agent dominates everywhere. A pool of near-identical strong models gives a router nothing to
route between; a pool with a genuinely weaker, cheaper option gives it a real decision to make.

Every agent is called under identical settings, so a score difference reflects the model and not
the prompt conditions. They live in `configs/agents.v1.json` under `protocol`, so the whole pool
moves together or not at all:

| Setting | Value |
| - | - |
| `max_tokens` | 4,096 |
| `temperature` | 0.1 |
| `top_p` | 1.0 |
| Reasoning effort | Minimal |
| Repetitions | 3 per task, per agent |
| Timeout | 180 seconds, up to 3 retries |

### Stage 2: build the task dataset

`02_build_task_dataset.py` runs one deterministic chain: load, map, dedupe, balance, split. It is
seeded from `configs/collection.v1.json` and safe to re-run, so the same config always produces a
byte-identical `data/tasks.v1.jsonl`.

```python pipeline/02_build_task_dataset.py theme={null}
config = load_collection(VERSION)
request = BuildRequest(
    per_source_limit=dict(config["per_source_limit"]),
    max_share=float(config["max_domain_share"]),
    seed=int(config["seed"]),
    cache_dir=CACHE_DIR,
    ratios=config["split_ratios"],
)
result = build_pool(request)

out = tasks_path(VERSION)
print(f"wrote {write_jsonl(out, result.tasks)} tasks to {out}")

problems = gate_2(result, request.max_share)
if problems:
    print("\nGate 2 FAILED:")
    for problem in problems[:20]:
        print(f"  - {problem}")
    return 1
print("\nGate 2 passed: balanced, answered, graded, split.")
```

What `build_pool` does, step by step:

> [card] Load and map
>
> One adapter per upstream source, all normalizing to the same `Task` schema. Column names
> drift between mirrors of the same benchmark, so each adapter accepts a short list of known
> spellings instead of guessing one and silently yielding zero rows.

> [card] Dedupe
>
> A SHA-1 fingerprint over normalized prompt text, first occurrence kept. Inputs are sorted by
> `task_id` first, so which copy survives is deterministic. This build dropped 0 duplicates.

> [card] Balance
>
> No domain above `max_domain_share`. A seeded binary search finds the largest per-domain cap
> that still satisfies the constraint, which keeps the most data. It cost 30 knowledge rows and
> 30 math rows.

> [card] Split
>
> Stratified by `(domain, difficulty)` at 60/20/20, with a separate seeded shuffle per stratum,
> then a leakage assertion that raises if any `task_id` landed in two splits.

Every row also carries full provenance (dataset, config, split, index, licence, and a
`redistributable` flag), and difficulty comes from the source where it has one. MATH500 levels 1
to 5 map onto easy, easy, medium, hard, hard; sources without a level use their own default.

The balance step is the one place where the config asks for something arithmetically impossible,
and the code says so rather than quietly failing its own gate:

```python taskpool/balance.py theme={null}
def effective_max_share(n_domains: int, max_share: float = DEFAULT_MAX_SHARE) -> float:
    """With `n` domains no allocation can put every domain below `1/n`.

    Asking for 30% across 3 domains is arithmetically impossible; the cap becomes 33.3% and the
    report says so rather than the build silently failing its own gate.
    """
    if n_domains <= 0:
        return max_share
    return max(max_share, 1.0 / n_domains)
```

Gate 2 then checks the finished pool: every domain inside the effective cap, every row with a
non-empty answer and a named grader, and no empty split. The result is a normalized set of
prompts drawn from eight public benchmark sources:

| Source | Tasks | Domain | Licence |
| - | -: | - | - |
| `math500` | 233 | Math | MIT |
| `rlpr` | 250 | Reasoning | Apache-2.0 |
| `mmlu_pro` | 186 | Knowledge | Unverified at collection time |
| `mmlu` | 184 | Knowledge | MIT |
| `arc_challenge` | 120 | Reasoning | CC-BY-SA-4.0 |
| `gsm8k` | 109 | Math | MIT |
| `aime2025_i` | 15 | Math | MIT |
| `aime2025_ii` | 13 | Math | MIT |
| **Total** | **1,110** | | |

Domain, difficulty, and split are balanced deliberately, not incidentally:

> [card] Domain
>
> Knowledge: 370 (33.3%)\
> Math: 370 (33.3%)\
> Reasoning: 370 (33.3%)

> [card] Difficulty
>
> Medium: 504 (45.4%)\
> Hard: 427 (38.5%)\
> Easy: 179 (16.1%)

> [card] Split
>
> Train: 648 (58.4%)\
> Test: 245 (22.1%)\
> Validation: 217 (19.5%)

All 1,110 tasks are published as the paired tasks dataset. Only the 46 tasks described below
currently carry reward labels; the rest of the pool exists so future collection rounds, on a wider
agent pool or a bigger budget, can reuse the same balanced task set instead of rebuilding it.

### Stage 3: collect the reward dataset

This is the only stage that spends money, so it starts by refusing to. `--dry-run` prints the
exact call count and an upper bound on cost, then exits without making a single call:

```bash theme={null}
$ python pipeline/03_collect_rewards.py --dry-run
tasks: 60  agents: 5  repetitions: 3
calls: 900
cost ceiling: $0.17
output: data/rewards.v1-pilot.jsonl
dry run, no calls made
```

The 60 tasks are a seeded draw of 20 per domain from the task pool. Seeding per domain rather
than globally means adding a domain later does not reshuffle the ones already collected:

```python pipeline/03_collect_rewards.py theme={null}
def sample_per_domain(tasks: list[Task], per_domain: dict[str, int], seed: int) -> list[Task]:
    """Seeded and sorted, so the same seed always draws the same tasks."""
    buckets: dict[str, list[Task]] = defaultdict(list)
    for task in tasks:
        buckets[task.domain].append(task)

    chosen: list[Task] = []
    for domain, want in sorted(per_domain.items()):
        bucket = sorted(buckets.get(domain, []), key=lambda t: t.task_id)
        rng = random.Random(f"{seed}/{domain}")
        chosen.extend(rng.sample(bucket, min(want, len(bucket))))
    return sorted(chosen, key=lambda t: t.task_id)
```

The real run then calls every active agent 3 times on each task. Every agent sees byte-identical
messages for a given task, a fixed system prompt plus the task prompt, with nothing
agent-specific anywhere in the payload:

```python pipeline/03_collect_rewards.py theme={null}
require_verified(pool)  # refuses to start against a slug Stage 1 never verified

async with OpenRouterClient(timeout_s=pool.protocol.timeout_s) as client:
    try:
        progress = await collect_rewards(
            tasks=tasks,
            pool=pool,
            chat=lambda agent, messages: client.chat(agent, messages, pool.protocol),
            out_path=OUT_PATH,
            repetitions=repetitions,
            concurrency=int(config["concurrency"]),
            store_raw=bool(config["store_raw_response"]),
            resume=True,
            on_progress=report,
        )
    except ProtocolViolation as exc:
        # The agent's numbers are no longer comparable and its cost is unbounded.
        print(f"\nSTOPPED, protocol violation: {exc}")
        return 2
    except CollectionAborted as exc:
        # A row written now would record a billing failure as a wrong answer, and resume
        # would then skip that task forever.
        print(f"\nSTOPPED, account-level failure: {exc}")
        return 2
```

Those two exception handlers and the resume flag are what make the run safe to leave unattended:

| Guard | What it does |
| - | - |
| **Resume** | One JSONL row is written per task, under a lock, as soon as that task's 15 calls finish, so a crash never loses completed work. A rerun skips tasks already collected under the same pool version, agent order and repetition count, and refuses to append to a file collected under a different pool. |
| **Account-level abort** | Out of credit or unauthorized raises instead of writing a row. Writing one would record a billing failure as a wrong answer, and resume would then skip that task forever. |
| **Protocol violation** | An agent returning more than 1.05x the `max_tokens` cap is a hard stop. A few tokens over is accounting noise, but a real overshoot means its scores are no longer comparable with the rest of the pool and its cost is unbounded. |

That last guard is not hypothetical. It fired during collection, when one candidate returned
14,433 completion tokens against the 4,096 cap. It had passed pre-flight only because its length
probe happened to answer in 640 tokens, which is not evidence of compliance. It was retired on
the spot, its pool index kept and never reused.

#### Grading, and how a reward row is built

Each reply is graded by a named grader that the task row references by name, so grading logic
lives in code and never in the data. Extraction runs from the most explicit signal to the weakest
fallback: a tagged answer, brace-balanced `\boxed{...}` (a plain regex breaks on nested braces
like `\frac`), a labelled answer, then a last-number fallback that strips markup first. An empty
response is never scored correct, and empties are counted separately from provider errors so a
broken transport is never mistaken for a weak model.

A row is then derived from the calls, never trusted from the file:

```python schemas/rewards.py theme={null}
@model_validator(mode="after")
def _recompute_bests(self) -> RewardRecord:
    winners = [self.agent_order[i] for i in best_indices(self.mean_reward)]
    # Derived, never trusted from the file: a stale best_agents silently corrupts the gate.
    self.best_agents = winners
    self.is_tie = len(winners) > 1
    return self
```

`mean_reward[i]` is agent `agent_order[i]`'s correct calls divided by repetitions, and
`best_agents` and `is_tie` are recomputed by that validator every single time a record loads.
Ties stay explicit rather than collapsing to a single winner, because on easy questions several
agents are genuinely equal and pretending otherwise teaches a router a coin flip:

```json theme={null}
{
  "task_id": "aime2025_i/test/000002",
  "agent_order": ["frontier_a", "frontier_b", "frontier_c", "open_mid", "open_cheap_reasoning"],
  "mean_reward": [1.0, 1.0, 0.6666666666666666, 0.0, 1.0],
  "best_agents": ["frontier_a", "frontier_b", "open_cheap_reasoning"],
  "is_tie": true
}
```

The pilot scored **60 tasks x 5 agents x 3 repetitions = 900 graded calls** across 8 source
datasets, with **zero call errors**, for a total of **\$0.0826** against that \$0.17 ceiling. Every
call is logged with its real, provider-reported cost, so the bill is auditable per agent, not just
as one total:

| Agent | Model | Calls | Cost | Share |
| - | - | -: | -: | -: |
| `frontier_b` | `deepseek/deepseek-v4-flash-0731` | 180 | \$0.0314 | 38.0% |
| `frontier_a` | `openai/gpt-oss-120b` | 180 | \$0.0234 | 28.4% |
| `open_cheap_reasoning` | `inclusionai/ling-3.0-flash` | 180 | \$0.0159 | 19.3% |
| `frontier_c` | `google/gemma-3-27b-it` | 180 | \$0.0102 | 12.4% |
| `open_mid` | `mistralai/mistral-nemo` | 180 | \$0.0016 | 2.0% |
| **Total** | | **900** | **\$0.0826** | 100% |

That is **\$0.000092 per call**, roughly **\$0.0014 per task** (5 agents x 3 repetitions). The
router head itself adds nothing on top of this number: it trains against the static matrix above
with sep-CMA-ES and makes zero further API calls, so **\$0.0826 is the entire cost of the data the
router head was evolved against**. Stage 1's pre-flight probes, 21 short calls per candidate
agent against a five-word prompt, add a further near-free cost, well under a cent across the
whole pool.

### Stage 4: decide whether this pool deserves a router at all

A routing dataset is only useful if no single agent dominates. If one agent is best almost
everywhere, the optimal router is "always pick that agent" and no amount of training helps. Stage
4 measures that before anything gets trained. It reads only `data/` and `configs/`, needs no
network and no API key, and exits non-zero when the gate says STOP so CI can enforce it:

```python pipeline/04_gate_and_baselines.py theme={null}
metrics = compute_health(records)
outcome = evaluate(load_gates(VERSION), metrics)
write_report("dataset_health.md", render_health(metrics, outcome, {REWARDS.name: REWARDS}))

held_out = {t.task_id for t in tasks if t.split == HELD_OUT_SPLIT}
baselines = compute_baselines([r for r in records if r.task_id in held_out])
write_report(
    "baselines.md", render_baselines(baselines, HELD_OUT_SPLIT, {REWARDS.name: REWARDS})
)

return 1 if outcome.decision == "STOP" else 0
```

The thresholds live in `configs/gates.v1.json`, each with a continue level and a stop level:

| Metric | Value | Continue at | Stop at | Verdict |
| - | -: | -: | -: | - |
| Relative Error Reduction, per dataset | 0.0485 | 0.10 or more | 0.03 or less | WARN |
| Relative Error Reduction, per question | 0.1731 | 0.15 or more | 0.08 or less | PASS |
| Datasets in the reward matrix | 8 | 3 or more | 1 or less | PASS |
| Tasks where all agents score equal | 43.3% | 45% or less | 65% or more | PASS |
| Tasks with a unique best agent | 11.7% | 25% or more | 15% or less | **FAIL** |
| Weakest agent's uniquely-best share, scaled | 0.0000 | 0.30 or more | 0.10 or less | **FAIL** |
| Worst agent's empty-response rate | 15.6% | 2% or less | 10% or more | **FAIL** |
| Worst agent's call-error rate | 0.0% | 2% or less | 10% or more | PASS |

**The pilot's verdict is STOP**, and the pipeline reports it rather than burying it. Three
metrics block:

* **Unique best agent on only 11.7% of tasks.** On most tasks either everyone gets it right or
  nobody does, and neither case carries any routing signal.
* **The weakest agent is never uniquely best.** An agent at zero here is dead weight in the
  action space: nothing is lost by removing it from the pool entirely.
* **A 15.6% empty-response rate on the worst agent.** High enough to depress that agent's
  measured reward for a transport reason rather than a capability one.

The gate exists because of an earlier attempt on this problem, which collected 2,700 real calls
and trained two heads before anyone noticed that 75.3% of its tasks scored every agent
identically. The router it produced exactly matched "always pick one specific model". The pilot
here is better than that on every axis and still does not clear the bar, which is precisely why
this release is a **pilot** and the head trained on it is **Lite**.

Stage 4's second output is the baselines, on the held-out `test` split, because a routing dataset
that reports only the winner's score invites exactly the mistake above:

| Policy | Mean reward |
| - | -: |
| `frontier_a` | 0.6667 |
| `open_cheap_reasoning` | 0.6667 |
| `frontier_b` | 0.6410 |
| `frontier_c` | 0.5641 |
| `open_mid` | 0.2308 |
| Uniform random pick | 0.5538 |
| **Best single fixed agent** | **0.6667** |
| **Per-question oracle (upper bound)** | **0.7692** |

The gap between the best fixed agent and the oracle, **0.1026**, is the routing headroom: the most
a trained router could possibly gain over always calling `frontier_a`. That is the bar the trained
router is measured against in [Benchmark](#3-benchmark) below.

### Stage 5: publish only what is safe to publish

The last stage drops two things. The `rlpr` source goes first: its answers
are free-form prose and tables, and the normalized string-match grader used here scores genuinely
correct answers as wrong. A label that cannot be trusted is worse than no label, so all 14 of its
tasks are excluded, leaving **46 tasks x 5 agents x 3 repetitions = 690 graded calls** in the
published rewards dataset.

Prompt text and raw completions go second, and two independent safeguards enforce it. The public
row type has no prompt or completion field at all and forbids extra fields, so one cannot be
added by accident, and the finished export is then scanned before a single byte is uploaded:

```python pipeline/05_publish.py theme={null}
LEAK_MARKERS = ('"prompt"', '"raw_response"', '"answer"')


def assert_no_prompt_text(out_dir: Path) -> None:
    """Cheap guard against a future change re-introducing prompts into the export."""
    for path in out_dir.iterdir():
        if path.suffix not in {".json", ".jsonl"}:
            continue
        body = path.read_text(encoding="utf-8")
        if any(marker in body for marker in LEAK_MARKERS):
            raise SystemExit(f"refusing to publish: {path.name} appears to contain question text")
```

Alongside the rewards goes an agent manifest naming which model produced each reward column, at
what price, and when it was last verified. Without it the reward vectors are just numbers.
Uploads are private by default; making a release public takes an explicit second flag.

> [!WARNING]
>
> Nothing published contains question text or raw model completions. Upstream licences differ per
> source and provider terms on republishing outputs were not cleared for every agent, so the reward
> signal (correctness, ties, empties, errors) is published without either. The `task_id` lets a
> consumer rehydrate the prompt from upstream themselves.

***

## 2. Train the router head

BenchGen Router Lite does not fine-tune a model, and it does not train a LoRA adapter on top of
one. What gets trained is a **router head**: a small classifier, a few thousand parameters, that
sits on top of a frozen backbone and learns which pool member to send each query to. The backbone
never updates. Only the head does.

| | Full fine-tune / LoRA | Router head |
| - | - | - |
| What changes | Model weights (or an adapter) | A small classifier on top of a frozen backbone |
| What it learns | How to answer | Which pool member should answer |
| Training method | Gradient descent over many steps | Separable CMA-ES, a gradient-free evolutionary search |
| Output at inference | Generated text | A routing decision; the picked pool member's real reply is what gets returned |

The head is trained with **separable CMA-ES** against the static reward matrix from the dataset
above, not by calling any pool model during training. Every `(task, agent)` reward is already in
the dataset, so a full training run makes zero API calls and costs nothing beyond the embedding
pass.

> [!NOTE]
>
> There are two ways to run this training. The walkthrough below is the platform path: point the
> **Train** tab at the dataset and click through. The same training worker is also published as a
> standalone script, `train/train_router_head.py`, in the
> [benchgen-router-lite-dataset](https://github.com/benchgen-ai/benchgen-router-lite-dataset) repo.
> It is not a rewrite: the embedding step, the head shapes, and the sep-CMA-ES loop below are the
> platform's own code, with only the storage boundary changed to write local files instead of
> uploading to platform-internal storage. See [Run it yourself](#run-it-yourself) at the end of
> this section.

### 1. Start a new training run and pick Head

In the [**Train** tab](https://benchgen.com/train), click **+ New Training**, then pick **Head** on
the training method toggle ("Learn from past agent scores"). Point **Base Model** at the frozen
backbone (this run used `Qwen/Qwen3-1.7B`) and **Dataset** at the rewards dataset,
`benchgen/router-pilot`.

![Training method set to Head, with Qwen3-1.7B as the base model and router-pilot as the dataset](https://mintcdn.com/benchgen-8fc81371/39Nn1jBJfIgq8JtT/images/guides/router-head/01-train-head-method.png?fit=max\&auto=format\&n=39Nn1jBJfIgq8JtT\&q=85\&s=67d5e01ce1d3f16b22c973c8ca4374ca)

The New Training form with Head selected, Qwen/Qwen3-1.7B as the base model, and router-pilot as the dataset

### 2. Fill in the head-specific fields

Add the **Tasks dataset**, `benchgen/router-pilot-tasks`, so prompts can be joined and embedded.
Set **Held-out split value** to `test`, the split the dataset's own reported baselines use, and
leave **Head hidden dimension** at `0` for a pure linear head. This run used the defaults for the
rest: `sigma0` 0.5, 60 generations, automatic population size, and seed 42, with the **CUDA**
embedding device.

![The Head-specific fields: tasks dataset, held-out split, head hidden dimension, and CMA-ES hyperparameters](https://mintcdn.com/benchgen-8fc81371/39Nn1jBJfIgq8JtT/images/guides/router-head/02-train-head-config.png?fit=max\&auto=format\&n=39Nn1jBJfIgq8JtT\&q=85\&s=113bcaa8237f77db6a00b64fb5d7feaf)

The Head-specific fields: tasks dataset, held-out split value, head hidden dimension, and the sep-CMA-ES hyperparameters (sigma0, generations, population, seed)

### 3. Submit and watch it train

Click **Start Training**. The logs confirm exactly what is loading before anything else happens:

```text theme={null}
=== Router head training: benchgen-router-lite ===
Loading rewards dataset benchgen/router-pilot (split=train)...
  46 reward rows loaded.
Loading tasks dataset benchgen/router-pilot-tasks (split=train) ...
  1110 tasks with prompt text loaded.
Pool (5 agents): ['frontier_a', 'frontier_b', 'frontier_c', 'open_mid', 'open_cheap_reasoning']
```

![Training logs showing the reward dataset, tasks dataset, and five-agent pool loading](https://mintcdn.com/benchgen-8fc81371/39Nn1jBJfIgq8JtT/images/guides/router-head/03-train-logs-start.png?fit=max\&auto=format\&n=39Nn1jBJfIgq8JtT\&q=85\&s=d1787286b5e5866031a186d729f8feea)

Training logs right after submit: the rewards dataset, the tasks dataset, and the five-agent pool all loading before embedding starts

### 4. CMA-ES evolves the head

The backbone embeds each prompt once, splits into 35 train rows and 11 test rows, and then a
10,245-parameter head is evolved against the training rows:

```text theme={null}
Train rows: 35, test rows: 11, embedding dim: 2048
sep-CMA-ES: 10245 head parameters, sigma0=0.5, generations=60, popsize=auto
  gen 0: best_reward_so_far=0.9333
  gen 1: best_reward_so_far=0.9429
  gen 2: best_reward_so_far=0.9429
  gen 3: best_reward_so_far=0.9429
```

![Training progress and logs showing sep-CMA-ES generations and the best training reward so far](https://mintcdn.com/benchgen-8fc81371/39Nn1jBJfIgq8JtT/images/guides/router-head/04-train-logs-cmaes.png?fit=max\&auto=format\&n=39Nn1jBJfIgq8JtT\&q=85\&s=74ec8513c5326aa5118263f0e809fed2)

Training Progress at 100% alongside the raw logs: 35 train rows, 11 test rows, a 10,245-parameter head, and the best training reward climbing across generations

That `10245` is not asserted, it falls out of a formula against the actual embedding dimension
and pool size, and a "head" is nothing more than the unflattened weights of a linear layer, or a
one-hidden-layer MLP if `head_hidden_dim` is set above `0`:

```python train/train_router_head.py theme={null}
def head_param_count(in_dim: int, hidden_dim: int, n_agents: int) -> int:
    if hidden_dim <= 0:
        return in_dim * n_agents + n_agents
    return in_dim * hidden_dim + hidden_dim + hidden_dim * n_agents + n_agents


def build_head(theta, in_dim: int, hidden_dim: int, n_agents: int):
    """Unflatten a CMA-ES candidate vector into a callable head(x) -> logits."""
    if hidden_dim <= 0:
        w = theta[: in_dim * n_agents].reshape(in_dim, n_agents)
        b = theta[in_dim * n_agents :]

        def head(x):
            return x @ w + b

        return head
    # ... a one-hidden-layer MLP when head_hidden_dim > 0
```

`2048 x 5 + 5 = 10245`: the embedding dimension times the pool size, plus one bias per agent.
Every candidate CMA-ES proposes is one of these vectors, scored by unflattening it into a head,
running every training row's embedding through it, and averaging the reward at the argmax pick:

```python train/train_router_head.py theme={null}
def train_cma(E_train, R_train, in_dim: int, n_agents: int, cfg: dict):
    import cma

    hidden_dim = int(cfg.get("head_hidden_dim") or 0)
    n_params = head_param_count(in_dim, hidden_dim, n_agents)
    es = cma.CMAEvolutionStrategy(np.zeros(n_params), float(cfg.get("cma_sigma0", 0.5)), {
        "seed": int(cfg.get("cma_seed", 42)), "verbose": -9,
    })

    best_theta, best_score = np.zeros(n_params), -1.0
    while not es.stop() and gen < int(cfg.get("cma_generations", 60)):
        population = es.ask()
        neg_scores = []
        for theta in population:
            head = build_head(np.asarray(theta), in_dim, hidden_dim, n_agents)
            picks = np.argmax(head(E_train), axis=1)
            reward = float(R_train[np.arange(len(picks)), picks].mean())
            neg_scores.append(-reward)  # CMA-ES minimizes
        es.tell(population, neg_scores)
        # ... track the best theta seen so far, log it, gen += 1
```

There is no gradient anywhere in this loop. `es.ask()` proposes a population of candidate weight
vectors from a search distribution, `es.tell()` updates that distribution toward whichever
candidates scored best, and nothing here ever needs to know how to differentiate through an
argmax pick, which a router head's output makes gradient descent awkward for in the first place.

This whole run, embedding included, finished in **6 seconds** on a single auto-selected GPU. That
`best_reward_so_far` number is the head's fit to the 35 training rows as CMA-ES optimizes, not a
held-out score. What the trained head actually generalizes to is what
[Benchmark](#3-benchmark) below measures.

### 5. Register the head

A completed job's **Use In Benchmarks** panel offers **Register as Model**. Click it, and the head
becomes selectable anywhere BenchGen lets you pick a model, carrying a **Head** badge and a stable
name (`benchgen-router-lite` for this run) so it is never confused with a regular fine-tuned
model. There is no merge or export step, since a router head has no adapter weights to fold into a
base model.

![A completed and registered router head, registered as benchgen-router-lite](https://mintcdn.com/benchgen-8fc81371/39Nn1jBJfIgq8JtT/images/guides/router-head/05-train-registered.png?fit=max\&auto=format\&n=39Nn1jBJfIgq8JtT\&q=85\&s=2fafda6c44f28358cbcf921314f45690)

The completed job, registered and ready as benchgen-router-lite, selectable anywhere BenchGen lets you pick a model

### Run it yourself

```bash theme={null}
pip install -e ".[train]"
python train/train_router_head.py
```

With no argument it reproduces this exact run against `benchgen/router-pilot` and
`benchgen/router-pilot-tasks`: the same backbone, `sigma0`, generation count, and seed as above.
Before this script shipped, its data-loading and joining path was run against the real published
dataset to confirm it: 46 joined rows, 0 missing, 35 train and 11 test after the split, embedding
dimension 2048, and `head_param_count(2048, 0, 5) == 10245`, matching every number on this page.

> [card] [train/ on GitHub](https://github.com/benchgen-ai/benchgen-router-lite-dataset/tree/main/train)
>
> The full trainer, its example config, and a two-way comparison with the platform path.

> [card] [Trained head](https://benchgen.com/models/benchgen/benchgen-router-lite)
>
> The `benchgen-router-lite` head this platform run and this script both produce.

Writes `head_weights.npy` and `manifest.json` to a local folder. It does not register a model,
serve one, or make any API calls; the **Register as Model** step above and the routing gateway
behind it are platform-only, and are what [Benchmark](#3-benchmark) below actually exercises.

***

## 3. Benchmark

A router head's own output is a routing decision, not an answer. Running it through a benchmark
scores the **router and its pool together**, not the head in isolation, since every response a user
sees comes from whichever pool member the head picked.

BenchGen Router Lite was evaluated against
**[Router Fidelity Benchmark](https://benchgen.com/benchmarks/platform/router-fidelity-benchmark)**,
a named, published BenchGen environment built specifically to answer one question: does a router
model actually route, or does it collapse to one agent? 46 English math, knowledge, and reasoning
tasks (MATH500, MMLU, MMLU-Pro, ARC-Challenge, GSM8K, AIME2025), drawn from the exact same
distribution the head's own reward matrix was trained and held out against, joined from
`benchgen/router-pilot` and `benchgen/router-pilot-tasks` by `task_id`. Model connection is
env-var-first (`RPE_*` / `MODEL_*`, injected by the platform, no `model.py` needed), and because
the model under test is a router, the results page adds a routing report: which pool member (and
the real underlying model it resolved to) answered each question, alongside the overall routing
distribution.

![Router Fidelity Benchmark overview page describing the 46-task in-distribution benchmark, its scoring rules, and its routing and cost reporting](https://mintcdn.com/benchgen-8fc81371/cdCD8XgQ4xJlxulo/images/guides/router-head/13-fidelity-benchmark-overview.png?fit=max\&auto=format\&n=cdCD8XgQ4xJlxulo\&q=85\&s=c3a53f7529e7dde3cbf84664fe5ecda3)

The Router Fidelity Benchmark overview: 46 in-distribution tasks, env-var-first model connection, and a routing report for router models

This is deliberately an **in-distribution** test. A router head embeds each query with a frozen
backbone and picks a pool member based on where that embedding falls relative to what it saw
during training; evaluate it on a wildly different distribution and the embedding lands somewhere
the classifier never learned to discriminate, and its pick becomes arbitrary rather than a genuine
routing decision. Router Fidelity Benchmark's tasks come from the exact sources the router trained
on, so a run here is a real fidelity check: does the routing decision hold up on the data it was
actually built for?

### Running the evaluation

From the benchmark's **Evaluate** tab, the registered head shows up under **Platform Models**
alongside every other trained model, carrying its **Head** badge. Selecting it auto-fills the
sampling parameters from the model, and the **Advanced** panel exposes `RPE_MAX_QUESTIONS` for a
quick debugging run against the first few questions before committing to the full 46. **Run
Evaluation** starts the same round trip described above: each question gets embedded, the head
picks a pool member, and that pool member answers for real.

![Selecting the registered benchgen-router-lite head under Platform Models on the Router Fidelity Benchmark, with the Advanced environment variable panel expanded](https://mintcdn.com/benchgen-8fc81371/cdCD8XgQ4xJlxulo/images/guides/router-head/14-fidelity-benchmark-select-model.png?fit=max\&auto=format\&n=cdCD8XgQ4xJlxulo\&q=85\&s=31605e1cb1809f653e07b903fc0b0bd1)

Selecting benchgen-router-lite under Platform Models on Router Fidelity Benchmark, with the env-var Advanced panel showing RPE\_MAX\_QUESTIONS for a quick debugging run

![The Router Fidelity Benchmark evaluation running live, with status logs streaming step-by-step progress through the 46 questions](https://mintcdn.com/benchgen-8fc81371/cdCD8XgQ4xJlxulo/images/guides/router-head/16-fidelity-benchmark-running.png?fit=max\&auto=format\&n=cdCD8XgQ4xJlxulo\&q=85\&s=30deb2987bf1e7bbd80f445d7bb60d5b)

The evaluation running live, streaming step-by-step progress through the 46 questions

### Watching the questions arrive at the pool

Because the router never generates text itself, every question it routes turns into a real API
call to the selected pool member. Those calls show up in the OpenRouter dashboard as the run
proceeds, which is the clearest way to confirm the routing is genuinely happening rather than
being simulated.

The generations log lists each call with the model that received it, the provider that served it,
token counts, and cost. The pool members reachable during this run appear here by name: **Claude
Sonnet 5**, **Ling-3.0-flash**, and **DeepSeek V4 Flash 0423**, `frontier_a`'s current pool
assignment alongside the other two agents the head actually reached for.

![OpenRouter generations log showing Claude Sonnet 5, Ling-3.0-flash, and DeepSeek V4 Flash 0423 calls with provider, input and output tokens, and cost](https://mintcdn.com/benchgen-8fc81371/cdCD8XgQ4xJlxulo/images/guides/router-head/17-fidelity-openrouter-logs.png?fit=max\&auto=format\&n=cdCD8XgQ4xJlxulo\&q=85\&s=849d73aac9e274f08faba5369561c335)

The OpenRouter generations log during the Router Fidelity Benchmark run: Claude Sonnet 5, Ling-3.0-flash, and DeepSeek V4 Flash calls, each with provider, tokens, and cost

Opening a single call shows the exact prompt the pool member received: the benchmark question and
its answer-format instruction, passed through untouched by the router. This one, `task_id`
`math500/test/000121`, "Solve for x, put the final answer inside `\boxed{}`," was routed to
`frontier_a` and answered by `anthropic/claude-sonnet-5-20260630`.

![OpenRouter prompt view showing a math500 question routed to claude-sonnet-5, with the boxed-answer format instruction](https://mintcdn.com/benchgen-8fc81371/cdCD8XgQ4xJlxulo/images/guides/router-head/18-fidelity-openrouter-prompt.png?fit=max\&auto=format\&n=cdCD8XgQ4xJlxulo\&q=85\&s=5cd11308c618c45b9c3d31181302a576)

One routed question as claude-sonnet-5 received it: the benchmark's own math prompt and boxed-answer instruction, passed through untouched

The generation details confirm which key issued the call, `benchgen-router-lite`, along with the
routing and generation timings, throughput, and the exact input and output token counts for that
single question.

![OpenRouter generation details showing the benchgen-router-lite API key, claude-sonnet-5 as the model, provider routing timings, throughput, and token counts](https://mintcdn.com/benchgen-8fc81371/cdCD8XgQ4xJlxulo/images/guides/router-head/19-fidelity-openrouter-generation.png?fit=max\&auto=format\&n=cdCD8XgQ4xJlxulo\&q=85\&s=2c6309d383b3fb1ed2b618f0e0c1f756)

Generation details for one routed call to claude-sonnet-5, issued by the benchgen-router-lite key, with routing timings, throughput, and token counts

### Results

> [!NOTE]
>
> The pool member behind `frontier_a` has moved on from data-collection time. The reward matrix in
> [Build the dataset](#1-build-the-dataset) above was collected against `openai/gpt-oss-120b`. This
> run, and the table below, route to the pool's current `frontier_a`, `anthropic/claude-sonnet-5`.
> The `agent_order` identifiers are stable; the real model each one resolves to is a serving-time
> mapping and can change independently of the training data, same as swapping any other agent in
> the pool.

Evaluating `benchgen-router-lite` here, instead of collapsing to a single agent, the head
scored **82.6%** (38 of 46 correct) and spread its picks across three different pool members:

| Routed to | Real model | Questions |
| - | - | -: |
| `frontier_a` | `anthropic/claude-sonnet-5` | 36 (78%) |
| `frontier_b` | `deepseek/deepseek-v4-flash` | 7 (15%) |
| `open_cheap_reasoning` | `inclusionai/ling-3.0-flash` | 3 (7%) |

| Breakdown | Score |
| - | -: |
| Easy | 88.9% (8/9) |
| Medium | 94.7% (18/19) |
| Hard | 66.7% (12/18) |
| Knowledge | 95.0% (19/20) |
| Math | 65.0% (13/20) |
| Reasoning | 100.0% (6/6) |

![Router Fidelity Benchmark results showing 82.6% accuracy, cost and token totals, difficulty and domain breakdowns, and the routing distribution](https://mintcdn.com/benchgen-8fc81371/cdCD8XgQ4xJlxulo/images/guides/router-head/15-fidelity-benchmark-results.png?fit=max\&auto=format\&n=cdCD8XgQ4xJlxulo\&q=85\&s=a3146e0df4bd0e0d8563f317e116cb69)

The completed Router Fidelity Benchmark run: 82.6% overall, difficulty and domain breakdowns, and the routing distribution across three pool members

That spread of three different agents actually receiving traffic, rather than one, is what a
router doing its job is supposed to look like: real evidence that the routing decision holds up
on the data it was built for, not a collapse to whichever agent happens to be cheapest. The run
also reports real cost: **\$0.0286 total**, **\$0.000622 per task**, across **14,483
tokens**. What that number is actually worth only shows up next to a baseline, which is exactly
what [Router vs. a single frontier model](#router-vs-a-single-frontier-model) further down
measures.

***

## Router vs. a single frontier model

The Cost KPI on Router Fidelity Benchmark exists precisely so a router's cost can sit on the same
leaderboard as a single fixed model and actually be compared. The baseline here is not an
arbitrary outside model: `anthropic/claude-sonnet-5` is `frontier_a`, the exact model the router
above picked 36 of 46 times. Calling it directly for every one of the same 46 questions, no
routing at all, answers a precise question: what does the pool's own strongest model cost when it
answers everything, against what it costs when the router only reaches for it when a question
actually calls for it?

![Four paired bar charts comparing BenchGen Router Lite against claude-sonnet-5 called alone on the same 46 questions: accuracy 82.6% vs 80.4%, total cost \$0.0286 vs \$0.0889, average cost per task \$0.000622 vs \$0.001932, total tokens 14,483 vs 16,021](https://mintcdn.com/benchgen-8fc81371/O_bY5sZUlrlFDTlB/images/guides/router-head/router-vs-sonnet-comparison.svg?fit=max\&auto=format\&n=O_bY5sZUlrlFDTlB\&q=85\&s=7ee1cf552b5003700f993a3c39c11514)

Accuracy, total cost, average cost per task, and total tokens, side by side: the router matches or beats the single model on everything except total tokens, where it is close, at roughly a third of the cost

| | BenchGen Router Lite | `claude-sonnet-5` alone |
| - | -: | -: |
| Accuracy | **82.6%** (38/46) | 80.4% (37/46) |
| Total cost | **\$0.0286** | \$0.0889 |
| Avg cost per task | **\$0.000622** | \$0.001932 |
| Total tokens | 14,483 | 16,021 |

Both numbers move the same direction: the router is **more accurate and roughly 3.1x cheaper**,
\$0.0889 against \$0.0286 in total cost, on the identical 46 questions. Total tokens are close,
14,483 against 16,021, only about 10% fewer for the router, so the savings are not coming from
shorter answers. They come from where the questions get sent: three of the five pool models cost
a fraction of a frontier model per token, and the router only reaches for `frontier_a` when a
question actually calls for it, 36 of 46 times here, not on every single one.

> [card] Easy
>
> Router 88.9% (8/9)\
> Sonnet 88.9% (8/9)\
> Tied

> [card] Medium
>
> Router 94.7% (18/19)\
> Sonnet 100.0% (19/19)\
> Sonnet ahead by 1

> [card] Hard
>
> Router 66.7% (12/18)\
> Sonnet 55.6% (10/18)\
> Router ahead by 2

The difficulty split is where it gets interesting rather than uniform: `claude-sonnet-5` alone
wins medium by one question, the router wins hard by two. By domain, the router leads knowledge
95.0% against 90.0%, and the two are exactly tied on math (65.0%) and reasoning (100.0%). These
are single runs of 6 to 20 questions per bucket, not a claim that routing always wins every
slice, the honest read is that the router matched or beat a frontier model used alone across
every domain and most difficulty bands, at under a third of the cost.

***

## Everything here is open source

The dataset, the pipeline, and the trained head all live in the open, not just described in this
guide, and so does the benchmark result: **82.6% accuracy, roughly 3.1x cheaper than the same
model called for every question instead of only the ones that need it.** Every link below is the
same set shown at the top, gathered again here now that you have the full story behind each one.

> [card] [Source and pipeline](https://github.com/benchgen-ai/benchgen-router-lite-dataset)
>
> The full five-stage generation pipeline, tests, and reports, as a runnable repository.

> [card] [Rewards dataset](https://benchgen.com/datasets/benchgen/benchgen-router-rewards-dataset)
>
> 46 tasks, 5 agents, 3 repetitions. Also on [Hugging Face](https://huggingface.co/datasets/benchgen/router-pilot).

> [card] [Task pool](https://benchgen.com/datasets/benchgen/benchgen-router-tasks)
>
> 1,110 tasks with prompt text. Also on [Hugging Face](https://huggingface.co/datasets/benchgen/router-pilot-tasks).

> [card] [Trained head](https://benchgen.com/models/benchgen/benchgen-router-lite)
>
> `benchgen-router-lite`. Also on [Hugging Face](https://huggingface.co/benchgen/benchgen-router-lite).

> [card] [Router Fidelity Benchmark](https://benchgen.com/benchmarks/platform/router-fidelity-benchmark)
>
> 46 in-distribution tasks. 82.6% accuracy, roughly 3.1x cheaper than its own strongest pool
> member called alone.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.