File size: 20,352 Bytes
2469e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
"""Whole-mapset generation: every difficulty of a song, from the song-level planner and the bar-planned generator,
written as .osz files for play-testing (and as a pickle for the distribution evaluation).

For each beatmap set:
  * timing: the red lines of the set's human chart with the most notes (oracle timing: this tests the charts, not
    beat tracking);
  * plan: the song planner on the whole song for each tier, decided like song_planner --predict (P(play) > 0.5; roll
    start and sustain by the calibrated thresholds in thresholds.json) and with rolls as objects (plan_decide);
  * notes: the generator over consecutive 20 s windows with the song-level plan, the rest mask and --plan-continue
    (no END before the plan's last measure with hit notes); N candidates per window, the one that agrees most with the
    others (MBR on onset F1) is kept;
  * kiai from the generator's kiai head.
The .osz holds the audio, the generated difficulties ("AI ..."), and the set's human difficulties for comparison.

    python -m chartgen.gen_mapset --data f*.pkl --audio-dir /content/audio --model b9.pt --encoder best_v1.pt \
        --planner sp9/best.pt --thresholds sp9/thresholds.json --sets 123 456 --out osz/ --label "v9.1"
"""

from __future__ import annotations

import argparse
import io
import json
import os
import pickle
import zipfile
from pathlib import Path

import numpy as np
import torch

from . import song_planner as sp
from .dataset import BAR_F, GRID, MAX_BARS, SUSTAIN, WINDOW, _beats_at, load_songs, make_example, measure_at, plan_active
from .generate import generate, match_count
from .infer import TIER_NAMES, GeneratedChart, _dummy_chart, decode_kiai, frame_activations, load_model, to_osu
from .plan_decide import count_then_place, roll_objects

CANDS = (("greedy", 0.0, 1.0), ("t0.7", 0.7, 1.0), ("t0.9", 0.9, 1.0), ("t0.9b", 0.9, 1.0))  # N = 4


def planner_rows(enc, mel, sections, device):
    """Planner input rows of the whole song (same features as training) and the first measure index."""
    mem = sp.song_memory(enc, mel, device)
    ons = sp.onset_bands(mel)
    lm = np.asarray(mel, np.float32).mean(1)
    ons = np.concatenate([ons, ((lm - lm.mean()) / (lm.std() + 1e-6))[:, None]], 1)
    dummy = {"sections": sections, "beat": np.zeros(0), "type": np.zeros(0, np.int8), "length_beats": np.zeros(0, np.float32)}
    feat, _, b0 = sp.chart_rows(mem, dummy, ons, True)
    return feat, b0


def song_property_amounts(o, tier=None, cutoffs=None, use=None, rng=None):
    """Triplet and 1/8 measure shares from the planner's own outputs (expected share over its hit measures).
    Stage 0a: these amounts are song properties (independent mapsets agree as much as mappers of one set), and the
    planner's expectation tracks them far better than the prior's music regression (validation: triplet corr 0.76 vs
    0.37; 1/8 0.24 vs 0.10), so they are taken from the music, not drawn."""
    sig = lambda v: 1 / (1 + np.exp(-v))  # noqa: E731
    hit = sig(o[:, 0]) > 0.5
    if not hit.any():
        return 0.0, 0.0
    trip, eighth = float(np.clip(sig(o[hit, 4]) / 0.47, 0, 1).mean()), float(np.clip(sig(o[hit, 5]) / 0.5, 0, 1).mean())
    if use is not None and tier is not None and rng is not None:
        # v10d: whether the chart uses them at all is drawn from P(use | expected share) (per-tier logistic fit on
        # pre-2022 validation charts, reports/figs/song_prop_use.py): a fixed cutoff makes every draw of a song agree,
        # far more sure than the data allow (1/8 use is barely predictable from the music in the hard tiers)
        u = use[str(tier)]
        for nm in ("triplet", "eighth"):
            a, b = u[nm]
            e = trip if nm == "triplet" else eighth
            p_use = 1 / (1 + np.exp(-(a + b * np.log(e + 1e-3))))
            if rng.random() >= p_use:
                if nm == "triplet":
                    trip = 0.0
                else:
                    eighth = 0.0
        return trip, eighth
    if cutoffs is not None and tier is not None:
        # humans either use triplets / 1/8 notes clearly or not at all; an expectation is never exactly 0, so below a
        # per-tier cutoff (set so the share of charts that use them matches the human share; calibrated on pre-2022
        # validation songs, not the modern evaluation songs) the amount is 0
        c = cutoffs[str(tier)] if str(tier) in cutoffs else cutoffs[tier]
        trip = trip if trip >= c["triplet"] else 0.0
        eighth = eighth if eighth >= c["eighth"] else 0.0
    return trip, eighth


