"""Batched autoregressive generation and event-level evaluation.""" from __future__ import annotations import numpy as np import torch from .model import DecodeCache from .dataset import AHEAD_END, GRID, MAX_EVENTS, Example, collate, sv_value DON_LIKE, KA_LIKE = {0, 2}, {1, 3} @torch.no_grad() def generate(model, examples: list[Example], device, temperature: float | list[float] = 0.0, plan_source: str = "pred", max_events: int = MAX_EVENTS, allowed: list[np.ndarray] | None = None, required: list[np.ndarray] | None = None, forced_type: list[dict] | None = None, rho_scale: float | list[float] = 1.0, use_cache: bool = True, type_temperature: float | None = None, bar_plan: np.ndarray | None = None, type_bias: np.ndarray | None = None, continue_until: list[int] | None = None, min_gap_ms: float | list[float] | None = None, phase_ok: list[np.ndarray | None] | None = None) -> list[dict]: """Autoregressive generation for a batch of windows. Optional constraints (per example, positions are offsets into the example's grid table): allowed -- bool mask; notes may only be placed where it is True (derive an easier chart) required -- sorted offsets that must all be placed (derive a harder chart) forced_type -- {offset: type} for notes whose type is kept from a source chart rho_scale -- multiplies the planned note density (continuous difficulty control) continue_until -- grid offset per example before which the window may not end (the plan still has measures with hit notes after it); without it a model can stop early, e.g. after a balloon, because many charts end with one min_gap_ms -- shortest allowed time (ms) from the previous event of the window to the next one (stage 4b: the tier's human floor); positions closer than this are masked, and a beat with no position left is masked as a choice of 'beats ahead'. None or 0 = no limit phase_ok -- per example a bool mask over the GRID positions of a beat (stage 5a: with the 1/8 family switched off, only the 1/12-beat positions stay open); events are placed on open positions only, and a beat with no open position left is masked as a choice of 'beats ahead'. None = all open temperature and rho_scale may also be per-example lists (several candidate kinds in one batch). bar_plan -- [B, MAX_BARS, BAR_F] per-bar plan for a bar-planned model (e.g. from a song-level planner); plan_source oracle_bar uses the human chart's bar plan instead type_bias -- added to the note-type logits; -log(training class weights) undoes the class-weighted type loss (train.type_weights), which otherwise inflates rare types such as rolls and big notes type_temperature -- cap on the temperature of the note-type choice (0 = most likely type); rare types (rolls, big notes) are over-sampled when types share the position temperature plan_source -- pred (planner argmax), sample (subdivision class sampled from the planner), oracle_r (human subdivision class, predicted density), oracle_gap (human gap distributions), oracle (human plan); the oracle modes need examples built from the human chart """ model.eval() batch = {k: v.to(device) for k, v in collate(examples).items()} hi, mem = model.encode(batch["mel"]) mem = model.with_grid(mem, batch["beat_feat"]) rho, r_logits, sec_mask, gap_logits, ratio_logits = model.plan_full(mem, batch["frame_section"], batch["tier"]) gap_pred = model.gap_probs(gap_logits, ratio_logits) if gap_logits is not None else None B = len(examples) if not isinstance(rho_scale, (int, float)): rho_scale = torch.as_tensor(rho_scale, dtype=torch.float32, device=device).view(B, *([1] * (rho.dim() - 1))) rho_p = rho.expm1().clamp(min=0) * rho_scale if plan_source == "pred": plan_emb = model.plan_embedding(rho_p, r_logits.argmax(-1), gap_pred) elif plan_source == "sample": # subdivision class drawn from the planner per example (candidate), not its argmax r = torch.distributions.Categorical(logits=r_logits.float()).sample() plan_emb = model.plan_embedding(rho_p, r, gap_pred) elif plan_source == "oracle_r": # the human chart's subdivision class, predicted density plan_emb = model.plan_embedding(rho_p, batch["plan_r"], gap_pred) elif plan_source == "oracle_gap": # the human chart's gap / ratio distributions, the rest predicted plan_emb = model.plan_embedding(rho_p, r_logits.argmax(-1), batch["plan_gap"]) else: plan_emb = model.plan_embedding(batch["plan_rho"] * rho_scale, batch["plan_r"], batch["plan_gap"]) mem = model.with_rep_hint(mem, batch.get("rep_hint"), batch["frame_bar"]) if plan_source == "oracle_bar": plan_emb = model.plan_embedding(rho_p, r_logits.argmax(-1), gap_pred) mem = model.with_bar_plan(mem, batch["bar_plan"], batch["frame_bar"]) elif bar_plan is not None: mem = model.with_bar_plan(mem, torch.as_tensor(bar_plan, device=device), batch["frame_bar"]) elif getattr(model.c, "bar_plan", False): mem = model.with_bar_plan(mem, batch["bar_plan"], batch["frame_bar"], torch.zeros(B, dtype=torch.bool, device=device)) # no plan given # window-level predicted gap / ratio distribution (sections weighted by predicted density), for selection energies win_gap = None if gap_pred is not None: wsec = rho_p * sec_mask.float() win_gap = ((gap_pred * wsec.unsqueeze(-1)).sum(1) / wsec.sum(1, keepdim=True).clamp(min=1e-6)).cpu().numpy() temp = torch.as_tensor(temperature, dtype=torch.float32, device=device).expand(B) tables = [(torch.as_tensor(e.grid_time, device=device), torch.as_tensor(e.grid_bar, device=device), torch.as_tensor(e.grid_section, device=device), e.start_grid) for e in examples] keys = ["ev_ahead", "ev_type", "ev_len", "ev_sv", "ev_phase", "ev_bar", "ev_frame", "ev_section"] seq = {k: torch.zeros(B, 0, dtype=torch.long, device=device) for k in keys} delta = torch.zeros(B, 0, device=device) start_grid = torch.tensor([tb[3] for tb in tables], device=device) cur = start_grid.clone() # absolute grid index of the last event done = torch.zeros(B, dtype=torch.bool, device=device) logp = torch.zeros(B, device=device) # log-probability of the decoded sequence (for L1 reranking) n_ev = torch.zeros(B, device=device) G = torch.tensor([len(t[0]) for t in tables], device=device) phases = torch.arange(GRID, device=device) alive_steps: list[torch.Tensor] = [] offs_steps: list[torch.Tensor] = [] Gmax = int(G.max()) allow_cum = None if allowed is not None: am = torch.zeros(B, Gmax + GRID * (AHEAD_END + 2), dtype=torch.long, device=device) for b, a in enumerate(allowed): am[b, : len(a)] = torch.as_tensor(a, device=device).long() allow_cum = torch.cat([torch.zeros(B, 1, dtype=torch.long, device=device), am.cumsum(1)], 1) # first forbidden grid offset at or after each offset (for capping roll bodies before planned rests) next_bad = [] for a in allowed: a = np.asarray(a, bool) bad = np.where(~a)[0] j = np.searchsorted(bad, np.arange(len(a) + 1)) next_bad.append(np.where(j < len(bad), bad[np.minimum(j, max(len(bad) - 1, 0))] if len(bad) else len(a), len(a))) req = None if required is not None: req = [torch.as_tensor(np.sort(r), device=device).long() for r in required] aheads = torch.arange(AHEAD_END, device=device) mg = None if min_gap_ms is not None: mg = torch.as_tensor(min_gap_ms, dtype=torch.float32, device=device).expand(B).clone() if not bool((mg > 0).any()): mg = None if mg is not None: # grid times per example, padded with +inf (searchsorted gives the first offset at or after a time) tab = torch.full((B, Gmax), float("inf"), device=device) for b, tb in enumerate(tables): tab[b, : len(tb[0])] = tb[0].float() prev_t = torch.full((B,), float("-inf"), device=device) pk = None if phase_ok is not None: pk = torch.as_tensor(np.stack([np.ones(GRID, bool) if q is None else np.asarray(q, bool) for q in phase_ok]), device=device) # [B, GRID] if bool(pk.all()): pk = None def pick(logits, tt=None): tt = temp if tt is None else tt greedy = logits.argmax(-1) if not bool((tt > 0).any()): return greedy sampled = torch.multinomial(torch.softmax(logits / tt.clamp(min=1e-3)[:, None], -1), 1)[:, 0] return torch.where(tt > 0, sampled, greedy) type_temp = temp if type_temperature is None else temp.clamp(max=type_temperature) cache = DecodeCache(model, mem) if use_cache else None for _ in range(max_events): if cache is not None: n_ev_seen = seq["ev_ahead"].shape[1] # token of the newest event only (BOS at the first step); positions match event_tokens() tok = model.event_tokens(mem, plan_emb, batch["tier"], {k: v[:, -1:] for k, v in seq.items()}) if n_ev_seen else None if tok is None: x = model.bos.expand(B, -1, -1) + model.tier_emb(batch["tier"])[:, None] + model.dec_pos[:, :1] else: x = tok[:, 1:] - model.dec_pos[:, 1:2] + model.dec_pos[:, n_ev_seen:n_ev_seen + 1] h = cache.step(x) else: tok = model.event_tokens(mem, plan_emb, batch["tier"], seq) h = model.decode(tok, mem, None)[:, -1:] ahead_logits = model.ahead_head(h)[:, 0].float() # a note in the same beat must come after the current phase: if none is left, ahead 0 is impossible no_room = (cur % GRID) >= GRID - 1 ahead_logits[:, 0] = torch.where(no_room, torch.full_like(ahead_logits[:, 0], -1e9), ahead_logits[:, 0]) rel_beat0 = torch.div(cur, GRID, rounding_mode="floor") * GRID - start_grid # offset of current beat start if allow_cum is not None: lo = rel_beat0[:, None] + aheads[None] * GRID lo = torch.where(aheads[None] == 0, (cur - start_grid)[:, None] + 1, lo).clamp(0, allow_cum.shape[1] - 1) up = (rel_beat0[:, None] + (aheads[None] + 1) * GRID).clamp(0, allow_cum.shape[1] - 1) cnt = allow_cum.gather(1, up) - allow_cum.gather(1, lo) ahead_logits[:, :AHEAD_END] = ahead_logits[:, :AHEAD_END].masked_fill(cnt <= 0, -1e9) min_t = None if mg is not None: # time-based (the grid-time table is not monotonic next to close red lines, verification report ยง3.2): # a position is open when its time is at least min_gap after the previous event of the window min_t = torch.where(torch.isfinite(prev_t), prev_t + mg, torch.full_like(prev_t, float("-inf"))) offs = rel_beat0[:, None] + torch.arange(AHEAD_END * GRID, device=device)[None] # [B, A * GRID] t_off = tab.gather(1, offs.clamp(0, Gmax - 1)) t_off = torch.where(offs >= Gmax, torch.full_like(t_off, float("inf")), t_off) open_ = (t_off >= min_t[:, None]) & (offs > (cur - start_grid)[:, None]) if allow_cum is not None: c = offs.clamp(0, allow_cum.shape[1] - 2) open_ &= (allow_cum.gather(1, c + 1) - allow_cum.gather(1, c)) > 0 if pk is not None: open_ &= pk.repeat(1, AHEAD_END) # offs starts at a beat boundary, so its phase is offs % GRID room = open_.view(B, AHEAD_END, GRID).any(-1) ahead_logits[:, :AHEAD_END] = ahead_logits[:, :AHEAD_END].masked_fill(~room, -1e9) elif pk is not None: offs = rel_beat0[:, None] + torch.arange(AHEAD_END * GRID, device=device)[None] # [B, A * GRID] open_ = (offs > (cur - start_grid)[:, None]) & pk.repeat(1, AHEAD_END) if allow_cum is not None: c = offs.clamp(0, allow_cum.shape[1] - 2) open_ &= (allow_cum.gather(1, c + 1) - allow_cum.gather(1, c)) > 0 room = open_.view(B, AHEAD_END, GRID).any(-1) ahead_logits[:, :AHEAD_END] = ahead_logits[:, :AHEAD_END].masked_fill(~room, -1e9) nreq = None if req is not None: nreq = torch.full((B,), -1, dtype=torch.long, device=device) for b in range(B): later = req[b][req[b] > (cur[b] - start_grid[b])] if len(later): nreq[b] = later[0] has = nreq >= 0 req_beat = torch.div(nreq + start_grid, GRID, rounding_mode="floor") - torch.div(cur, GRID, rounding_mode="floor") too_far = has[:, None] & (aheads[None] > req_beat[:, None]) ahead_logits[:, :AHEAD_END] = ahead_logits[:, :AHEAD_END].masked_fill(too_far, -1e9) ahead_logits[:, AHEAD_END] = torch.where(has, torch.full_like(ahead_logits[:, 0], -1e9), ahead_logits[:, AHEAD_END]) if continue_until is not None: cu = torch.as_tensor(continue_until, device=device) can_place = (ahead_logits[:, :AHEAD_END] > -1e8).any(1) # keep END when nothing else is possible no_end = ((cur - start_grid) < cu) & can_place ahead_logits[:, AHEAD_END] = torch.where(no_end, torch.full_like(ahead_logits[:, 0], -1e9), ahead_logits[:, AHEAD_END]) ahead = pick(ahead_logits) live = ~done logp += torch.where(live, torch.log_softmax(ahead_logits, -1).gather(1, ahead[:, None])[:, 0], torch.zeros_like(logp)) end = ahead == AHEAD_END ah = ahead.clamp(max=AHEAD_END - 1) ph_logits = model.phase_logits(h, ah[:, None])[:, 0].float() same_beat = (ah == 0)[:, None] invalid = same_beat & (phases[None, :] <= (cur % GRID)[:, None]) ph_logits = ph_logits.masked_fill(invalid, -1e9) beat_off = rel_beat0 + ah * GRID # offset of the chosen beat's phase 0 if allow_cum is not None: idx = (beat_off[:, None] + phases[None]).clamp(0, allow_cum.shape[1] - 2) ok = (allow_cum.gather(1, idx + 1) - allow_cum.gather(1, idx)) > 0 ph_logits = ph_logits.masked_fill(~ok, -1e9) if nreq is not None: on_req_beat = (nreq >= 0) & (ah == req_beat.clamp(min=0)) beyond = on_req_beat[:, None] & ((beat_off[:, None] + phases[None]) > nreq[:, None]) ph_logits = ph_logits.masked_fill(beyond, -1e9) if min_t is not None: po = beat_off[:, None] + phases[None] t_ph = tab.gather(1, po.clamp(0, Gmax - 1)) t_ph = torch.where(po >= Gmax, torch.full_like(t_ph, float("inf")), t_ph) ph_logits = ph_logits.masked_fill(t_ph < min_t[:, None], -1e9) if pk is not None: ph_logits = ph_logits.masked_fill(~pk, -1e9) phase = pick(ph_logits) live_note = live & (ahead != AHEAD_END) logp += torch.where(live_note, torch.log_softmax(ph_logits, -1).gather(1, phase[:, None])[:, 0], torch.zeros_like(logp)) nxt = (torch.div(cur, GRID, rounding_mode="floor") + ah) * GRID + phase off = nxt - start_grid done |= end | (off >= G - 1) if done.all(): break off = torch.where(done, torch.zeros_like(off), off) t = torch.stack([tables[b][0][off[b]] for b in range(B)]) bar = torch.stack([tables[b][1][off[b]] for b in range(B)]) sec = torch.stack([tables[b][2][off[b]] for b in range(B)]) frame = (t / 10).round().long().clamp(0, hi.shape[1] - 1) tl, ll, svl, dl = model.note_heads(h, hi, plan_emb, ah[:, None], phase[:, None], bar[:, None], frame[:, None], sec[:, None]) if type_bias is not None: tl = tl + torch.as_tensor(type_bias, dtype=tl.dtype, device=tl.device) ntype = pick(tl[:, 0].float(), type_temp) keep_ev = ~done if mg is not None: prev_t = torch.where(keep_ev, t.float(), prev_t) logp += torch.where(keep_ev, torch.log_softmax(tl[:, 0].float(), -1).gather(1, ntype[:, None])[:, 0], torch.zeros_like(logp)) n_ev += keep_ev.float() if forced_type is not None: for b in range(B): ft = forced_type[b].get(int(off[b])) if ft is not None: ntype[b] = ft # hit notes have no length; a roll / balloon takes its most likely non-zero length (the head is trained on rolls). # With a rest mask the body must end before the next forbidden grid position: lengths are in quarter beats of the # local tempo, so the limit is converted through the grid times (ms). len_logits = ll[:, 0, 1:].float() if allow_cum is not None and bool(((ntype >= 4) & ~done).any()): for b in torch.where((ntype >= 4) & ~done)[0].tolist(): o = int(off[b]); gt = tables[b][0] nb = int(next_bad[b][min(o + 1, len(next_bad[b]) - 1)]) if nb >= len(gt) or o + 1 >= len(gt): continue beat_ms = float(gt[o + 1] - gt[o]) * GRID # tolerance of half a grid step (1/24 quarter beat): above the float32 error of the grid times, below the # 1/12-quarter-beat grid resolution, so a whole number of quarter beats is not rounded down q = int(np.floor(float(gt[nb] - gt[o]) / max(beat_ms, 1e-6) * 4 + 1.0 / 24)) if q < len_logits.shape[1]: len_logits[b, max(q, 1):] = -1e9 # at least a quarter beat nlen = torch.where(ntype >= 4, len_logits.argmax(-1) + 1, torch.zeros_like(ntype)) nsv = svl[:, 0].argmax(-1) for k, v in zip(keys, [ah, ntype, nlen, nsv, phase, bar, frame, sec]): seq[k] = torch.cat([seq[k], v[:, None]], 1) delta = torch.cat([delta, dl[:, 0:1].float()], 1) alive_steps.append(~done) offs_steps.append(off) cur = torch.where(done, cur, nxt) alive = torch.stack(alive_steps, 1) if alive_steps else torch.zeros(B, 0, dtype=torch.bool, device=device) offs_all = torch.stack(offs_steps, 1) if offs_steps else torch.zeros(B, 0, dtype=torch.long, device=device) out = [] for b, e in enumerate(examples): m = alive[b].cpu().numpy().astype(bool) offs = offs_all[b].cpu().numpy()[m] times = e.grid_time[np.minimum(offs, len(e.grid_time) - 1)] + delta[b].cpu().numpy()[m] out.append({"time": times, "type": seq["ev_type"][b].cpu().numpy()[m], "length": seq["ev_len"][b].cpu().numpy()[m] / 4.0, "frame": seq["ev_frame"][b].cpu().numpy()[m], "sv": sv_value(seq["ev_sv"][b].cpu().numpy()[m]), "grid_offset": offs, "logp": float(logp[b]), "n_events": float(n_ev[b]), "gap_pred": None if win_gap is None else win_gap[b]}) return out def match_count(pred: np.ndarray, ref: np.ndarray, tol: float) -> int: """Maximum one-to-one matching of sorted 1-D onsets within +/- tol (two-pointer greedy is optimal).""" i = j = n = 0 pred, ref = np.sort(pred), np.sort(ref) while i < len(pred) and j < len(ref): d = pred[i] - ref[j] if abs(d) <= tol: n += 1 i += 1 j += 1 elif d < 0: i += 1 else: j += 1 return n def evaluate_generation(preds: list[dict], examples: list[Example], tols=(10, 25, 50)) -> dict[str, float]: res = {} tot_p = sum(len(p["time"]) for p in preds) tot_r = sum(len(e.ref_time) for e in examples) for tol in tols: tp = sum(match_count(p["time"], e.ref_time, tol) for p, e in zip(preds, examples)) prec, rec = tp / max(tot_p, 1), tp / max(tot_r, 1) res[f"f1@{tol}"] = 2 * prec * rec / max(prec + rec, 1e-9) res[f"p@{tol}"], res[f"r@{tol}"] = prec, rec # colour-aware F1 at 25 ms: Don-like and Ka-like matched separately tp = 0 for p, e in zip(preds, examples): for group in (DON_LIKE, KA_LIKE): pm = np.isin(p["type"], list(group)) rm = np.isin(e.ev_type, list(group)) tp += match_count(p["time"][pm], e.ref_time[rm], 25) prec, rec = tp / max(tot_p, 1), tp / max(tot_r, 1) res["color_f1@25"] = 2 * prec * rec / max(prec + rec, 1e-9) res["density_ratio"] = tot_p / max(tot_r, 1) # scroll speed (reading load): share of notes off SV 1 and SV changes per minute, generated vs reference def sv_stats(svs, seconds): allv = np.concatenate(svs) if svs else np.zeros(0) changes = sum(int(np.sum(np.abs(np.diff(np.log2(v))) > 1e-3)) for v in svs if len(v) > 1) return float(np.mean(np.abs(np.log2(allv)) > 1e-3)) if len(allv) else 0.0, changes / max(seconds / 60, 1e-6) secs = sum(float(e.grid_time[-1]) / 1000 for e in examples) res["sv_off1_gen"], res["sv_changes_per_min_gen"] = sv_stats([p["sv"] for p in preds], secs) res["sv_off1_ref"], res["sv_changes_per_min_ref"] = sv_stats([sv_value(e.ev_sv) for e in examples], secs) return res