File size: 10,928 Bytes
3472f0c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | """Benchmark typed-decision models on LocalLLaMA/typed-decisions (all/test).
Models: mrm8488/embeddinggemma-2-ft-typed-decision, ai-forever/FRIDA-Decisions,
convaiinnovations/laya-typed-decisions.
Metrics per model: accuracy (argmax vs gold label, overall + per question type),
Brier score vs gold distributions, speed (per-case latency, decisions/sec).
Usage: python benchmark.py --limit 2 --device cpu --no-upload (debug)
python benchmark.py --device cuda (full run)
"""
import argparse
import builtins
import gc
import inspect
import json
import os
import statistics
import time
# Auto-accept any interactive trust_remote_code prompt in non-tty job environments.
builtins.input = lambda *a, **k: "y"
os.environ.setdefault("USE_TF", "0")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
import datasets
import torch
import trackio
DATASET = "LocalLLaMA/typed-decisions"
CONFIG = "all"
SPLIT = "test"
RESULTS_REPO = "ML-Intern-lab/typed-decisions-benchmark"
TRACKIO_SPACE = "ML-Intern-lab/typed-decisions-benchmark-trackio"
# noul semantics (verified against probe runs + FRIDA/laya docs): the returned
# scalar is P(true); label = 'true' if p > 0.5 else 'false'.
def flatten_state(state, indent=0):
lines = []
for k, v in state.items():
if isinstance(v, dict):
lines.append(" " * indent + f"{k}:")
lines.append(flatten_state(v, indent + 2))
elif isinstance(v, list):
lines.append(" " * indent + f"{k}: " + "; ".join(str(x) for x in v))
else:
lines.append(" " * indent + f"{k}: {v}")
return "\n".join(lines)
def load_rows(limit):
ds = datasets.load_dataset(DATASET, CONFIG, split=SPLIT)
rows = [dict(r) for r in ds]
for r in rows:
r["state"] = json.loads(r["state"])
r["questions"] = json.loads(r["questions"])
r["gold"] = json.loads(r["gold"])
if limit:
rows = rows[:limit]
print(f"loaded {len(rows)} rows from {DATASET}/{CONFIG}:{SPLIT}", flush=True)
return rows
# ------------------------------------------------------------------ models
class EmbeddingGemmaRunner:
name = "mrm8488/embeddinggemma-2-ft-typed-decision"
short = "embeddinggemma-2-ft-typed-decision"
def load(self, device):
from transformers import AutoModel
self.model = AutoModel.from_pretrained(
self.name, trust_remote_code=True
).eval().to(device)
def predict(self, row):
answers = self.model.decide(
row["state"], row["questions"], workflow=row["workflow"]
)
out = {}
for qid, a in answers.items():
out[qid] = {
"label": str(a.label),
"probabilities": {str(k): float(v) for k, v in a.probabilities.items()},
}
return out
class FridaRunner:
name = "ai-forever/FRIDA-Decisions"
short = "frida-decisions"
def load(self, device):
from frida_decisions import Judge
self.judge = Judge.from_pretrained(self.name, device=device)
def predict(self, row):
resp = self.judge.judge(
{"state": flatten_state(row["state"]), "questions": row["questions"]}
)
out = {}
for qid, a in resp["answers"].items():
qtype = a["type"]
if qtype == "choice":
label, probs = str(a["choice"]), a["probabilities"]
elif qtype == "noul":
p = float(a["noul"])
label = "true" if p > 0.5 else "false"
probs = {"true": p, "false": 1.0 - p}
elif qtype == "score":
probs = a["probabilities"]
label = max(probs, key=probs.get)
else:
raise ValueError(f"unexpected FRIDA answer type {qtype} for {qid}")
out[qid] = {
"label": str(label),
"probabilities": {str(k): float(v) for k, v in probs.items()},
}
return out
class LayaRunner:
name = "convaiinnovations/laya-typed-decisions"
short = "laya-typed-decisions"
def load(self, device):
import laya
kwargs = {}
if "device" in inspect.signature(laya.load).parameters:
kwargs["device"] = device
self.agent = laya.load(self.name, **kwargs)
def predict(self, row):
out_raw = self.agent.predict(row["state"], row["questions"])
out = {}
for qid, a in out_raw["answers"].items():
qtype = a["type"]
if qtype == "choice":
label, probs = str(a["choice"]), a["probabilities"]
elif qtype == "noul":
p = float(a["noul"])
label = "true" if p > 0.5 else "false"
probs = {"true": p, "false": 1.0 - p}
elif qtype == "score":
probs = a["probabilities"]
label = max(probs, key=probs.get)
else:
raise ValueError(f"unexpected laya answer type {qtype} for {qid}")
out[qid] = {
"label": str(label),
"probabilities": {str(k): float(v) for k, v in probs.items()},
}
return out
RUNNERS = [EmbeddingGemmaRunner, FridaRunner, LayaRunner]
# ----------------------------------------------------------------- metrics
def evaluate(runner, rows, device):
print(f"=== loading {runner.short} ===", flush=True)
t0 = time.perf_counter()
runner.load(device)
load_s = time.perf_counter() - t0
print(f"loaded in {load_s:.1f}s", flush=True)
# warm-up on row 0 (excluded from timing, kept in accuracy)
runner.predict(rows[0])
per_q = [] # one entry per (case, question)
latencies = []
t_start = time.perf_counter()
for i, row in enumerate(rows):
t1 = time.perf_counter()
preds = runner.predict(row)
latencies.append(time.perf_counter() - t1)
for qid, qdef in row["questions"].items():
gold = row["gold"][qid]
pred = preds[qid]
gold_label = str(gold["label"])
gold_probs = {str(k): float(v) for k, v in gold["probabilities"].items()}
keys = set(gold_probs) | set(pred["probabilities"])
brier = sum(
(pred["probabilities"].get(k, 0.0) - gold_probs.get(k, 0.0)) ** 2
for k in keys
)
per_q.append({
"case_id": row["id"],
"workflow": row["workflow"],
"qid": qid,
"qtype": qdef["type"],
"gold_label": gold_label,
"pred_label": pred["label"],
"correct": pred["label"] == gold_label,
"brier": brier,
"pred_probabilities": pred["probabilities"],
})
if (i + 1) % 50 == 0 or i + 1 == len(rows):
acc = sum(q["correct"] for q in per_q) / len(per_q)
print(f" row {i+1}/{len(rows)} running accuracy {acc:.3f}", flush=True)
eval_s = time.perf_counter() - t_start
metrics = {
"model": runner.name,
"short": runner.short,
"n_cases": len(rows),
"n_decisions": len(per_q),
"accuracy": sum(q["correct"] for q in per_q) / len(per_q),
"brier": sum(q["brier"] for q in per_q) / len(per_q),
"load_seconds": load_s,
"eval_seconds": eval_s,
"latency_mean_ms": statistics.mean(latencies) * 1000,
"latency_median_ms": statistics.median(latencies) * 1000,
"latency_p95_ms": sorted(latencies)[int(0.95 * len(latencies))] * 1000,
"decisions_per_sec": len(per_q) / eval_s,
}
by_type = {}
for t in ("choice", "score", "noul"):
qs = [q for q in per_q if q["qtype"] == t]
by_type[t] = {
"n": len(qs),
"accuracy": sum(q["correct"] for q in qs) / len(qs),
"brier": sum(q["brier"] for q in qs) / len(qs),
}
metrics["by_type"] = by_type
del runner
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
return metrics, per_q
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--limit", type=int, default=0, help="first N cases only (0 = all 400)")
ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
ap.add_argument("--models", nargs="*", default=None, help="subset: embeddinggemma frida laya")
ap.add_argument("--no-upload", action="store_true")
ap.add_argument("--tag", default="run", help="subfolder tag for results files")
args = ap.parse_args()
rows = load_rows(args.limit)
all_runners = {r.short.split("-")[0]: r for r in RUNNERS}
alias = {"embeddinggemma": EmbeddingGemmaRunner, "frida": FridaRunner,
"laya": LayaRunner, "all": None}
chosen = RUNNERS
if args.models:
chosen = [alias[m] for m in args.models]
if not args.no_upload:
trackio.init(project="typed-decisions-benchmark", space_id=TRACKIO_SPACE)
summary = {"dataset": f"{DATASET}/{CONFIG}:{SPLIT}", "device": args.device,
"n_cases": len(rows), "models": []}
for k, runner_cls in enumerate(chosen):
metrics, per_q = evaluate(runner_cls(), rows, args.device)
summary["models"].append(metrics)
print("METRICS " + json.dumps(metrics), flush=True)
if not args.no_upload:
trackio.log({
f"{metrics['short']}/accuracy": metrics["accuracy"],
f"{metrics['short']}/brier": metrics["brier"],
f"{metrics['short']}/latency_mean_ms": metrics["latency_mean_ms"],
f"{metrics['short']}/decisions_per_sec": metrics["decisions_per_sec"],
}, step=k + 1)
if not args.no_upload:
from huggingface_hub import HfApi
api = HfApi()
base = f"results/{args.tag}/{metrics['short']}"
api.upload_file(
path_or_fileobj=json.dumps(metrics, indent=2).encode(),
path_in_repo=f"{base}/metrics.json",
repo_id=RESULTS_REPO, repo_type="dataset",
)
api.upload_file(
path_or_fileobj="\n".join(json.dumps(q) for q in per_q).encode(),
path_in_repo=f"{base}/predictions.jsonl",
repo_id=RESULTS_REPO, repo_type="dataset",
)
if not args.no_upload:
from huggingface_hub import HfApi
HfApi().upload_file(
path_or_fileobj=json.dumps(summary, indent=2).encode(),
path_in_repo=f"results/{args.tag}/summary.json",
repo_id=RESULTS_REPO, repo_type="dataset",
)
if not args.no_upload:
trackio.finish()
print("ALL DONE\n" + json.dumps(summary, indent=2), flush=True)
if __name__ == "__main__":
main() |