JacobLinCool's picture
Release Model P chart generation demo for osu!taiko and TJA
2469e25 verified
Raw History Blame Contribute Delete
18.7 kB
"""Train B0 with live, logged adjustments (README section 4, "訓練中的調整方式").
The run directory holds:
metrics.jsonl training / validation records
control.json written by the operator (agent); read every --control-every steps
interventions.jsonl every applied control change with step and reason
status.json latest summary
last.pt / best.pt checkpoints
control.json keys (all optional): lr, weights {note,length,timing,plan}, eval_now, gen_now,
save, stop, reason. Only validation data drive decisions; the test split is never loaded here.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import os
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from .dataset import N_TYPE, WindowSampler, collate, fixed_windows, load_songs
from .generate import evaluate_generation, generate
from .model import DEFAULT_WEIGHTS, B0, B0Config, b0_loss
def song_split(key: str, val_frac: float = 0.1, test_frac: float = 0.1) -> str:
"""Deterministic split by song key (normalised artist|title), shared by all scripts."""
h = int(hashlib.sha1(f"split:{key}".encode()).hexdigest(), 16) % 10_000 / 10_000
return "test" if h < test_frac else ("val" if h < test_frac + val_frac else "train")
def split_songs(songs, val_frac, min_year=0):
keep = []
for s in songs:
charts = [c for c in s["charts"] if c.get("year", 9999) >= min_year]
if charts:
keep.append({**s, "charts": charts})
key = lambda s: s.get("song_key") or str(s["beatmapset_id"]) # noqa: E731
train = [s for s in keep if song_split(key(s), val_frac) == "train"]
val = [s for s in keep if song_split(key(s), val_frac) == "val"]
return train, val
def type_weights(songs):
counts = np.ones(N_TYPE)
for s in songs:
for c in s["charts"]:
counts += np.bincount(c["type"], minlength=N_TYPE)
w = counts ** -0.5
return torch.tensor(w / w.mean(), dtype=torch.float32)
class Run:
def __init__(self, run_dir: Path):
self.dir = run_dir
self.dir.mkdir(parents=True, exist_ok=True)
self.metrics = open(run_dir / "metrics.jsonl", "a")
self.interventions = open(run_dir / "interventions.jsonl", "a")
self.control_path = run_dir / "control.json"
self._control_mtime = self.control_path.stat().st_mtime if self.control_path.exists() else 0.0
def log(self, rec):
self.metrics.write(json.dumps(rec) + "\n")
self.metrics.flush()
def status(self, rec):
tmp = self.dir / "status.json.tmp"
tmp.write_text(json.dumps(rec, indent=1))
os.replace(tmp, self.dir / "status.json")
def read_control(self):
if not self.control_path.exists():
return None
m = self.control_path.stat().st_mtime
if m == self._control_mtime:
return None
self._control_mtime = m
try:
return json.loads(self.control_path.read_text())
except json.JSONDecodeError:
return None
def intervene(self, step, changes, reason):
self.interventions.write(json.dumps({"step": step, "time": time.time(), "changes": changes, "reason": reason}) + "\n")
self.interventions.flush()
@torch.no_grad()
def validate(model, val_windows, device, weights, tw, bs=32, amp=None):
model.eval()
sums, n = {}, 0
gap_correct = gap_total = type_correct = type_total = sv_correct = 0
beat_tp = beat_np = beat_nr = 0
kiai_tp = kiai_fp = kiai_fn = kiai_n = kiai_ok = 0
for i in range(0, len(val_windows), bs):
batch = {k: v.to(device) for k, v in collate(val_windows[i:i + bs]).items()}
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=amp is not None):
out = model(batch, plan_source="pred")
total, parts = b0_loss(out, batch, weights, tw)
for k, v in {"total": total, **parts}.items():
sums[k] = sums.get(k, 0.0) + float(v)
n += 1
gm = batch["tgt_ahead"] != -100
ok_ahead = out["ahead_logits"].argmax(-1) == batch["tgt_ahead"]
ok_phase = (out["phase_logits"].argmax(-1) == batch["tgt_phase"]) | (batch["tgt_phase"] == -100)
gap_correct += int((ok_ahead & ok_phase)[gm].sum())
gap_total += int(gm.sum())
tm = batch["ev_type"] != -100
type_correct += int((out["type_logits"].argmax(-1)[tm] == batch["ev_type"][tm]).sum())
type_total += int(tm.sum())
sv_correct += int((out["sv_logits"].argmax(-1)[tm] == batch["ev_sv"][tm]).sum())
# beat peaks within +/-2 frames (20 ms) of reference beats, on frames where timing is defined
act = torch.sigmoid(out["timing_logits"][..., 0].float())
peak = (act > 0.5) & (act >= F.max_pool1d(act[:, None], 5, 1, 2)[:, 0])
ref = batch["beat_tgt"] >= 0.5
bm = batch["beat_mask"] > 0
near_ref = F.max_pool1d(ref[:, None].float(), 5, 1, 2)[:, 0] > 0
near_peak = F.max_pool1d(peak[:, None].float(), 5, 1, 2)[:, 0] > 0
beat_tp += int((peak & near_ref & bm).sum())
beat_np += int((peak & bm).sum())
beat_nr += int((ref & bm).sum())
beat_rec_hit = int((ref & near_peak & bm).sum())
kp = torch.sigmoid(out["kiai_logits"].float()) > 0.5
kt = batch["kiai_tgt"] > 0.5
km = batch["kiai_mask"] > 0
kiai_tp += int((kp & kt & km).sum()); kiai_fp += int((kp & ~kt & km).sum()); kiai_fn += int((~kp & kt & km).sum())
kiai_ok += int(((kp == kt) & km).sum()); kiai_n += int(km.sum())
sums["_beat_rec_hit"] = sums.get("_beat_rec_hit", 0.0) + beat_rec_hit
model.train()
res = {f"val_{k}": v / n for k, v in sums.items()}
res["val_pos_acc"] = gap_correct / max(gap_total, 1)
res["val_type_acc"] = type_correct / max(type_total, 1)
res["val_sv_acc"] = sv_correct / max(type_total, 1)
bp, br = beat_tp / max(beat_np, 1), sums.pop("_beat_rec_hit", 0.0) / max(beat_nr, 1)
res.pop("val__beat_rec_hit", None)
res["val_beat_f1"] = 2 * bp * br / max(bp + br, 1e-9)
res["val_kiai_acc"] = kiai_ok / max(kiai_n, 1)
res["val_kiai_f1"] = 2 * kiai_tp / max(2 * kiai_tp + kiai_fp + kiai_fn, 1)
return res
def main(argv=None):
p = argparse.ArgumentParser()
p.add_argument("--data", nargs="+", type=Path, required=True)
p.add_argument("--run-dir", type=Path, required=True)
p.add_argument("--val-frac", type=float, default=0.1)
p.add_argument("--batch", type=int, default=32)
p.add_argument("--lr", type=float, default=3e-4)
p.add_argument("--warmup", type=int, default=300)
p.add_argument("--max-steps", type=int, default=20000, help="compute cap; the operator usually stops earlier")
p.add_argument("--log-every", type=int, default=50)
p.add_argument("--control-every", type=int, default=50)
p.add_argument("--eval-every", type=int, default=500)
p.add_argument("--gen-every", type=int, default=2000)
p.add_argument("--val-windows", type=int, default=256)
p.add_argument("--gen-windows", type=int, default=64)
p.add_argument("--workers", type=int, default=4)
p.add_argument("--lr-range-test", type=int, default=0, help="steps of exponential LR sweep 1e-6 -> 1e-1, then exit")
p.add_argument("--resume", type=Path)
p.add_argument("--seed", type=int, default=0)
p.add_argument("--small", action="store_true", help="tiny model for CPU smoke tests")
p.add_argument("--replay", nargs="*", default=[],
help="replay a recorded schedule, e.g. 6450:lr=1e-4 4000:weights.plan=0.1 9150:stop (same changes at the same steps)")
p.add_argument("--init-model", type=Path, help="B0 checkpoint to fine-tune from (new modules, e.g. --gap-plan, start fresh)")
p.add_argument("--new-lr-mult", type=float, default=10.0,
help="learning-rate multiplier for modules that --init-model did not provide (zero-initialised, start slow)")
p.add_argument("--no-type-weights", action="store_true", help="plain cross-entropy for note types (no class weights)")
p.add_argument("--note-coord", choices=["true", "grid"], default="true",
help="note-head lookups in training from the note's real time (old) or its grid time (stage 4b)")
p.add_argument("--stretch-p", type=float, default=0.0, help="probability of a tempo-stretched training window")
p.add_argument("--plan-corrupt", type=float, default=0.0, help="probability that a given bar plan is corrupted like a prediction")
p.add_argument("--plan-drop", type=float, default=0.3, help="probability that no bar plan is given in training")
p.add_argument("--rep-hint", action="store_true", help="per-bar repetition hint from the audio")
p.add_argument("--bar-plan", action="store_true", help="decoder conditioned on a per-bar plan (oracle in training)")
p.add_argument("--gap-plan", action="store_true", help="planner predicts and decoder uses per-section note-gap distributions")
p.add_argument("--init-encoder", type=Path, help="Stage A checkpoint: load its (EMA target) music encoder into B0")
p.add_argument("--mmap", action="store_true", help="memory-map mel features (corpus larger than RAM)")
p.add_argument("--min-year", type=int, default=2014, help="drop charts ranked before this year")
a = p.parse_args(argv)
from . import dataset as _ds
_ds.NOTE_COORD = a.note_coord # read by make_example (forked loader workers inherit it)
torch.manual_seed(a.seed)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
amp = torch.bfloat16 if device.type == "cuda" else None
run = Run(a.run_dir)
songs = load_songs(a.data, mmap=a.mmap)
train_songs, val_songs = split_songs(songs, a.val_frac, a.min_year)
(a.run_dir / "split.json").write_text(json.dumps({"train": sorted({s.get("song_key", "") for s in train_songs}),
"val": sorted({s.get("song_key", "") for s in val_songs})}))
val_windows = fixed_windows(val_songs, a.val_windows)
gen_windows = val_windows[: a.gen_windows]
tw = None if a.no_type_weights else type_weights(train_songs).to(device)
cfg = B0Config(d_model=64, enc_layers=1, dec_layers=1, n_heads=4, d_plan=32, plan_layers=1, branch_ch=16) if a.small else B0Config()
cfg.gap_plan = a.gap_plan
cfg.bar_plan = a.bar_plan
cfg.bar_plan_corrupt = a.plan_corrupt
cfg.bar_plan_drop = a.plan_drop
cfg.rep_hint = a.rep_hint
model = B0(cfg).to(device)
if a.init_model:
ck = torch.load(a.init_model, map_location=device, weights_only=False)
sd = dict(ck["model"])
w_old = sd.get("bar_plan_proj.weight")
if w_old is not None and hasattr(model, "bar_plan_proj") and w_old.shape != model.bar_plan_proj.weight.shape:
# plan grew from 16 features + "plan given" flag to BAR_F (17: + sustain) + flag: keep the learned columns,
# move the flag column, start the new feature at zero
w_new = torch.zeros_like(model.bar_plan_proj.weight)
n_old = w_old.shape[1] - 1
w_new[:, :n_old] = w_old[:, :n_old]
w_new[:, -1] = w_old[:, -1]
sd["bar_plan_proj.weight"] = w_new
print(f"bar_plan_proj expanded {tuple(w_old.shape)} -> {tuple(w_new.shape)}", flush=True)
missing, unexpected = model.load_state_dict(sd, strict=False)
assert not unexpected, unexpected
print("init model from", a.init_model, "new (untrained) tensors:", missing, flush=True)
if a.init_encoder:
ck = torch.load(a.init_encoder, map_location=device, weights_only=False)
sd = {k: v for k, v in ck["target_encoder"].items() if k != "mask_tok"}
missing, unexpected = model.load_state_dict(sd, strict=False)
assert not unexpected, unexpected
print("init encoder from", a.init_encoder, "loaded", len(sd), "tensors", flush=True)
n_params = sum(p.numel() for p in model.parameters())
new_names = set(missing) if a.init_model else set()
groups = [{"params": [p_ for n_, p_ in model.named_parameters() if n_ not in new_names], "mult": 1.0},
{"params": [p_ for n_, p_ in model.named_parameters() if n_ in new_names], "mult": a.new_lr_mult}]
opt = torch.optim.AdamW([g for g in groups if g["params"]], lr=a.lr, weight_decay=0.01)
state = {"lr": a.lr, "weights": dict(DEFAULT_WEIGHTS)}
step, best = 0, math.inf
if a.resume:
ck = torch.load(a.resume, map_location=device, weights_only=False)
model.load_state_dict(ck["model"])
opt.load_state_dict(ck["opt"])
step, best, state = ck["step"], ck["best"], ck["state"]
run.log({"event": "start", "step": step, "params": n_params, "device": str(device),
"gpu": torch.cuda.get_device_name() if device.type == "cuda" else None,
"train_songs": len(train_songs), "val_songs": len(val_songs),
"train_charts": sum(len(s["charts"]) for s in train_songs), "args": {k: str(v) for k, v in vars(a).items()}})
loader = torch.utils.data.DataLoader(
WindowSampler(train_songs, a.seed, stretch_p=a.stretch_p), batch_size=a.batch, collate_fn=collate,
num_workers=a.workers, pin_memory=device.type == "cuda", persistent_workers=a.workers > 0,
prefetch_factor=4 if a.workers > 0 else None)
it = iter(loader)
def save(name):
torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "step": step, "best": best,
"state": state, "config": cfg.__dict__}, a.run_dir / name)
ema, t_last, wait_acc, comp_acc, n_since = {}, time.time(), 0.0, 0.0, 0
min_loss = math.inf
model.train()
while step < (a.lr_range_test or a.max_steps):
t0 = time.time()
batch = next(it)
batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}
t1 = time.time()
if a.lr_range_test:
lr = 1e-6 * (1e-1 / 1e-6) ** (step / a.lr_range_test)
else:
lr = state["lr"] * min(1.0, (step + 1) / a.warmup)
for g in opt.param_groups:
g["lr"] = lr * g.get("mult", 1.0)
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=amp is not None):
out = model(batch)
loss, parts = b0_loss(out, batch, state["weights"], tw)
opt.zero_grad(set_to_none=True)
loss.backward()
gnorm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0))
opt.step()
step += 1
if device.type == "cuda":
torch.cuda.synchronize()
t2 = time.time()
wait_acc += t1 - t0
comp_acc += t2 - t1
n_since += 1
lv = float(loss.detach())
if not math.isfinite(lv):
run.log({"event": "nonfinite_loss", "step": step, "lr": lr})
if a.lr_range_test:
break
continue
for k, v in {"loss": lv, **{k: float(v) for k, v in parts.items()}}.items():
ema[k] = v if k not in ema else 0.9 * ema[k] + 0.1 * v
if a.lr_range_test:
run.log({"event": "lr_range", "step": step, "lr": lr, "loss": lv, "loss_ema": ema["loss"]})
min_loss = min(min_loss, ema["loss"])
if step > 20 and ema["loss"] > 4 * min_loss:
break
continue
if step % a.log_every == 0:
dt = time.time() - t_last
rec = {"event": "train", "step": step, "lr": lr, "grad_norm": gnorm,
**{f"train_{k}": v for k, v in ema.items()},
"windows_per_s": n_since * a.batch / dt, "data_wait_frac": wait_acc / max(wait_acc + comp_acc, 1e-9)}
if device.type == "cuda":
rec["gpu_mem_gb"] = torch.cuda.max_memory_allocated() / 1e9
run.log(rec)
run.status({"step": step, "time": time.time(), **rec})
t_last, wait_acc, comp_acc, n_since = time.time(), 0.0, 0.0, 0
ctl = run.read_control() if step % a.control_every == 0 else None
for item in a.replay: # replayed interventions of a reference run (README: same rules for all variants)
at, what = item.split(":", 1)
if int(at) == step:
key, _, val = what.partition("=")
if what == "stop":
ctl = (ctl or {}) | {"stop": True}
elif key.startswith("weights."): # e.g. 4000:weights.plan=0.1
ctl = ctl or {}
ctl["weights"] = {**(ctl.get("weights") or {}), key.split(".", 1)[1]: float(val)}
else:
ctl = (ctl or {}) | {key: float(val)}
ctl["reason"] = f"replayed schedule: {item}"
force_eval = force_gen = False
if ctl:
changes = {}
if "lr" in ctl and ctl["lr"] != state["lr"]:
changes["lr"] = [state["lr"], ctl["lr"]]
state["lr"] = float(ctl["lr"])
for k, v in (ctl.get("weights") or {}).items():
if state["weights"].get(k) != v:
changes[f"weight.{k}"] = [state["weights"].get(k), v]
state["weights"][k] = float(v)
force_eval, force_gen = bool(ctl.get("eval_now")), bool(ctl.get("gen_now"))
if ctl.get("save"):
save(f"step{step}.pt")
changes["save"] = f"step{step}.pt"
if ctl.get("stop"):
changes["stop"] = True
if changes or force_eval or force_gen:
run.intervene(step, changes | ({"eval_now": True} if force_eval else {}) | ({"gen_now": True} if force_gen else {}),
ctl.get("reason", ""))
if ctl.get("stop"):
break
if step % a.eval_every == 0 or force_eval or force_gen:
v = validate(model, val_windows, device, state["weights"], tw, amp=amp)
rec = {"event": "val", "step": step, **v}
if step % a.gen_every == 0 or force_gen:
preds = generate(model, gen_windows, device)
model.train()
rec.update({f"gen_{k}": x for k, x in evaluate_generation(preds, gen_windows).items()})
run.log(rec)
save("last.pt")
# selection metric is independent of operator-set loss weights
sel = v["val_pos"] + v["val_note"] + v["val_beat"]
if sel < best:
best = sel
save("best.pt")
save("last.pt")
run.log({"event": "end", "step": step})
if __name__ == "__main__":
main()