Add frozen eval sets and scorer; document both
This commit is contained in:
1 parent
6965ab25db
commit
b37df2b05a
9 files changed
+914
No files matched your search
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the frozen evaluation sets. Answers are computed by code, not written by hand.
|
||||
|
||||
Outputs (committed to git, never used for training):
|
||||
eval/tool_calls.jsonl request -> expected tool call (or none)
|
||||
eval/manifest_reasoning.jsonl cluster snapshot -> question -> computed answer
|
||||
eval/english_heldout.jsonl held-out English prose sampled from corpora/english-prose.jsonl
|
||||
eval/english_heldout_ids.txt identifiers to exclude from the training corpus
|
||||
|
||||
Re-running with the same seed reproduces the same files. Hand-written concept questions
|
||||
live in eval/concepts.jsonl and are not generated.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
from pathlib import Path
|
||||
|
||||
SEED = 20260101
|
||||
NAMESPACES = ["default", "payments", "frontend", "monitoring", "batch"]
|
||||
APPS = ["checkout", "cart", "search", "billing", "auth", "metrics"]
|
||||
DEPLOYMENTS = ["checkout", "cart", "search", "billing", "auth", "metrics", "ingest", "report"]
|
||||
NODES_REQUEST = [
|
||||
"Which nodes are in the cluster?",
|
||||
"List all the nodes.",
|
||||
"Show me the cluster nodes.",
|
||||
]
|
||||
|
||||
|
||||
def tool_calls(rng):
|
||||
items = []
|
||||
|
||||
def add(request, expected):
|
||||
items.append({"id": f"tool-{len(items) + 1:03d}", "request": request, "expected": expected})
|
||||
|
||||
for _ in range(12):
|
||||
ns = rng.choice(NAMESPACES)
|
||||
add(rng.choice([f"List the pods in the {ns} namespace.",
|
||||
f"Show every pod running in {ns}.",
|
||||
f"What pods are in the {ns} namespace?"]),
|
||||
{"name": "kubectl_get", "arguments": {"resource": "pods", "namespace": ns}})
|
||||
for _ in range(8):
|
||||
app, ns = rng.choice(APPS), rng.choice(NAMESPACES)
|
||||
add(rng.choice([f"Show pods with label app={app} in {ns}.",
|
||||
f"Which pods in {ns} carry the label app={app}?"]),
|
||||
{"name": "kubectl_get", "arguments": {"resource": "pods", "namespace": ns,
|
||||
"selector": f"app={app}"}})
|
||||
for _ in range(10):
|
||||
name, ns = rng.choice(DEPLOYMENTS), rng.choice(NAMESPACES)
|
||||
add(rng.choice([f"Describe the deployment {name} in {ns}.",
|
||||
f"Give me the details of deployment {name} in the {ns} namespace."]),
|
||||
{"name": "kubectl_describe", "arguments": {"resource": "deployments",
|
||||
"name": name, "namespace": ns}})
|
||||
for _ in range(10):
|
||||
pod, ns = f"{rng.choice(APPS)}-{rng.randint(1000, 9999)}", rng.choice(NAMESPACES)
|
||||
tail = rng.choice([20, 50, 100, 200])
|
||||
add(f"Get the last {tail} log lines of pod {pod} in {ns}.",
|
||||
{"name": "kubectl_logs", "arguments": {"pod": pod, "namespace": ns, "tail": tail}})
|
||||
for _ in range(10):
|
||||
name, ns, replicas = rng.choice(DEPLOYMENTS), rng.choice(NAMESPACES), rng.randint(0, 10)
|
||||
add(rng.choice([f"Scale deployment {name} to {replicas} replicas in {ns}.",
|
||||
f"Set the replica count of {name} in {ns} to {replicas}."]),
|
||||
{"name": "kubectl_scale", "arguments": {"deployment": name, "replicas": replicas,
|
||||
"namespace": ns}})
|
||||
for request in NODES_REQUEST:
|
||||
add(request, {"name": "kubectl_get", "arguments": {"resource": "nodes"}})
|
||||
# Requests that need no tool call: the model must answer in prose.
|
||||
for request in ["What is a pod in Kubernetes?",
|
||||
"Explain the difference between a Deployment and a StatefulSet.",
|
||||
"Write a haiku about containers.",
|
||||
"What does the replicas field control?",
|
||||
"Is a Service the same as an Ingress?",
|
||||
"Define a namespace."]:
|
||||
add(request, {"name": None})
|
||||
rng.shuffle(items)
|
||||
return items
|
||||
|
||||
|
||||
def manifest_reasoning(rng, count=60):
|
||||
items = []
|
||||
for index in range(count):
|
||||
ns = rng.choice(NAMESPACES)
|
||||
app = rng.choice(APPS)
|
||||
pods = []
|
||||
for n in range(rng.randint(4, 7)):
|
||||
name = f"{app}-{rng.randint(10000, 99999):05d}-{n}"
|
||||
total = rng.randint(1, 3)
|
||||
ready = total if rng.random() < 0.7 else rng.randint(0, total - 1)
|
||||
restarts = rng.choice([0, 0, 1, 2, 3, 5, 8])
|
||||
status = "Running" if ready == total else rng.choice(["CrashLoopBackOff", "Pending"])
|
||||
pod_app = app if rng.random() < 0.8 else rng.choice(APPS)
|
||||
pods.append({"name": name, "ready": f"{ready}/{total}", "ready_ok": ready == total,
|
||||
"status": status, "restarts": restarts, "app": pod_app})
|
||||
service_app = app
|
||||
selector = {"app": service_app}
|
||||
question_type = index % 3
|
||||
if question_type == 0:
|
||||
question = "Which pods are not fully ready? List their names, sorted."
|
||||
answer = sorted(p["name"] for p in pods if not p["ready_ok"])
|
||||
elif question_type == 1:
|
||||
question = "Which pods have restarted more than 2 times? List their names, sorted."
|
||||
answer = sorted(p["name"] for p in pods if p["restarts"] > 2)
|
||||
else:
|
||||
question = (f"Which pods does the Service named {service_app} in namespace {ns} "
|
||||
"route traffic to? List their names, sorted.")
|
||||
answer = sorted(p["name"] for p in pods if p["app"] == selector["app"])
|
||||
rows = ["NAME | READY | STATUS | RESTARTS | LABEL app"]
|
||||
rows += [f"{p['name']} | {p['ready']} | {p['status']} | {p['restarts']} | {p['app']}"
|
||||
for p in pods]
|
||||
snapshot = (f"Namespace: {ns}\nService {service_app}: selector app={selector['app']}\n"
|
||||
+ "\n".join(rows))
|
||||
items.append({"id": f"manifest-{index + 1:03d}",
|
||||
"context": snapshot, "question": question, "expected": answer})
|
||||
return items
|
||||
|
||||
|
||||
def english_sample(corpus, count, rng, max_words):
|
||||
"""Reservoir-sample documents so the sample is uniform over the whole corpus."""
|
||||
reservoir, seen = [], 0
|
||||
with corpus.open(encoding="utf-8") as stream:
|
||||
for line in stream:
|
||||
seen += 1
|
||||
if len(reservoir) < count:
|
||||
reservoir.append(line)
|
||||
else:
|
||||
slot = rng.randint(0, seen - 1)
|
||||
if slot < count:
|
||||
reservoir[slot] = line
|
||||
items = []
|
||||
for line in reservoir:
|
||||
record = json.loads(line)
|
||||
words = record["text"].split()[:max_words]
|
||||
items.append({"identifier": record["identifier"], "license": record["license"],
|
||||
"collection": record["collection"], "text": " ".join(words)})
|
||||
return items
|
||||
|
||||
|
||||
def write_jsonl(path, items):
|
||||
with path.open("w", encoding="utf-8") as stream:
|
||||
for item in items:
|
||||
stream.write(json.dumps(item, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--corpus", type=Path, default=Path("corpora/english-prose.jsonl"))
|
||||
parser.add_argument("--eval-dir", type=Path, default=Path("eval"))
|
||||
parser.add_argument("--english-count", type=int, default=200)
|
||||
parser.add_argument("--english-max-words", type=int, default=600)
|
||||
args = parser.parse_args()
|
||||
args.eval_dir.mkdir(parents=True, exist_ok=True)
|
||||
rng = random.Random(SEED)
|
||||
write_jsonl(args.eval_dir / "tool_calls.jsonl", tool_calls(rng))
|
||||
write_jsonl(args.eval_dir / "manifest_reasoning.jsonl", manifest_reasoning(rng))
|
||||
english = english_sample(args.corpus, args.english_count, rng, args.english_max_words)
|
||||
write_jsonl(args.eval_dir / "english_heldout.jsonl", english)
|
||||
(args.eval_dir / "english_heldout_ids.txt").write_text(
|
||||
"\n".join(item["identifier"] for item in english) + "\n", encoding="utf-8")
|
||||
print(f"wrote {args.eval_dir} (seed {SEED})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Score model replies against the frozen eval sets in eval/.
|
||||
|
||||
Input is a predictions JSONL with one line per eval item: {"id": "...", "reply": "..."}.
|
||||
Ids are unique across eval files, so one predictions file can cover all of them.
|
||||
Items without a reply count as failures and are reported separately.
|
||||
|
||||
English held-out perplexity is not scored here: it needs the model, so use
|
||||
kubertrainer's test-model.py with eval/english_heldout.jsonl as the test file.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
NAME_PATTERN = re.compile(r"\b[a-z]+-\d{5}-\d+\b")
|
||||
|
||||
|
||||
def first_json(reply):
|
||||
"""Return the first JSON object or array in the reply, or None if there is none."""
|
||||
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", reply.strip())
|
||||
decoder = json.JSONDecoder()
|
||||
for index, char in enumerate(text):
|
||||
if char in "{[":
|
||||
try:
|
||||
value, _ = decoder.raw_decode(text[index:])
|
||||
return value
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def score_tool(item, reply):
|
||||
call = first_json(reply)
|
||||
result = {"parsed": isinstance(call, dict)}
|
||||
if not result["parsed"]:
|
||||
return {**result, "exact": False, "name": False, "false_tool": False}
|
||||
expected = item["expected"]
|
||||
name = call.get("name")
|
||||
if expected["name"] is None:
|
||||
result.update(exact=name is None, name=name is None, false_tool=name is not None)
|
||||
else:
|
||||
result.update(exact=name == expected["name"] and call.get("arguments") == expected["arguments"],
|
||||
name=name == expected["name"], false_tool=False)
|
||||
return result
|
||||
|
||||
|
||||
def score_manifest(item, reply):
|
||||
found = set(NAME_PATTERN.findall(reply))
|
||||
return {"exact": found == set(item["expected"])}
|
||||
|
||||
|
||||
def score_concept(item, reply):
|
||||
lowered = reply.lower()
|
||||
hits = [term for term in item["key_terms"] if term.lower() in lowered]
|
||||
return {"recall": len(hits) / len(item["key_terms"]),
|
||||
"all_terms": len(hits) == len(item["key_terms"])}
|
||||
|
||||
|
||||
def load(path):
|
||||
return [json.loads(line) for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
|
||||
|
||||
def mean(values):
|
||||
return round(sum(values) / len(values), 3) if values else None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--predictions", required=True, type=Path)
|
||||
parser.add_argument("--eval-dir", type=Path, default=Path("eval"))
|
||||
parser.add_argument("--report", type=Path, help="Optional JSON file for the full report")
|
||||
args = parser.parse_args()
|
||||
|
||||
replies = {row["id"]: row["reply"] for row in load(args.predictions)}
|
||||
report, missing = {}, []
|
||||
|
||||
scored = [] # (item, result) pairs, so missing replies cannot shift the alignment
|
||||
for item in load(args.eval_dir / "tool_calls.jsonl"):
|
||||
if item["id"] not in replies:
|
||||
missing.append(item["id"])
|
||||
continue
|
||||
scored.append((item, score_tool(item, replies[item["id"]])))
|
||||
results = [result for _, result in scored]
|
||||
with_call = [result for item, result in scored if item["expected"]["name"]]
|
||||
without_call = [result for item, result in scored if not item["expected"]["name"]]
|
||||
report["tool_calls"] = {
|
||||
"items": len(results),
|
||||
"json_parse_rate": mean([r["parsed"] for r in results]),
|
||||
"exact_match": mean([r["exact"] for r in results]),
|
||||
"tool_name_accuracy": mean([r["name"] for r in with_call]),
|
||||
"false_tool_rate": mean([r["false_tool"] for r in without_call]),
|
||||
}
|
||||
|
||||
manifests = load(args.eval_dir / "manifest_reasoning.jsonl")
|
||||
manifest_results = []
|
||||
for item in manifests:
|
||||
if item["id"] not in replies:
|
||||
missing.append(item["id"])
|
||||
continue
|
||||
manifest_results.append(score_manifest(item, replies[item["id"]]))
|
||||
report["manifest_reasoning"] = {"items": len(manifest_results),
|
||||
"exact_match": mean([r["exact"] for r in manifest_results])}
|
||||
|
||||
concepts = load(args.eval_dir / "concepts.jsonl")
|
||||
concept_results = []
|
||||
for item in concepts:
|
||||
if item["id"] not in replies:
|
||||
missing.append(item["id"])
|
||||
continue
|
||||
concept_results.append(score_concept(item, replies[item["id"]]))
|
||||
report["concepts"] = {"items": len(concept_results),
|
||||
"key_term_recall": mean([r["recall"] for r in concept_results]),
|
||||
"all_terms_present": mean([r["all_terms"] for r in concept_results])}
|
||||
|
||||
report["missing_replies"] = len(missing)
|
||||
print(json.dumps(report, indent=2))
|
||||
if args.report:
|
||||
args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user