Designing an Evaluation Framework for Local Language Models
System DesignModel answerLast updated
Design and implement a robust, extensible evaluation harness for local LLM endpoints with metrics, concurrency control, and fault tolerance.
Engineers and researchers frequently need to evaluate language model performance on custom offline datasets. Relying on cloud APIs can become expensive and introduce external privacy concerns, leading many teams to serve models locally (e.g., via Ollama, vLLM, or TGI).
Design and implement a lightweight, production-grade evaluation harness capable of testing a locally served language model.
Requirements
- Data Ingestion & Processing: Read test cases containing at least an
id, aprompt, and an optionalreference_answer. - Execution & Metadata Capture: Execute prompts against a local inference endpoint (such as Ollama). Record status (
okorerror), response content, latency, retry counts, token usage, and system configuration. - Metrics & Aggregation: Compute standard system and accuracy metrics, such as exact match rate, overall pass rate, response latency percentiles ($P_{50}$, $P_{95}$), and infra error rates.
- Reliability & Resilience: Handle hardware timeouts, transient server failures, and out-of-memory events gracefully using retries with backoff, concurrency limits, and stateful checkpointing/resumability.
- Extensibility: Architect the solution cleanly so that alternative inference backends (e.g., OpenAI, vLLM) and custom metric evaluation functions (e.g., regex extraction, BLEU, LLM-as-judge) can be swapped in with minimal code changes.
Explain your architecture, metric definitions, concurrency trade-offs, and failure mitigation strategies. Provide a runnable Python implementation illustrating the core runner, backend abstraction, and scoring mechanism.
Hints
Hint 1
Distinguish clearly between infrastructure error rate, accuracy on valid responses (Exact Match), and total end-to-end task success (Pass Rate).
Hint 2
Consider how local server parallel settings (like OLLAMA_NUM_PARALLEL) interact with client-side concurrency controls.
Hint 3
Ensure the evaluation harness persists state per-example to enable resuming an evaluation run after an unexpected crash or system reset.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. System Requirements & Architecture Overview
Evaluating local models poses unique operational challenges compared to calling cloud APIs. Local engines can crash due to Out-of-Memory (OOM) errors, lock up when context windows fill up, or bottleneck under excessive parallel requests.
Key Considerations
- Throughput vs. Queueing: An evaluation dataset might contain $1,000$ to $50,000$ prompts. Running serially at $3\text{ seconds/prompt}$ for $10,000$ prompts takes over 8 hours. Introducing client-side concurrency speeds this up, but exceeding the server's local compute capacity (
OLLAMA_NUM_PARALLEL) simply creates internal queueing and inflates measured latency. - Resumability: Given long runtime windows, the harness must write results incrementally. If the job fails at sample 8,500, restarting it should pick up at sample 8,501 without re-running previous inferences.
- Separation of Infrastructure Failure from Model Quality: System errors (e.g., HTTP 500 or timeout) should not be conflated with incorrect answers.
+-----------------------------------------------------------------------+
| Evaluation Harness |
| |
| +------------------+ +-------------------+ +--------------+ |
| | Dataset Loader | | Execution Runner | | Backend | |
| | (JSONL / Scenarios)-->| (Async Task Pool) |--->| Interface |--+--> [ Local Ollama Server ]
| +------------------+ +-------------------+ +--------------+ |
| | |
| v |
| +-------------------+ |
| | Metric Scorers | |
| | (ExactMatch, etc) | |
| +-------------------+ |
| | |
| v |
| +-------------------+ |
| | Stream Writer & | |
| | Aggregator | |
| +-------------------+ |
| | |
+-------------------------------------|---------------------------------+
v
[ results.jsonl & summary.json ]
2. Metric Definitions & Data Schema
To accurately assess performance, we define metrics over explicit subsets of the dataset:
| Metric | Calculation | Purpose |
|---|---|---|
| Error Rate | $\frac{\text{Count}(\text{status} = \text{error})}{\text{Total Samples}}$ | Evaluates server stability and reliability. |
| Exact Match (EM) | $\frac{\text{Count}(\text{correct} = \text{True})}{\text{Count}(\text{status} = \text{ok} \land \text{has_reference})}$ | Measures model output correctness purely on successful requests. |
| Pass Rate | $\frac{\text{Count}(\text{correct} = \text{True})}{\text{Total Samples with Reference}}$ | Measures end-to-end task completion (infrastructure failures count as incorrect). |
| Latency ($P_{50}, P_{95}$) | Quantiles of latency_s where $\text{status} = \text{ok}$ | Evaluates generation speed without including backoff delay from retries. |
Data Schemas
Per-Sample Result Output (results.jsonl):
{
"id": "item_042",
"model": "llama3.1:8b",
"backend": "ollama",
"prompt": "What is the capital of France?",
"output": "Paris",
"reference_answer": "Paris",
"correct": true,
"status": "ok",
"error": null,
"attempts": 1,
"latency_s": 0.412,
"tokens_out": 2,
"timestamp": "2023-10-27T10:00:00Z"
}
3. Implementation
The following complete Python program demonstrates an asynchronous evaluation framework supporting retry mechanisms, state persistence, concurrency control, and modular backends.
import asyncio
import json
import math
import os
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Protocol
import httpx
# ---------------------------------------------------------------------------
# Configuration & Core Data Classes
# ---------------------------------------------------------------------------
@dataclass
class EvalConfig:
model: str = "llama3.1:8b"
base_url: str = "http://localhost:11434"
timeout_s: float = 60.0
max_retries: int = 3
temperature: float = 0.0
seed: Optional[int] = 42
concurrency: int = 4
output_dir: str = "./eval_results"
@dataclass
class GenResult:
text: str
tokens_out: Optional[int] = None
meta: Dict[str, Any] = field(default_factory=dict)
class TransientError(Exception):
"""Raised when an error occurs that is safe to retry (e.g., 503, timeouts)."""
pass
# ---------------------------------------------------------------------------
# Backend Abstraction Layer
# ---------------------------------------------------------------------------
class InferenceBackend(Protocol):
name: str
async def generate(self, prompt: str, cfg: EvalConfig) -> GenResult:
...
async def close(self) -> None:
...
class OllamaBackend:
name = "ollama"
def __init__(self, cfg: EvalConfig):
self.client = httpx.AsyncClient(
base_url=cfg.base_url,
timeout=httpx.Timeout(cfg.timeout_s)
)
async def generate(self, prompt: str, cfg: EvalConfig) -> GenResult:
options: Dict[str, Any] = {"temperature": cfg.temperature}
if cfg.seed is not None:
options["seed"] = cfg.seed
payload = {
"model": cfg.model,
"prompt": prompt,
"stream": False,
"options": options,
}
try:
response = await self.client.post("/api/generate", json=payload)
except (httpx.TransportError, httpx.TimeoutException) as exc:
raise TransientError(f"Network failure: {exc}") from exc
if response.status_code in (429, 502, 503, 504):
raise TransientError(f"Server busy (HTTP {response.status_code})")
if response.status_code != 200:
# 4xx errors (except 429) are unrecoverable; do not wrap in TransientError
raise RuntimeError(f"HTTP {response.status_code}: {response.text}")
data = response.json()
return GenResult(
text=data.get("response", ""),
tokens_out=data.get("eval_count"),
meta={"created_at": data.get("created_at")}
)
async def close(self) -> None:
await self.client.aclose()
# ---------------------------------------------------------------------------
# Scoring Logic
# ---------------------------------------------------------------------------
def normalize_text(text: str) -> str:
"""Standardizes string formatting by stripping space and lowercasing."""
return " ".join(text.strip().casefold().split())
def exact_match_scorer(output: str, reference: str) -> bool:
return normalize_text(output) == normalize_text(reference)
# ---------------------------------------------------------------------------
# Execution Pipeline & Resilience Layer
# ---------------------------------------------------------------------------
async def process_single_case(
case: Dict[str, Any],
backend: InferenceBackend,
cfg: EvalConfig,
semaphore: asyncio.Semaphore
) -> Dict[str, Any]:
case_id = case["id"]
prompt = case["prompt"]
reference = case.get("reference_answer")
record: Dict[str, Any] = {
"id": case_id,
"model": cfg.model,
"backend": backend.name,
"prompt": prompt,
"reference_answer": reference,
"output": None,
"correct": None,
"status": "error",
"error": None,
"attempts": 0,
"latency_s": None,
"tokens_out": None,
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
}
async with semaphore:
for attempt in range(1, cfg.max_retries + 2):
record["attempts"] = attempt
start_time = time.perf_counter()
try:
result = await backend.generate(prompt, cfg)
elapsed = time.perf_counter() - start_time
record["output"] = result.text
record["tokens_out"] = result.tokens_out
record["latency_s"] = round(elapsed, 4)
record["status"] = "ok"
if reference is not None:
record["correct"] = exact_match_scorer(result.text, reference)
return record
except TransientError as exc:
record["error"] = str(exc)
if attempt <= cfg.max_retries:
# Exponential backoff with light jitter
backoff = (2 ** (attempt - 1)) + (0.1 * attempt)
await asyncio.sleep(backoff)
else:
break
except Exception as exc:
# Permanent failure (e.g., malformed input, 400 Bad Request)
record["error"] = f"Fatal: {str(exc)}"
break
return record
class EvaluationHarness:
def __init__(self, cfg: EvalConfig, backend: InferenceBackend):
self.cfg = cfg
self.backend = backend
self.out_dir = Path(cfg.output_dir)
self.out_dir.mkdir(parents=True, exist_ok=True)
self.results_path = self.out_dir / "results.jsonl"
self.summary_path = self.out_dir / "summary.json"
def _load_completed_ids(self) -> set:
completed = set()
if self.results_path.exists():
with open(self.results_path, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
data = json.loads(line)
completed.add(data["id"])
return completed
async def run(self, dataset: List[Dict[str, Any]]) -> None:
completed_ids = self._load_completed_ids()
pending_cases = [c for c in dataset if c["id"] not in completed_ids]
print(f"Total cases: {len(dataset)} | Already completed: {len(completed_ids)} | Remaining: {len(pending_cases)}")
semaphore = asyncio.Semaphore(self.cfg.concurrency)
with open(self.results_path, "a", encoding="utf-8") as out_file:
tasks = [
process_single_case(case, self.backend, self.cfg, semaphore)
for case in pending_cases
]
for future in asyncio.as_completed(tasks):
record = await future
out_file.write(json.dumps(record) + "\n")
out_file.flush()
self.generate_summary()
def generate_summary(self) -> Dict[str, Any]:
records = []
with open(self.results_path, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
records.append(json.loads(line))
total = len(records)
if total == 0:
return {}
errors = [r for r in records if r["status"] == "error"]
successes = [r for r in records if r["status"] == "ok"]
latencies = sorted([r["latency_s"] for r in successes if r["latency_s"] is not None])
def percentile(arr: List[float], p: float) -> Optional[float]:
if not arr:
return None
k = (len(arr) - 1) * p
f = math.floor(k)
c = math.ceil(k)
if f == c:
return arr[int(k)]
return arr[int(f)] * (c - k) + arr[int(c)] * (k - f)
scored_records = [r for r in records if r["reference_answer"] is not None]
scored_successes = [r for r in scored_records if r["status"] == "ok"]
correct_records = [r for r in scored_records if r.get("correct") is True]
summary = {
"config": asdict(self.cfg),
"counts": {
"total": total,
"ok": len(successes),
"error": len(errors),
"with_reference": len(scored_records)
},
"metrics": {
"error_rate": round(len(errors) / total, 4),
"exact_match": round(len(correct_records) / len(scored_successes), 4) if scored_successes else None,
"pass_rate": round(len(correct_records) / len(scored_records), 4) if scored_records else None,
},
"latency_seconds": {
"mean": round(sum(latencies) / len(latencies), 4) if latencies else None,
"p50": round(percentile(latencies, 0.50), 4) if latencies else None,
"p95": round(percentile(latencies, 0.95), 4) if latencies else None,
}
}
with open(self.summary_path, "w", encoding="utf-8") as f:
json.dump(summary, f, indent=2)
return summary
4. Complexity & Operational Trade-Offs
Time & Resource Complexity
- Time Complexity: For $N$ items, serial processing takes $\mathcal{O}\left(N \cdot T_{\text{gen}}\right)$. Under client concurrency $C$, runtime scales near $\mathcal{O}\left(\frac{N \cdot T_{\text{gen}}}{\min(C, S)}\right)$, where $S$ is the maximum parallel slot limit configured on the local LLM server.
- Space Complexity: Memory overhead is kept to $\mathcal{O}(C)$ concurrent prompt streams in flight. Writing JSONL line-by-line keeps memory footprint flat regardless of whether the dataset contains 1,000 or 1,000,000 items.
Common Pitfalls & Solutions
- Silent Failures vs. Crash Early: Client non-retryable status codes (like
404 Model Not Found) should fail immediately instead of consuming retries across all items in the dataset. - Normalizing Exact Match: Without string stripping and case-folding, outputs like
" Paris"or"Paris\n"fail exact match checks against"Paris". - Local Server Overload: If concurrency is configured too high on the client, request queues backlog inside the local server. Setting client concurrency to match server parallelism yields optimal latency profiles.