LevelUpWith

Explore / Autoresearch Loops: Agents That Experiment and Improve / Lesson 2

Lesson 2: One Number: Building a Scorer and a Baseline

Turn a vague goal on a small codebase into a scorer script that prints one number, records which direction counts as better, and measures the starting point every later change is judged against.

Free to read, no account needed. Part of Autoresearch Loops: Agents That Experiment and Improve.

By the end of this level you'll be able to

  • Write a Python or TypeScript scorer that runs the target and prints a single metric in a form a machine can read
  • Run the baseline, record the score with the commit hash, and state which direction counts as better
  • Reject a candidate metric that is too slow, too vague or cannot be computed automatically

Why the loop needs one number first

In Level 1 you met the loop: hypothesis, edit, run, measure, keep or revert. Every step after "measure" depends on comparing two numbers. If you can't produce that number by machine, cheaply and the same way every time, you don't have a loop. You have an agent offering opinions.

So before any agent touches the code, you build two things:

  1. A scorer: a script that runs the target and prints exactly one metric.
  2. A baseline: the score of the untouched code, recorded with the commit it came from.

Think of the scorer as the test suite for improvement. Unit tests answer "is it broken?" The scorer answers "is it better, and by how much?" Karpathy's open-source autoresearch repo shows the pattern. The agent edits one file, train.py. Data prep in prepare.py stays fixed. Every run is judged on one number, val_bpb (validation bits per byte), and the README states that lower is better. Training gets a fixed 5-minute wall-clock budget, so runs stay comparable.

The worked example: a slow log summariser

Say your small codebase has a function summarise(text). It parses an access log and returns counts per status code. The vague goal is "make the log parser better". Make it measurable: median runtime in milliseconds on a fixed input, provided the output is still correct. Lower is better.

The correctness condition matters. Without it, return {} is the fastest parser ever written.

Walkthrough: the Python scorer

#!/usr/bin/env python3
# score.py: prints ONE line: METRIC runtime_ms=<float>
import json, statistics, sys, time
from pathlib import Path

from parselog import summarise  # the code being improved

# Fixed inputs live in bench/. The agent must never edit them.
DATA = Path("bench/access.log").read_text()
EXPECTED = json.loads(Path("bench/expected.json").read_text())

def main() -> int:
    # 1. Correctness gate: a fast wrong answer gets no score at all.
    if summarise(DATA) != EXPECTED:
        print("scorer: output mismatch", file=sys.stderr)
        return 1                     # non-zero exit, no METRIC line

    summarise(DATA)                  # 2. warm-up run (caches, imports)

    times = []
    for _ in range(7):               # 3. several timed runs...
        t0 = time.perf_counter()     # high-resolution clock for short durations
        summarise(DATA)
        times.append((time.perf_counter() - t0) * 1000)

    # 4. ...and report the median, which resists one-off hiccups
    print(f"METRIC runtime_ms={statistics.median(times):.2f}")
    return 0

if __name__ == "__main__":
    sys.exit(main())

A realistic run:

$ python score.py
METRIC runtime_ms=41.87

The output follows three rules:

  • One labelled line on stdout. Logs and warnings go to stderr. A later script can match ^METRIC runtime_ms= and parse the number without guessing.
  • Failure is loud. A broken candidate exits non-zero and prints no metric. It never prints 0, because for a lower-is-better metric that reads as a perfect score.
  • Fixed inputs. The benchmark files sit outside the code under test, so a change can't make the problem easier.

The same scorer in TypeScript

// score.ts: run with `npx tsx score.ts`
import { readFileSync } from "node:fs";
import { isDeepStrictEqual } from "node:util";
import { summarise } from "./src/parselog";

const data = readFileSync("bench/access.log", "utf8");
const expected = JSON.parse(readFileSync("bench/expected.json", "utf8"));

if (!isDeepStrictEqual(summarise(data), expected)) {
  console.error("scorer: output mismatch");
  process.exit(1);                        // no METRIC line on failure
}

