Sub topic 9
Controlling cost and runtime with test tiers
A regression suite that is too slow or too expensive gets skipped, and a skipped suite catches nothing. This chapter shows how to split your evals into tiers. Each tier has a trigger, a size, and a budget. The goal is a suite people will run on every change.
This chapter assumes you have a golden dataset in JSONL, deterministic checks running under pytest, and a GitHub Actions workflow like the one from the previous chapter. It also assumes you can read a pass-rate baseline and a tolerance. Prices in the examples are illustrative. Use your provider's current price list.
Where the cost comes from
Every eval case is at least one model call. The total cost of a run is:
cost = cases x repeats x (generation call + judge call)The multipliers stack. 600 cases, 3 repeats to handle nondeterminism, and a judge call per output is 3,600 calls. Runtime follows the same arithmetic, because model calls take seconds and rate limits cap how many you can run in parallel.
A small estimator makes this concrete before you commit to a design:
def estimate_cost(n_cases, repeats, in_tokens, out_tokens, price_in, price_out):
"""Prices are USD per million tokens."""
per_call = in_tokens / 1e6 * price_in + out_tokens / 1e6 * price_out
return n_cases * repeats * per_call
smoke = estimate_cost(40, 1, 1500, 300, 3.0, 15.0)
full = estimate_cost(600, 3, 1500, 300, 3.0, 15.0)
print(f"smoke: ${smoke:.2f} full: ${full:.2f}")
# smoke: $0.36 full: $16.20At $0.36 you can run the smoke suite on every push. At $16.20 you cannot, because ten pushes to a pull request cost $162. The cost gap between tiers is what makes tiering worthwhile.
The three tiers
A tier is a named subset of the suite with its own trigger and budget. Three is a good starting point.
| Tier | Runs when | Cases | Repeats | Judge | Target |
|---|---|---|---|---|---|
| smoke | Every pull request push | 30 to 50 | 1 | None, or a cheap model | Under 3 minutes, cents |
| standard | Pull requests that touch prompts or model settings, and merges to main | Several hundred | 1 to 2 | Cheap judge | Under 15 minutes, a few dollars |
| full | Nightly, before a release, and on model upgrades | Everything | 3 to 5 | Strongest judge | An hour or less, tens of dollars |
The tiers are cumulative. Every smoke case also belongs to standard and full. This lets you read a smoke failure as a subset of a larger failure instead of a different problem.
Choosing what goes in the smoke tier
The smoke tier has to be small and still sensitive. A random sample of the dataset gives you neither. Build it deliberately:
- Include one or two cases for each failure category you have seen in production.
- Include every case from a past incident. These are the regressions you already know how to cause.
- Include your safety and refusal cases, since a break there is serious even when the pass rate looks fine.
- Prefer cases that pass reliably. A smoke case that flickers between pass and fail wastes everyone's attention.
Mark each case with the lowest tier at which it runs. Add a tier field to each line of the dataset:
{"id": "refund-001", "tier": "smoke", "input": "I want my money back for order 1182", "required_keys": ["intent", "reply"], "must_contain": ["refund"]}
{"id": "refund-014", "tier": "full", "input": "chargeback vs refund, which is faster?", "required_keys": ["intent", "reply"]}A case with no tier field defaults to standard. Choosing that default is a decision about what you want to happen when someone forgets to label a case.
Selecting a tier at run time
Keep the selection logic in one small module so the test file and any scripts agree on what each tier contains.
# evals/tiers.py
import json
from pathlib import Path
ORDER = {"smoke": 0, "standard": 1, "full": 2}
def load_cases(path, tier):
"""Return every case whose tier is at or below the requested tier."""
limit = ORDER[tier]
cases = []
for line in Path(path).read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
case = json.loads(line)
if ORDER[case.get("tier", "standard")] <= limit:
cases.append(case)
return casesThe test file reads the tier from an environment variable. That keeps CI configuration out of the code and lets you run any tier on your laptop.
# evals/test_cases.py
import json
import os
import pytest
from app.llm import run_prompt # your own wrapper around the model call
from tiers import load_cases
TIER = os.environ.get("EVAL_TIER", "smoke")
CASES = load_cases("evals/cases.jsonl", TIER)
@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
def test_case(case):
output = run_prompt(case["input"])
data = json.loads(output)
assert set(case["required_keys"]) <= set(data)
for phrase in case.get("must_contain", []):
assert phrase.lower() in output.lower()Run it with EVAL_TIER=standard pytest evals -q. Defaulting to smoke means a bare pytest on a developer machine is cheap.
Pytest's default import mode puts the test file's directory on sys.path, which is why from tiers import load_cases works here. If you use a different import mode or package layout, adjust the import.
Cheaper ways to run the same checks
Tiers decide how many cases run. These techniques cut the cost of each case.
Run deterministic checks before the judge
A judge call costs as much as a generation call, sometimes more. If the output is not valid JSON or lacks a required key, a judge score adds no information. Order checks from cheapest to most expensive and stop at the first failure. In the pytest example above, a failed assert already stops the test, so put the judge call last in the function.
Use a cheaper judge below the full tier
A small model can grade easy rubrics such as "does the reply mention the refund policy?" at a fraction of the price. Reserve the strongest judge for the full tier and for rubrics that need fine distinctions. Either way, the judge must still agree with your human labels. Re-check agreement whenever you swap the judge model, because a cheap judge that disagrees with humans is worse than no judge.
Cache model outputs while you iterate
When you are only changing a check, or re-running after a flaky infrastructure failure, the model outputs have not changed. Cache them under a key that covers everything that could change the output:
import hashlib
import json
from pathlib import Path
CACHE_DIR = Path(".eval_cache")
def cache_key(prompt_text, model, params, case_input, repeat=0):
payload = json.dumps(
{
"prompt": prompt_text,
"model": model,
"params": params,
"input": case_input,
"repeat": repeat,
},
sort_keys=True,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def cached_call(call, prompt_text, model, params, case_input, repeat=0):
CACHE_DIR.mkdir(exist_ok=True)
path = CACHE_DIR / f"{cache_key(prompt_text, model, params, case_input, repeat)}.json"
if path.exists():
return json.loads(path.read_text(encoding="utf-8"))["output"]
output = call(prompt_text, model, params, case_input)
path.write_text(json.dumps({"output": output}), encoding="utf-8")
return outputThe repeat index is part of the key on purpose. Without it, three repeats of one case would return the same cached text three times, and your variance measurement would show no variance.
Run in parallel, within rate limits
Model calls spend most of their time waiting, so parallelism helps a lot. With pytest-xdist, pytest evals -n 8 runs eight workers. Too many workers produce HTTP 429 rate-limit errors, which look like test failures. Your run_prompt wrapper should retry on 429 and 5xx responses with exponential backoff, and it should never count an exhausted retry as a model regression. Report it as an infrastructure error instead.
Cap spending
A runaway loop or a dataset ten times bigger than expected can produce a surprising bill. Add a hard budget to the harness:
class BudgetExceeded(RuntimeError):
pass
class Budget:
def __init__(self, max_usd):
self.max_usd = max_usd
self.spent = 0.0
def charge(self, usd):
self.spent += usd
if self.spent > self.max_usd:
raise BudgetExceeded(
f"Spent ${self.spent:.2f}, limit is ${self.max_usd:.2f}"
)Call charge after each model call with the cost computed from the token counts the API returns. Set the limit per tier, for example $1 for smoke and $40 for full. Also set timeout-minutes on the CI job as a second guard.
Wiring the tiers into CI
One workflow can serve all three tiers. The trigger decides the tier. Path filters send prompt changes to a larger tier.
name: prompt-regression
on:
pull_request:
paths:
- "prompts/**"
- "evals/**"
- "app/**"
schedule:
- cron: "0 3 * * *"
workflow_dispatch:
inputs:
tier:
description: "smoke, standard, or full"
default: "full"
concurrency:
group: evals-${{ github.ref }}
cancel-in-progress: true
jobs:
evals:
runs-on: ubuntu-latest
timeout-minutes: 60
env:
EVAL_TIER: ${{ github.event_name == 'pull_request' && 'smoke' || github.event.inputs.tier || 'full' }}
LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements.txt
- run: pytest evals -q -n 4Three details matter here:
concurrencywithcancel-in-progressstops the older run when you push again to the same branch. Without it, three quick pushes pay for three full runs.- The
EVAL_TIERexpression pickssmokefor pull requests, the manual input for a dispatch, andfullfor the nightly schedule, where no input exists. -n 4needspytest-xdistinrequirements.txt.
To escalate to the standard tier when a prompt file changes, add a second job gated by a path filter action, or split the workflow in two files, one triggered by prompts/** with EVAL_TIER: standard. Pull requests from forks do not receive repository secrets, so the eval job will fail for them. Decide up front whether maintainers re-run those from a trusted branch.
Failure modes of tiering
- Smoke passes, full fails. This is expected, and it is the reason the full tier exists. Treat a nightly failure as a bug report against the commits since the last green night. Use the report to find which cases failed, then bisect the commits.
- Smoke is too narrow. If regressions keep reaching the nightly run, the smoke set misses a category. Add one case from each missed regression to the smoke tier.
- Smoke is too flaky. If developers re-run it to get green, they have stopped trusting it. Replace flickering cases with stable ones, or move them to a tier that uses repeats and a threshold.
- Silent skips. A path filter that never matches means the suite never runs. Check once that a change to each watched path actually triggers the job.
- Model upgrades. Changing the model version can alter every output. Always run the full tier for that change, regardless of how small the diff looks.
Exercise
Your full tier has 500 cases and 4 repeats. Each generation call costs $0.006 and each judge call costs $0.004. What does one full run cost, and what is the cost if you skip judge calls on cases whose deterministic checks already failed, assuming 10% of the 2,000 outputs fail those checks?
Show answer
One full run makes 500 x 4 = 2,000 outputs. With a judge call on each, the cost is 2,000 x ($0.006 + $0.004) = $20.00. If 10% of outputs (200) fail deterministic checks and skip the judge, you save 200 x $0.004 = $0.80, so the run costs $19.20. The saving is small here because generation dominates. It grows when the judge is more expensive than the generator or when the failure rate is higher.
Exercise
A developer's pull request changes only a file under prompts/. The smoke tier passes. Why is that not enough to merge, and what change to your CI setup addresses it?
Show answer
A prompt edit can change behavior for any input, but the smoke tier covers only 30 to 50 cases. A regression in an uncovered category passes unnoticed. Add a path-triggered job that runs the standard tier whenever prompts/** changes, so the larger set of cases and the threshold against the baseline check the edit before merge. The full tier still runs nightly as a backstop.