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

# Evals and RL

> Score a model or an agent on many tasks: one identical, isolated environment per episode, all running in parallel, a checker that runs inside each, and the results collected into one table.

To find out whether a new prompt, model or agent is actually better, you run it on **many tasks** and score each
result. This is called an *eval*. For coding tasks, scoring means **running code**: the model's solution is run
against tests it has not seen. Reinforcement learning (RL) is similar: each attempt, called an *episode*, needs a
fresh environment in which the model can act.

Both need the same thing: **a clean, identical machine for every episode**, many of them at once, with nothing
shared between them, so that one episode can never affect another's score. Here is how Fibre provides each part:

| Need | Fibre |
| - | - |
| Identical starting state | Every episode is a copy of one [snapshot](https://docs.fibre.dev/setup/snapshots.md) |
| No cross-talk | Each episode has its own sandbox |
| Throughput | All episodes in parallel |
| Untrusted solutions | Run the model's code with [no network](https://docs.fibre.dev/production/network.md) |
| Cost | Billed per second while each episode runs |

## A small eval

This example evaluates three small programming tasks. For each task there is a candidate solution (standing in
for what a model would return) and a set of hidden test cases. Every episode runs in its own sandbox, with no
network access, and the scores are collected into one table.

**1. The environment, once**

```bash title="CLI" run theme={null}
ENV=$(fibre create --no-network --lifetime 30m --label eval=docs-demo --json | jq -r .id)
fibre exec "$ENV" -i -- sh -c 'mkdir -p /eval && cat > /eval/run.py' <<'PY'
import json, sys, importlib.util
spec = importlib.util.spec_from_file_location("solution", "/eval/solution.py")
solution = importlib.util.module_from_spec(spec); spec.loader.exec_module(solution)
cases = json.load(open("/eval/cases.json"))
passed = sum(1 for c in cases if solution.solve(*c["input"]) == c["expected"])
print(json.dumps({"passed": passed, "total": len(cases)}))
PY
fibre snapshot create docs-eval-env --from "$ENV"
```

```typescript title="TypeScript" run theme={null}
import { Sandbox, Snapshot } from "@fibre-dev/sdk";

const env = await Sandbox.create({ network: { block: true }, lifetime: 1800, labels: { eval: "docs-demo" } });
await env.files.write("/eval/run.py", `
import json, sys, importlib.util
spec = importlib.util.spec_from_file_location("solution", "/eval/solution.py")
solution = importlib.util.module_from_spec(spec); spec.loader.exec_module(solution)
cases = json.load(open("/eval/cases.json"))
passed = sum(1 for c in cases if solution.solve(*c["input"]) == c["expected"])
print(json.dumps({"passed": passed, "total": len(cases)}))
`);
await env.snapshot({ name: "docs-eval-env" });
```

```python title="Python" run theme={null}
from fibre import Sandbox, Snapshot

env = Sandbox.create(network={"block": True}, lifetime=1800, labels={"eval": "docs-demo"})
env.files.write("/eval/run.py", """
import json, sys, importlib.util
spec = importlib.util.spec_from_file_location("solution", "/eval/solution.py")
solution = importlib.util.module_from_spec(spec); spec.loader.exec_module(solution)
cases = json.load(open("/eval/cases.json"))
passed = sum(1 for c in cases if solution.solve(*c["input"]) == c["expected"])
print(json.dumps({"passed": passed, "total": len(cases)}))
""")
env.snapshot(name="docs-eval-env")
```

**2. The tasks and the model's answers**

```bash title="CLI" run theme={null}
mkdir -p episodes/reverse episodes/fibonacci episodes/palindrome
printf 'def solve(s):\n    return s[::-1]\n' > episodes/reverse/solution.py
echo '[{"input": ["abc"], "expected": "cba"}, {"input": [""], "expected": ""}]' > episodes/reverse/cases.json
printf 'def solve(n):\n    a, b = 0, 1\n    for _ in range(n): a, b = b, a + b\n    return a\n' > episodes/fibonacci/solution.py
echo '[{"input": [0], "expected": 0}, {"input": [10], "expected": 55}, {"input": [20], "expected": 6765}]' > episodes/fibonacci/cases.json
printf 'def solve(s):\n    return s == s[::-1]\n' > episodes/palindrome/solution.py   # misses case and spaces: should fail one case
echo '[{"input": ["racecar"], "expected": true}, {"input": ["Never odd or even"], "expected": true}]' > episodes/palindrome/cases.json
```

```typescript title="TypeScript" run theme={null}
const episodes = [
  {
    task: "reverse a string",
    solution: "def solve(s):\n    return s[::-1]\n",
    cases: [{ input: ["abc"], expected: "cba" }, { input: [""], expected: "" }],
  },
  {
    task: "nth fibonacci",
    solution: "def solve(n):\n    a, b = 0, 1\n    for _ in range(n): a, b = b, a + b\n    return a\n",
    cases: [{ input: [0], expected: 0 }, { input: [10], expected: 55 }, { input: [20], expected: 6765 }],
  },
  {
    task: "is a palindrome",
    solution: "def solve(s):\n    return s == s[::-1]\n",          // misses case and spaces: should fail one case
    cases: [{ input: ["racecar"], expected: true }, { input: ["Never odd or even"], expected: true }],
  },
];
```

```python title="Python" run theme={null}
episodes = [
    {
        "task": "reverse a string",
        "solution": "def solve(s):\n    return s[::-1]\n",
        "cases": [{"input": ["abc"], "expected": "cba"}, {"input": [""], "expected": ""}],
    },
    {
        "task": "nth fibonacci",
        "solution": "def solve(n):\n    a, b = 0, 1\n    for _ in range(n): a, b = b, a + b\n    return a\n",
        "cases": [{"input": [0], "expected": 0}, {"input": [10], "expected": 55}, {"input": [20], "expected": 6765}],
    },
    {
        "task": "is a palindrome",
        "solution": "def solve(s):\n    return s == s[::-1]\n",  # misses case and spaces: should fail one case
        "cases": [{"input": ["racecar"], "expected": True}, {"input": ["Never odd or even"], "expected": True}],
    },
]
```

**3. Run every episode in parallel**

```bash title="CLI" run theme={null}
mkdir -p scores
for ep in reverse fibonacci palindrome; do
  (
    S=$(fibre create --snapshot docs-eval-env --lifetime 10m --label eval=docs-demo --label episode=$ep --json | jq -r .id)
    fibre cp episodes/$ep/solution.py "$S:/eval/solution.py" > /dev/null
    fibre cp episodes/$ep/cases.json "$S:/eval/cases.json" > /dev/null
    fibre exec "$S" --timeout 60 -- python3 /eval/run.py > scores/$ep.json
    fibre delete "$S" > /dev/null
  ) &
done
wait

for ep in reverse fibonacci palindrome; do echo "$ep $(jq -r '"\(.passed) / \(.total)"' scores/$ep.json)"; done
# reverse 2 / 2 · fibonacci 3 / 3 · palindrome 1 / 2
jq -s '"score: \((map(.passed) | add) * 100 / (map(.total) | add) | round)%"' -r scores/*.json   # score: 86%
```

```typescript title="TypeScript" run theme={null}
const scores = await Promise.all(episodes.map(async (ep, i) => {
  const sbx = await Sandbox.create({ snapshot: "docs-eval-env", lifetime: 600, labels: { eval: "docs-demo", episode: String(i) } });
  try {
    await sbx.files.write("/eval/solution.py", ep.solution);
    await sbx.files.write("/eval/cases.json", JSON.stringify(ep.cases));
    const r = await sbx.run("python3 /eval/run.py", { timeout: 60 });
    return { task: ep.task, ...JSON.parse(r.stdout) };
  } finally {
    await sbx.delete();
  }
}));

console.table(scores);
// reverse a string    2 / 2
// nth fibonacci       3 / 3
// is a palindrome     1 / 2
const total = scores.reduce((t, s) => t + s.passed, 0) / scores.reduce((t, s) => t + s.total, 0);
console.log(`score: ${(total * 100).toFixed(0)}%`); // score: 86%
```

```python title="Python" run theme={null}
import asyncio
import json

from fibre import AsyncSandbox


async def score(i, ep):
    async with await AsyncSandbox.create(snapshot="docs-eval-env", lifetime=600, labels={"eval": "docs-demo", "episode": str(i)}) as sbx:
        await sbx.files.write("/eval/solution.py", ep["solution"])
        await sbx.files.write("/eval/cases.json", json.dumps(ep["cases"]))
        r = await sbx.run("python3 /eval/run.py", timeout=60)
        return {"task": ep["task"], **json.loads(r.stdout)}


async def main():
    return await asyncio.gather(*(score(i, ep) for i, ep in enumerate(episodes)))


scores = asyncio.run(main())
for s in scores:
    print(f"{s['task']:20} {s['passed']} / {s['total']}")
# reverse a string     2 / 2
# nth fibonacci        3 / 3
# is a palindrome      1 / 2
total = sum(s["passed"] for s in scores) / sum(s["total"] for s in scores)
print(f"score: {total:.0%}")  # score: 86%
```

**4. Clean up**

```bash title="CLI" run theme={null}
fibre snapshot delete docs-eval-env
fibre delete "$ENV"
rm -rf episodes scores
```

```typescript title="TypeScript" run theme={null}
await (await Snapshot.get("docs-eval-env")).delete();
await env.delete();
```

```python title="Python" run theme={null}
Snapshot.get("docs-eval-env").delete()
env.delete()
```

## For agents and RL

The same approach works for agent benchmarks and RL training runs. Each episode goes through four stages:

1. **It starts from the task's snapshot**: for example a repository at a given commit, a database with data in it,
   or a desktop with an application open.
2. **The agent acts**: it runs commands, edits files, or uses the browser or [desktop](https://docs.fibre.dev/connect/desktop.md), for as many
   steps as it needs.
3. **A checker scores the result** inside the same sandbox, for example by running hidden tests, comparing the
   final state, or computing a reward.
4. **The sandbox is deleted**, so the next episode starts from a clean state.

Because a sandbox keeps its memory while it sleeps, **a long episode can pause**, for example while it waits for a
slow model or for a person to label something, without keeping a machine awake and paid for.

## At scale

When you run hundreds or thousands of episodes, keep these points in mind:

| | |
| - | - |
| Hundreds of episodes | Fan out in batches below your plan's sandboxes-at-once; [limits](https://docs.fibre.dev/production/errors-and-limits.md#limits) |
| Retries | An `Idempotency-Key` per episode, so a retried create never doubles an episode |
| Reproducibility | Version the snapshot name (`swe-task-1432-v2`); the same snapshot gives the same start |
| Cost | Per second: 500 episodes of 2 minutes on `small` is about 17 hours, **\$0.25** |

## Related

> [card] [Snapshots](https://docs.fibre.dev/setup/snapshots.md)
>
> How every episode gets the same starting point.

> [card] [Agents in parallel](https://docs.fibre.dev/use-cases/parallel.md)
>
> The same pattern, used for real work instead of scoring.


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