internal-model-p / chartgen /rhythm_eval.py
JacobLinCool's picture
Release Model P chart generation demo for osu!taiko and TJA
2469e25 verified
Raw History Blame Contribute Delete
21.5 kB
"""Rhythm-following metrics: does a chart's rhythm follow its song the way a human chart of that song does?
uv run python -m chartgen.rhythm_eval --out reports/figs/rhythm_eval.json
Definitions are pre-registered in reports/節奏跟隨指標設計(草案).md, section 5. Everything is compared on one beat
grid, the reference mapset's timing (the timing the AI used); a second human team's notes are first moved onto that
time axis with disteval's alignment (offset_ms). Note positions are snapped to the 1/48-beat grid; hit notes only.
A subdivision mix: share of hit notes per subdivision class (beat, 1/2, 1/3, 1/4, 1/6, 1/8, 1/12, 1/16, finer);
total variation distance between one candidate chart and the reference chart of the same tier.
B beat patterns (the set of 1/48 positions of the hit notes inside one beat):
foreign share of the candidate's beats whose pattern occurs in no tier of the reference mapset;
missing share of the reference chart's beats whose pattern the candidate chart of the same tier never uses.
D rhythm profile = subdivision mix (9) + gap mix (12 gap classes); distance = mean of the two TVs.
D1 identification: share of other songs whose reference is farther from the candidate than its own song's
reference (0.5 = guessing, 1 = always picks its own song);
D2 spread ratio: mean distance between candidates of different songs / the same for the references;
D3 per profile entry: across-song slope and correlation of the candidate on the reference.
Human floor: songs outside the test split with two or more independent teams (different mappers, lined up in time);
the main team is the reference, every other team a candidate. Threshold = 95th percentile of the floor per tier.
AI: each draw is judged on its own; the flag rate is the mean over draws, then over songs. Tempo-only baseline:
mean profile of training charts of the tier whose main BPM is within 10% of the song's.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import pickle
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np
from . import disteval as de
from .dataset import DIVISORS, GRID, _beats_at, subdiv_class
from .train import song_split
REPO = Path(__file__).resolve().parents[2]
TNAMES = ["Kantan", "Futsuu", "Muzukashii", "Oni", "Inner Oni"]
N_SUB = len(DIVISORS) + 1
SUB_NAMES = [f"1/{d}" if d > 1 else "beat" for d in DIVISORS] + ["finer"]
GAP_VALUES = [1 / 6, 1 / 4, 1 / 3, 1 / 2, 2 / 3, 3 / 4, 1.0, 1.5, 2.0]
GAP_NAMES = ["<=1/8", "1/6", "1/4", "1/3", "1/2", "2/3", "3/4", "1", "3/2", "2", ">2", "other"]
MIN_HITS = 30
SYSTEMS = {"v9.1": "evalgen_v91/mapsets_AI_v9.1.pkl", "v10c": "evalgen_v10c/mapsets_AI_v10c.pkl"}
# ---------------------------------------------------------------- per-chart features
def hit_grid(chart: dict, sections, offset: float = 0.0) -> np.ndarray:
"""Hit-note positions on `sections`' beat grid, as 1/48-beat indices (sorted, unique)."""
t = np.asarray(chart["time"], np.float64) + offset
ty = np.asarray(chart["type"])
t = np.sort(t[ty <= 3])
if len(t) == 0:
return np.zeros(0, np.int64)
return np.unique(np.round(_beats_at(np.asarray(sections, np.float64), t) * GRID).astype(np.int64))
def sub_mix(g: np.ndarray) -> np.ndarray:
return np.bincount(subdiv_class(g), minlength=N_SUB)[:N_SUB] / max(len(g), 1)
def gap_mix(g: np.ndarray) -> np.ndarray:
d = np.diff(g) / GRID
k = np.full(len(d), len(GAP_NAMES) - 1)
k[d <= 1 / 8 + 1e-6] = 0
for i, v in enumerate(GAP_VALUES):
k[np.abs(d - v) < 1e-6] = i + 1
k[d > 2 + 1e-6] = len(GAP_NAMES) - 2
return np.bincount(k, minlength=len(GAP_NAMES)) / max(len(d), 1)
def patterns(g: np.ndarray) -> Counter:
beats = g // GRID
pos = g % GRID
out = Counter()
for b in np.unique(beats):
out[tuple(pos[beats == b].tolist())] += 1
return out
def tv(a, b) -> float:
return 0.5 * float(np.abs(np.asarray(a) - np.asarray(b)).sum())
def outside(pat: Counter, vocab) -> float:
n = sum(pat.values())
return sum(v for p, v in pat.items() if p not in vocab) / max(n, 1)
def profile(g):
return np.r_[sub_mix(g), gap_mix(g)]
def pdist(a, b) -> float:
return 0.5 * (tv(a[:N_SUB], b[:N_SUB]) + tv(a[N_SUB:], b[N_SUB:]))
def pmat(P, Q) -> np.ndarray:
"""[len(P), len(Q)] profile distances (pdist for every pair)."""
P, Q = np.asarray(P), np.asarray(Q)
d = np.abs(P[:, None, :] - Q[None, :, :])
return 0.25 * (d[..., :N_SUB].sum(-1) + d[..., N_SUB:].sum(-1))
def main_bpm(sections) -> float:
s = np.asarray(sections, np.float64)
if len(s) == 1:
return 60000 / s[0, 1]
span = np.diff(np.r_[s[:, 0], s[-1, 0] + 60000])
cover = defaultdict(float)
for bl, d in zip(np.round(s[:, 1], 3), span):
cover[bl] += d
return 60000 / max(cover, key=cover.get)
def common(cand_g, ref_g):
"""Both charts cut to the stretch where both have notes (whole beats), so a different cut of the song is not
counted as a different rhythm."""
lo = max(cand_g[0], ref_g[0]) // GRID * GRID
hi = (min(cand_g[-1], ref_g[-1]) // GRID + 1) * GRID
return cand_g[(cand_g >= lo) & (cand_g < hi)], ref_g[(ref_g >= lo) & (ref_g < hi)]
def finer_share(grids) -> float:
g = np.concatenate(list(grids))
return float((subdiv_class(g) == N_SUB - 1).mean()) if len(g) else 0.0
def ab(cand_g, ref_g, ref_vocab):
"""A, B foreign, B missing for one candidate chart against the reference chart of the same tier (common stretch)."""
cand_g, ref_g = common(cand_g, ref_g)
pc = patterns(cand_g)
return (tv(sub_mix(cand_g), sub_mix(ref_g)), outside(pc, ref_vocab), outside(patterns(ref_g), set(pc)))
# ---------------------------------------------------------------- data
def mapset_grids(ms: dict, sections=None):
"""tier -> hit grid of a mapset ({tier: chart}); on `sections` (default: each chart's own) with its offset."""
out = {}
for t, c in ms.items():
g = hit_grid(c, c["sections"] if sections is None else sections, float(c.get("offset_ms", 0.0)))
if len(g) >= MIN_HITS:
out[int(t)] = g
return out
def floor_pairs(E, cat, cache: Path):
"""[(song key, year, ref grids {tier: g}, cand grids {tier: g})] for every non-test song with independent teams."""
if cache.exists():
return pickle.load(open(cache, "rb"))
out = []
for split in ("train", "val"):
col = de.build_human_collection(E, modern_only=False, catalog=cat, split=split)
for key, v in col.items():
if len(v["human"]) < 2:
continue
ref = v["human"][0]
sec = ref[max(ref)]["sections"]
rg = mapset_grids(ref)
for j, ms in enumerate(v["human"][1:], 1):
cg = mapset_grids(ms, sec)
if set(rg) & set(cg):
out.append((key, v["meta"]["years"][0], rg, cg))
cache.parent.mkdir(parents=True, exist_ok=True)
pickle.dump(out, open(cache, "wb"))
return out
def eval_songs(E, cat, sets):
"""set -> reference grids and the second teams lined up with it (when its collection's main team is this set)."""
by_id = {e["beatmapset_id"]: e for e in E}
out = {}
for s in sets:
e = by_id.get(s)
if e is None or song_split(e.get("song_key") or str(s)) == "test":
continue
ms = de._entry_mapset(e, cat)
rg = mapset_grids(ms)
if not rg:
continue
sec = ms[max(ms)]["sections"]
extra = []
col = de.build_human_collection(E, songs=[e.get("song_key") or str(s)], modern_only=True, catalog=cat,
split="val")
v = next(iter(col.values()), None)
if v and v["meta"]["beatmapset_ids"][0] == s:
extra = [mapset_grids(m, sec) for m in v["human"][1:]]
out[s] = {"ref": rg, "sec": sec, "bpm": main_bpm(sec), "extra": extra}
return out
def tempo_bank(E):
"""tier -> (main BPMs, profiles) of training charts (one chart per tier per mapset)."""
bank = defaultdict(lambda: ([], []))
for e in E:
if song_split(e.get("song_key") or str(e["beatmapset_id"])) != "train":
continue
for t, c in de._entry_mapset(e, None).items():
g = hit_grid(c, c["sections"])
if len(g) >= MIN_HITS:
bank[int(t)][0].append(main_bpm(c["sections"]))
bank[int(t)][1].append(profile(g))
return {t: (np.array(b), np.stack(p)) for t, (b, p) in bank.items()}
# ---------------------------------------------------------------- corruptions (sensitivity)
def corrupt(g, kind, dose, rng, other=None):
g = g.copy()
pos = g % GRID
if kind == "binarize": # triplet-family notes moved to the nearest 1/4-beat position
cls = subdiv_class(g)
trip = np.isin(cls, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)])
sel = trip & (rng.random(len(g)) < dose)
g[sel] = (g[sel] // GRID) * GRID + np.round(pos[sel] / 12).astype(np.int64) * 12
elif kind == "drop_fine": # 1/8 and finer notes removed
fine = subdiv_class(g) >= DIVISORS.index(8)
g = g[~(fine & (rng.random(len(g)) < dose))]
elif kind == "shift": # off-beat notes moved by a quarter beat
sel = (pos != 0) & (rng.random(len(g)) < dose)
g[sel] = g[sel] + 12
elif kind == "swap": # another song's rhythm, placed from this chart's first note
g = other - other[0] + g[0]
return np.unique(g)
def eligible(g, kind):
cls = subdiv_class(g)
if kind == "binarize":
return np.isin(cls, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)]).mean() >= 0.05
if kind == "drop_fine":
return (cls >= DIVISORS.index(8)).mean() >= 0.02
return True
# ---------------------------------------------------------------- statistics
def boot_ci(per_song: np.ndarray, B: int, rng) -> tuple:
n = len(per_song)
idx = rng.integers(0, n, (B, n))
m = np.nanmean(per_song[idx], 1)
return float(np.nanmean(per_song)), float(np.nanpercentile(m, 2.5)), float(np.nanpercentile(m, 97.5))
def d1_scores(cands, refs):
"""cands, refs: [n, P] profiles of the same n songs; per song the share of other songs' refs farther away."""
n = len(refs)
D = pmat(cands, refs)
own = np.diag(D)
return np.array([(D[i, np.arange(n) != i] > own[i]).mean() for i in range(n)]), D
def d2_ratio(Dc, Dr, idx):
"""mean distance between candidates of different songs over the same for references, songs `idx` (resampled)."""
a, b = np.meshgrid(idx, idx, indexing="ij")
m = a != b
return Dc[a[m], b[m]].mean() / Dr[a[m], b[m]].mean()
# ---------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", type=Path, default=REPO / "reports/figs/rhythm_eval.json")
ap.add_argument("--cache", type=Path, default=REPO / "data/eval/rhythm_floor_pairs.pkl")
ap.add_argument("--boot", type=int, default=1000)
ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
rng = np.random.default_rng(a.seed)
E = de.load_charts_all()
cat = de.load_catalog()
res = {"tiers": {}}
# ---- human floor
pairs = floor_pairs(E, cat, a.cache)
half = lambda k: int(hashlib.sha1(k.encode()).hexdigest(), 16) % 2 # noqa: E731
floor = defaultdict(list) # tier -> [(key, year, A, Bf, Bm, cand g, ref g)]
dropped = 0
for key, year, rg, cg in pairs:
both = sorted(set(rg) & set(cg))
# second team off the reference grid (timing not lined up, or another cut of the song): not a mapper difference
if finer_share(cg[t] for t in both) > finer_share(rg[t] for t in both) + 0.03:
dropped += 1
continue
vocab = set().union(*[set(patterns(g)) for g in rg.values()])
for t in both:
c2, r2 = common(cg[t], rg[t])
if len(c2) >= MIN_HITS and len(r2) >= MIN_HITS:
floor[t].append((key, year, *ab(cg[t], rg[t], vocab), c2, r2, vocab))
res["floor_pairs"] = {"all": len(pairs), "dropped_off_grid": dropped}
print(f"floor: {len(pairs)} team pairs, {dropped} dropped as off the reference grid; charts per tier " + ", ".join(f"{TNAMES[t]} {len(floor[t])}" for t in range(5)))
sets = [int(x) for x in open(REPO / "data/eval_modern_val_sets.txt").read().split()]
ev = eval_songs(E, cat, sets)
systems = {k: pickle.load(open(REPO / "data/hfruns/runs" / p, "rb")) for k, p in SYSTEMS.items()}
bank = tempo_bank(E)
print(f"eval songs with a reference: {len(ev)}; with a second team: {sum(1 for v in ev.values() if v['extra'])}")
for t in range(5):
F = floor[t]
if len(F) < 20:
continue
M = np.array([f[2:5] for f in F]) # [pairs, 3] A, Bf, Bm
thr = np.percentile(M, 95, axis=0)
r = {"floor_n": len(F), "floor_modern_n": int(sum(f[1] >= 2022 for f in F)),
"threshold": dict(zip(("A", "B_foreign", "B_missing"), thr.tolist())),
"floor_median": dict(zip(("A", "B_foreign", "B_missing"), np.median(M, 0).tolist()))}
# R1 specificity: thresholds from one half of the songs, flag rate on the other half
h = np.array([half(f[0]) for f in F])
spec = {}
for k in (0, 1):
th = np.percentile(M[h == k], 95, axis=0)
spec[f"half{1 - k}"] = ((M[h != k] > th).mean(0)).tolist()
r["specificity_false_flag"] = spec
# R2 sensitivity: corruptions of the held-out half's candidates, thresholds from the other half
th = np.percentile(M[h == 0], 95, axis=0)
sens = {}
test = [f for f, hh in zip(F, h) if hh == 1]
crng = np.random.default_rng(a.seed + 1)
for kind in ("binarize", "drop_fine", "shift", "swap"):
for dose in ((1.0,) if kind == "swap" else (0.25, 0.5, 1.0)):
flags, n = [], 0
for i, f in enumerate(test):
cg, rgt, vocab = f[5], f[6], f[7]
if not eligible(cg, kind):
continue
other = test[(i + 1 + crng.integers(len(test) - 1)) % len(test)][5] if kind == "swap" else None
g2 = corrupt(cg, kind, dose, crng, other)
if len(g2) < MIN_HITS:
continue
v = np.array(ab(g2, rgt, vocab))
flags.append(np.r_[v > th, (v > th).any()])
n += 1
if n:
sens[f"{kind}@{dose}"] = {"n": n, "flag_A": float(np.mean([x[0] for x in flags])),
"flag_Bf": float(np.mean([x[1] for x in flags])),
"flag_Bm": float(np.mean([x[2] for x in flags])),
"flag_any": float(np.mean([x[3] for x in flags]))}
r["sensitivity"] = sens
# ---- systems on the evaluation songs
songs = sorted(s for s in ev if t in ev[s]["ref"])
r["eval_n"] = len(songs)
refs = np.stack([profile(ev[s]["ref"][t]) for s in songs])
per = {}
Dr = pmat(refs, refs)
boot_idx = rng.integers(0, len(songs), (a.boot, len(songs)))
for sysn, d in systems.items():
vals = np.full((len(songs), 4, 3), np.nan)
profs = np.full((4, len(songs), refs.shape[1]), np.nan)
for i, s in enumerate(songs):
vocab = set().union(*[set(patterns(g)) for g in ev[s]["ref"].values()])
for k, dr in enumerate(d.get(s, {}).get("draws", [])[:4]):
c = dr["charts"].get(t)
if c is None:
continue
g = hit_grid(c, c["sections"])
if len(g) < MIN_HITS:
continue
vals[i, k] = ab(g, ev[s]["ref"][t], vocab)
profs[k, i] = profile(g)
flag = (vals > thr[None, None, :])
flag = np.where(np.isnan(vals), np.nan, flag)
fl_song = np.nanmean(flag, 1) # [songs, 3]
any_song = np.nanmean(np.where(np.isnan(vals[..., 0]), np.nan, flag.max(2)), 1)
ok = ~np.isnan(profs).any(2) # [4, songs]
d1 = np.full((4, len(songs)), np.nan)
Dcs = []
for k in range(4):
if ok[k].sum() < 20:
continue
sel = np.where(ok[k])[0]
sc, _ = d1_scores(profs[k, sel], refs[sel])
d1[k, sel] = sc
Dc = np.full((len(songs), len(songs)), np.nan)
Dc[np.ix_(sel, sel)] = pmat(profs[k, sel], profs[k, sel])
Dcs.append(Dc)
d1_song = np.nanmean(d1, 0)
Dc_mean = np.nanmean(np.stack(Dcs), 0)
okc = ~np.isnan(Dc_mean).all(1)
d2_point = d2_ratio(np.nan_to_num(Dc_mean, nan=np.nanmean(Dc_mean)), Dr, np.where(okc)[0])
d2_boot = [d2_ratio(np.nan_to_num(Dc_mean, nan=np.nanmean(Dc_mean)), Dr, bi[okc[bi]]) for bi in boot_idx]
# D3: per profile entry, across-song slope / correlation (draw-mean profile)
pm = np.nanmean(profs, 0)
d3 = {}
for j, name in enumerate([f"sub {x}" for x in SUB_NAMES] + [f"gap {x}" for x in GAP_NAMES]):
x, y = refs[:, j], pm[:, j]
m = ~np.isnan(y)
if x[m].std() > 1e-6 and y[m].std() > 1e-6:
d3[name] = {"slope": float(np.polyfit(x[m], y[m], 1)[0]), "corr": float(np.corrcoef(x[m], y[m])[0, 1]),
"human_mean": float(x[m].mean()), "ai_mean": float(y[m].mean())}
stat = lambda v: [float(np.nanmean(v)), float(np.nanpercentile(np.nanmean(v[boot_idx], 1), 2.5)), # noqa: E731
float(np.nanpercentile(np.nanmean(v[boot_idx], 1), 97.5))]
per[sysn] = {
"flag_A": stat(fl_song[:, 0]), "flag_Bf": stat(fl_song[:, 1]), "flag_Bm": stat(fl_song[:, 2]),
"flag_any": stat(any_song),
"mean_A": stat(np.nanmean(vals[..., 0], 1)), "mean_Bf": stat(np.nanmean(vals[..., 1], 1)),
"mean_Bm": stat(np.nanmean(vals[..., 2], 1)),
"D1": stat(d1_song), "D2": [float(d2_point), float(np.percentile(d2_boot, 2.5)), float(np.percentile(d2_boot, 97.5))],
"D3": d3,
"flagged": sorted([[int(s), float(fl_song[i, 0]), float(np.nanmean(vals[i, :, 0])), float(np.nanmean(vals[i, :, 1])),
float(np.nanmean(vals[i, :, 2]))] for i, s in enumerate(songs) if fl_song[i, 0] >= 0.5],
key=lambda x: -x[2]),
"_song": {"A": np.nanmean(vals[..., 0], 1), "flagA": fl_song[:, 0], "any": any_song, "D1": d1_song},
}
# paired differences v10c - v9.1
diff = {}
for key in ("A", "any", "D1"):
x = per["v10c"]["_song"][key] - per["v9.1"]["_song"][key]
diff[key] = stat(x)
diff["flag_A"] = stat(per["v10c"]["_song"]["flagA"] - per["v9.1"]["_song"]["flagA"])
for sysn in per:
per[sysn].pop("_song")
r["systems"] = per
r["v10c_minus_v91"] = diff
# tempo-only baseline
bb, bp = bank[t]
base = []
for s in songs:
m = np.abs(np.log(bb / ev[s]["bpm"])) < np.log(1.1)
base.append(bp[m].mean(0) if m.sum() >= 20 else bp[np.argsort(np.abs(np.log(bb / ev[s]["bpm"])))[:20]].mean(0))
base = np.stack(base)
bd1, _ = d1_scores(base, refs)
r["tempo_baseline"] = {"D1": stat(bd1), "mean_A": stat(np.array([tv(b[:N_SUB], x[:N_SUB]) for b, x in zip(base, refs)]))}
# human level for D1 / D2 on the floor pairs of this tier
fr = np.stack([profile(f[6]) for f in F])
fc = np.stack([profile(f[5]) for f in F])
keys = [f[0] for f in F]
first = {}
for i, k in enumerate(keys):
first.setdefault(k, i)
u = np.array(sorted(first.values())) # one pair per song
hd1, _ = d1_scores(fc[u], fr[u])
Dfr = pmat(fr[u], fr[u])
Dfc = pmat(fc[u], fc[u])
r["human_level"] = {"n_songs": int(len(u)), "D1": float(hd1.mean()),
"D2": float(d2_ratio(Dfc, Dfr, np.arange(len(u))))}
# second teams on the evaluation songs (sanity check of the floor on modern songs)
sec_vals = []
for s in songs:
vocab = set().union(*[set(patterns(g)) for g in ev[s]["ref"].values()])
for x in ev[s]["extra"]:
if t in x:
sec_vals.append(ab(x[t], ev[s]["ref"][t], vocab))
if sec_vals:
sv = np.array(sec_vals)
r["eval_second_teams"] = {"n": len(sv), "flag": (sv > thr).mean(0).tolist(), "mean": sv.mean(0).tolist()}
res["tiers"][TNAMES[t]] = r
print(f"done tier {TNAMES[t]}")
a.out.parent.mkdir(parents=True, exist_ok=True)
json.dump(res, open(a.out, "w"), ensure_ascii=False, indent=1)
print(f"wrote {a.out}")
if __name__ == "__main__":
main()