def planner_out(planner, feat, tier, device):
    X = torch.from_numpy(feat.astype(np.float32))[None].to(device)
    M = torch.ones(1, len(feat), dtype=torch.bool, device=device)
    with torch.no_grad():
        return planner(X, torch.tensor([tier], device=device), M)[0].cpu().numpy()


def song_plan(planner, enc, mel, sections, tier, th_roll, th_sus, device):
    """(first measure index, [n, BAR_F] decided plan) for the whole song at this tier (v9.1 decoding)."""
    mem = sp.song_memory(enc, mel, device)
    ons = sp.onset_bands(mel)
    lm = np.asarray(mel, np.float32).mean(1)
    ons = np.concatenate([ons, ((lm - lm.mean()) / (lm.std() + 1e-6))[:, None]], 1)
    dummy = {"sections": sections, "beat": np.zeros(0), "type": np.zeros(0, np.int8), "length_beats": np.zeros(0, np.float32)}
    feat, _, b0 = sp.chart_rows(mem, dummy, ons, True)
    X = torch.from_numpy(feat.astype(np.float32))[None].to(device)
    M = torch.ones(1, len(feat), dtype=torch.bool, device=device)
    with torch.no_grad():
        pl = sp.SongPlanner.to_plan(planner(X, torch.tensor([tier], device=device), M))[0].cpu().numpy()
    pl[:, 3] = (pl[:, 3] >= th_roll).astype(np.float32)
    pl[:, SUSTAIN] = np.where(pl[:, SUSTAIN] >= th_sus, np.maximum(pl[:, SUSTAIN], 0.11), 0.0)
    return b0, roll_objects(pl)


def window_plan(plan, b_song, sections, start_f):
    bar0 = int(measure_at(sections, _beats_at(sections, np.array([start_f * 10.0])))[0])
    w = np.zeros((MAX_BARS, BAR_F), np.float32)
    k0 = bar0 - b_song
    seg = plan[max(k0, 0): max(k0, 0) + MAX_BARS - max(-k0, 0)]
    w[max(-k0, 0): max(-k0, 0) + len(seg)] = seg
    covered = np.zeros(MAX_BARS, bool)
    covered[max(-k0, 0): max(-k0, 0) + len(seg)] = True
    return w, covered, bar0


def masks(ex, sections, w, covered, bar0):
    gb = (ex.start_grid + np.arange(len(ex.grid_time))) / GRID
    bi = measure_at(sections, gb) - bar0
    inside = (bi >= 0) & (bi < MAX_BARS)
    al = np.ones(len(gb), bool)
    act = plan_active(w) | ~covered
    al[inside] = act[bi[inside]]
    hitm = np.where((w[:, 0] > 0.5) & covered)[0]
    pos = np.where(inside & np.isin(bi, hitm))[0] if len(hitm) else np.zeros(0, np.int64)
    cont = int(pos[bi[pos] == bi[pos].max()].min()) if len(pos) else 0
    return al, cont


def mbr_pick(preds):
    """Index of the candidate with the highest mean onset F1 to the others (ties: higher logp)."""
    hits = [p["time"][p["type"] <= 3] for p in preds]
    n = len(preds)
    score = np.zeros(n)
    for i in range(n):
        for j in range(n):
            if i != j:
                score[i] += 2 * match_count(hits[i], hits[j], 25.0) / max(len(hits[i]) + len(hits[j]), 1)
    lp = np.array([p["logp"] / max(p["n_events"], 1.0) for p in preds])
    return int(np.lexsort((lp, score))[-1])


