Spaces:
Running
Running
Download chartgen/v11/writer_data.py from JacobLinCool/internal-model-p: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/v11/writer_data.py
- Command line
-
hf download hf://spaces/JacobLinCool/internal-model-p/chartgen/v11/writer_data.py
-
curl -L -o writer_data.py https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/v11/writer_data.py
11.7 kB
| """v11 stage 3: per-beat training data of the pattern writer W (reports/v11 階段 3 預先登記:節奏型寫手 W.md, section 1). | |
| Built from the stage-2 R caches (<shard>.r.pkl: song records with raw charts and timing groups), so the beat tables | |
| and roles are exactly R's. One record per chart, on its group's beat table (n beats): | |
| tok [n] int16 pattern token (patterns.Vocab ids: EMPTY 0, OTHER 1, patterns 2..) | |
| allowed [n] uint32 24-bit mask of the positions a note may take: valid (inside the audio, before a red line) and | |
| not strictly inside a roll / balloon body; 0 for a beat with a note off the 24 positions | |
| col [n] uint64 colour of each hit note, 2 bits per position (0 don, 1 ka, 2 big don, 3 big ka) | |
| objs [k, 4] int32 roll / balloon objects: (beat row, position index 0-23, kind 0 roll / 1 big roll / | |
| 2 balloon, length in ms) | |
| settings [5] float32 nps, big, triplet, eighth, rolls per minute (definitions in the registration) | |
| mapper catalog mapper_user_id (-1 if unknown); year; beatmap id | |
| A beat is trained on when allowed != 0 and tok != OTHER (train_mask()). | |
| python -m chartgen.v11.writer_data prep --caches data/hfruns/runs/v11_s2/caches/*.r.pkl | |
| python -m chartgen.v11.writer_data --selftest | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import pickle | |
| from pathlib import Path | |
| import numpy as np | |
| from chartgen.dataset import beat_ms, roll_end_beats | |
| from chartgen.v11.patterns import GRID, OTHER, POS_BIT, POSITIONS, Vocab | |
| from chartgen.v11.rmap_data import FAMILY_OF_CLASS, N_POS, POS, POS_CLASS, chart_masks | |
| REPO = Path(__file__).resolve().parents[2] | |
| VOCAB_JSON = REPO / "reports/figs/v11_s0_vocab.json" | |
| CATALOG = REPO / "data/catalog/taiko_beatmaps.parquet" | |
| SETTINGS = ("nps", "big", "triplet", "eighth", "rolls_per_min") | |
| FAM_OF_POS = np.array([FAMILY_OF_CLASS[c] for c in POS_CLASS]) | |
| TRIPLET_POS = FAM_OF_POS == "triplet" | |
| EIGHTH_POS = FAM_OF_POS == "eighth" | |
| _POS_ARR = np.asarray(POSITIONS) | |
| def load_vocab() -> Vocab: | |
| d = json.loads(VOCAB_JSON.read_text()) | |
| return Vocab.from_dict(d["vocab_pooled"]) | |
| def load_mappers() -> dict: | |
| import pyarrow.parquet as pq | |
| t = pq.read_table(CATALOG, columns=["beatmap_id", "mapper_user_id"]).to_pydict() | |
| return {int(b): (int(m) if m is not None else -1) for b, m in zip(t["beatmap_id"], t["mapper_user_id"])} | |
| def nearest_pos(k: int) -> int: | |
| """Index (0-23) of the candidate position nearest to 1/48 index k (k in 0..47).""" | |
| return int(np.argmin(np.abs(_POS_ARR - k))) | |
| def chart_settings_w(chart: dict) -> np.ndarray: | |
| ty = np.asarray(chart["type"]) | |
| t = np.asarray(chart["time"], np.float64) | |
| beat = np.asarray(chart["beat"], np.float64) | |
| hit = ty <= 3 | |
| n = int(hit.sum()) | |
| out = np.zeros(5, np.float32) | |
| if n < 2: | |
| return out | |
| span = max((t[hit].max() - t[hit].min()) / 1000.0, 1.0) | |
| out[0] = n / span | |
| out[1] = float((ty[hit] >= 2).mean()) | |
| k = np.mod(np.round(beat[hit] * GRID).astype(np.int64), GRID) | |
| bit = POS_BIT[k] | |
| on = bit >= 0 | |
| out[2] = float(TRIPLET_POS[bit[on]].sum() / n) | |
| out[3] = float(EIGHTH_POS[bit[on]].sum() / n) | |
| span_all = max((t.max() - t.min()) / 60000.0, 1.0 / 60) | |
| out[4] = float((ty >= 4).sum() / span_all) | |
| return out | |
| def chart_w(chart: dict, table, vocab: Vocab) -> dict: | |
| tgt, loss = chart_masks(chart, table) | |
| n = len(table) | |
| tok = vocab.ids(tgt.astype(np.int64)).astype(np.int16) | |
| col = np.zeros(n, np.uint64) | |
| beat = np.asarray(chart["beat"], np.float64) | |
| ty = np.asarray(chart["type"]) | |
| hit = ty <= 3 | |
| g = np.round(beat[hit] * GRID).astype(np.int64) | |
| bb, kk = np.floor_divide(g, GRID), np.mod(g, GRID) | |
| row = np.searchsorted(table.beat, bb) | |
| ok = (row < n) & (table.beat[np.minimum(row, n - 1)] == bb) & (POS_BIT[kk] >= 0) | |
| for r, b, c in zip(row[ok], POS_BIT[kk[ok]], ty[hit][ok]): | |
| col[r] |= np.uint64(int(c) & 3) << np.uint64(2 * int(b)) | |
| objs = [] | |
| roll = ty >= 4 | |
| if roll.any(): | |
| sec = np.asarray(chart["sections"], np.float64) | |
| sb = beat[roll] | |
| eb = roll_end_beats(sec, sb, np.asarray(chart["length_beats"], np.float64)[roll]) | |
| ms0, ms1 = beat_ms(sec, sb), beat_ms(sec, eb) | |
| for a, kind, l0, l1 in zip(sb, ty[roll], ms0, ms1): | |
| b0 = int(np.floor(a + 1e-9)) | |
| r = int(np.searchsorted(table.beat, b0)) | |
| if r >= n or table.beat[r] != b0: | |
| continue | |
| k = int(round((a - b0) * GRID)) % GRID | |
| objs.append((r, nearest_pos(k), int(kind) - 4, int(round(max(l1 - l0, 0.0))))) | |
| return {"tok": tok, "allowed": loss.astype(np.uint32), "col": col, | |
| "objs": np.asarray(objs, np.int32).reshape(-1, 4), "settings": chart_settings_w(chart)} | |
| def train_mask(rec: dict) -> np.ndarray: | |
| return (rec["allowed"] != 0) & (rec["tok"] != OTHER) | |
| def w_cache_path(rcache) -> Path: | |
| return Path(str(rcache).replace(".r.pkl", ".w.pkl")) | |
| def prep_w(rcache, vocab: Vocab | None = None, mappers: dict | None = None) -> Path: | |
| """<shard>.w.pkl: [{set, key, groups: [{uid, role, era, charts: {tier: [record]}}]}] from <shard>.r.pkl.""" | |
| out = w_cache_path(rcache) | |
| if out.exists(): | |
| return out | |
| vocab = vocab or load_vocab() | |
| mappers = mappers if mappers is not None else load_mappers() | |
| recs = pickle.load(open(rcache, "rb")) | |
| songs = [] | |
| for r in recs: | |
| by_bid = {int(c["beatmap_id"]): c for c in r["charts"]} | |
| gs = [] | |
| for g in r["groups"]: | |
| charts = {} | |
| for t, lst in g.charts.items(): | |
| for bid, year, _, _ in lst: | |
| c = by_bid[int(bid)] | |
| w = chart_w(c, g.table, vocab) | |
| w.update(bid=int(bid), year=int(year), mapper=mappers.get(int(bid), -1)) | |
| charts.setdefault(int(t), []).append(w) | |
| gs.append({"uid": g.uid, "role": g.role, "era": g.era, "n": len(g.table), "charts": charts}) | |
| songs.append({"set": int(r["beatmapset_id"]), "key": r["song_key"] or str(r["beatmapset_id"]), "groups": gs}) | |
| tmp = out.with_suffix(f".{os.getpid()}.tmp") | |
| with open(tmp, "wb") as f: | |
| pickle.dump(songs, f, protocol=pickle.HIGHEST_PROTOCOL) | |
| os.replace(tmp, out) | |
| return out | |
| # ------------------------------------------------------------------------------------------------ decoding | |
| def decode_chart(tok, col, objs, table, sections, vocab: Vocab, tier: int) -> dict: | |
| """W records (or generated arrays) -> chart dict (time ms, type, length_beats, sv, kiai empty) on the table.""" | |
| masks = vocab.mask(np.where(np.asarray(tok) == OTHER, 0, tok)).astype(np.int64) | |
| times, types, lens = [], [], [] | |
| pt = table.pos_ms() # [n, 24] | |
| for r in np.nonzero(masks > 0)[0]: | |
| m = int(masks[r]) | |
| for i in range(N_POS): | |
| if m >> i & 1: | |
| times.append(pt[r, i]) | |
| types.append(int((int(col[r]) >> (2 * i)) & 3)) | |
| lens.append(0.0) | |
| sec = np.asarray(sections, np.float64) | |
| for r, i, kind, lms in np.asarray(objs).reshape(-1, 4): | |
| t0 = pt[r, i] | |
| b0 = table.beat[r] + POS[i] / GRID | |
| # length in beats of the section where the object starts | |
| j = max(int(np.searchsorted(sec[:, 0], t0, side="right")) - 1, 0) | |
| times.append(t0) | |
| types.append(int(kind) + 4) | |
| lens.append(float(lms) / sec[j, 1]) | |
| _ = b0 | |
| o = np.argsort(times, kind="stable") | |
| return {"tier": tier, "sections": sec, "time": np.asarray(times)[o], "type": np.asarray(types, int)[o], | |
| "length_beats": np.asarray(lens)[o], "sv": np.ones(len(o)), "kiai": []} | |
| # ------------------------------------------------------------------------------------------------ self-test | |
| def selftest(rcache="data/hfruns/runs/v11_s2/caches/taiko-00000.r.pkl", max_charts=400): | |
| """Round trip: chart -> W records -> chart reproduces every hit note (time within 1 ms, same type) on the beats | |
| that are trained on, and every roll / balloon start, kind and length (within 1 ms).""" | |
| from chartgen.rhythm_eval2 import grid_of | |
| vocab = load_vocab() | |
| recs = pickle.load(open(rcache, "rb")) | |
| n_ch = n_note = n_obj = bad = 0 | |
| devs = [] | |
| for r in recs: | |
| by_bid = {int(c["beatmap_id"]): c for c in r["charts"]} | |
| for g in r["groups"]: | |
| for t, lst in g.charts.items(): | |
| for bid, _, _, _ in lst: | |
| c = by_bid[int(bid)] | |
| w = chart_w(c, g.table, vocab) | |
| dec = decode_chart(w["tok"], w["col"], w["objs"], g.table, g.sections, vocab, t) | |
| tm = train_mask(w) | |
| # human hit notes on trained beats | |
| ty = np.asarray(c["type"]) | |
| hit = ty <= 3 | |
| gh = np.round(np.asarray(c["beat"], np.float64)[hit] * GRID).astype(np.int64) | |
| rows = np.searchsorted(g.table.beat, np.floor_divide(gh, GRID)) | |
| okr = (rows < len(g.table)) & (g.table.beat[np.minimum(rows, len(g.table) - 1)] == np.floor_divide(gh, GRID)) | |
| sel = okr.copy() | |
| sel[okr] = tm[rows[okr]] | |
| raw = np.asarray(c["time"], np.float64)[hit][sel] | |
| ht = beat_ms(np.asarray(c["sections"], np.float64), gh[sel] / GRID) # grid time of each note | |
| devs.append(np.abs(raw - ht)) | |
| hty = ty[hit][sel] | |
| dh = dec["type"] <= 3 | |
| dt, dty = dec["time"][dh], dec["type"][dh] | |
| drow = np.searchsorted(g.table.t0, dt, side="right") - 1 | |
| dsel = tm[np.clip(drow, 0, len(tm) - 1)] | |
| dt, dty = dt[dsel], dty[dsel] | |
| if len(ht) != len(dt) or (len(ht) and (np.abs(np.sort(ht) - np.sort(dt)).max() > 1.0)): | |
| bad += 1 | |
| if bad <= 3: | |
| print("hit mismatch", bid, t, len(ht), len(dt)) | |
| elif len(ht) and (hty[np.argsort(ht)] != dty[np.argsort(dt)]).any(): | |
| bad += 1 | |
| if bad <= 3: | |
| print("type mismatch", bid, t) | |
| ro = ty >= 4 | |
| if ro.sum() != (dec["type"] >= 4).sum(): | |
| bad += 1 | |
| if bad <= 3: | |
| print("object count mismatch", bid, t, ro.sum(), (dec["type"] >= 4).sum()) | |
| n_ch += 1 | |
| n_note += len(ht) | |
| n_obj += int(ro.sum()) | |
| if n_ch >= max_charts: | |
| break | |
| d = np.concatenate(devs) if devs else np.zeros(1) | |
| print(f"selftest: {n_ch} charts, {n_note} notes on trained beats, {n_obj} objects, {bad} mismatches; " | |
| f"raw time vs grid time: median {np.median(d):.2f} ms, 99th pct {np.percentile(d, 99):.2f} ms") | |
| assert bad == 0 | |
| return True | |
| def main(argv=None): | |
| p = argparse.ArgumentParser() | |
| p.add_argument("cmd", nargs="?", choices=["prep"]) | |
| p.add_argument("--caches", nargs="*", default=[]) | |
| p.add_argument("--workers", type=int, default=4) | |
| p.add_argument("--selftest", action="store_true") | |
| a = p.parse_args(argv) | |
| if a.selftest: | |
| selftest() | |
| return | |
| if a.cmd == "prep": | |
| from multiprocessing import Pool | |
| with Pool(a.workers) as pool: | |
| for out in pool.imap_unordered(prep_w, a.caches): | |
| print("wrote", out, flush=True) | |
| if __name__ == "__main__": | |
| main() | |