Spaces:
Running
Running
Download chartgen/v11/rmap_eval.py from JacobLinCool/internal-model-p: direct link, hf CLI and curl.
- Browser
- Download file 34.8 kB
-
https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/v11/rmap_eval.py
- Command line
-
hf download hf://spaces/JacobLinCool/internal-model-p/chartgen/v11/rmap_eval.py
-
curl -L -o rmap_eval.py https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/v11/rmap_eval.py
34.8 kB
| """v11 stage 2 evaluation of the position map R (reports/v11 階段 2 預先登記:位置圖 R.md, sections 2-6). | |
| Maps are npz files of rmap.export / rmap_base (per group uid: logits [n_beats, 24, 5] float16). Targets and loss masks | |
| come from the shard caches (rmap.prep_shard) through rmap.Corpus. Only Oni (3) and Inner Oni (4) are judged. | |
| calib temperature T and offset b per (tier, family), fitted on the tuning set: logit' = logit / T + b; offset | |
| fixed at 0 for families with positives in fewer than 100 tuning songs | |
| position S2.1 (log-loss of calibrated R vs the calibrated simple baseline, paired song bootstrap) and S2.2 (count | |
| ratio and calibration slope) on val, judged cells = (tier, family) with positives in >= 100 val songs; | |
| AUC and the 2022+ subset reported | |
| Bootstrap: songs (song key) resampled 1000x with seed 0 from one rng per population; weights shared by all maps. | |
| python -m chartgen.v11.rmap_eval calib --data f*.pkl --maps tune_R.npz --out calib_R.json | |
| python -m chartgen.v11.rmap_eval position --data f*.pkl --maps val_R.npz --calib calib_R.json \ | |
| --simple val_simple.npz --simple-calib calib_simple.json --prior val_prior.npz --out position.json | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from chartgen.v11.rmap import Corpus | |
| from chartgen.v11.rmap_data import POS_CLASS, bits_to_bool | |
| TIERS = (3, 4) | |
| TNAME = {3: "Oni", 4: "Inner Oni"} | |
| FAMS = ("beat", "1/2", "1/4", "triplet", "eighth") | |
| FAM_CLASSES = {"beat": (0,), "1/2": (1,), "1/4": (3,), "triplet": (2, 4, 6), "eighth": (5, 7)} | |
| FAM_POS = {f: np.isin(POS_CLASS, c) for f, c in FAM_CLASSES.items()} | |
| N_BOOT, SEED = 1000, 0 | |
| MIN_SONGS = 100 | |
| class Maps: | |
| def __init__(self, path): | |
| self.z = np.load(path) | |
| self.index = {r["uid"]: r for r in json.loads(str(self.z["index"]))} | |
| def __contains__(self, uid): | |
| return uid in self.index | |
| def __getitem__(self, uid) -> np.ndarray: | |
| return self.z[uid].astype(np.float32) | |
| def apply_calib(lg: np.ndarray, calib: dict | None) -> np.ndarray: | |
| """Calibrated logits of tiers 3-4 (other tiers untouched).""" | |
| if not calib: | |
| return lg | |
| out = lg.copy() | |
| for t in TIERS: | |
| for f in FAMS: | |
| T, b = calib[str(t)][f] | |
| out[:, FAM_POS[f], t] = lg[:, FAM_POS[f], t] / T + b | |
| return out | |
| def rows(corpus: Corpus, maps_list, calibs, tier: int, fam: str, roles=None, era=None): | |
| """Positions of one (tier, family): y, logits of each map [m, N], song keys, era of the group.""" | |
| Y, Z, K, E = [], [[] for _ in maps_list], [], [] | |
| sel_pos = FAM_POS[fam] | |
| for g in corpus.groups: | |
| if tier not in g.charts or (roles and g.role not in roles) or (era is not None and g.era != era): | |
| continue | |
| if not all(g.uid in m for m in maps_list): | |
| continue | |
| lgs = [apply_calib(m[g.uid], c)[:, sel_pos, tier] for m, c in zip(maps_list, calibs)] | |
| for _, _, tgt, los in g.charts[tier]: | |
| L = bits_to_bool(los)[:, sel_pos] | |
| T = bits_to_bool(tgt)[:, sel_pos] | |
| Y.append(T[L]) | |
| for i, lg in enumerate(lgs): | |
| Z[i].append(lg[L]) | |
| K += [g.key] * int(L.sum()) | |
| E += [g.era] * int(L.sum()) | |
| if not Y: | |
| return None | |
| return (np.concatenate(Y).astype(np.float32), [np.concatenate(z) for z in Z], np.array(K), np.array(E)) | |
| def fit_tb(z, y, temp_only: bool): | |
| zt, yt = torch.tensor(z, dtype=torch.float64), torch.tensor(y, dtype=torch.float64) | |
| logT = torch.zeros(1, dtype=torch.float64, requires_grad=True) | |
| b = torch.zeros(1, dtype=torch.float64, requires_grad=not temp_only) | |
| params = [logT] + ([] if temp_only else [b]) | |
| opt = torch.optim.LBFGS(params, lr=1.0, max_iter=100, line_search_fn="strong_wolfe") | |
| def closure(): | |
| opt.zero_grad() | |
| loss = torch.nn.functional.binary_cross_entropy_with_logits(zt / torch.exp(logT) + b, yt) | |
| loss.backward() | |
| return loss | |
| opt.step(closure) | |
| return float(torch.exp(logT)), float(b) | |
| def calib(a): | |
| c = Corpus(a.data, {"tune"}, tiers=TIERS, log=lambda m: None) | |
| m = Maps(a.maps) | |
| out, info = {}, {} | |
| for t in TIERS: | |
| out[str(t)] = {} | |
| for f in FAMS: | |
| r = rows(c, [m], [None], t, f) | |
| y, (z,), keys, _ = r | |
| n_pos_songs = len(np.unique(keys[y > 0])) | |
| T, b = fit_tb(z, y, temp_only=n_pos_songs < MIN_SONGS) | |
| out[str(t)][f] = [T, b] | |
| info[f"{t}|{f}"] = {"positions": int(len(y)), "positives": int(y.sum()), "songs_with_positives": int(n_pos_songs), | |
| "temperature": T, "offset": b, "offset_fitted": n_pos_songs >= MIN_SONGS} | |
| print(t, f, info[f"{t}|{f}"], flush=True) | |
| Path(a.out).write_text(json.dumps({"calib": out, "info": info}, indent=1)) | |
| def load_calib(path): | |
| return json.loads(Path(path).read_text())["calib"] if path else None | |
| # ------------------------------------------------------------------------------------------------ statistics | |
| def song_weights(keys_unique, seed=SEED): | |
| rng = np.random.default_rng(seed) | |
| n = len(keys_unique) | |
| return rng.multinomial(n, np.full(n, 1.0 / n), size=N_BOOT).astype(np.float64) | |
| def per_song(keys, *vals): | |
| u, inv = np.unique(keys, return_inverse=True) | |
| return u, [np.bincount(inv, weights=v, minlength=len(u)) for v in vals] | |
| def ci(boot): | |
| b = np.asarray(boot, float) | |
| b = b[np.isfinite(b)] | |
| return [float(np.percentile(b, 2.5)), float(np.percentile(b, 97.5))] if len(b) > 10 else [None, None] | |
| def auc(y, s): | |
| y = np.asarray(y, bool) | |
| n1, n0 = int(y.sum()), int((~y).sum()) | |
| if n1 == 0 or n0 == 0: | |
| return float("nan") | |
| o = np.argsort(s, kind="mergesort") | |
| ss = s[o] | |
| r = np.empty(len(s), np.float64) | |
| # average ranks over ties | |
| _, first, cnt = np.unique(ss, return_index=True, return_counts=True) | |
| avg = first + (cnt - 1) / 2.0 + 1 | |
| r[o] = np.repeat(avg, cnt) | |
| return float((r[y].sum() - n1 * (n1 + 1) / 2) / (n1 * n0)) | |
| def logloss_terms(z, y): | |
| return np.logaddexp(0, z) - y * z | |
| def calib_slope(z, y): | |
| zt, yt = torch.tensor(z, dtype=torch.float64), torch.tensor(y, dtype=torch.float64) | |
| w = torch.tensor([1.0, 0.0], dtype=torch.float64, requires_grad=True) | |
| opt = torch.optim.LBFGS([w], lr=1.0, max_iter=100, line_search_fn="strong_wolfe") | |
| def closure(): | |
| opt.zero_grad() | |
| loss = torch.nn.functional.binary_cross_entropy_with_logits(w[0] * zt + w[1], yt) | |
| loss.backward() | |
| return loss | |
| opt.step(closure) | |
| return float(w[0]) | |
| def position(a): | |
| c = Corpus(a.data, {"val"}, tiers=TIERS, log=lambda m: None) | |
| R, S, P = Maps(a.maps), Maps(a.simple), Maps(a.prior) | |
| cR, cS = load_calib(a.calib), load_calib(a.simple_calib) | |
| res = {"pre_registration": "reports/v11 階段 2 預先登記:位置圖 R.md", "n_boot": N_BOOT, "seed": SEED, "cells": {}} | |
| for t in TIERS: | |
| for f in FAMS: | |
| for subset, era in (("all", None), ("2022+", 3)): | |
| r = rows(c, [R, S, P], [cR, cS, None], t, f, era=era) | |
| if r is None: | |
| continue | |
| y, (zR, zS, zP), keys, _ = r | |
| u, (n, ys, pR, lR, lS, lP) = per_song(keys, np.ones_like(y), y, 1 / (1 + np.exp(-zR)), | |
| logloss_terms(zR, y), logloss_terms(zS, y), logloss_terms(zP, y)) | |
| W = song_weights(u) | |
| n_pos_songs = int((ys > 0).sum()) | |
| d = (lR.sum() - lS.sum()) / n.sum() | |
| dB = (W @ lR - W @ lS) / (W @ n) | |
| ratio = pR.sum() / max(ys.sum(), 1e-9) | |
| ratioB = (W @ pR) / np.maximum(W @ ys, 1e-9) | |
| slope = calib_slope(zR, y) | |
| blk = {"songs": int(len(u)), "songs_with_positives": n_pos_songs, "positions": int(len(y)), | |
| "positives": int(y.sum()), "judged": subset == "all" and n_pos_songs >= MIN_SONGS, | |
| "logloss": {"R": float(lR.sum() / n.sum()), "simple": float(lS.sum() / n.sum()), | |
| "prior": float(lP.sum() / n.sum())}, | |
| "R_minus_simple": [float(d), *ci(dB)], | |
| "auc": {"R": auc(y, zR), "simple": auc(y, zS), "prior": auc(y, zP)}, | |
| "count_ratio": [float(ratio), *ci(ratioB)], "calibration_slope": slope} | |
| if blk["judged"]: | |
| lo, hi = blk["R_minus_simple"][1:] | |
| blk["S2.1"] = bool(d < 0 and hi is not None and hi < 0) | |
| rl, rh = blk["count_ratio"][1:] | |
| blk["S2.2"] = bool(0.8 <= ratio <= 1.25 and rl is not None and rl <= 1 <= rh and 0.8 <= slope <= 1.2) | |
| res["cells"][f"{TNAME[t]}|{f}|{subset}"] = blk | |
| print(TNAME[t], f, subset, {k: blk[k] for k in ("songs_with_positives", "R_minus_simple", "count_ratio", | |
| "calibration_slope")}, blk.get("S2.1"), blk.get("S2.2"), flush=True) | |
| judged = [v for v in res["cells"].values() if v["judged"]] | |
| res["S2.1"] = bool(judged) and all(v["S2.1"] for v in judged) | |
| res["S2.2"] = bool(judged) and all(v["S2.2"] for v in judged) | |
| Path(a.out).write_text(json.dumps(res, indent=1)) | |
| print("S2.1", res["S2.1"], "S2.2", res["S2.2"]) | |
| # ------------------------------------------------------------------------------------------------ bars (S2.3) | |
| BAR_LABELS = {"1/6": np.isin(POS_CLASS, [4]), "triplet": np.isin(POS_CLASS, [2, 4, 6]), "eighth": np.isin(POS_CLASS, [5, 7])} | |
| JUDGED_BAR = ("1/6", "triplet") | |
| def complete_bars(g, n_frames): | |
| """Bars helper of the group (rows 0..383 from the measure at 0 ms) and a mask of complete bars: length equal to | |
| the meter and every beat of the bar in the table with all positions valid.""" | |
| from chartgen.dataset import measure_span | |
| from chartgen.v11.rmap_pseudo import Bars | |
| bars = Bars.for_song(g.sections, g.table.beat, n_frames) | |
| s = np.asarray(g.sections, np.float64) | |
| st, en = measure_span(s, np.arange(bars.n) + bars.b0) | |
| j = np.clip(np.searchsorted(s[:, 3], st + 1e-9, side="right") - 1, 0, len(s) - 1) | |
| meter = np.where(s[j, 2] > 0, s[j, 2], 4) | |
| ok = np.isclose(en - st, meter) | |
| full_valid = bits_to_bool(g.table.valid).all(1) | |
| cnt = np.bincount(bars.row[bars.ok], minlength=bars.n) | |
| good = np.bincount(bars.row[bars.ok], weights=full_valid[bars.ok].astype(float), minlength=bars.n) | |
| ok &= (cnt == meter) & (good == cnt) | |
| return bars, ok | |
| def bar_scores(lg_tier: np.ndarray, valid: np.ndarray, bars, sel: np.ndarray) -> np.ndarray: | |
| """1 - prod(1 - p) over the bar's positions of a class set; returned as log-odds-free score in [0, 1].""" | |
| p = 1 / (1 + np.exp(-lg_tier)) | |
| l1 = np.where(valid & sel[None], np.log1p(-np.clip(p, 0, 1 - 1e-7)), 0.0).sum(1) | |
| tot = np.zeros(bars.n) | |
| np.add.at(tot, bars.row[bars.ok], l1[bars.ok]) | |
| return 1 - np.exp(tot) | |
| def song_mean_stat(keys, vals): | |
| """Per-chart values -> per song mean -> (song keys, values).""" | |
| u, inv = np.unique(keys, return_inverse=True) | |
| s = np.bincount(inv, weights=vals, minlength=len(u)) | |
| n = np.bincount(inv, minlength=len(u)) | |
| return u, s / n | |
| def paired_song_diff(u, a, b, W): | |
| est = float(a.mean() - b.mean()) | |
| boot = (W @ a - W @ b) / W.sum(1) | |
| return [est, *ci(boot)] | |
| def bars_eval(a): | |
| import pickle | |
| c = Corpus(a.data, {"val"}, tiers=TIERS, log=lambda m: None) | |
| R, S = Maps(a.maps), Maps(a.simple) | |
| cR, cS = load_calib(a.calib), load_calib(a.simple_calib) | |
| sp9 = pickle.load(open(a.sp9, "rb")) # {(uid, tier): (b0, o [n, 17])} | |
| res = {"cells": {}} | |
| for t in TIERS: | |
| per = {lab: {"keys": [], "R": [], "simple": [], "sp9": []} for lab in BAR_LABELS} | |
| for g in c.groups: | |
| if t not in g.charts or g.uid not in R or g.uid not in S or (g.uid, t) not in sp9: | |
| continue | |
| n_frames = len(c.songs[g.song_index]["mel"]) | |
| bars, ok = complete_bars(g, n_frames) | |
| valid = bits_to_bool(g.table.valid) | |
| lR = apply_calib(R[g.uid], cR)[:, :, t] | |
| lS = apply_calib(S[g.uid], cS)[:, :, t] | |
| b0, o = sp9[(g.uid, t)] | |
| assert b0 == bars.b0, (g.uid, b0, bars.b0) | |
| sig = 1 / (1 + np.exp(-o[:, :6])) | |
| gl = o[:, 6:16] | |
| gap = np.exp(gl - gl.max(1, keepdims=True)) | |
| gap /= gap.sum(1, keepdims=True) | |
| sp = {"1/6": gap[:, 1], "triplet": sig[:, 4], "eighth": sig[:, 5]} | |
| for _, _, tgt, _ in g.charts[t]: | |
| T = bits_to_bool(tgt) | |
| for lab, sel in BAR_LABELS.items(): | |
| has = np.zeros(bars.n, bool) | |
| np.logical_or.at(has, bars.row[bars.ok], (T & sel[None]).any(1)[bars.ok]) | |
| nb = min(bars.n, len(sp[lab])) | |
| m = ok[:nb] | |
| y = has[:nb][m] | |
| if y.all() or not y.any(): | |
| continue | |
| per[lab]["keys"].append(g.key) | |
| per[lab]["R"].append(auc(y, bar_scores(lR, valid, bars, sel)[:nb][m])) | |
| per[lab]["simple"].append(auc(y, bar_scores(lS, valid, bars, sel)[:nb][m])) | |
| per[lab]["sp9"].append(auc(y, sp[lab][:nb][m])) | |
| for lab, d in per.items(): | |
| if not d["keys"]: | |
| continue | |
| keys = np.array(d["keys"]) | |
| u, vR = song_mean_stat(keys, np.array(d["R"])) | |
| _, vS = song_mean_stat(keys, np.array(d["simple"])) | |
| _, vP = song_mean_stat(keys, np.array(d["sp9"])) | |
| W = song_weights(u) | |
| best = "sp9" if vP.mean() >= vS.mean() else "simple" | |
| diff = paired_song_diff(u, vR, vP if best == "sp9" else vS, W) | |
| blk = {"charts": len(keys), "songs": len(u), "auc": {"R": float(vR.mean()), "simple": float(vS.mean()), | |
| "sp9": float(vP.mean())}, | |
| "stronger_comparator": best, "R_minus_stronger": diff, | |
| "R_minus_sp9": paired_song_diff(u, vR, vP, W), "R_minus_simple": paired_song_diff(u, vR, vS, W)} | |
| if lab in JUDGED_BAR: | |
| blk["holds"] = bool(diff[1] is not None and diff[1] > 0) | |
| res["cells"][f"{TNAME[t]}|{lab}"] = blk | |
| print(TNAME[t], lab, blk, flush=True) | |
| res["S2.3"] = all(res["cells"].get(f"{TNAME[t]}|{lab}", {}).get("holds", False) for t in TIERS for lab in JUDGED_BAR) | |
| Path(a.out).write_text(json.dumps(res, indent=1)) | |
| print("S2.3", res["S2.3"]) | |
| # ------------------------------------------------------------------------------------------------ slow-song 1/8 (S2.4) | |
| EIGHTH_POS = POS_CLASS == 5 | |
| def slow8_eval(a): | |
| """Val (full model maps) + train cross-fit (A model on B songs, B model on A songs).""" | |
| from chartgen.rhythm_eval import main_bpm | |
| c = Corpus(a.data, {"val", "A", "B"}, tiers=TIERS, log=lambda m: None) | |
| Rv, Rtr = Maps(a.maps), [Maps(p) for p in a.maps_train] | |
| Sv, Str = Maps(a.simple), [Maps(p) for p in a.simple_train] | |
| Pv, Ptr = Maps(a.prior), [Maps(p) for p in a.prior_train] | |
| def pick(uid, val_map, tr_maps): | |
| if uid in val_map: | |
| return val_map[uid] | |
| for m in tr_maps: | |
| if uid in m: | |
| return m[uid] | |
| return None | |
| res = {"cells": {}} | |
| for t in TIERS: | |
| keys, vals = [], {"R": [], "simple": [], "prior": []} | |
| for g in c.groups: | |
| if t not in g.charts or main_bpm(g.sections) >= 110: | |
| continue | |
| lgs = {"R": pick(g.uid, Rv, Rtr), "simple": pick(g.uid, Sv, Str), "prior": pick(g.uid, Pv, Ptr)} | |
| if any(v is None for v in lgs.values()): | |
| continue | |
| n_frames = len(c.songs[g.song_index]["mel"]) | |
| from chartgen.v11.rmap_pseudo import Bars | |
| bars = Bars.for_song(g.sections, g.table.beat, n_frames) | |
| valid = bits_to_bool(g.table.valid) | |
| for _, _, tgt, _ in g.charts[t]: | |
| T = bits_to_bool(tgt) | |
| hit8 = np.zeros(bars.n, bool) | |
| np.logical_or.at(hit8, bars.row[bars.ok], (T & EIGHTH_POS[None]).any(1)[bars.ok]) | |
| per_bar = {k: [] for k in vals} | |
| for bi in np.where(hit8)[0]: | |
| rows_b = np.where(bars.ok & (bars.row == bi))[0] | |
| cand = valid[rows_b][:, EIGHTH_POS] | |
| y = T[rows_b][:, EIGHTH_POS][cand] | |
| if y.sum() < 1 or y.sum() > len(y) - 1: | |
| continue | |
| for k, lg in lgs.items(): | |
| per_bar[k].append(auc(y, lg[rows_b][:, EIGHTH_POS, t][cand])) | |
| if per_bar["R"]: | |
| keys.append(g.key) | |
| for k in vals: | |
| vals[k].append(float(np.mean(per_bar[k]))) | |
| if not keys: | |
| continue | |
| keys = np.array(keys) | |
| u, vR = song_mean_stat(keys, np.array(vals["R"])) | |
| _, vS = song_mean_stat(keys, np.array(vals["simple"])) | |
| _, vP = song_mean_stat(keys, np.array(vals["prior"])) | |
| W = song_weights(u) | |
| best = "simple" if vS.mean() >= vP.mean() else "prior" | |
| diff = paired_song_diff(u, vR, vS if best == "simple" else vP, W) | |
| blk = {"charts": len(keys), "songs": len(u), "auc": {"R": float(vR.mean()), "simple": float(vS.mean()), | |
| "prior": float(vP.mean())}, | |
| "stronger_comparator": best, "R_minus_stronger": diff, "holds": bool(diff[1] is not None and diff[1] > 0)} | |
| res["cells"][TNAME[t]] = blk | |
| print(TNAME[t], blk, flush=True) | |
| res["S2.4"] = all(res["cells"].get(TNAME[t], {}).get("holds", False) for t in TIERS) | |
| Path(a.out).write_text(json.dumps(res, indent=1)) | |
| print("S2.4", res["S2.4"]) | |
| # ------------------------------------------------------------------------------------------------ pseudo-chart readouts | |
| def human_settings(song, chart): | |
| from chartgen.latent_stats import chart_settings | |
| from chartgen.song_planner import chart_rows | |
| _, H, _ = chart_rows(np.zeros(((len(song["mel"]) + 1) // 2, 1), np.float32), chart) | |
| return chart_settings(H) | |
| def chart_of(song, bid): | |
| return next(ch for ch in song["charts"] if int(ch["beatmap_id"]) == int(bid)) | |
| def pseudo_draws(sampler, lg_tier, valid, bid, k=16): | |
| from chartgen.v11.rmap_pseudo import pseudo_seed | |
| S0 = sampler.scores(lg_tier, valid) | |
| G = np.stack([sampler.gumbel(np.random.default_rng(pseudo_seed(bid, i)), 1, len(lg_tier))[0] for i in range(k)]) | |
| return sampler.draw(S0, G) # [k, n] masks | |
| def song_level(a): | |
| """S2.5: triplet amount of R's pseudo-charts, line fitted on the tuning set, R2 on the ceiling's val charts.""" | |
| from chartgen.v11.rmap_pseudo import Bars, Sampler, fast_settings | |
| smp = Sampler() | |
| out = {} | |
| for role, mp in (("tune", a.maps_tune), ("val", a.maps)): | |
| c = Corpus(a.data, {role}, tiers=TIERS, log=lambda m: None) | |
| M, cal = Maps(mp), load_calib(a.calib) | |
| recs = [] | |
| for g in c.groups: | |
| if g.uid not in M: | |
| continue | |
| song = c.songs[g.song_index] | |
| bars = Bars.for_song(g.sections, g.table.beat, len(song["mel"])) | |
| lg = apply_calib(M[g.uid], cal) | |
| valid = bits_to_bool(g.table.valid) | |
| for t in TIERS: | |
| for bid, _, _, _ in g.charts.get(t, []): | |
| hs = human_settings(song, chart_of(song, bid)) | |
| if hs is None: | |
| continue | |
| fs = fast_settings(pseudo_draws(smp, lg[:, :, t], valid, bid), bars) | |
| recs.append({"set": g.set_id, "bid": bid, "tier": t, "key": g.key, "y": float(hs[2]), | |
| "r": float(np.nanmean(fs["triplet"]))}) | |
| out[role] = recs | |
| print(role, len(recs), "charts", flush=True) | |
| ceil = np.load(a.ceilings) | |
| res = {"cells": {}} | |
| for t in TIERS: | |
| tu = [r for r in out["tune"] if r["tier"] == t and np.isfinite(r["r"])] | |
| A = np.polyfit([r["r"] for r in tu], [r["y"] for r in tu], 1) | |
| va = {(r["set"], r["bid"]): r for r in out["val"] if r["tier"] == t and np.isfinite(r["r"])} | |
| sets, bids = ceil[f"sig|{t}|set"], ceil[f"sig|{t}|bid"] | |
| y, pc = ceil[f"pos12|triplet|{t}|y"], ceil[f"pos12|triplet|{t}|pred"] | |
| songs = ceil[f"sig|{t}|song"] | |
| keep = np.array([(int(s_), int(b_)) in va for s_, b_ in zip(sets, bids)]) | |
| pr = np.array([np.polyval(A, va[(int(s_), int(b_))]["r"]) for s_, b_, k in zip(sets, bids, keep) if k]) | |
| yy, pcc, ss = y[keep], pc[keep], songs[keep] | |
| def r2(yv, pv): | |
| return 1 - ((yv - pv) ** 2).sum() / ((yv - yv.mean()) ** 2).sum() | |
| u, inv = np.unique(ss, return_inverse=True) | |
| W = song_weights(u) | |
| Wi = W[:, inv] | |
| def wr2(pv): | |
| m = (Wi @ yy) / Wi.sum(1) | |
| return 1 - (Wi * (yy[None] - pv[None]) ** 2).sum(1) / (Wi * (yy[None] - m[:, None]) ** 2).sum(1) | |
| est_R, est_C = r2(yy, pr), r2(yy, pcc) | |
| blk = {"charts": int(keep.sum()), "ceiling_charts": int(len(keep)), "line": A.tolist(), | |
| "r2_R": float(est_R), "r2_pos12": float(est_C), "diff": [float(est_R - est_C), *ci(wr2(pr) - wr2(pcc))], | |
| "corr2_R": float(np.corrcoef(yy, pr)[0, 1] ** 2), "corr2_pos12": float(np.corrcoef(yy, pcc)[0, 1] ** 2), | |
| "holds": bool(est_R >= est_C + 0.02)} | |
| res["cells"][TNAME[t]] = blk | |
| print(TNAME[t], blk, flush=True) | |
| res["S2.5"] = all(res["cells"][TNAME[t]]["holds"] for t in TIERS) | |
| res["per_chart"] = out | |
| Path(a.out).write_text(json.dumps(res, indent=1)) | |
| print("S2.5", res["S2.5"]) | |
| # ------------------------------------------------------------------------------------------------ tempo slope (S2.6) | |
| def pseudo_log_median_gap(masks, g): | |
| """mean over draws of log median gap (ms) between consecutive distinct hit times of the pseudo-charts.""" | |
| from chartgen.v11.rmap_data import POS as P24 | |
| out = [] | |
| for m in masks: | |
| bits = (np.asarray(m, np.int64)[:, None] >> np.arange(24)) & 1 | |
| r, k = np.nonzero(bits) | |
| t = np.unique(g.table.t0[r] + g.table.bl[r].astype(np.float64) * P24[k] / 48.0) | |
| if len(t) >= 16: | |
| out.append(np.log(np.median(np.diff(t)))) | |
| return float(np.mean(out)) if out else np.nan | |
| def main_charts_val(tiers=TIERS): | |
| """{(song key, tier): beatmap id} of the main human mapset per val song (as stage 0: build_human_collection).""" | |
| from chartgen import disteval as de | |
| E, cat = de.load_charts_all(), de.load_catalog() | |
| col = de.build_human_collection(E, modern_only=False, catalog=cat, split="val") | |
| out = {} | |
| for key, v in col.items(): | |
| ms = v["human"][0] | |
| for t in tiers: | |
| if t in ms: | |
| out[(key, t)] = int(ms[t]["beatmap_id"]) | |
| return out | |
| def slope_with_ci(x, y, keys): | |
| u, inv = np.unique(keys, return_inverse=True) | |
| W = np.vstack([np.ones(len(u)), song_weights(u)])[:, inv] | |
| S = W.sum(1) | |
| mx, my = W @ x / S, W @ y / S | |
| dx, dy = x[None] - mx[:, None], y[None] - my[:, None] | |
| sl = (W * dx * dy).sum(1) / (W * dx * dx).sum(1) | |
| return sl | |
| def tempo(a): | |
| from chartgen.rhythm_eval import main_bpm | |
| from chartgen.v11.rmap_pseudo import Sampler | |
| smp = Sampler() | |
| c = Corpus(a.data, {"val"}, tiers=TIERS, log=lambda m: None) | |
| mains = main_charts_val() | |
| models = {"R": (Maps(a.maps), load_calib(a.calib)), "noms": (Maps(a.noms), load_calib(a.noms_calib)), | |
| "simple": (Maps(a.simple), load_calib(a.simple_calib)), "prior": (Maps(a.prior), None)} | |
| res = {"cells": {}} | |
| for t in TIERS: | |
| X, Y, K, Z = [], [], [], {k: [] for k in models} | |
| for g in c.groups: | |
| if t not in g.charts or not all(g.uid in m for m, _ in models.values()): | |
| continue | |
| song = c.songs[g.song_index] | |
| for bid, _, _, _ in g.charts[t]: | |
| if mains.get((g.key, t)) != bid: | |
| continue | |
| ch = chart_of(song, bid) | |
| ht = np.unique(np.sort(np.asarray(ch["time"], np.float64)[np.asarray(ch["type"]) <= 3])) | |
| if len(ht) < 16: | |
| continue | |
| vals = {} | |
| valid = bits_to_bool(g.table.valid) | |
| for k, (M, cal) in models.items(): | |
| vals[k] = pseudo_log_median_gap(pseudo_draws(smp, apply_calib(M[g.uid], cal)[:, :, t], valid, bid), g) | |
| if not all(np.isfinite(v) for v in vals.values()): | |
| continue | |
| X.append(np.log(main_bpm(ch["sections"]))); Y.append(np.log(np.median(np.diff(ht)))); K.append(g.key) | |
| for k in models: | |
| Z[k].append(vals[k]) | |
| X, Y, K = np.array(X), np.array(Y), np.array(K) | |
| hs = slope_with_ci(X, Y, K) | |
| blk = {"songs": int(len(np.unique(K))), "human": [float(hs[0]), *ci(hs[1:])]} | |
| for k in models: | |
| ms_ = slope_with_ci(X, np.array(Z[k]), K) | |
| blk[k] = [float(ms_[0]), *ci(ms_[1:])] | |
| blk[f"{k}_minus_human"] = [float(ms_[0] - hs[0]), *ci(ms_[1:] - hs[1:])] | |
| lo, hi = blk["human"][1:] | |
| blk["full_inside_human_ci"] = bool(lo is not None and lo <= blk["R"][0] <= hi) | |
| blk["noms_extra_distance"] = abs(blk["noms"][0] - blk["human"][0]) - abs(blk["R"][0] - blk["human"][0]) | |
| res["cells"][TNAME[t]] = blk | |
| print(TNAME[t], blk, flush=True) | |
| if a.hidden: | |
| z = np.load(a.hidden) | |
| H, yb, kk = z["h"].astype(np.float32), z["logbl"].astype(np.float64), z["key"] | |
| fold = np.array([int(__import__("hashlib").sha1(f"probe:{k}".encode()).hexdigest(), 16) % 5 for k in kk]) | |
| pred = np.zeros_like(yb) | |
| for f in range(5): | |
| tr, te = fold != f, fold == f | |
| mu, sd = H[tr].mean(0), H[tr].std(0) + 1e-6 | |
| A = (H[tr] - mu) / sd | |
| w = np.linalg.solve(A.T @ A + 1.0 * len(A) / 100 * np.eye(A.shape[1]), A.T @ (yb[tr] - yb[tr].mean())) | |
| pred[te] = ((H[te] - mu) / sd) @ w + yb[tr].mean() | |
| r2 = 1 - ((yb - pred) ** 2).sum() / ((yb - yb.mean()) ** 2).sum() | |
| res["manipulation_check_r2"] = float(r2) | |
| res["manipulation_check_tempo_removed"] = bool(r2 < 0.8) | |
| print("manipulation check R2", r2) | |
| res["S2.6_first"] = all(res["cells"][TNAME[t]]["full_inside_human_ci"] for t in TIERS) | |
| second = res["cells"]["Oni"]["noms_extra_distance"] >= 0.10 | |
| res["S2.6_second"] = (None if not res.get("manipulation_check_tempo_removed", True) else bool(second)) | |
| Path(a.out).write_text(json.dumps(res, indent=1)) | |
| print("S2.6 first", res["S2.6_first"], "second", res["S2.6_second"]) | |
| # ------------------------------------------------------------------------------------------------ fidelity (pre-run check 3) | |
| def fidelity(a): | |
| from chartgen.dataset import subdiv_class | |
| from chartgen.gapstats import gap_bins | |
| from chartgen.v11.rmap_data import POS as P24 | |
| from chartgen.v11.rmap_pseudo import Bars, Sampler, fast_settings | |
| smp = Sampler() | |
| c = Corpus(a.data, {"tune"}, tiers=TIERS, log=lambda m: None) | |
| M, cal = Maps(a.maps), load_calib(a.calib) | |
| from chartgen.v11.rmap_pseudo import apply_tau | |
| taus = json.loads(Path(a.taus).read_text())["tau"]["R"] if a.taus else {} | |
| def stats_of_grid(gr, bl_of): | |
| gr = np.unique(gr) | |
| if len(gr) < 16: | |
| return None | |
| blk = gr // (48 * 16) | |
| fine = subdiv_class(gr) >= 5 | |
| u = np.unique(blk) | |
| a_ = float(np.isin(u, np.unique(blk[fine])).mean()) | |
| gb = gap_bins(np.diff(gr) / 48.0) | |
| c_ = float((gb == 8).mean()) | |
| return a_, c_ | |
| rec = {t: {"pseudo": [], "human": []} for t in TIERS} | |
| for g in c.groups: | |
| if g.uid not in M: | |
| continue | |
| song = c.songs[g.song_index] | |
| bars = Bars.for_song(g.sections, g.table.beat, len(song["mel"])) | |
| lg = apply_calib(M[g.uid], cal) | |
| valid = bits_to_bool(g.table.valid) | |
| for t in TIERS: | |
| for bid, _, tgt, _ in g.charts.get(t, []): | |
| ch = chart_of(song, bid) | |
| hs = human_settings(song, ch) | |
| hit = np.asarray(ch["type"]) <= 3 | |
| hg = np.round(np.asarray(ch["beat"])[hit] * 48).astype(np.int64) | |
| hst = stats_of_grid(hg, None) | |
| m = pseudo_draws(smp, apply_tau(lg[:, :, t], taus.get(str(t))), valid, bid, k=1) | |
| bits = (np.asarray(m[0], np.int64)[:, None] >> np.arange(24)) & 1 | |
| r, k = np.nonzero(bits) | |
| pg = g.table.beat[r] * 48 + P24[k] | |
| pst = stats_of_grid(pg, None) | |
| fs = fast_settings(m, bars) | |
| if hs is None or hst is None or pst is None or not np.isfinite(fs["triplet"][0]): | |
| continue | |
| ht = np.unique(np.asarray(ch["time"], np.float64)[hit]) | |
| pt = np.unique(g.table.t0[r] + g.table.bl[r].astype(np.float64) * P24[k] / 48.0) | |
| rec[t]["human"].append([hst[0], hs[2], hs[3], hst[1], np.log(np.median(np.diff(ht)))]) | |
| rec[t]["pseudo"].append([pst[0], fs["triplet"][0], fs["eighth"][0], pst[1], np.log(np.median(np.diff(pt)))]) | |
| names = ["blocks_with_1/8_or_finer", "triplet_setting", "eighth_setting", "gap_other_share", "log_median_gap_ms"] | |
| res = {} | |
| for t in TIERS: | |
| H, P = np.array(rec[t]["human"]), np.array(rec[t]["pseudo"]) | |
| blk = {"charts": len(H)} | |
| for i, nm in enumerate(names): | |
| blk[nm] = {"human": float(H[:, i].mean()), "pseudo": float(P[:, i].mean()), | |
| "ratio": float(P[:, i].mean() / H[:, i].mean()) if i < 4 else None, | |
| "diff": float(P[:, i].mean() - H[:, i].mean())} | |
| blk["flag"] = any(blk[nm]["ratio"] > 1.5 for nm in names[:3]) | |
| res[TNAME[t]] = blk | |
| print(TNAME[t], blk, flush=True) | |
| res["flag_any"] = any(res[TNAME[t]]["flag"] for t in TIERS) | |
| Path(a.out).write_text(json.dumps(res, indent=1)) | |
| # ------------------------------------------------------------------------------------------------ sampling temperature | |
| def taufit(a): | |
| """Addendum of 2026-11-20: per map, tier and family, the temperature tau (logits / tau before the end-to-end | |
| conversion samples) that makes the share of 16-beat blocks holding a note of the family equal to the human share, | |
| on the tuning set (one pseudo-chart per chart, seed pseudo_seed(beatmap id, 0)); triplet family first, then the | |
| 1/8 family with the triplet tau fixed; bisection on log tau in [log 0.05, log 2], 20 steps.""" | |
| from chartgen.v11.rmap_pseudo import FAMILY_POS, Sampler, apply_tau, block_share, pseudo_seed | |
| smp = Sampler() | |
| c = Corpus(a.data, {"tune"}, tiers=TIERS, log=lambda m: None) | |
| specs = {"R": (a.maps, a.calib), "prior": (a.prior, None), "simple": (a.simple, a.simple_calib)} | |
| out, info = {}, {} | |
| for name, (mp, cp) in specs.items(): | |
| M, cal = Maps(mp), load_calib(cp) | |
| out[name] = {} | |
| for t in TIERS: | |
| items = [] | |
| for g in c.groups: | |
| if t not in g.charts or g.uid not in M: | |
| continue | |
| lg = apply_calib(M[g.uid], cal)[:, :, t] | |
| valid = bits_to_bool(g.table.valid) | |
| for bid, _, tgt, _ in g.charts[t]: | |
| G = smp.gumbel(np.random.default_rng(pseudo_seed(bid, 0)), 1, len(lg))[0] | |
| items.append((lg, valid, G, g.table.beat, tgt)) | |
| human = {f: float(np.nanmean([block_share(it[4].astype(np.int64), it[3], FAMILY_POS[f]) for it in items])) | |
| for f in ("triplet", "eighth")} | |
| def share(tau, fam): | |
| v = [block_share(smp.masks[np.argmax(smp.scores(apply_tau(lg, tau), valid) + G, -1)], beats, | |
| FAMILY_POS[fam]) for lg, valid, G, beats, _ in items] | |
| return float(np.nanmean(v)) | |
| tau = {"triplet": 1.0, "eighth": 1.0} | |
| rec = {} | |
| for fam in ("triplet", "eighth"): | |
| lo, hi = np.log(0.05), np.log(2.0) | |
| s_hi = share({**tau, fam: float(np.exp(hi))}, fam) | |
| s_lo = share({**tau, fam: float(np.exp(lo))}, fam) | |
| if human[fam] >= s_hi: | |
| tau[fam] = float(np.exp(hi)) | |
| elif human[fam] <= s_lo: | |
| tau[fam] = float(np.exp(lo)) | |
| else: | |
| for _ in range(20): | |
| mid = 0.5 * (lo + hi) | |
| if share({**tau, fam: float(np.exp(mid))}, fam) < human[fam]: | |
| lo = mid | |
| else: | |
| hi = mid | |
| tau[fam] = float(np.exp(0.5 * (lo + hi))) | |
| rec[fam] = {"human_block_share": human[fam], "pseudo_block_share_tau1": share({**tau, fam: 1.0}, fam), | |
| "tau": tau[fam], "pseudo_block_share_fitted": share(tau, fam)} | |
| out[name][str(t)] = tau | |
| info[f"{name}|{t}"] = {"charts": len(items), **rec} | |
| print(name, t, info[f"{name}|{t}"], flush=True) | |
| Path(a.out).write_text(json.dumps({"tau": out, "info": info}, indent=1)) | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | |
| ap.add_argument("cmd", choices=["calib", "position", "bars", "slow8", "song", "tempo", "fidelity", "taufit"]) | |
| ap.add_argument("--data", nargs="+", required=True) | |
| ap.add_argument("--maps", required=True) | |
| ap.add_argument("--calib") | |
| ap.add_argument("--simple") | |
| ap.add_argument("--simple-calib") | |
| ap.add_argument("--prior") | |
| ap.add_argument("--sp9") | |
| ap.add_argument("--maps-train", nargs="*", default=[]) | |
| ap.add_argument("--simple-train", nargs="*", default=[]) | |
| ap.add_argument("--prior-train", nargs="*", default=[]) | |
| ap.add_argument("--maps-tune") | |
| ap.add_argument("--ceilings") | |
| ap.add_argument("--noms") | |
| ap.add_argument("--noms-calib") | |
| ap.add_argument("--hidden") | |
| ap.add_argument("--taus") | |
| ap.add_argument("--out", required=True) | |
| a = ap.parse_args(argv) | |
| {"calib": calib, "position": position, "bars": bars_eval, "slow8": slow8_eval, "song": song_level, | |
| "tempo": tempo, "fidelity": fidelity, "taufit": taufit}[a.cmd](a) | |
| if __name__ == "__main__": | |
| main() | |