def generate_tier(model, planner, enc, mel, sections, tier, t0, t1, th_roll, th_sus, device, seed, plan_override=None):
    b_song, plan = plan_override if plan_override is not None else song_plan(planner, enc, mel, sections, tier, th_roll, th_sus, device)
    chart = _dummy_chart(sections, tier)
    song = {"mel": mel}
    starts = list(range(int(max(t0, 0) // 10), int(t1 // 10), WINDOW))
    times, types, lens, svs = [], [], [], []
    for gi in range(0, len(starts), 24):
        exs, bplans, allowed, conts, temps, scales, meta = [], [], [], [], [], [], []
        for st in starts[gi:gi + 24]:
            ex = make_example(song, chart, st)
            w, cov, bar0 = window_plan(plan, b_song, sections, st)
            al, cont = masks(ex, sections, w, cov, bar0)
            for name, temp, sc in CANDS:
                exs.append(ex); bplans.append(w); allowed.append(al); conts.append(cont); temps.append(temp); scales.append(sc)
            meta.append(ex)
        torch.manual_seed(seed + gi)
        preds = generate(model, exs, device, temperature=temps, rho_scale=scales, plan_source="pred",
                         bar_plan=np.stack(bplans), allowed=allowed, continue_until=conts)
        for k, ex in enumerate(meta):
            group = preds[k * len(CANDS):(k + 1) * len(CANDS)]
            p = group[mbr_pick(group)]
            t = p["time"] + ex.start_ms
            keep = (t < ex.start_ms + WINDOW * 10.0) & (t <= t1 + 2000)
            times.append(t[keep]); types.append(p["type"][keep]); lens.append(p["length"][keep]); svs.append(p["sv"][keep])
    time = np.concatenate(times) if times else np.zeros(0)
    order = np.argsort(time, kind="stable")
    time = time[order]
    keep = np.r_[True, np.diff(time) > 1.0] if len(time) else np.zeros(0, bool)
    _, _, kiai_p = frame_activations(model, mel, device, sections, tier)
    first, last = (time[0], time[-1]) if len(time) else (t0, t1)
    kiai = decode_kiai(kiai_p, sections, first, last)
    return GeneratedChart(sections=sections, kiai=kiai, time=time[keep],
                          type=np.concatenate(types)[order][keep] if types else np.zeros(0, int),
                          length_beats=np.concatenate(lens)[order][keep] if lens else np.zeros(0),
                          sv=np.concatenate(svs)[order][keep] if svs else np.zeros(0), tier=tier), (b_song, plan)


def human_chart(c, sections):
    return GeneratedChart(sections=c["sections"], kiai=[tuple(x) for x in np.asarray(c.get("kiai", np.zeros((0, 2))))],
                          time=np.asarray(c["time"], float), type=np.asarray(c["type"]),
                          length_beats=np.asarray(c["length_beats"], float), sv=np.asarray(c.get("sv", np.ones(len(c["time"])))),
                          tier=int(c["tier"]))


def make_draw(model, planner, enc, mel, sections, t0, t1, tiers, cal, device, seed, prior=None, protos=None, sure_rest=0.05,
              feat=None, b_song=None, rest_band=None, cutoffs=None, coordinate=False, use=None, sample_place=False):
    """One draw of the whole set: {tier: chart dict}, settings per tier (v10a) and the mapset offset.
    coordinate (v10c): tiers are decided from the hardest down, each guided by the next harder tier's plan.
    use, sample_place (v10d): triplet / 1/8 use drawn from P(use | expected share); places sampled, not ranked."""
    overrides, settings, bvec = {}, {}, None
    if prior is not None:
        rng = np.random.default_rng(seed)
        draw, bvec = prior.sample_set({t: feat for t in tiers}, rng)
        guide = None
        for t in (sorted(tiers, reverse=True) if coordinate else tiers):
            o_t = planner_out(planner, feat, t, device)
            d = np.array(draw[t], float)
            d[2], d[3] = song_property_amounts(o_t, t, cutoffs, use, rng)  # song properties from the music
            plan_t, log = count_then_place(o_t, d, t, protos, cal["th_sustain"], sure_rest=sure_rest, rest_band=rest_band,
                                           guide=guide, rng=rng if sample_place else None)
            if coordinate:
                guide = plan_t
            overrides[t] = (b_song, plan_t)
            settings[t] = (d, log)
    charts = {}
    for tier in tiers:
        g, plan = generate_tier(model, planner, enc, mel, sections, tier, t0, t1, cal["th_roll"], cal["th_sustain"], device,
                                seed + 1000 * tier, plan_override=overrides.get(tier))
        charts[tier] = {"tier": tier, "sections": sections, "time": g.time, "type": g.type, "length_beats": g.length_beats,
                        "sv": g.sv, "kiai": g.kiai}
    return charts, settings, bvec


def main(argv=None):
    p = argparse.ArgumentParser()
    p.add_argument("--data", nargs="+", type=Path, required=True)
    p.add_argument("--audio-dir", type=Path, help="audio/taiko/<shard>.tar (downloaded on demand; needed for .osz)")
    p.add_argument("--model", type=Path, required=True, help="bar-planned generator (b9)")
    p.add_argument("--encoder", type=Path, required=True, help="B0 checkpoint for the planner's music memory")
    p.add_argument("--planner", type=Path, required=True)
    p.add_argument("--thresholds", type=Path, required=True, help="song_planner thresholds.json (calibration)")
    p.add_argument("--sets", nargs="*", type=int, default=[])
    p.add_argument("--sets-file", type=Path, help="file with set ids (whitespace separated)")
    p.add_argument("--catalog", type=Path, default=Path("data/catalog/taiko_beatmaps.parquet"))
    p.add_argument("--tiers", nargs="+", type=int, default=[0, 1, 2, 3, 4])
    p.add_argument("--label", default="AI")
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--draws", type=int, default=1, help="independent draws of every set (distribution evaluation: 4)")
    p.add_argument("--no-osz", action="store_true", help="only the pickle (no audio, no .osz)")
    p.add_argument("--no-human", action="store_true", help="do not add the human difficulties to the .osz")
    p.add_argument("--prior", type=Path, help="v10a: chart_prior.ChartPrior pickle; amounts drawn per set, count-then-place")
    p.add_argument("--protos", type=Path, help="v10a: plan_decide.prototypes pickle")
    p.add_argument("--sure-rest", type=float, default=0.05)
    p.add_argument("--rest-band", type=float, nargs=2, help="v10b: calibrated P(rest) band (lo hi): sure rests follow the music")
    p.add_argument("--song-cutoffs", type=Path, help="v10b: per-tier cutoffs for triplet / 1/8 amounts (json)")
    p.add_argument("--coordinate", action="store_true", help="v10c: each tier's rests and rolls guided by the next harder tier")
    p.add_argument("--song-use", type=Path, help="v10d: P(use) of triplets / 1/8 per tier (json, reports/figs/song_prop_use.py)")
    p.add_argument("--sample-place", action="store_true", help="v10d: sample places from the calibrated probabilities")
    p.add_argument("--save-every", type=int, default=10, help="sets between pickle saves (resume after a reclaim)")
    p.add_argument("--out", type=Path, required=True)
    a = p.parse_args(argv)
    import pyarrow.parquet as pq
    from .prep import read_shard
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model = load_model(a.model, device)
    enc = load_model(a.encoder, device).eval()
    cal = json.loads(a.thresholds.read_text())["calibration"]
    ck = torch.load(a.planner, map_location=device)
    planner = sp.SongPlanner(ck["d_in"]).to(device).eval()
    planner.load_state_dict(ck["model"])
    prior = pickle.load(open(a.prior, "rb")) if a.prior else None
    protos = pickle.load(open(a.protos, "rb")) if a.protos else None
    cutoffs = json.loads(a.song_cutoffs.read_text()) if a.song_cutoffs else None
    use = json.loads(a.song_use.read_text()) if a.song_use else None
    # artist / title only name the .osz; without the catalog the set id is used
    cat = {r["beatmapset_id"]: r for r in pq.read_table(a.catalog, columns=["beatmapset_id", "artist", "title"]).to_pylist()} \
        if a.catalog.exists() else {}
    a.out.mkdir(parents=True, exist_ok=True)
    out_pkl = a.out / f"mapsets_{a.label.replace(' ', '_')}.pkl"
    record = pickle.load(open(out_pkl, "rb")) if out_pkl.exists() else {}  # resume
    want = set(a.sets) | (set(int(x) for x in a.sets_file.read_text().split()) if a.sets_file else set())
    want -= set(record)
    print(f"sets to do {len(want)} (done {len(record)})", flush=True)
    n_new = 0
    for f in a.data:
        if not want:
            break
        songs = [s for s in load_songs([f], mmap=True) if s["beatmapset_id"] in want]
        if not songs:
            continue
        audio = {}
        if not a.no_osz:
            tar = a.audio_dir / f"{f.stem}.tar"
            if not tar.exists():
                from huggingface_hub import hf_hub_download
                tok = open("/content/.hf_env").read().strip() if Path("/content/.hf_env").exists() else None
                got = hf_hub_download("JacobLinCool/taiko-chart-audio", f"audio/taiko/{f.stem}.tar", repo_type="dataset",
                                      local_dir=str(a.audio_dir / "hf"), token=tok)
                os.replace(got, tar)
            audio = read_shard(tar)
        for s in songs:
            sid = s["beatmapset_id"]
            mel = np.asarray(s["mel"], np.float32)
            ref = max(s["charts"], key=lambda c: len(c["time"]))
            sections = np.asarray(ref["sections"], np.float64)
            t0 = min(float(c["time"][0]) for c in s["charts"]) - 2000.0
            t1 = max(float(c["time"][-1]) for c in s["charts"])
            feat, b_song = planner_rows(enc, mel, sections, device) if prior is not None else (None, None)
            rec = {"song_key": s.get("song_key"), "sections": sections, "draws": []}
            for k in range(a.draws):
                charts, settings, bvec = make_draw(model, planner, enc, mel, sections, t0, t1, a.tiers, cal, device,
                                                   a.seed + int(sid) + 7919 * k, prior, protos, a.sure_rest, feat, b_song,
                                                   tuple(a.rest_band) if a.rest_band else None, cutoffs, a.coordinate, use,
                                                   a.sample_place)
                rec["draws"].append({"charts": charts, "settings": settings, "b": bvec})
                print(f"{sid} draw {k}: " + ", ".join(f"{TIER_NAMES[t]} {len(c['time'])} notes/{int((c['type'] >= 4).sum())} rolls"
                                                       for t, c in charts.items()), flush=True)
            record[sid] = rec
            n_new += 1
            if not a.no_osz:
                ameta, files = audio.get(int(sid), ({}, {}))
                if s.get("audio_member") not in files:
                    print(sid, "no audio: no .osz", flush=True)
                else:
                    artist, title = cat.get(sid, {}).get("artist", "Unknown"), cat.get(sid, {}).get("title", str(sid))
                    aname = (ameta.get("audio") or [{}])[0].get("name") or f"audio.{s['audio_member'].split('.')[-1]}"
                    zbuf = io.BytesIO()
                    with zipfile.ZipFile(zbuf, "w", zipfile.ZIP_DEFLATED) as z:
                        z.writestr(aname, files[s["audio_member"]])
                        for tier, c in rec["draws"][0]["charts"].items():
                            g = GeneratedChart(sections=sections, kiai=c["kiai"], time=c["time"], type=c["type"],
                                               length_beats=c["length_beats"], sv=c["sv"], tier=tier)
                            osu = to_osu(g, aname, title, artist).replace(f"Version:{TIER_NAMES[tier]}", f"Version:{a.label} {TIER_NAMES[tier]}")
                            osu = osu.replace("Creator:chartgen", f"Creator:chartgen {a.label}")
                            z.writestr(f"{artist} - {title} (chartgen) [{a.label} {TIER_NAMES[tier]}].osu".replace("/", "_"), osu)
                        if not a.no_human:
                            for c in s["charts"]:
                                h = human_chart(c, sections)
                                osu = to_osu(h, aname, title, artist).replace(f"Version:{TIER_NAMES[h.tier]}", f"Version:Human {TIER_NAMES[h.tier]} #{c['beatmap_id']}")
                                z.writestr(f"{artist} - {title} (chartgen) [Human {TIER_NAMES[h.tier]} {c['beatmap_id']}].osu".replace("/", "_"), osu)
                    name = f"{sid} {artist} - {title} ({a.label}).osz".replace("/", "_")
                    (a.out / name).write_bytes(zbuf.getvalue())
                    print(f"{sid} -> {name}", flush=True)
            if n_new % a.save_every == 0:
                pickle.dump(record, open(out_pkl, "wb"))
        if audio:
            del audio
            (a.audio_dir / f"{f.stem}.tar").unlink(missing_ok=True)
        want -= set(record)
    pickle.dump(record, open(out_pkl, "wb"))
    print("done", len(record), flush=True)


if __name__ == "__main__":
    main()