"""Benchmark evaluation.
* IPA - instruction parsing accuracy: the predicted plan matches a reference plan step by step.
* IPA-strict - every parameter matches exactly (unstated ones at their defaults);
* TSR - task success rate: predicted and reference plans are executed in the kinematic simulator
from the same start; success if the end poses agree within ``robot.control.goal_tolerance_m`` (0.2
m in the paper) and ``yaw_tolerance_deg``, and the same queries were answered;
* ART - average response time of the planner (instruction -> parsed plan).
Benchmark file::
{"id": "de-001", "language": "de", "tier": "HRL", "category": "W_c",
"text": "Fahre zwei Meter vorwärts.", "intent": "execute",
"gold": [{"action": "MOVE", "distance": 2}],
"alternatives": [[...another acceptable plan...]],
"start": {"x": 0, "y": 0, "yaw_deg": 0}}
``intent`` may be a list of acceptable intents (e.g. ``["execute", "clarify"]`` when asking for a
missing value is as good as assuming the default). STOP steps are ignored when comparing plans,
because they have no effect on the outcome.
"""
from __future__ import annotations
import gzip
import json
import logging
import math
import random
import time
from collections import Counter, defaultdict
from collections.abc import Iterable
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
from .actions import Catalog, expand, is_motion
from .config import ReLIConfig
from .executor import Executor
from .llm import LLMError, LLMProvider
from .perception.base import tokens
from .perception.grounder import SimGrounder
from .planner import Planner, PlanningContext
from .prompts import Prompts
from .robot.sim import SimRobot
from .safety import SafetyGuard
from .types import Action, Pose2D
log = logging.getLogger(__name__)
@dataclass
class Tolerance:
abs: float = 0.05 # metres / degrees / seconds
rel: float = 0.05
yaw_deg: float = 15.0
@dataclass
class ItemResult:
id: str
language: str
tier: str
category: str
text: str
intent_gold: list[str]
intent_pred: str | None = None
predicted: list[dict] = field(default_factory=list)
ipa: bool = False
ipa_strict: bool = False
tsr: bool = False
latency_s: float | None = None
error: str | None = None
# ------------------------------------------------------------- comparison
def _close(a: Any, b: Any, tol: Tolerance, strict: bool) -> bool:
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
if strict:
return math.isclose(a, b, abs_tol=1e-6)
return abs(a - b) <= max(tol.abs, tol.rel * abs(b))
sa, sb = str(a).strip().casefold(), str(b).strip().casefold()
if strict or sa == sb:
return sa == sb
# Noun phrases: "chair" matches "the chair near you" (one contains the other).
ta, tb = tokens(sa), tokens(sb)
return bool(ta and tb) and (ta <= tb or tb <= ta)
def _effective(actions: list[Action]) -> list[Action]:
"""Expanded primitives without STOP steps (they do not change the outcome)."""
prims = expand(actions)
kept = [a for a in prims if a.name != "STOP"]
return kept if kept else prims
[docs]
def plans_match(pred: list[Action], gold: list[Action], tol: Tolerance, strict: bool) -> bool:
"""Compare expanded primitives. The tolerant variant only checks parameters the reference
states; the strict variant compares every parameter."""
p, g = _effective(pred), _effective(gold)
if len(p) != len(g):
return False
for a, b in zip(p, g, strict=True):
if a.name != b.name:
return False
keys = set(b.params) | (set(a.params) if strict else set())
for k in keys:
va, vb = a.params.get(k), b.params.get(k)
if vb is None and not strict:
continue
if (va is None) != (vb is None):
return False
if va is not None and not _close(va, vb, tol, strict):
return False
return True
# -------------------------------------------------------------- execution
def _simulate(cfg: ReLIConfig, actions: list[Action], start: Pose2D) -> tuple[Pose2D, Counter]:
robot = SimRobot(cfg.robot)
robot.set_pose(start)
grounder = SimGrounder(cfg, robot.pose) if cfg.robot.sim.objects else None
executor = Executor(cfg, robot, grounder, SafetyGuard(cfg))
executor.run(expand(actions))
queries = Counter(a.name for a in actions if not is_motion([a]))
return robot.pose(), queries
[docs]
def task_success(
cfg: ReLIConfig, pred: list[Action], gold: list[Action], start: Pose2D, tol: Tolerance
) -> bool:
end_p, q_p = _simulate(cfg, pred, start)
end_g, q_g = _simulate(cfg, gold, start)
dyaw = abs(
math.degrees(math.atan2(math.sin(end_p.yaw - end_g.yaw), math.cos(end_p.yaw - end_g.yaw)))
)
near = math.hypot(end_p.x - end_g.x, end_p.y - end_g.y) <= cfg.robot.control.goal_tolerance_m
return near and dyaw <= tol.yaw_deg and q_p == q_g
# --------------------------------------------------------------- runner
def load_benchmark(path: str | Path) -> list[dict]:
"""Read a JSONL(.gz) benchmark: a path, or a bundled one by name (``sample``, ``paper``)."""
from .config import find_file
path = find_file(path, "benchmarks", (".jsonl.gz", ".jsonl"))
items = []
opener = gzip.open if str(path).endswith(".gz") else open
with opener(path, "rt", encoding="utf-8") as f:
for n, line in enumerate(f, 1):
line = line.strip()
if line and not line.startswith("#"):
try:
items.append(json.loads(line))
except json.JSONDecodeError as exc:
raise ValueError(f"{path}:{n}: {exc}") from exc
return items
[docs]
def evaluate(
cfg: ReLIConfig, provider: LLMProvider, items: Iterable[dict], tol: Tolerance | None = None
) -> list[ItemResult]:
tol = tol or Tolerance()
cfg = cfg.model_copy(deep=True)
cfg.robot.sim.realtime_factor = 0 # simulate as fast as possible
caps = {"camera"} if cfg.robot.sim.objects else set()
catalog = Catalog(caps, list(cfg.destinations), cfg.safety.allowed_actions)
planner = Planner(
cfg,
provider,
Prompts.load(cfg.resolve(cfg.prompts_file) if cfg.prompts_file else None),
catalog,
)
results = []
for i, item in enumerate(items, 1):
s = item.get("start") or {}
start = Pose2D(s.get("x", 0.0), s.get("y", 0.0), math.radians(s.get("yaw_deg", 0.0)))
intents = item.get("intent", "execute")
intents = [intents] if isinstance(intents, str) else list(intents)
res = ItemResult(
str(item.get("id", i)),
item.get("language", "?"),
item.get("tier", "-"),
item.get("category", "-"),
item["text"],
intents,
)
references = _references(catalog, item, res.id)
ctx = PlanningContext(
pose=start, language=cfg.language.default, fixed_language=cfg.language.fixed
)
try:
plan = planner.plan(item["text"], ctx)
except LLMError as exc:
res.error = str(exc)
results.append(res)
continue
res.latency_s = plan.latency_s
res.intent_pred = plan.intent
res.predicted = [a.to_dict() for a in plan.actions]
if plan.errors:
res.error = "; ".join(plan.errors)
if plan.usable and plan.intent in intents:
if plan.intent != "execute":
res.ipa = res.ipa_strict = res.tsr = True
else:
res.ipa = any(plans_match(plan.actions, st, tol, False) for st, _ in references)
res.ipa_strict = any(
plans_match(plan.actions, fu, tol, True) for _, fu in references
)
res.tsr = any(
task_success(cfg, plan.actions, fu, start, tol) for _, fu in references
)
log.info("[%d] %s ipa=%s tsr=%s %.2fs", i, res.id, res.ipa, res.tsr, res.latency_s or 0.0)
results.append(res)
return results
def _references(
catalog: Catalog, item: dict, item_id: str
) -> list[tuple[list[Action], list[Action]]]:
"""(stated, with-defaults) versions of the reference plan and its alternatives."""
plans = [item["gold"]] if item.get("gold") else []
plans += item.get("alternatives") or []
refs = []
for raw in plans:
stated, errors = catalog.validate(raw, fill_defaults=False)
full, _ = catalog.validate(raw)
if errors:
raise ValueError(f"benchmark item {item_id}: invalid reference plan: {errors}")
refs.append((stated, full))
return refs
def select(
items: list[dict],
languages: Iterable[str] = (),
tiers: Iterable[str] = (),
per_language: int | None = None,
seed: int = 0,
) -> list[dict]:
"""Filter benchmark items by language and tier; optionally sample per language."""
langs, tiers = {x.casefold() for x in languages}, {x.casefold() for x in tiers}
out = [
it
for it in items
if (not langs or str(it.get("language", "")).casefold() in langs)
and (not tiers or str(it.get("tier", "")).casefold() in tiers)
]
if per_language:
by_lang: dict[str, list[dict]] = defaultdict(list)
for it in out:
by_lang[it.get("language", "?")].append(it)
rng = random.Random(seed)
out = [
it
for group in by_lang.values()
for it in (rng.sample(group, per_language) if len(group) > per_language else group)
]
return out
[docs]
def summarise(results: list[ItemResult], by: str = "tier") -> dict[str, dict[str, float]]:
groups: dict[str, list[ItemResult]] = defaultdict(list)
for r in results:
keys = getattr(r, by)
# an item tagged "G_n,W_c" counts towards both categories
for key in str(keys).split(",") if by == "category" else [keys]:
groups[key.strip()].append(r)
groups["ALL"].append(r)
table = {}
for key, rs in sorted(groups.items(), key=lambda kv: (kv[0] == "ALL", kv[0])):
lat = [r.latency_s for r in rs if r.latency_s is not None]
table[key] = {
"n": len(rs),
"IPA": 100.0 * sum(r.ipa for r in rs) / len(rs),
"IPA_strict": 100.0 * sum(r.ipa_strict for r in rs) / len(rs),
"TSR": 100.0 * sum(r.tsr for r in rs) / len(rs),
"ART_s": sum(lat) / len(lat) if lat else float("nan"),
}
return table
def format_table(table: dict[str, dict[str, float]], by: str) -> str:
lines = [f"{by:<12}{'n':>5}{'IPA %':>9}{'strict %':>10}{'TSR %':>9}{'ART s':>8}"]
for key, row in table.items():
lines.append(
f"{key:<12}{row['n']:>5}{row['IPA']:>9.1f}{row['IPA_strict']:>10.1f}"
f"{row['TSR']:>9.1f}{row['ART_s']:>8.2f}"
)
return "\n".join(lines)
def write_results(results: list[ItemResult], path: str | Path) -> None:
with open(path, "w", encoding="utf-8") as f:
for r in results:
f.write(json.dumps(asdict(r), ensure_ascii=False) + "\n")
def run(
cfg: ReLIConfig,
provider: LLMProvider,
benchmark: str | Path,
out: str | Path | None = None,
by: str = "tier",
languages: Iterable[str] = (),
tiers: Iterable[str] = (),
per_language: int | None = None,
) -> dict:
t0 = time.monotonic()
items = select(load_benchmark(benchmark), languages, tiers, per_language)
if not items:
raise ValueError("no benchmark items match the selection")
results = evaluate(cfg, provider, items)
if out:
write_results(results, out)
table = summarise(results, by)
print(format_table(table, by))
print(f"({len(results)} items in {time.monotonic() - t0:.1f} s)")
return table