Spaces:
Running
Running
Download evaluate.py from WideChaos/tiny-hash-intent: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/spaces/WideChaos/tiny-hash-intent/resolve/main/evaluate.py
- Command line
-
hf download hf://spaces/WideChaos/tiny-hash-intent/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/spaces/WideChaos/tiny-hash-intent/resolve/main/evaluate.py
10 kB
| """Score all official rows only after the selected model/export test freeze.""" | |
| import argparse, csv, json | |
| from pathlib import Path | |
| import unicodedata | |
| import numpy as np | |
| from model import ( | |
| CONFIG, | |
| PARAMETERS, | |
| file_sha, | |
| load_csv, | |
| features, | |
| logits_for, | |
| nll, | |
| probabilities, | |
| decode_portable, | |
| normalized, | |
| ) | |
| def statistics(logits, gold, temperature, labels): | |
| n = len(gold) | |
| c = len(labels) | |
| prob = probabilities(logits, temperature) | |
| pred = np.argmax(logits, axis=1) | |
| confidence = prob[np.arange(n), pred] | |
| loss = nll(logits, gold, temperature) | |
| difference = prob.copy() | |
| difference[np.arange(n), gold] -= 1 | |
| brier = np.sum(difference * difference, axis=1) | |
| cm = np.zeros((c, c), dtype=np.int64) | |
| np.add.at(cm, (gold, pred), 1) | |
| classes = [] | |
| for k, label in enumerate(labels): | |
| actual = int(cm[k].sum()) | |
| called = int(cm[:, k].sum()) | |
| tp = int(cm[k, k]) | |
| classes.append( | |
| { | |
| "label_id": k, | |
| "label": label, | |
| "support": actual, | |
| "predicted": called, | |
| "correct": tp, | |
| "precision": tp / called if called else 0.0, | |
| "recall": tp / actual if actual else 0.0, | |
| "f1": 2 * tp / (actual + called) if actual + called else 0.0, | |
| } | |
| ) | |
| bins = [] | |
| binids = np.minimum(9, np.floor(confidence * 10).astype(int)) | |
| ece = 0.0 | |
| for b in range(10): | |
| mask = binids == b | |
| size = int(mask.sum()) | |
| acc = float((pred[mask] == gold[mask]).mean()) if size else None | |
| conf = float(confidence[mask].mean()) if size else None | |
| bins.append( | |
| { | |
| "bin": b, | |
| "lower_inclusive": b / 10, | |
| "upper": (b + 1) / 10, | |
| "upper_inclusive": b == 9, | |
| "n": size, | |
| "accuracy": acc, | |
| "mean_confidence": conf, | |
| } | |
| ) | |
| if size: | |
| ece += size / n * abs(acc - conf) | |
| summary = { | |
| "n": n, | |
| "correct": int((pred == gold).sum()), | |
| "accuracy": float((pred == gold).mean()) if n else None, | |
| "macro_f1": float(np.mean([x["f1"] for x in classes])) if n else None, | |
| "nll": float(loss.mean()) if n else None, | |
| "brier": float(brier.mean()) if n else None, | |
| "ece10": ece if n else None, | |
| "ece_bins": bins, | |
| "per_class": classes, | |
| "confusion": cm.tolist(), | |
| } | |
| return summary, { | |
| "pred": pred, | |
| "confidence": confidence, | |
| "p_gold": prob[np.arange(n), gold], | |
| "nll": loss, | |
| "brier": brier, | |
| } | |
| def evaluate(data, run, out): | |
| if out.exists(): | |
| raise ValueError("New evaluation directory required.") | |
| root = Path(__file__).resolve().parent | |
| pre = json.loads((run / "PRETEST.json").read_text()) | |
| if pre["configuration"] != CONFIG: | |
| raise ValueError("Configuration differs from PRETEST.") | |
| for name, digest in pre["artifact_sha256"].items(): | |
| if file_sha(run / name) != digest: | |
| raise ValueError("Frozen model/run artifact changed: " + name) | |
| for name, digest in pre["implementation_sha256"].items(): | |
| if file_sha(root / name) != digest: | |
| raise ValueError("Frozen implementation changed: " + name) | |
| for name, digest in pre["source_sha256"].items(): | |
| if file_sha(data / name) != digest: | |
| raise ValueError("Original data changed: " + name) | |
| frozen_protocol = json.loads((root / "PROTOCOL-FREEZE.json").read_text()) | |
| for name, digest in frozen_protocol["sha256"].items(): | |
| if file_sha(root / name) != digest: | |
| raise ValueError("Protocol/source snapshot differs.") | |
| labels = json.loads((data / "categories.json").read_text()) | |
| lookup = {l: i for i, l in enumerate(labels)} | |
| prefit = json.loads((run / "PREFIT.json").read_text()) | |
| test = load_csv(data / "test.csv", labels) | |
| train = load_csv(data / "train.csv", labels) | |
| assert len(test) == 3080 | |
| # First semantic test load for this model occurs after all freeze gates above. | |
| tx = [features(r["text"]) for r in test] | |
| gold = np.array([lookup[r["category"]] for r in test]) | |
| lower = {normalized(r["text"]) for r in train} | |
| casepreserved = lambda s: " ".join(unicodedata.normalize("NFC", s).split()) | |
| case_set = {casepreserved(r["text"]) for r in train} | |
| exact = {r["text"] for r in train} | |
| fitset = {normalized(train[i]["text"]) for i in prefit["train_row_ids"]} | |
| valset = {normalized(train[i]["text"]) for i in prefit["validation_row_ids"]} | |
| overlap = [i for i, r in enumerate(test) if normalized(r["text"]) in lower] | |
| overset = set(overlap) | |
| nonoverlap = np.array( | |
| [i for i in range(len(test)) if i not in overset], dtype=np.int64 | |
| ) | |
| audit = { | |
| "official_train_rows": len(train), | |
| "official_test_rows": len(test), | |
| "fit_rows": prefit["training_rows"], | |
| "validation_rows": prefit["validation_rows"], | |
| "exact_overlap_test_row_ids": [ | |
| i for i, r in enumerate(test) if r["text"] in exact | |
| ], | |
| "case_preserving_NFC_whitespace_overlap_test_row_ids": [ | |
| i for i, r in enumerate(test) if casepreserved(r["text"]) in case_set | |
| ], | |
| "feature_normalized_overlap_test_row_ids": overlap, | |
| "feature_overlap_with_fit_test_row_ids": [ | |
| i for i, r in enumerate(test) if normalized(r["text"]) in fitset | |
| ], | |
| "feature_overlap_with_validation_test_row_ids": [ | |
| i for i, r in enumerate(test) if normalized(r["text"]) in valset | |
| ], | |
| "nonoverlap_test_rows": len(nonoverlap), | |
| "scope": "literal/normalized duplicate diagnostics only, not semantic contamination or IID certification; all original rows retained", | |
| } | |
| with np.load(run / "model-float64.npz", allow_pickle=False) as z: | |
| p = {k: z[k] for k in PARAMETERS} | |
| qmodel = json.loads((run / "model-int8.json").read_text()) | |
| q = decode_portable(qmodel) | |
| fl = logits_for(tx, p) | |
| ql = logits_for(tx, q) | |
| out.mkdir() | |
| np.savez_compressed( | |
| out / "test-logits.npz", | |
| float_logits=fl, | |
| int8_logits=ql, | |
| gold=gold, | |
| nonoverlap_row_ids=nonoverlap, | |
| ) | |
| modes = [] | |
| temperature = pre["selected_temperature"] | |
| for representation, logits in [("float64", fl), ("int8", ql)]: | |
| for name, temp in [("raw", 1.0), ("validation_temperature", temperature)]: | |
| mode = f"{representation}-{name}" | |
| all_stats, rows = statistics(logits, gold, temp, labels) | |
| subset_stats, _ = statistics( | |
| logits[nonoverlap], gold[nonoverlap], temp, labels | |
| ) | |
| path = out / (mode + ".csv") | |
| with path.open("w", newline="", encoding="utf-8") as f: | |
| w = csv.writer(f) | |
| w.writerow( | |
| [ | |
| "test_row_id", | |
| "gold_label_id", | |
| "predicted_label_id", | |
| "correct", | |
| "confidence", | |
| "p_gold", | |
| "nll", | |
| "brier", | |
| ] | |
| ) | |
| for i in range(len(test)): | |
| w.writerow( | |
| [ | |
| i, | |
| int(gold[i]), | |
| int(rows["pred"][i]), | |
| int(rows["pred"][i] == gold[i]), | |
| float(rows["confidence"][i]), | |
| float(rows["p_gold"][i]), | |
| float(rows["nll"][i]), | |
| float(rows["brier"][i]), | |
| ] | |
| ) | |
| modes.append( | |
| { | |
| "mode": mode, | |
| "representation": representation, | |
| "temperature": temp, | |
| "official": all_stats, | |
| "nonoverlap": subset_stats, | |
| "row_file": path.name, | |
| "row_sha256": file_sha(path), | |
| } | |
| ) | |
| print( | |
| mode, | |
| all_stats["correct"], | |
| "/", | |
| len(test), | |
| "NLL", | |
| all_stats["nll"], | |
| "ECE10", | |
| all_stats["ece10"], | |
| flush=True, | |
| ) | |
| disagree = np.flatnonzero(np.argmax(fl, axis=1) != np.argmax(ql, axis=1)).tolist() | |
| report = { | |
| "work_identity": CONFIG["model_identity"], | |
| "version": CONFIG["version"], | |
| "pretest_sha256": file_sha(run / "PRETEST.json"), | |
| "evaluator_sha256": file_sha(Path(__file__)), | |
| "selected_epoch": pre["selected_epoch"], | |
| "selected_temperature": temperature, | |
| "one_fit_multiple_representations": True, | |
| "labels": labels, | |
| "data_audit": audit, | |
| "quantization_disagreement_test_row_ids": disagree, | |
| "quantization_disagreement_count": len(disagree), | |
| "max_abs_test_logit_difference": float(np.max(np.abs(fl - ql))), | |
| "modes": modes, | |
| "scope": "Known public benchmark previously studied; this model first scored it after frozen selection. Closed-set English classifier, no OOD rejection or production/financial-decision claim.", | |
| } | |
| (out / "results.json").write_text( | |
| json.dumps(report, ensure_ascii=False, separators=(",", ":"), allow_nan=False) | |
| + "\n" | |
| ) | |
| (out / "data-audit.json").write_text(json.dumps(audit, indent=2) + "\n") | |
| print("RESULTS", file_sha(out / "results.json"), flush=True) | |
| if __name__ == "__main__": | |
| a = argparse.ArgumentParser() | |
| a.add_argument("--data", type=Path, default=Path("data")) | |
| a.add_argument("--run", type=Path, required=True) | |
| a.add_argument("--output", type=Path, required=True) | |
| x = a.parse_args() | |
| evaluate(x.data, x.run, x.output) | |