leafant 0.2.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
leafant/benchmarks.py ADDED
@@ -0,0 +1,291 @@
1
+ """Reproducible benchmark suite (Phase 4).
2
+
3
+ Principles enforced here:
4
+ - frozen, seeded suites; every run stores RAW per-row predictions
5
+ - baselines computed from the data itself (majority, random) — never invented
6
+ - bootstrap CIs on headline accuracy
7
+ - robustness probes must not crash and their behavior is recorded
8
+ - the report distinguishes MEASURED results from TARGETS (targets are never
9
+ presented as results; unmeasured cells say "not measured")
10
+
11
+ Usage:
12
+ python -m leafant.benchmarks --checkpoint results/leafant-bench-checkpoint \
13
+ --out results/bench [--skip-laya]
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import hashlib
19
+ import json
20
+ import os
21
+ import random
22
+ import time
23
+ from typing import Dict, List
24
+
25
+ import numpy as np
26
+
27
+ from .data import build_demo_data, gen_code_tasks, gen_extraction, read_jsonl
28
+ from .evals import (by_language, collect_predictions, macro_f1,
29
+ metrics_from_predictions, order_flip_rate)
30
+
31
+ SEED = 20261123
32
+
33
+
34
+ # ---------------------------------------------------------------- suite builders
35
+ def build_suites() -> Dict[str, List[Dict]]:
36
+ rng = random.Random(SEED)
37
+ train, test = build_demo_data(seed=7)
38
+ suites = {f"synthetic_{k}": v for k, v in test.items() if k != "orderflip"}
39
+ suites["synthetic_orderflip"] = test["orderflip"]
40
+ suites["synthetic_extraction"] = (gen_extraction(120, random.Random(SEED + 1), "excerpt") +
41
+ gen_extraction(80, random.Random(SEED + 2), "number"))
42
+ suites["synthetic_code"] = (gen_code_tasks(80, random.Random(SEED + 3), "bug_triage") +
43
+ gen_code_tasks(50, random.Random(SEED + 4), "needs_human") +
44
+ gen_code_tasks(40, random.Random(SEED + 5), "next_action"))
45
+ # real data (cached): 100 official AG News test rows
46
+ ag_path = os.path.join("..", "_h2h", "ag_news.json")
47
+ if os.path.exists(ag_path):
48
+ data = json.load(open(ag_path, encoding="utf-8"))
49
+ names = data["names"]
50
+ suites["real_agnews100"] = [
51
+ {"state": r["text"],
52
+ "questions": {"topic": {"type": "choice",
53
+ "instructions": "Which section does this article belong to?",
54
+ "criteria": {n: None for n in names}}},
55
+ "expected": {"topic": names[int(r["label"])]}}
56
+ for r in data["rows"][:100]]
57
+ return suites
58
+
59
+
60
+ def majority_baseline(rows: List[Dict], metric="accuracy") -> float:
61
+ from collections import Counter
62
+ if metric not in {"accuracy", "mode_accuracy"}:
63
+ raise ValueError("majority metric must be accuracy or mode_accuracy")
64
+ grouped = {}
65
+ for row in rows:
66
+ for qid, value in row.get("expected", {}).items():
67
+ gold = row.get("gold", {}).get(qid)
68
+ if metric == "mode_accuracy" and isinstance(gold, dict) and gold:
69
+ value = max(gold, key=gold.get)
70
+ elif metric == "mode_accuracy" and qid in row.get("gold_labels", {}):
71
+ value = row["gold_labels"][qid]
72
+ elif row.get("questions", {}).get(qid, {}).get("type") == "score":
73
+ value = round(float(value))
74
+ grouped.setdefault((row.get("workflow"), qid), Counter())[str(value)] += 1
75
+ total = sum(sum(counts.values()) for counts in grouped.values())
76
+ return sum(max(counts.values()) for counts in grouped.values()) / total if total else float("nan")
77
+
78
+
79
+ def bootstrap_ci(correct: List[bool], n_boot: int = 1000, seed: int = 0) -> tuple:
80
+ rng = np.random.RandomState(seed)
81
+ arr = np.asarray(correct, dtype=np.float64)
82
+ if len(arr) == 0:
83
+ return (float("nan"), float("nan"))
84
+ idx = rng.randint(0, len(arr), (n_boot, len(arr)))
85
+ means = arr[idx].mean(1)
86
+ return (round(float(np.percentile(means, 2.5)), 4),
87
+ round(float(np.percentile(means, 97.5)), 4))
88
+
89
+
90
+ def robustness_probes(agent) -> Dict:
91
+ """Malformed/degenerate inputs must not crash; behavior is recorded."""
92
+ q = {"d": {"type": "choice", "criteria": {"a": "alpha things", "b": "beta things"}}}
93
+ probes = {}
94
+ cases = {"empty_state": "",
95
+ "whitespace": " \n\t ",
96
+ "long_30k": "word " * 6000,
97
+ "unicode_soup": "中文🚀🔥 مرحبا امتحان \U0001F600 " * 40,
98
+ "newline_bomb": "\n" * 5000}
99
+ for name, state in cases.items():
100
+ try:
101
+ t0 = time.perf_counter()
102
+ res = agent.predict(state, q)
103
+ dt = (time.perf_counter() - t0) * 1000
104
+ probes[name] = {"status": "ok", "ms": round(dt, 1),
105
+ "answer": res["answers"]["d"]["choice"]}
106
+ except Exception as e: # noqa: BLE001 — recorded, not hidden
107
+ probes[name] = {"status": "error", "error": f"{type(e).__name__}: {e}"[:160]}
108
+ return probes
109
+
110
+
111
+ def latency_by_k(agent, ks=(2, 16, 64), reps: int = 30) -> Dict:
112
+ out = {}
113
+ for k in ks:
114
+ crit = {f"opt_{i:03d}": f"describes option {i}" for i in range(k)}
115
+ q = {"d": {"type": "choice", "instructions": "Pick one.", "criteria": crit}}
116
+ times = []
117
+ for i in range(reps):
118
+ t0 = time.perf_counter()
119
+ agent.predict(f"query mentioning opt_{k // 2:03d} specifically", q)
120
+ times.append((time.perf_counter() - t0) * 1000)
121
+ out[f"K={k}"] = {"p50_ms": round(float(np.percentile(times, 50)), 1),
122
+ "p95_ms": round(float(np.percentile(times, 95)), 1)}
123
+ return out
124
+
125
+
126
+ def run_benchmark(checkpoint: str, out_dir: str, skip_laya: bool = False,
127
+ laya_model: str = "english", limit: int = 80) -> Dict:
128
+ from .agent import LeafAnt
129
+
130
+ os.makedirs(out_dir, exist_ok=True)
131
+ raw_dir = os.path.join(out_dir, "raw_predictions")
132
+ os.makedirs(raw_dir, exist_ok=True)
133
+ agent = LeafAnt.load(checkpoint)
134
+ suites = build_suites()
135
+ report = {"config": {"checkpoint": checkpoint, "seed": SEED,
136
+ "checkpoint_sha": hashlib.sha256(
137
+ open(os.path.join(checkpoint, "model.pt"), "rb").read()).hexdigest()[:16],
138
+ "params": sum(p.numel() for p in agent.model.parameters())},
139
+ "suites": {}, "robustness": robustness_probes(agent),
140
+ "latency_by_k": latency_by_k(agent)}
141
+
142
+ orderflip_rows = suites.get("synthetic_orderflip")
143
+ for name, rows in sorted(suites.items()):
144
+ if name == "synthetic_orderflip":
145
+ continue
146
+ rows = rows[:limit] if limit else rows
147
+ preds = collect_predictions(agent, rows)
148
+ rep = metrics_from_predictions(preds, name)
149
+ correct = [p["correct"] for p in preds]
150
+ rep["baseline_majority"] = round(majority_baseline(rows), 4)
151
+ lo, hi = bootstrap_ci(correct)
152
+ rep["accuracy_ci95"] = [lo, hi]
153
+ if name == "synthetic_orderflip":
154
+ continue
155
+ if "language" in rows[0] if rows else False:
156
+ rep["languages"] = by_language(preds)
157
+ with open(os.path.join(raw_dir, f"{name}.jsonl"), "w", encoding="utf-8") as f:
158
+ for prediction in preds:
159
+ f.write(json.dumps({"row_index": prediction["row_index"], "qid": prediction["qid"],
160
+ "expected": prediction["expected"], "pred": prediction["answer"],
161
+ "correct": prediction["correct"], "confidence": prediction["confidence"]},
162
+ ensure_ascii=False) + "\n")
163
+ report["suites"][name] = rep
164
+
165
+ # order-flip: paired choice16 vs its permuted twins
166
+ if orderflip_rows:
167
+ base = suites["synthetic_choice16"]
168
+ n = min(len(base), len(orderflip_rows))
169
+ report["order_flip_rate"] = round(order_flip_rate(agent, base[:n], orderflip_rows[:n]), 4)
170
+
171
+ # optional laya baseline on the same suites (raw predictions also stored)
172
+ if not skip_laya:
173
+ try:
174
+ import laya
175
+ laya_agent = laya.load(laya_model)
176
+ laya_suites = {}
177
+ for name in ("synthetic_choice16", "synthetic_highk64", "synthetic_negation",
178
+ "synthetic_noul", "synthetic_score", "real_agnews100"):
179
+ rows = suites.get(name, [])
180
+ rows = rows[:limit] if limit else rows
181
+ if not rows:
182
+ continue
183
+ preds = []
184
+ lat = []
185
+ errors = 0
186
+ correct = []
187
+ for r in rows:
188
+ try:
189
+ t0 = time.perf_counter()
190
+ res = laya_agent.predict(r["state"], r["questions"])
191
+ lat.append((time.perf_counter() - t0) * 1000)
192
+ for qid, exp in r.get("expected", {}).items():
193
+ a = res["answers"].get(qid, {})
194
+ tname = r["questions"][qid].get("type", "choice")
195
+ if tname == "choice":
196
+ okc = str(a.get("choice")) == str(exp)
197
+ probs = {k: float(v) for k, v in (a.get("probabilities") or {}).items()}
198
+ elif tname == "noul":
199
+ pt = float(a.get("noul", a.get("answer", 0.5)))
200
+ okc = (pt >= 0.5) == bool(exp)
201
+ probs = {"false": 1 - pt, "true": pt}
202
+ else:
203
+ sv = a.get("score")
204
+ okc = sv is not None and int(round(float(sv))) == int(round(float(exp)))
205
+ probs = {}
206
+ correct.append(okc)
207
+ preds.append({"expected": {qid: exp}, "pred": a, "correct": okc,
208
+ "confidence": float(a.get("answer_confidence") or 0)})
209
+ except Exception:
210
+ errors += 1
211
+ correct.extend(False for _ in r.get("expected", {}))
212
+ rep = {"n": len(correct), "accuracy": round(float(np.mean(correct)), 4) if correct else None,
213
+ "errors": errors,
214
+ "latency_p50_ms": round(float(np.percentile(lat, 50)), 1) if lat else None,
215
+ "macro_f1": None}
216
+ labels = [str(list(r["expected"].values())[0]) for r in rows for _ in r["expected"]]
217
+ with open(os.path.join(raw_dir, f"laya_{name}.jsonl"), "w", encoding="utf-8") as f:
218
+ for p_ in preds:
219
+ f.write(json.dumps(p_, ensure_ascii=False) + "\n")
220
+ laya_suites[name] = rep
221
+ report["laya_baseline"] = {"model": laya_model, "suites": laya_suites}
222
+ except ImportError:
223
+ report["laya_baseline"] = {"status": "laya not installed — baseline skipped"}
224
+
225
+ with open(os.path.join(out_dir, "benchmark_report.json"), "w", encoding="utf-8") as f:
226
+ json.dump(report, f, indent=2)
227
+ return report
228
+
229
+
230
+ def render_report(report: Dict, out_path: str) -> str:
231
+ """Markdown report — every table cell is MEASURED or explicitly 'not measured'."""
232
+ lines = ["# Leaf Ant benchmark report", "",
233
+ f"*checkpoint:* `{report['config']['checkpoint']}` "
234
+ f"(sha {report['config']['checkpoint_sha']}, {report['config']['params']:,} params, "
235
+ f"seed {report['config']['seed']})", "",
236
+ "All numbers below are MEASURED on this machine. Cells that were not run say so.",
237
+ ""]
238
+ lines.append("| suite | n | accuracy [CI95] | macro-F1 | majority baseline |")
239
+ lines.append("|---|---|---|---|---|")
240
+ for name, rep in report["suites"].items():
241
+ overall = rep.get("overall", {})
242
+ acc = overall.get("accuracy")
243
+ ci = rep.get("accuracy_ci95")
244
+ cell = f"{acc}" if acc is not None else "not measured"
245
+ if ci and acc is not None:
246
+ cell = f"{acc} [{ci[0]}, {ci[1]}]"
247
+ f1 = rep.get("choice", {}).get("macro_f1") or rep.get("noul", {}).get("macro_f1") or "—"
248
+ lines.append(f"| {name} | {rep.get('choice', {}).get('n', rep.get('noul', {}).get('n', '—'))} "
249
+ f"| {cell} | {f1} | {rep.get('baseline_majority', '—')} |")
250
+ lines += ["", f"**order flip rate:** {report.get('order_flip_rate', 'not measured')}", ""]
251
+ lines.append("| latency by K | p50 ms | p95 ms |")
252
+ lines.append("|---|---|---|")
253
+ for k, v in report.get("latency_by_k", {}).items():
254
+ lines.append(f"| {k} | {v['p50_ms']} | {v['p95_ms']} |")
255
+ lines += ["", "## Robustness probes", "", "| probe | status | detail |", "|---|---|---|"]
256
+ for name, p in report.get("robustness", {}).items():
257
+ lines.append(f"| {name} | {p['status']} | {p.get('answer', p.get('error', ''))} |")
258
+ laya = report.get("laya_baseline")
259
+ if laya and "suites" in laya:
260
+ lines += ["", "## laya baseline (same suites, same machine)", "",
261
+ "| suite | laya accuracy | laya p50 ms | errors |", "|---|---|---|---|"]
262
+ for name, rep in laya["suites"].items():
263
+ lines.append(f"| {name} | {rep['accuracy']} | {rep['latency_p50_ms']} | {rep['errors']} |")
264
+ lines += ["", "## Targets (NOT results)", "",
265
+ "Targets are goals for the GPU training run — they are not claims:",
266
+ "", "- AG News ≥ 0.92 (measured here: see real_agnews100 row)",
267
+ "- Banking77 ≥ 0.70 (not measured — dataset blocked locally)",
268
+ "- order flip 0.0 at K≤64 (measured above)",
269
+ "- abstention AUROC ≥ 0.85 (see suite `selective` blocks)"]
270
+ with open(out_path, "w", encoding="utf-8") as f:
271
+ f.write("\n".join(lines))
272
+ return out_path
273
+
274
+
275
+ def main():
276
+ ap = argparse.ArgumentParser()
277
+ ap.add_argument("--checkpoint", default=os.path.join("results", "leafant-bench-checkpoint"))
278
+ ap.add_argument("--out", default=os.path.join("results", "bench"))
279
+ ap.add_argument("--skip-laya", action="store_true")
280
+ ap.add_argument("--laya-model", default="english")
281
+ ap.add_argument("--limit", type=int, default=80)
282
+ args = ap.parse_args()
283
+ report = run_benchmark(args.checkpoint, args.out, skip_laya=args.skip_laya,
284
+ laya_model=args.laya_model, limit=args.limit)
285
+ path = render_report(report, os.path.join(args.out, "benchmark_report.md"))
286
+ print(f"report: {path}")
287
+ print(json.dumps({k: v.get("overall") for k, v in report["suites"].items()}, indent=1))
288
+
289
+
290
+ if __name__ == "__main__":
291
+ main()
leafant/box_reader.py ADDED
@@ -0,0 +1,154 @@
1
+ """Experimental phrase-to-box inference on a PNG or JPEG using Grounding DINO Tiny."""
2
+ import argparse
3
+ import base64
4
+ import binascii
5
+ from io import BytesIO
6
+ import json
7
+ import math
8
+ import re
9
+
10
+ import torch
11
+
12
+ MODEL = "IDEA-Research/grounding-dino-tiny"
13
+ REVISION = "a2bb814dd30d776dcf7e30523b00659f4f141c71"
14
+
15
+
16
+ class BoxInputError(ValueError):
17
+ def __init__(self, message, status=422):
18
+ super().__init__(message)
19
+ self.status = status
20
+
21
+
22
+ def image_reference(state, assets):
23
+ """Resolve an image from the single referenced field in this request."""
24
+ if not isinstance(assets, dict) or len(assets) != 1 or not isinstance(state, dict) or len(state) != 1:
25
+ raise BoxInputError("Expected one image asset and one state field referring to it")
26
+ reference, asset = next(iter(assets.items()))
27
+ field, value = next(iter(state.items()))
28
+ if not reference.strip() or value != reference or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_-]*", field):
29
+ raise BoxInputError("state must identify the image asset in one named field")
30
+ if len(reference.encode("utf-8", errors="surrogatepass")) > 1024:
31
+ raise BoxInputError("image reference exceeds 1024 bytes", 413)
32
+ if (not isinstance(asset, dict) or asset.keys() - {"type", "format", "data_base64"}
33
+ or asset.get("type", "image") != "image" or asset.get("format") not in ("png", "jpeg", "jpg")
34
+ or not isinstance(asset.get("data_base64"), str) or not asset["data_base64"]):
35
+ raise BoxInputError("asset must contain a PNG or JPEG format and data_base64")
36
+ return field, asset
37
+
38
+
39
+ def box_phrases(field, questions):
40
+ phrases = {}
41
+ for qid, question in questions.items():
42
+ if (not isinstance(question, dict) or question.keys() != {"type", "instructions"}
43
+ or question["type"] != "box" or not isinstance(question["instructions"], str)):
44
+ raise BoxInputError("image requests accept Box questions with instructions only")
45
+ instruction = question["instructions"].strip()
46
+ if instruction.endswith((".", "?")):
47
+ instruction = instruction[:-1]
48
+ parts = instruction.rsplit(None, 2)
49
+ if (len(parts) != 3 or parts[1] != "in" or parts[2] != f"`{field}`" or "`" in parts[0]
50
+ or not parts[0].strip(". ")):
51
+ raise BoxInputError("Box instructions must name a target followed by in and the backticked image field")
52
+ phrases[qid] = parts[0]
53
+ return phrases
54
+
55
+
56
+ def decode_asset(asset):
57
+ """Decode and inspect pixels inside the serving worker before running inference."""
58
+ from PIL import Image
59
+
60
+ try:
61
+ data = base64.b64decode(asset["data_base64"], validate=True)
62
+ except (ValueError, binascii.Error):
63
+ raise BoxInputError("invalid standard base64 image", 400) from None
64
+ expected = "PNG" if asset["format"] == "png" else "JPEG"
65
+ try:
66
+ stream = BytesIO(data)
67
+ with Image.open(stream, formats=("PNG", "JPEG")) as image:
68
+ if image.format != expected:
69
+ raise BoxInputError("image bytes do not match the declared format", 400)
70
+ if max(image.size) > 1568:
71
+ raise BoxInputError("image width and height must be at most 1568 pixels", 413)
72
+ if min(image.size) < 280 or getattr(image, "is_animated", False):
73
+ raise BoxInputError("expected a still image at least 280 pixels on each side", 400)
74
+ image.verify()
75
+ stream.seek(0)
76
+ with Image.open(stream, formats=(expected,)) as image:
77
+ image.load()
78
+ pixels = image.convert("RGB")
79
+ except BoxInputError:
80
+ raise
81
+ except Image.DecompressionBombError:
82
+ raise BoxInputError("decoded image exceeds the pixel limit", 413) from None
83
+ except (ValueError, SyntaxError, OSError, EOFError):
84
+ raise BoxInputError("damaged or unsupported PNG or JPEG image", 400) from None
85
+ return pixels
86
+
87
+
88
+ def image_answers(asset, questions, phrases, box_reader, decision_reader, threshold):
89
+ typed = {key:q for key,q in questions.items() if key not in phrases}
90
+ with decode_asset(asset) as pixels:
91
+ result = decision_reader.predict(pixels, typed) if typed else {"answers":{}}
92
+ answers = result["answers"]
93
+ for answer in answers.values():
94
+ accepted = threshold is None or answer["answer_confidence"] >= threshold
95
+ answer["abstention"] = "passed" if accepted else "abstained"
96
+ if not accepted:
97
+ answer["decision"] = None
98
+ for key,phrase in phrases.items():
99
+ answers[key] = box_reader.locate(pixels,phrase,threshold or 0.)
100
+ result["answers"] = {key:answers[key] for key in questions}
101
+ return result
102
+
103
+
104
+ class BoxReader:
105
+ def __init__(self, directory=MODEL, device="cpu", *, local_files_only=True):
106
+ from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
107
+ args = dict(revision=REVISION, local_files_only=local_files_only) if directory == MODEL else dict(local_files_only=True)
108
+ self.processor = AutoProcessor.from_pretrained(directory, **args)
109
+ self.model = AutoModelForZeroShotObjectDetection.from_pretrained(
110
+ directory, use_safetensors=True, **args).to(device).eval()
111
+
112
+ @torch.inference_mode()
113
+ def locate(self, image, target, threshold=.35):
114
+ """Return the most confident box, with normalized edges in input image coordinates."""
115
+ if not isinstance(target, str) or not target.strip() or not 0 <= threshold <= 1:
116
+ raise ValueError("Expected a target phrase and a threshold in [0, 1]")
117
+ prompt = target.strip().rstrip(".").lower() + "."
118
+ inputs = self.processor(images=image.convert("RGB"), text=prompt, return_tensors="pt")
119
+ if inputs.input_ids.shape[-1] > self.model.config.max_text_len:
120
+ raise ValueError("Target phrase exceeds the detector's text limit")
121
+ inputs = inputs.to(self.model.device)
122
+ outputs = self.model(**inputs)
123
+ # Sigmoid scores over text tokens and center-size boxes are the native Grounding DINO outputs.
124
+ scores = outputs.logits[0].sigmoid().amax(dim=-1)
125
+ index = scores.argmax().item()
126
+ score = scores[index].item()
127
+ cx, cy, w, h = outputs.pred_boxes[0,index].float().cpu().tolist()
128
+ if not all(math.isfinite(v) for v in (score,cx,cy,w,h)):
129
+ raise FloatingPointError("Nonfinite detector output")
130
+ left, right = max(0.,cx-w/2), min(1.,cx+w/2)
131
+ top, bottom = max(0.,cy-h/2), min(1.,cy+h/2)
132
+ box = (dict(left=left, right=right, top=top, bottom=bottom)
133
+ if score >= threshold and left < right and top < bottom else None)
134
+ return dict(type="box", box=box, confidence=score)
135
+
136
+
137
+ def main():
138
+ from PIL import Image
139
+ p = argparse.ArgumentParser(description=__doc__)
140
+ p.add_argument("image")
141
+ p.add_argument("target")
142
+ p.add_argument("--model-dir", default=MODEL, help="Local snapshot or the pinned model already in the cache")
143
+ p.add_argument("--device", default="cpu")
144
+ p.add_argument("--threshold", type=float, default=.35, help="Minimum raw detector score")
145
+ args = p.parse_args()
146
+ with Image.open(args.image) as image:
147
+ if image.format not in {"JPEG","PNG"}:
148
+ raise ValueError("Expected a PNG or JPEG")
149
+ answer = BoxReader(args.model_dir, args.device).locate(image, args.target, args.threshold)
150
+ print(json.dumps(answer))
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()