JacobLinCool's picture
Release Model P chart generation demo for osu!taiko and TJA
2469e25 verified
Raw History Blame Contribute Delete
25.1 kB
"""v11 stage 2: the position map R (reports/v11 階段 2 預先登記:位置圖 R.md, section 2).
Inputs per candidate position (24 per beat): log-Mel (128) and 6 onset/loudness columns (song_signature.song_onsets)
read at the position's exact time by linear interpolation at t + d*10 ms, d = -3..3 (7 frames); with ms inputs also
the max of the 6 columns over the position's own window (halfway to the neighbouring positions, at least +-1 frame),
log beat length and the log ms gaps to the previous / next candidate position. Per beat: beat-in-measure, era band and
(with ms) log beat length. A position embedding (MLP) -> the 24 embeddings of a beat concatenated -> beat token ->
bidirectional Transformer over the beats of a crop (sinusoidal positions; training crops of 512 beats; inference
crops of 512 with stride 384, keeping the middle) -> each position's embedding + its beat's state -> 5 tier logits.
BCE per tier, no class weights; loss only where the tier has a chart and the loss mask is set.
The no-ms model drops the window max, beat length and gaps, and reads its 7 frames at d*10/a ms with a drawn from
U(0.87, 1.15) (p = 0.5 per crop, i.e. a +-15% time stretch around fixed beat positions) during training.
Random init, no B0/b9/sp9 weights. Training: AdamW, bf16, warmup + cosine, early stopping on the tuning set's loss;
last.pt every eval for --resume.
python -m chartgen.v11.rmap train --data f*.pkl --roles A B --out runs/r_full [--no-ms] [--steps N]
python -m chartgen.v11.rmap export --data f*.pkl --model runs/r_full/best.pt --roles val tune --out maps_val.npz
python -m chartgen.v11.rmap --selftest
"""
from __future__ import annotations
import argparse
import json
import math
import os
import pickle
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from chartgen.dataset import load_songs
from chartgen.v11.patterns import GRID
from chartgen.v11.rmap_data import (N_ERA, N_POS, N_TIERS, POS, Group, bits_to_bool, song_groups)
from chartgen.v11.song_signature import song_onsets
N_MEL, N_ONS = 128, 6
D_OFF = np.arange(-3, 4)
CROP = 512
STRIDE = 384
PAD_F = 8
GAP_PREV = np.diff(np.r_[POS[-1] - GRID, POS]).astype(np.float32) # in 1/48 beat
GAP_NEXT = np.diff(np.r_[POS, POS[0] + GRID]).astype(np.float32)
# ------------------------------------------------------------------------------------------------ data
def cache_path(shard) -> Path:
return Path(shard).with_suffix(".r.pkl")
def prep_shard(shard) -> Path:
"""Write <shard>.r.pkl: per non-test song its charts (no mel), mel offset/length in the <shard>.mel.npy sidecar,
onset columns (float16) and groups (all roles). The sidecar is written by load_songs(mmap=True)."""
out = cache_path(shard)
if out.exists():
return out
songs = load_songs([shard], mmap=True)
recs, o = [], 0
for s in songs:
n = len(s["mel"])
gs = song_groups(s)
if gs:
recs.append({"beatmapset_id": s["beatmapset_id"], "song_key": s.get("song_key"), "charts": s["charts"],
"mel_off": o, "mel_len": n,
"ons": song_onsets(np.asarray(s["mel"], np.float32)).astype(np.float16), "groups": gs})
o += n
tmp = out.with_suffix(f".{os.getpid()}.tmp")
with open(tmp, "wb") as f:
pickle.dump(recs, f, protocol=pickle.HIGHEST_PROTOCOL)
os.replace(tmp, out)
return out
class Corpus:
"""Song records (mel memmaps), their onset columns and the groups of the requested roles (from the per-shard
caches of prep_shard, built on first use)."""
def __init__(self, paths, roles, tiers=range(N_TIERS), log=print):
t0 = time.time()
self.songs, self.ons, self.groups = [], [], []
for p in sorted(x for x in paths if not str(x).endswith(".r.pkl")):
cp = cache_path(p)
recs = pickle.load(open(cp if cp.exists() and not Path(p).exists() else prep_shard(p), "rb"))
npy = Path(p).with_suffix(".mel.npy")
mm = np.load(npy, mmap_mode="r") if npy.exists() else None # evaluation only: no mel needed
for r in recs:
gs = [g for g in r["groups"] if g.role in roles and any(t in g.charts for t in tiers)]
if not gs:
continue
song = {"beatmapset_id": r["beatmapset_id"], "song_key": r["song_key"], "charts": r["charts"],
"mel": (mm[r["mel_off"]:r["mel_off"] + r["mel_len"]] if mm is not None
else np.zeros((r["mel_len"], 0), np.float16))}
self.songs.append(song)
self.ons.append(r["ons"])
for g in gs:
g.song_index = len(self.songs) - 1
g.charts = {t: v for t, v in g.charts.items() if t in tiers}
self.groups.append(g)
log(f"{Path(p).name}: {len(self.songs)} songs, {len(self.groups)} groups ({time.time() - t0:.0f} s)")
def examples(self):
"""[(group index, example index, n beats)]"""
return [(gi, i, len(g.table)) for gi, g in enumerate(self.groups) for i in range(g.n_examples())]
def crop_arrays(corpus: Corpus, gi: int, ei: int, r0: int, r1: int, use_ms: bool, stretch: float = 1.0):
"""Numpy arrays of one crop (beat rows r0..r1 of group gi, example ei)."""
g: Group = corpus.groups[gi]
tb = g.table
mel = corpus.songs[g.song_index]["mel"]
ons = corpus.ons[g.song_index]
T = len(mel)
pt = tb.t0[r0:r1, None] + tb.bl[r0:r1, None].astype(np.float64) * POS[None] / GRID # [L, 24] ms
f0 = int(math.floor(pt.min() / 10.0)) - PAD_F
f1 = int(math.ceil(pt.max() / 10.0)) + PAD_F + 1
a, b = max(f0, 0), min(f1, T)
W = f1 - f0
m = np.full((W, N_MEL), float(np.min(mel[a:b])) if b > a else 0.0, np.float16)
o = np.zeros((W, N_ONS), np.float16)
if b > a:
m[a - f0:b - f0] = mel[a:b]
o[a - f0:b - f0] = ons[a:b]
tpos = (pt / 10.0 - f0).astype(np.float32)
out = {"mel": m, "ons": o, "tpos": tpos, "bib": tb.bib[r0:r1].astype(np.int64),
"era": np.int64(g.era), "valid": bits_to_bool(tb.valid[r0:r1]), "stretch": np.float32(stretch)}
tgt, los, has = g.example(ei)
out["tgt"] = np.stack([bits_to_bool(tgt[r0:r1, t]) for t in range(N_TIERS)], -1)
out["loss"] = np.stack([bits_to_bool(los[r0:r1, t]) for t in range(N_TIERS)], -1) & has[None, None, :]
if use_ms:
bl = tb.bl[r0:r1].astype(np.float32)
out["logbl"] = np.log(bl)
hl = bl[:, None] * GAP_PREV[None] / GRID / 2 / 10.0
hr = bl[:, None] * GAP_NEXT[None] / GRID / 2 / 10.0
c = np.round(tpos).astype(np.int64)
lo = np.clip(np.minimum(c - 1, np.ceil(tpos - hl - 1e-6).astype(np.int64)), 0, W - 1)
hi = np.clip(np.maximum(c + 1, np.floor(tpos + hr + 1e-6).astype(np.int64)), 0, W - 1)
mx = np.full(lo.shape + (N_ONS,), -np.inf, np.float32)
of = o.astype(np.float32)
for d in range(int((hi - lo).max()) + 1):
gidx = lo + d
ok = gidx <= hi
mx[ok] = np.maximum(mx[ok], of[gidx[ok]])
out["hmax"] = mx
return out
def collate(items, use_ms: bool):
B = len(items)
L = max(len(x["bib"]) for x in items)
W = max(len(x["mel"]) for x in items)
batch = {
"mel": torch.zeros(B, W, N_MEL, dtype=torch.float16), "ons": torch.zeros(B, W, N_ONS, dtype=torch.float16),
"tpos": torch.zeros(B, L, N_POS), "bib": torch.zeros(B, L, dtype=torch.long),
"era": torch.tensor([int(x["era"]) for x in items]), "stretch": torch.tensor([float(x["stretch"]) for x in items]),
"beat": torch.zeros(B, L, dtype=torch.bool), "valid": torch.zeros(B, L, N_POS, dtype=torch.bool),
"tgt": torch.zeros(B, L, N_POS, N_TIERS, dtype=torch.bool), "loss": torch.zeros(B, L, N_POS, N_TIERS, dtype=torch.bool),
"wlen": torch.tensor([len(x["mel"]) for x in items]),
}
if use_ms:
batch["logbl"] = torch.zeros(B, L)
batch["hmax"] = torch.zeros(B, L, N_POS, N_ONS)
for i, x in enumerate(items):
n, w = len(x["bib"]), len(x["mel"])
batch["mel"][i, :w] = torch.from_numpy(x["mel"])
batch["ons"][i, :w] = torch.from_numpy(x["ons"])
batch["tpos"][i, :n] = torch.from_numpy(x["tpos"])
batch["bib"][i, :n] = torch.from_numpy(x["bib"])
batch["beat"][i, :n] = True
batch["valid"][i, :n] = torch.from_numpy(x["valid"])
batch["tgt"][i, :n] = torch.from_numpy(x["tgt"])
batch["loss"][i, :n] = torch.from_numpy(x["loss"] & x["valid"][..., None])
if use_ms:
batch["logbl"][i, :n] = torch.from_numpy(x["logbl"])
batch["hmax"][i, :n] = torch.from_numpy(np.nan_to_num(x["hmax"], neginf=0.0))
return batch
class CropStream(torch.utils.data.IterableDataset):
"""Endless random training crops; examples drawn in proportion to their number of beats."""
def __init__(self, corpus: Corpus, use_ms: bool, batch: int, seed: int, stretch_p: float = 0.0):
self.c, self.use_ms, self.batch, self.seed, self.stretch_p = corpus, use_ms, batch, seed, stretch_p
ex = corpus.examples()
self.ex = ex
w = np.array([n for _, _, n in ex], np.float64)
self.p = w / w.sum()
def __iter__(self):
wi = torch.utils.data.get_worker_info()
rng = np.random.default_rng([self.seed, wi.id if wi else 0, int(time.time() * 1e3) % (2 ** 31)])
while True:
items = []
for j in rng.choice(len(self.ex), self.batch, p=self.p):
gi, ei, n = self.ex[j]
r0 = int(rng.integers(0, max(n - CROP, 0) + 1))
a = float(rng.uniform(0.87, 1.15)) if rng.random() < self.stretch_p else 1.0
items.append(crop_arrays(self.c, gi, ei, r0, min(n, r0 + CROP), self.use_ms, a))
yield collate(items, self.use_ms)
# ------------------------------------------------------------------------------------------------ model
class RMap(nn.Module):
def __init__(self, use_ms: bool = True, d_pos: int = 96, d: int = 256, layers: int = 6, heads: int = 8,
drop: float = 0.1):
super().__init__()
self.use_ms = use_ms
self.cfg = {"use_ms": use_ms, "d_pos": d_pos, "d": d, "layers": layers, "heads": heads, "drop": drop}
fin = len(D_OFF) * (N_MEL + N_ONS) + N_POS + ((N_ONS + 3) if use_ms else 0)
self.inp = nn.Sequential(nn.LayerNorm(fin), nn.Linear(fin, d_pos), nn.GELU(), nn.Linear(d_pos, d_pos))
self.beat_in = nn.Linear(N_POS * d_pos, d)
self.bib = nn.Embedding(16, d)
self.era = nn.Embedding(N_ERA, d)
self.tempo = nn.Linear(1, d) if use_ms else None
layer = nn.TransformerEncoderLayer(d, heads, 4 * d, drop, batch_first=True, norm_first=True, activation="gelu")
self.enc = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
self.back = nn.Linear(d, d_pos)
self.head = nn.Sequential(nn.LayerNorm(d_pos), nn.Linear(d_pos, d_pos), nn.GELU(), nn.Linear(d_pos, N_TIERS))
pe = torch.zeros(4096, d)
pos = torch.arange(4096).float()[:, None]
div = torch.exp(torch.arange(0, d, 2).float() * (-math.log(10000.0) / d))
pe[:, 0::2], pe[:, 1::2] = torch.sin(pos * div), torch.cos(pos * div)
self.register_buffer("pe", pe, persistent=False)
self.register_buffer("pos_eye", torch.eye(N_POS), persistent=False)
gp, gn = torch.tensor(GAP_PREV / GRID), torch.tensor(GAP_NEXT / GRID)
self.register_buffer("gap_prev", gp, persistent=False)
self.register_buffer("gap_next", gn, persistent=False)
def read(self, b):
"""[B, L, 24, 7 * 134] interpolated features."""
x = torch.cat([b["mel"], b["ons"]], -1).float() # [B, W, 134]
B, W, _ = x.shape
step = torch.ones(B, device=x.device) if self.use_ms else 1.0 / b["stretch"]
off = torch.as_tensor(D_OFF, device=x.device, dtype=torch.float32)
t = b["tpos"][..., None] + off * step[:, None, None, None] # [B, L, 24, 7]
t = t.clamp(0, W - 1.001)
i0 = t.floor().long()
w = (t - i0).unsqueeze(-1)
bi = torch.arange(B, device=x.device)[:, None]
flat0, flat1 = i0.reshape(B, -1), (i0 + 1).reshape(B, -1)
v = x[bi, flat0] * (1 - w.reshape(B, -1, 1)) + x[bi, flat1] * w.reshape(B, -1, 1)
return v.reshape(*i0.shape, x.shape[-1]).flatten(-2)
def forward(self, b):
feat = self.read(b)
B, L = feat.shape[:2]
parts = [feat, self.pos_eye.expand(B, L, N_POS, N_POS)]
if self.use_ms:
lbl = b["logbl"][..., None, None].expand(B, L, N_POS, 1)
parts += [b["hmax"], lbl, lbl + torch.log(self.gap_prev)[None, None, :, None],
lbl + torch.log(self.gap_next)[None, None, :, None]]
h = self.inp(torch.cat(parts, -1)) # [B, L, 24, d_pos]
z = self.beat_in(h.flatten(-2)) + self.bib(b["bib"].clamp(max=15)) + self.era(b["era"])[:, None]
if self.use_ms:
z = z + self.tempo(b["logbl"][..., None])
z = z + self.pe[:L][None]
z = self.enc(z, src_key_padding_mask=~b["beat"])
out = self.head(h + self.back(z)[:, :, None]) # [B, L, 24, 5]
return out, z
def masked_bce(logits, b):
m = b["loss"]
y = b["tgt"].float()
l = F.binary_cross_entropy_with_logits(logits.float(), y, reduction="none")
return (l * m).sum() / m.sum().clamp(min=1)
# ------------------------------------------------------------------------------------------------ inference
@torch.no_grad()
def predict_group(model: RMap, corpus: Corpus, gi: int, device, ei: int = 0, hidden: bool = False):
"""[n_beats, 24, 5] logits (float32) of a whole group, crops of CROP beats with stride STRIDE (middle kept);
with hidden=True also the beat states [n_beats, d] of the Transformer."""
g = corpus.groups[gi]
n = len(g.table)
out = np.zeros((n, N_POS, N_TIERS), np.float32)
hz = np.zeros((n, model.cfg["d"]), np.float32) if hidden else None
starts = list(range(0, max(n - CROP, 0) + 1, STRIDE))
if starts[-1] + CROP < n:
starts.append(n - CROP)
edge = (CROP - STRIDE) // 2
for k, s in enumerate(starts):
e = min(n, s + CROP)
items = [crop_arrays(corpus, gi, ei, s, e, model.use_ms)]
bt = {kk: (v.to(device) if torch.is_tensor(v) else v) for kk, v in collate(items, model.use_ms).items()}
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
lg, z = model(bt)
lg = lg[0].float().cpu().numpy()
a = 0 if k == 0 else edge
bnd = e - s if e == n else (e - s) - edge
out[s + a:s + bnd] = lg[a:bnd]
if hidden:
hz[s + a:s + bnd] = z[0].float().cpu().numpy()[a:bnd]
return (out, hz) if hidden else out
# ------------------------------------------------------------------------------------------------ training
def tune_batches(corpus: Corpus, use_ms: bool, n: int, batch: int, seed: int = 0):
rng = np.random.default_rng(seed)
ex = corpus.examples()
w = np.array([x[2] for x in ex], np.float64)
picks = rng.choice(len(ex), n, p=w / w.sum())
items = []
for j in picks:
gi, ei, nb = ex[j]
r0 = int(rng.integers(0, max(nb - CROP, 0) + 1))
items.append((gi, ei, r0, min(nb, r0 + CROP)))
return [items[i:i + batch] for i in range(0, len(items), batch)]
def train(a):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
logf = open(out / "metrics.jsonl", "a")
def log(rec):
rec["time"] = time.time()
logf.write(json.dumps(rec) + "\n")
logf.flush()
print(json.dumps(rec), flush=True)
use_ms = not a.no_ms
tr = Corpus(a.data, set(a.roles), log=lambda m: print(m, flush=True))
tu = Corpus(a.data, {"tune"}, log=lambda m: print(m, flush=True)) if a.tune_crops > 0 else None
model = RMap(use_ms=use_ms, d_pos=a.d_pos, d=a.d, layers=a.layers, heads=a.heads).to(device)
n_par = sum(p.numel() for p in model.parameters())
opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=0.01)
sched = lambda s: min(1.0, (s + 1) / a.warmup) * (0.5 * (1 + math.cos(math.pi * min(s, a.steps) / a.steps)) * 0.95 + 0.05) # noqa: E731
step, best = 0, math.inf
if a.resume and (out / "last.pt").exists():
ck = torch.load(out / "last.pt", map_location=device)
model.load_state_dict(ck["model"]); opt.load_state_dict(ck["opt"])
step, best = ck["step"], ck["best"]
print(f"resumed at step {step}, best {best:.5f}", flush=True)
log({"event": "start", "step": step, "params": n_par, "train_groups": len(tr.groups), "roles": a.roles,
"use_ms": use_ms, "args": vars(a)})
stream = CropStream(tr, use_ms, a.batch, a.seed + step, stretch_p=0.5 if a.no_ms else 0.0)
dl = torch.utils.data.DataLoader(stream, batch_size=None, num_workers=a.workers, prefetch_factor=4 if a.workers else None,
persistent_workers=a.workers > 0)
tune = tune_batches(tu, use_ms, a.tune_crops, a.batch) if tu else []
it = iter(dl)
t_last, n_tok, ema = time.time(), 0, None
model.train()
while step < a.steps:
t_d = time.time()
b = next(it)
t_w = time.time() - t_d
b = {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v) for k, v in b.items()}
for gp in opt.param_groups:
gp["lr"] = a.lr * sched(step)
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
lg, _ = model(b)
loss = masked_bce(lg, b)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
step += 1
n_tok += int(b["beat"].sum())
ema = loss.item() if ema is None else 0.98 * ema + 0.02 * loss.item()
if step % 50 == 0:
dt = time.time() - t_last
log({"event": "train", "step": step, "loss_ema": ema, "lr": a.lr * sched(step), "beats_per_s": n_tok / dt,
"data_wait_s": t_w})
t_last, n_tok = time.time(), 0
if step % a.eval_every == 0 or step == a.steps:
vl = evaluate(model, tu, tune, use_ms, device) if tune else float("nan")
is_best = vl < best
best = min(best, vl)
ck = {"model": model.state_dict(), "opt": opt.state_dict(), "step": step, "best": best, "cfg": model.cfg}
torch.save(ck, out / "last.pt.tmp"); os.replace(out / "last.pt.tmp", out / "last.pt")
if is_best:
torch.save({"model": model.state_dict(), "cfg": model.cfg, "step": step, "tune_loss": vl}, out / "best.pt.tmp")
os.replace(out / "best.pt.tmp", out / "best.pt")
log({"event": "eval", "step": step, "tune_loss": vl, "best": best, "is_best": is_best})
model.train()
if a.patience and is_best is False and step - _last_best(out) >= a.patience:
log({"event": "early_stop", "step": step})
break
log({"event": "end", "step": step, "best": best})
def _last_best(out: Path) -> int:
best_step = 0
for line in open(out / "metrics.jsonl"):
r = json.loads(line)
if r.get("event") == "eval" and r.get("is_best"):
best_step = r["step"]
return best_step
@torch.no_grad()
def evaluate(model, corpus, batches, use_ms, device):
model.eval()
tot, cnt = 0.0, 0.0
for bl in batches:
items = [crop_arrays(corpus, gi, ei, r0, r1, use_ms) for gi, ei, r0, r1 in bl]
b = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in collate(items, use_ms).items()}
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
lg, _ = model(b)
m = b["loss"]
l = F.binary_cross_entropy_with_logits(lg.float(), b["tgt"].float(), reduction="none")
tot += float((l * m).sum())
cnt += float(m.sum())
return tot / max(cnt, 1.0)
def load_rmap(path, device):
ck = torch.load(path, map_location=device)
m = RMap(**ck["cfg"]).to(device)
m.load_state_dict(ck["model"])
return m.eval()
def export(a):
"""Logits of every group of the given roles: one npz with per-group arrays (float16, key = group uid) and an index.
With --hidden, also beat states and log beat length of every 4th beat (manipulation check of the no-ms model)."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = load_rmap(a.model, device)
c = Corpus(a.data, set(a.roles), log=lambda m: print(m, flush=True))
arrs, index, H, Y, K = {}, [], [], [], []
t0 = time.time()
for gi, g in enumerate(c.groups):
if a.hidden:
lg, hz = predict_group(model, c, gi, device, hidden=True)
H.append(hz[::4].astype(np.float16)); Y.append(np.log(g.table.bl[::4])); K += [g.key] * len(hz[::4])
else:
lg = predict_group(model, c, gi, device)
arrs[g.uid] = lg.astype(np.float16)
index.append({"uid": g.uid, "set": g.set_id, "key": g.key, "role": g.role, "era": g.era,
"beat0": int(g.table.beat[0]), "n": len(g.table)})
if gi % 200 == 0:
print(f"{gi}/{len(c.groups)} groups ({time.time() - t0:.0f} s)", flush=True)
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
np.savez_compressed(a.out, index=json.dumps(index), **arrs)
if a.hidden:
np.savez_compressed(str(a.out).replace(".npz", "_hidden.npz"), h=np.concatenate(H), logbl=np.concatenate(Y),
key=np.array(K))
print("wrote", a.out, len(index), "groups")
# ------------------------------------------------------------------------------------------------ self-test
def selftest(shard="data/pilot/features/taiko-00000.pkl"):
torch.manual_seed(0)
for use_ms in (True, False):
c = Corpus([shard], {"A", "B"}, log=lambda m: None)
st = CropStream(c, use_ms, 2, 0, stretch_p=0.0 if use_ms else 0.5)
b = next(iter(st))
m = RMap(use_ms=use_ms, d_pos=32, d=64, layers=2, heads=4)
lg, z = m(b)
assert lg.shape == (*b["tpos"].shape, N_TIERS), lg.shape
loss = masked_bce(lg, b)
loss.backward()
print(f"use_ms={use_ms}: batch beats {int(b['beat'].sum())}, positives {int((b['tgt'] & b['loss']).sum())}, "
f"loss {loss.item():.4f}, params {sum(p.numel() for p in m.parameters())}")
# interpolation check: a position read at an integer frame equals that frame
x = torch.cat([b["mel"], b["ons"]], -1).float()
tp = b["tpos"][0, 0, 0].item()
bb = {k: v.clone() if torch.is_tensor(v) else v for k, v in b.items()}
bb["tpos"][0, 0, 0] = float(round(tp))
feat = m.read(bb)
assert torch.allclose(feat[0, 0, 0].reshape(7, -1)[3], x[0, round(tp)], atol=1e-3)
lg2 = predict_group(m.eval(), c, 0, torch.device("cpu"))
assert lg2.shape == (len(c.groups[0].table), N_POS, N_TIERS)
print("selftest ok")
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("cmd", nargs="?", choices=["train", "export", "prep"])
ap.add_argument("--selftest", action="store_true")
ap.add_argument("--data", nargs="+")
ap.add_argument("--roles", nargs="+", default=["A", "B"])
ap.add_argument("--out")
ap.add_argument("--model")
ap.add_argument("--no-ms", action="store_true")
ap.add_argument("--steps", type=int, default=20000)
ap.add_argument("--batch", type=int, default=16)
ap.add_argument("--lr", type=float, default=3e-4)
ap.add_argument("--warmup", type=int, default=500)
ap.add_argument("--d-pos", type=int, default=96)
ap.add_argument("--d", type=int, default=256)
ap.add_argument("--layers", type=int, default=6)
ap.add_argument("--heads", type=int, default=8)
ap.add_argument("--workers", type=int, default=6)
ap.add_argument("--eval-every", type=int, default=500)
ap.add_argument("--tune-crops", type=int, default=256)
ap.add_argument("--patience", type=int, default=3000)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--resume", action="store_true")
ap.add_argument("--hidden", action="store_true")
a = ap.parse_args(argv)
if a.selftest:
selftest()
elif a.cmd == "train":
train(a)
elif a.cmd == "export":
export(a)
elif a.cmd == "prep":
for p in sorted(a.data):
t0 = time.time()
prep_shard(p)
print(f"{Path(p).name}: cache ready ({time.time() - t0:.0f} s)", flush=True)
if __name__ == "__main__":
main()