summarise(data);                          // warm-up (lets the JIT settle)
const times: number[] = [];
for (let i = 0; i < 7; i++) {
  const t0 = process.hrtime.bigint();     // nanoseconds, as a bigint
  summarise(data);
  times.push(Number(process.hrtime.bigint() - t0) / 1e6); // to ms
}
times.sort((a, b) => a - b);
console.log(`METRIC runtime_ms=${times[3].toFixed(2)}`); // median of 7

The same shape works for prompt work. Swap the timing loop for "run each labelled example through the model and count correct answers", and print METRIC accuracy=0.84. The scorer doesn't care whether the call goes to Claude, an OpenAI or Gemini model, or a local open-weight model. Only the number has to be consistent.

Write down which way is better

"41.87" means nothing until you know which direction counts as better. Runtime and val_bpb improve downward. Accuracy improves upward. Record the direction next to the metric so no human or agent has to infer it:

// objective.json
{ "metric": "runtime_ms", "direction": "lower", "scorer": "python score.py" }

Gotcha: If you flip a direction by mistake, the loop works hard to make your code worse, and every log looks healthy.

Recording the baseline

The baseline is the reference every later change is judged against, so tie it to the exact code that produced it:

git status --porcelain        # must print nothing: score committed code only
COMMIT=$(git rev-parse --short HEAD)   # abbreviated SHA of the current commit
SCORE=$(python score.py | grep '^METRIC' | cut -d= -f2)
printf "commit\tmetric\tvalue\tdirection\n%s\truntime_ms\t%s\tlower\n" \
  "$COMMIT" "$SCORE" > baseline.tsv
cat baseline.tsv
# commit   metric      value   direction
# 3f9c2ab  runtime_ms  41.87   lower

If the working tree has uncommitted edits, the hash doesn't describe what you measured. That's why the clean-tree check comes first.

Best practice: Run the scorer three times on the baseline and look at the spread. If it swings between 38 and 46 ms, a later "2 ms win" is noise. Fix the noise with more runs or a quieter machine before you trust any comparison.

Rejecting bad metrics

Before you commit to a metric, test it against three filters:

Candidate Problem Usable replacement
"Code is cleaner" Vague: no number, and people disagree Lint warnings count, if that's what you actually care about
"Accuracy after a full 6-hour training run" Too slow: about four tries a day A proxy on a fixed short budget, like autoresearch's 5 minutes
"Users like the replies more" Not automatic: needs a human each run Pass rate on a fixed labelled set, with human checks later

A rough rule: if one scorer run takes longer than you'd wait for a test suite, the loop will be starved of iterations.

Exercise

Pick a small repo of your own, or write a 30-line parselog.

  1. Turn one vague goal into a metric, a direction and a correctness gate. Write them in objective.json.
  2. Write score.py or score.ts so it prints exactly one METRIC name=value line and exits non-zero on bad output.
  3. Break the code on purpose. Confirm the scorer fails loudly and prints no metric.
  4. Commit, then record the baseline in baseline.tsv with the short hash. Run the scorer three times and note the spread.
  5. Write down one metric you rejected and which filter it failed.

Key takeaways

  • No machine-readable number means no loop. Build the scorer before the agent.
  • Print one labelled line on stdout and send everything else to stderr. Failure means a non-zero exit, never a fake score.
  • Gate on correctness so the loop can't win by being fast and wrong.
  • Record the direction explicitly. Lower is better for runtime and val_bpb, higher is better for accuracy.
  • Measure the baseline on a clean, committed tree and store it with the commit hash.
  • Reject metrics that are vague, too slow or need a human in every run.

A 6-question knowledge check follows this lesson in the app, free and without an account.

Keep going: levels 3 and 4 are free

Create a free account to open the next two levels, try the AI tutor, save your progress and pick up where you left off. No card needed.

Next: Level 3, Run the Loop by Hand First.

Create a free account →See the whole course

More like this