Download code/analyze.py from PugarHuda/benak: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/PugarHuda/benak/resolve/main/code/analyze.py
- Command line
-
hf download hf://datasets/PugarHuda/benak/code/analyze.py
-
curl -L -o analyze.py https://huggingface.co/datasets/PugarHuda/benak/resolve/main/code/analyze.py
10.8 kB
| """Aggregate all runs -> data/results.json (feeds the Space + README) and print the pre-registered verdicts.""" | |
| import json, os, statistics as st | |
| from collections import defaultdict | |
| R = {} | |
| mean = lambda xs: round(st.mean(xs), 3) if xs else None | |
| def load(p): | |
| return [json.loads(l) for l in open(p, encoding="utf-8")] if os.path.exists(p) else [] | |
| def agg(rows, key): | |
| g = defaultdict(list) | |
| for r in rows: | |
| g[key(r)].append(r) | |
| out = {} | |
| for k, rs in g.items(): | |
| t = [r["lid"]["target_share"] for r in rs if r["lid"]["target_share"] is not None] | |
| e = [r["lid"]["eng_share"] for r in rs if r["lid"]["eng_share"] is not None] | |
| out["|".join(map(str, k))] = { | |
| "n": len(rs), "acc": round(100 * sum(r["correct"] for r in rs) / len(rs), 1), | |
| "target_share": mean(t), "eng_share": mean(e), | |
| "pct_mostly_target": round(100 * sum(x >= 0.5 for x in t) / len(t), 1) if t else None, | |
| "no_reasoning_signal": len(rs) - len(t), | |
| "empty_or_truncated": sum(r["finish_reason"] == "length" or not r.get("content") for r in rs), | |
| "reasoning_tokens": mean([(r["usage"].get("completion_tokens_details") or {}).get("reasoning_tokens", 0) | |
| for r in rs]), | |
| "completion_tokens": mean([r["usage"].get("completion_tokens", 0) for r in rs])} | |
| return out | |
| atlas = load("data/atlas/runs_low.jsonl") + load("data/atlas/runs_high.jsonl") | |
| math_ = load("data/math/runs_low.jsonl") + load("data/math/runs_high.jsonl") | |
| R["atlas"] = agg(atlas, lambda r: (r["lang"], r["cond"], r["effort"])) | |
| R["math"] = agg(math_, lambda r: (r["lang"], r["cond"], r["effort"])) | |
| R["replication"] = json.load(open("data/replication/profiled_summary.json")) if os.path.exists( | |
| "data/replication/profiled_summary.json") else [] | |
| if os.path.exists("data/bugis/results.json"): | |
| R["grammar"] = json.load(open("data/bugis/results.json", encoding="utf-8"))["results"] | |
| R["lid_calibration"] = json.load(open("data/lid_calibration.json")) | |
| # ---- pre-registered verdicts (thresholds copied verbatim from PREREGISTRATION.md) ---- | |
| A = R["atlas"]; langs = sorted({k.split("|")[0] for k in A}); non_en = [l for l in langs if l != "eng_Latn"] | |
| get = lambda l, c, f, e="low": (A.get(f"{l}|{c}|{e}") or {}).get(f) | |
| V = {} | |
| h1 = [l for l in non_en if (get(l, "C0", "eng_share") or 0) >= 0.5] | |
| V["H1"] = {"pass": len(h1) >= 10, "detail": f"{len(h1)}/{len(non_en)} languages with C0 eng_share >= 0.5", "langs": h1} | |
| up = [l for l in non_en if (get(l, "C2", "target_share") or 0) > (get(l, "C0", "target_share") or 0)] | |
| below = [l for l in up if (get(l, "C2", "target_share") or 0) < 0.8] | |
| V["H2"] = {"pass": len(up) >= 12 and len(below) >= len(up) / 2, | |
| "detail": f"C2 > C0 in {len(up)}/{len(non_en)}; of those {len(below)} still < 0.8"} | |
| h3 = [l for l in non_en if (get(l, "C3", "target_share") or 0) > (get(l, "C2", "target_share") or 0)] | |
| V["H3"] = {"pass": len(h3) >= 12, "detail": f"C3 > C2 in {len(h3)}/{len(non_en)}"} | |
| M = R["math"] | |
| diffs = [(M[f"{l}|C2|low"]["acc"] - M[f"{l}|C0|low"]["acc"]) for l in {k.split("|")[0] for k in M} | |
| if f"{l}|C2|low" in M and f"{l}|C0|low" in M] | |
| V["H5"] = {"pass": bool(diffs) and abs(st.mean(diffs)) <= 3, | |
| "detail": f"mean acc(C2)-acc(C0) = {round(st.mean(diffs), 2) if diffs else None} pts over {len(diffs)} langs"} | |
| if "grammar" in R: | |
| g = R["grammar"]; ok = True; det = [] | |
| for d in ("x2ind", "ind2x"): | |
| s = [g.get(f"{k}/{d}", {}).get("chrf++") for k in ("K0", "K1", "K2", "K3")] | |
| det.append(f"{d}: {s}") | |
| ok &= None not in s and s[0] < min(s[1], s[2]) and max(s[1], s[2]) < s[3] | |
| V["H6"] = {"pass": ok, "detail": "; ".join(det)} | |
| t = (g.get("K3/think") or {}).get("target_share") | |
| V["H7"] = {"pass": t is not None and 0 < t < 0.5, "detail": f"K3 think target_share = {t}"} | |
| # H4: resource tier (Joshi et al. 2020 taxonomy, microsoft.github.io/linguisticdiversity/assets/lang2tax.txt) | |
| TAX_NAME = {"ind_Latn": "indonesian", "jav_Latn": "javanese", "sun_Latn": "sundanese", "zsm_Latn": "malay", | |
| "tgl_Latn": "tagalog", "ceb_Latn": "cebuano", "vie_Latn": "vietnamese", "tha_Thai": "thai", | |
| "khm_Khmr": "khmer", "lao_Laoo": "lao", "mya_Mymr": "burmese", "hin_Deva": "hindi", "tam_Taml": "tamil", | |
| "kor_Hang": "korean", "jpn_Jpan": "japanese", "arb_Arab": "arabic", "yor_Latn": "yoruba", | |
| "plt_Latn": "malagasy", "eng_Latn": "english", "bug_Latn": "buginese"} | |
| tax = dict(l.strip().rsplit(",", 1) for l in open("data/external/lang2tax.txt", encoding="utf-8") if "," in l) | |
| tier = {c: int(tax[n]) for c, n in TAX_NAME.items() if n in tax} | |
| def rank(xs): | |
| o = sorted(range(len(xs)), key=lambda i: xs[i]); r = [0.0] * len(xs); i = 0 | |
| while i < len(o): | |
| j = i | |
| while j + 1 < len(o) and xs[o[j + 1]] == xs[o[i]]: | |
| j += 1 | |
| for k in range(i, j + 1): | |
| r[o[k]] = (i + j) / 2 + 1 | |
| i = j + 1 | |
| return r | |
| def spearman(a, b): | |
| ra, rb = rank(a), rank(b); ma, mb = st.mean(ra), st.mean(rb) | |
| num = sum((x - ma) * (y - mb) for x, y in zip(ra, rb)) | |
| den = (sum((x - ma) ** 2 for x in ra) * sum((y - mb) ** 2 for y in rb)) ** 0.5 | |
| return round(num / den, 3) if den else None | |
| h4 = [(tier[l], get(l, "C2", "target_share")) for l in non_en if l in tier and get(l, "C2", "target_share") is not None] | |
| rho = spearman([t for t, _ in h4], [s for _, s in h4]) if len(h4) > 2 else None | |
| # H4 as written: lower-resource -> less compliance, i.e. compliance rises with tier -> rho(tier, share) > 0 | |
| V["H4"] = {"pass": rho is not None and rho > 0, "detail": f"Spearman(Joshi tier, C2 target_share) = {rho} over {len(h4)} languages " | |
| "(pre-registration phrased it as a negative correlation with 'low-resource-ness'; tier is ordered high=5)"} | |
| if rho is not None: # exact-ish permutation p-value (two-sided) for the weak correlation | |
| prng = __import__("random").Random(1); ts_ = [t for t, _ in h4]; ss = [s for _, s in h4]; hits = 0 | |
| for _ in range(5000): | |
| prng.shuffle(ss) | |
| hits += abs(spearman(ts_, ss) or 0) >= abs(rho) | |
| V["H4"]["detail"] += f"; permutation p = {hits / 5000:.3f} (direction as predicted, not significant)" | |
| R["tiers"] = tier | |
| # Grammar 'think in Buginese' probe, quote-stripped: the x2ind probe quotes Buginese input sentences in its reasoning | |
| if "grammar" in R: | |
| from lid import profile as _prof | |
| gtest = [json.loads(l) for l in open("data/bugis/test.jsonl", encoding="utf-8")] | |
| for r in json.load(open("data/bugis/results.json", encoding="utf-8"))["rows"]: | |
| if r["think"]: | |
| src = "\n".join(s["bug"] for s in gtest[r["batch"] * 50:(r["batch"] + 1) * 50]) | |
| R["grammar"][f"{r['cond']}/think_noquote"] = _prof(r["reasoning"], "bug_Latn", exclude=src) | |
| if os.path.exists("data/routecheck/results.json"): | |
| R["route_check"] = json.load(open("data/routecheck/results.json", encoding="utf-8"))["summary"] | |
| if os.path.exists("data/reward_by_cond.json"): | |
| R["reward_by_cond"] = json.load(open("data/reward_by_cond.json")) | |
| if os.path.exists("data/distill/summary_baseline.json"): | |
| R["distill"] = {t: json.load(open(f"data/distill/summary_{t}.json")) for t in ("baseline", "after", "after_rp") | |
| if os.path.exists(f"data/distill/summary_{t}.json")} | |
| if os.path.exists("data/distill/stats.json"): | |
| R["distill_stats"] = json.load(open("data/distill/stats.json")) | |
| R["verdicts"] = dict(sorted(V.items())) | |
| V = R["verdicts"] | |
| # ---- exploratory / robustness ---- | |
| import random | |
| rng = random.Random(0) | |
| def boot(xs, n=2000): | |
| xs = [x for x in xs if x is not None] | |
| if len(xs) < 3: | |
| return None | |
| ms = sorted(st.mean(rng.choices(xs, k=len(xs))) for _ in range(n)) | |
| return [round(ms[int(.025 * n)], 3), round(ms[int(.975 * n)], 3)] | |
| low = [r for r in atlas if r["effort"] == "low"] | |
| ci, rob = {}, {} | |
| for l in langs: | |
| for c in ("C0", "C1", "C2", "C3"): | |
| rs = [r for r in low if r["lang"] == l and r["cond"] == c] | |
| if not rs: | |
| continue | |
| ci[f"{l}|{c}"] = boot([r["lid"]["eng_share"] for r in rs]) | |
| rob[f"{l}|{c}"] = { | |
| "eng_share_prereg": mean([r["lid"]["eng_share"] for r in rs if r["lid"]["eng_share"] is not None]), | |
| "eng_share_noquote": mean([r["lid_noquote"]["eng_share"] for r in rs if r.get("lid_noquote", {}).get("eng_share") is not None]), | |
| "target_share_noquote": mean([r["lid_noquote"]["target_share"] for r in rs if r.get("lid_noquote", {}).get("target_share") is not None]), | |
| "lingua_eng": mean([r["lingua_eng"] for r in rs if r.get("lingua_eng") is not None]), | |
| "lingua_eng_noquote": mean([r["lingua_eng_noquote"] for r in rs if r.get("lingua_eng_noquote") is not None])} | |
| R["atlas_eng_share_ci95"] = ci | |
| R["robustness"] = rob | |
| pairs = [(r["lid"]["eng_share"], r["lingua_eng"]) for r in low if r["lid"]["eng_share"] is not None and r.get("lingua_eng") is not None] | |
| if pairs: | |
| R["detector_agreement"] = {"n": len(pairs), "mean_abs_diff": round(st.mean(abs(a - b) for a, b in pairs), 3), | |
| "same_majority": round(sum((a >= .5) == (b >= .5) for a, b in pairs) / len(pairs), 3)} | |
| # condition means across non-English languages (each language weighted equally) | |
| R["condition_means"] = {c: {"eng_share": mean([get(l, c, "eng_share") for l in non_en if get(l, c, "eng_share") is not None]), | |
| "target_share": mean([get(l, c, "target_share") for l in non_en if get(l, c, "target_share") is not None]), | |
| "acc": mean([get(l, c, "acc") for l in non_en if get(l, c, "acc") is not None])} | |
| for c in ("C0", "C1", "C2", "C3")} | |
| # McNemar (exact, two-sided) on paired math items: C0 vs C2 correctness per (problem, language) | |
| from math import comb | |
| mm = {} | |
| for r in math_: | |
| if r["effort"] == "low": | |
| mm.setdefault((r["id"], r["lang"]), {})[r["cond"]] = r["correct"] | |
| b = sum(1 for v in mm.values() if v.get("C0") is True and v.get("C2") is False) | |
| c_ = sum(1 for v in mm.values() if v.get("C0") is False and v.get("C2") is True) | |
| p = min(1.0, 2 * sum(comb(b + c_, k) for k in range(0, min(b, c_) + 1)) / 2 ** (b + c_)) if b + c_ else None | |
| R["math_mcnemar_C0_vs_C2"] = {"C0_only_correct": b, "C2_only_correct": c_, "p_exact": round(p, 4) if p is not None else None} | |
| R["routes"] = {k: sum(1 for r in atlas + math_ if k in r.get("route", "")) for k in ("reflection.ai", "huggingface")} | |
| R["verdicts"] = V | |
| json.dump(R, open("data/results.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) | |
| for k, v in V.items(): | |
| print(k, "PASS" if v["pass"] else "FAIL", "-", v["detail"]) | |