File size: 26,539 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
"""Window sampling and event tokenization for the B0 chart model.

A training example is a 20 s window of one chart:

* audio: log-Mel frames plus beat-phase features from the chart's timing points
  (an oracle beat grid for now; inference will need a beat tracker);
* events: the notes in the window as decoder tokens;
* plan: per 16-beat section, note density (rho) and finest subdivision class (r).

Decoder step k reads tokens [BOS, e_1..e_k] and predicts where e_{k+1} is: how many beats
ahead (0..MAX_AHEAD, or END) and its absolute 1/48 phase within that beat. Positions are
anchored to the grid, so one wrong prediction does not shift every later note (as relative
gaps would). Given the position, it predicts the note's type, length, SV and delta.
"""

from __future__ import annotations

import math
import os
import pickle
import random
from dataclasses import dataclass
from pathlib import Path

import numpy as np
import torch

GRID = 48
MAX_GAP = 32 * GRID          # largest representable distance between notes
N_GAP = MAX_GAP + 1
MAX_AHEAD = 32               # beats ahead classes 0..MAX_AHEAD
AHEAD_END = MAX_AHEAD + 1    # end of window
N_AHEAD = MAX_AHEAD + 2
N_TYPE = 7
N_LEN = 65                   # length in quarter beats, 0..64
SECTION_BEATS = 16
DIVISORS = [1, 2, 3, 4, 6, 8, 12, 16]  # anything finer -> class 8
N_SUBDIV = len(DIVISORS) + 1
WINDOW = 2000                # frames (100 fps) = 20 s
MAX_EVENTS = 384
MAX_BARS = 40                # measures per window for the per-measure plan (a 20 s window stretched by 15% holds up to 35)
BAR_F = 17                   # per-measure plan features, see bar_plan()
SUSTAIN = 16                 # plan column: share of the measure covered by a roll / balloon body
# Coordinates of the note heads' audio-frame and bar-position lookups in training: "true" = the note's real time
# (residual included; the behaviour up to b9), "grid" = its grid time, as generation uses (verification report §9.2;
# stage 4b). Set from train.py --note-coord.
NOTE_COORD = "true"
GAP0 = 6                     # plan columns GAP0 .. GAP0 + N_GAP_BINS - 1: gap histogram
REP_F = 9                    # per-bar repetition hint: offset to the most similar earlier bar (1..8, one-hot) + similarity
MAX_SECTIONS = 16
SV_STEPS = 12                # SV classes: log2(sv) in 1/12-octave steps over [-2, 2]
N_SV = 4 * SV_STEPS + 1
SV_ONE = 2 * SV_STEPS        # class of SV = 1.0


def sv_class(sv: np.ndarray) -> np.ndarray:
    return np.clip(np.round(np.log2(np.maximum(sv, 1e-3)) * SV_STEPS) + SV_ONE, 0, N_SV - 1).astype(np.int64)


def sv_value(cls: np.ndarray) -> np.ndarray:
    return 2.0 ** ((np.asarray(cls) - SV_ONE) / SV_STEPS)


def load_songs(paths: list[Path], mmap: bool = False) -> list[dict]:
    """Load feature shards. With mmap, each shard's mel spectrograms are written once to a
    sibling .mel.npy file and replaced by read-only memory-mapped slices, so the full corpus
    does not have to fit in RAM (the OS page cache keeps the hot part)."""
    songs = []
    for p in paths:
        p = Path(p)
        with open(p, "rb") as f:
            shard = pickle.load(f)
        if mmap and shard:
            npy = p.with_suffix(".mel.npy")
            lens = [len(s["mel"]) for s in shard]
            if not npy.exists():
                tmp = npy.with_suffix(f".{os.getpid()}.tmp.npy")  # per process: concurrent loaders may race
                mm = np.lib.format.open_memmap(tmp, mode="w+", dtype=np.float16, shape=(sum(lens), shard[0]["mel"].shape[1]))
                o = 0
                for s, n in zip(shard, lens):
                    mm[o:o + n] = s["mel"]
                    o += n
                mm.flush()
                del mm
                os.replace(tmp, npy)
            mm = np.load(npy, mmap_mode="r")
            o = 0
            for s, n in zip(shard, lens):
                s["mel"] = mm[o:o + n]
                o += n
        songs.extend(shard)
    return songs


def _beats_at(sections: np.ndarray, t_ms: np.ndarray) -> np.ndarray:
    idx = np.clip(np.searchsorted(sections[:, 0], t_ms, side="right") - 1, 0, len(sections) - 1)
    s = sections[idx]
    return s[:, 3] + (t_ms - s[:, 0]) / s[:, 1]


def _measure_pos(sections: np.ndarray, t_ms: np.ndarray) -> np.ndarray:
    idx = np.clip(np.searchsorted(sections[:, 0], t_ms, side="right") - 1, 0, len(sections) - 1)
    s = sections[idx]
    local = (t_ms - s[:, 0]) / s[:, 1]
    return np.mod(local, s[:, 2]) / s[:, 2]  # 0..1 within the bar


def _measure_table(sections: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """(section start beats, meters, index of each section's first measure). A red line restarts the bar in
    osu!, so measures run from each section's start in steps of its meter; the last measure of a section can be
    partial (it ends where the next section starts)."""
    sb = np.asarray(sections[:, 3], np.float64)
    meter = np.where(sections[:, 2] > 0, sections[:, 2], 4).astype(np.float64)
    n = np.ceil(np.maximum(np.diff(sb), 0) / meter[:-1] - 1e-9).astype(np.int64)
    return sb, meter, np.concatenate([[0], np.cumsum(n)]).astype(np.int64)


def measure_at(sections: np.ndarray, beats: np.ndarray) -> np.ndarray:
    """Global measure index (real measures, see _measure_table) of global beat positions. Beats before the first
    section extend its measures backwards (negative indices)."""
    sb, meter, first = _measure_table(sections)
    b = np.asarray(beats, np.float64)
    j = np.clip(np.searchsorted(sb, b + 1e-9, side="right") - 1, 0, len(sb) - 1)
    return first[j] + np.floor((b - sb[j]) / meter[j] + 1e-9).astype(np.int64)


def measure_span(sections: np.ndarray, idx: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """(start beat, end beat) of global measures; the end is cut at the next section's start."""
    sb, meter, first = _measure_table(sections)
    idx = np.asarray(idx, np.int64)
    j = np.clip(np.searchsorted(first, idx, side="right") - 1, 0, len(sb) - 1)
    # several sections can share a first index when a section is empty; take the last one whose range holds idx
    start = sb[j] + (idx - first[j]) * meter[j]
    nxt = np.where(j + 1 < len(sb), sb[np.minimum(j + 1, len(sb) - 1)], np.inf)
    return start, np.minimum(start + meter[j], nxt)


def beat_ms(sections: np.ndarray, beats: np.ndarray) -> np.ndarray:
    """ms of global beat positions (inverse of _beats_at)."""
    b = np.asarray(beats, np.float64)
    j = np.clip(np.searchsorted(sections[:, 3], b + 1e-9, side="right") - 1, 0, len(sections) - 1)
    return sections[j, 0] + (b - sections[j, 3]) * sections[j, 1]


def roll_end_beats(sections: np.ndarray, start_beats: np.ndarray, lengths: np.ndarray) -> np.ndarray:
    """Global beat where a roll / balloon ends. length_beats is counted in the beats of the section where the note
    starts (osu.data), so the end is found in ms and mapped back; this matters when the body crosses a red line."""
    sb = np.asarray(start_beats, np.float64)
    j = np.clip(np.searchsorted(sections[:, 3], sb + 1e-9, side="right") - 1, 0, len(sections) - 1)
    end_ms = beat_ms(sections, sb) + np.maximum(np.asarray(lengths, np.float64), 0.0) * sections[j, 1]
    return np.maximum(_beats_at(sections, end_ms), sb)


def plan_active(plan: np.ndarray) -> np.ndarray:
    """Measures that are not rests under a (human or predicted) plan: a hit note, a roll / balloon starting in the
    measure, or a sustained note covering part of it. The rest mask allows notes only in these measures."""
    return (plan[..., 0] > 0.5) | (plan[..., 3] > 0.5) | (plan[..., SUSTAIN] > 0.1)


def section_gap_dists(all_g: np.ndarray, hit: np.ndarray, all_sec: np.ndarray) -> np.ndarray:
    """Per section: distribution of gaps between consecutive hit notes (bin of the later note's section)
    and of consecutive-gap ratios (section of the last note of the pair); zero rows where undefined."""
    from .gapstats import N_GAP_BINS, N_RATIO_BINS, gap_bins, ratio_bins
    out = np.zeros((MAX_SECTIONS, N_GAP_BINS + N_RATIO_BINS), np.float32)
    g, sec = all_g[hit], all_sec[hit]
    if len(g) < 2:
        return out
    gaps = np.diff(g) / GRID
    gb, s1 = gap_bins(gaps), sec[1:]
    ok = (s1 >= 0) & (s1 < MAX_SECTIONS)
    np.add.at(out, (s1[ok], gb[ok]), 1.0)
    rb, s2 = ratio_bins(gaps), sec[2:]
    ok = (rb >= 0) & (s2 >= 0) & (s2 < MAX_SECTIONS)
    np.add.at(out, (s2[ok], N_GAP_BINS + rb[ok]), 1.0)
    for a, b in ((0, N_GAP_BINS), (N_GAP_BINS, N_GAP_BINS + N_RATIO_BINS)):
        tot = out[:, a:b].sum(1, keepdims=True)
        out[:, a:b] = np.where(tot > 0, out[:, a:b] / np.maximum(tot, 1), 0)
    return out


def bar_plan(all_g: np.ndarray, types: np.ndarray, bar0: int, sections: np.ndarray, lengths: np.ndarray | None = None,
             n_bars: int = MAX_BARS) -> np.ndarray:
    """Per measure (real measures from the chart's timing sections, index relative to bar0) of a chart:
    [play (has a hit note), log1p(hit notes per beat), big-note share, roll start, triplet-grid share (1/3, 1/6, 1/12),
    1/8-or-finer share, gap histogram (10 bins of gapstats, gaps ending in the measure, normalised),
    sustain (share of the measure covered by a roll / balloon body)]. A measure is a rest when it has neither a hit
    note nor a sustained note: play = 0 and sustain = 0."""
    from .gapstats import N_GAP_BINS, gap_bins
    out = np.zeros((n_bars, BAR_F), np.float32)
    bar = measure_at(sections, all_g / GRID) - bar0
    st, en = measure_span(sections, np.arange(n_bars) + bar0)
    mlen = np.maximum(en - st, 1e-6)
    hit = types <= 3
    div = subdiv_class(all_g)
    trip = np.isin(div, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)])
    fine = div >= DIVISORS.index(8)
    gh = all_g[hit]
    gb = gap_bins(np.diff(gh) / GRID) if len(gh) > 1 else np.zeros(0, np.int64)
    gbar = bar[hit][1:]
    for k in range(n_bars):
        m = (bar == k)
        mh = m & hit
        if not m.any():
            continue
        n = int(mh.sum())
        out[k, 0] = float(n > 0)
        out[k, 1] = np.log1p(n / mlen[k])
        if n:
            out[k, 2] = float((types[mh] >= 2).mean())
            out[k, 4] = float(trip[mh].mean())
            out[k, 5] = float(fine[mh].mean())
        out[k, 3] = float(((types >= 4) & m).any())
        sel = gb[gbar == k]
        if len(sel):
            out[k, GAP0:GAP0 + N_GAP_BINS] = np.bincount(sel, minlength=N_GAP_BINS) / len(sel)
    if lengths is not None:  # roll / balloon bodies: overlap of [start, end] beats with each measure
        b = all_g / GRID
        rb = b[types >= 4]
        for x, e in zip(rb, roll_end_beats(sections, rb, np.asarray(lengths, np.float64)[types >= 4])):
            ov = np.minimum(en, e) - np.maximum(st, x)
            cover = np.where(ov > 0, ov, 0.0) / mlen
            cover[(st <= x) & (x < en)] = np.maximum(cover[(st <= x) & (x < en)], 1e-3)  # a zero-length start still marks its measure
            out[:, SUSTAIN] = np.minimum(out[:, SUSTAIN] + cover, 1.0)
    return out


def rep_hint(mel: np.ndarray, frame_bar: np.ndarray, phase: np.ndarray) -> np.ndarray:
    """For each measure of the window: which earlier measure (1..8 back) sounds most alike, and how much.
    Profile: full-band positive spectral flux at 48 slots of the measure (phase within the measure, 12 per beat in
    4/4); cosine similarity. Uses the audio only, so it is available at generation time."""
    m = np.asarray(mel, np.float32)
    flux = np.maximum(np.diff(m, axis=0, prepend=m[:1]), 0).mean(1)
    flux = (flux - flux.mean()) / (flux.std() + 1e-6)
    out = np.zeros((MAX_BARS, REP_F), np.float32)
    prof = {}
    for k in range(MAX_BARS):
        fr = np.where(frame_bar == k)[0]
        if len(fr) < 8:
            continue
        pos = np.clip((phase[fr] * 48).astype(np.int64), 0, 47)
        v = np.full(48, np.nan, np.float32)
        for q in range(48):
            sel = flux[fr][pos == q]
            if len(sel):
                v[q] = sel.max()
        if np.isnan(v).mean() < 0.3:
            v = np.nan_to_num(v, nan=float(np.nanmean(v)))
            prof[k] = (v - v.mean()) / (np.linalg.norm(v - v.mean()) + 1e-6)
    for k, v in prof.items():
        best, off = -1.0, 0
        for o in range(1, 9):
            if k - o in prof:
                c = float(v @ prof[k - o])
                if c > best:
                    best, off = c, o
        if off:
            out[k, off - 1] = 1.0
            out[k, 8] = best
    return out


def stretch(song: dict, chart: dict, start_frame: int, r: float):
    """Tempo augmentation: the window starting at start_frame played r times faster (r > 1) or slower.
    Returns (song-like dict, chart dict, 0): mel resampled in time; note times, timing sections and kiai
    rescaled around the window start; beat positions and lengths in beats unchanged."""
    mel = song["mel"]
    src = start_frame + np.arange(WINDOW) * r
    i0 = np.clip(np.floor(src).astype(np.int64), 0, len(mel) - 1)
    i1 = np.clip(i0 + 1, 0, len(mel) - 1)
    w = (src - np.floor(src))[:, None].astype(np.float32)
    seg = (np.asarray(mel[i0], np.float32) * (1 - w) + np.asarray(mel[i1], np.float32) * w).astype(mel.dtype)
    t0 = start_frame * 10.0
    c = dict(chart)
    c["time"] = (chart["time"] - t0) / r
    sec = chart["sections"].copy()
    sec[:, 0] = (sec[:, 0] - t0) / r
    sec[:, 1] = sec[:, 1] / r
    c["sections"] = sec
    c["delta_ms"] = chart["delta_ms"] / r
    if "kiai" in chart and len(chart["kiai"]):
        c["kiai"] = (np.asarray(chart["kiai"], float) - t0) / r
    return {"mel": seg}, c, 0


def subdiv_class(grid_idx: np.ndarray) -> np.ndarray:
    r = np.mod(grid_idx, GRID)
    div = np.where(r == 0, 1, GRID // np.gcd(r, GRID))
    out = np.full(div.shape, len(DIVISORS), dtype=np.int64)
    for i, d in enumerate(DIVISORS):
        out[div == d] = i
    return out


@dataclass
class Example:
    mel: np.ndarray        # [W, 128] float16
    beat_feat: np.ndarray  # [W, 4]
    frame_section: np.ndarray  # [W] section index or -1
    tier: int
    gap: np.ndarray        # [N+1] grid distance to next note (last = 0, end of window); kept for analysis
    ev_gap: np.ndarray     # [N] grid distance from the previous note
    tgt_ahead: np.ndarray  # [N+1] beats ahead of the next note (last = AHEAD_END)
    tgt_phase: np.ndarray  # [N+1] absolute phase (0..47) of the next note (last = -100)
    ev_ahead: np.ndarray   # [N] beats ahead of each event relative to the previous one
    ev_type: np.ndarray    # [N]
    ev_len: np.ndarray     # [N]
    ev_delta: np.ndarray   # [N] ms
    ev_frame: np.ndarray   # [N] frame within window
    ev_phase: np.ndarray   # [N] grid index mod 48
    ev_bar: np.ndarray     # [N] position in bar, 0..15 (sixteenths of the bar)
    ev_section: np.ndarray # [N]
    plan_rho: np.ndarray   # [S] notes per beat
    plan_r: np.ndarray     # [S] subdivision class
    ref_time: np.ndarray   # [N] ms relative to window start (for F1)
    start_grid: int        # grid index the first gap is measured from
    start_ms: float
    grid_time: np.ndarray  # [G] ms (relative to window start) of grid index start_grid + k
    grid_bar: np.ndarray   # [G] bar position in sixteenths
    grid_section: np.ndarray  # [G]
    ev_sv: np.ndarray      # [N] SV class
    beat_tgt: np.ndarray   # [W] soft beat target (linear interpolation onto frames)
    down_tgt: np.ndarray   # [W] soft downbeat target
    beat_mask: np.ndarray  # [W] frames where the chart's timing is defined
    kiai_tgt: np.ndarray   # [W]
    kiai_mask: np.ndarray  # [W]
    plan_gap: np.ndarray | None = None  # [S, N_GAP_BINS + N_RATIO_BINS] per-section gap and ratio distributions (gapstats)
    bar_plan: np.ndarray | None = None  # [MAX_BARS, BAR_F] per-bar plan of the chart (bar_plan())
    frame_bar: np.ndarray | None = None  # [W] bar index of each frame (-1 outside)
    rep_hint: np.ndarray | None = None  # [MAX_BARS, REP_F] repetition hint from the audio (rep_hint())


def make_example(song: dict, chart: dict, start_frame: int) -> Example:
    W = WINDOW
    mel = song["mel"][start_frame:start_frame + W]
    if len(mel) < W:
        mel = np.concatenate([mel, np.full((W - len(mel), mel.shape[1]), mel.min(), dtype=mel.dtype)])
    sec = chart["sections"]
    start_ms = start_frame * 10.0
    t = start_ms + np.arange(W) * 10.0
    beats = _beats_at(sec, t)
    bar = _measure_pos(sec, t)
    beat_feat = np.stack([np.sin(2 * np.pi * beats), np.cos(2 * np.pi * beats),
                          np.sin(2 * np.pi * bar), np.cos(2 * np.pi * bar)], 1).astype(np.float32)

    b0 = beats[0]
    start_grid = math.ceil(b0 * GRID) - 1
    sec0 = math.floor(b0 / SECTION_BEATS)
    frame_section = np.floor(beats / SECTION_BEATS).astype(np.int64) - sec0
    frame_section[(frame_section < 0) | (frame_section >= MAX_SECTIONS)] = -1

    # notes in window
    times = chart["time"]
    sel = (times >= start_ms) & (times < start_ms + W * 10.0)
    g = np.round(chart["beat"][sel] * GRID).astype(np.int64)
    prev = np.concatenate([[start_grid], g])
    gaps = np.diff(prev)
    ahead_all = np.floor_divide(prev[1:], GRID) - np.floor_divide(prev[:-1], GRID)
    keep = np.cumsum((gaps < 1) | (ahead_all > MAX_AHEAD)) == 0  # truncate at the first unrepresentable step
    n = min(int(keep.sum()), MAX_EVENTS)
    g, gaps, ahead = g[:n], gaps[:n], ahead_all[:n]
    ev_time = times[sel][:n]
    ev_type = chart["type"][sel][:n].astype(np.int64)
    ev_len = np.clip(np.round(chart["length_beats"][sel][:n] * 4), 0, N_LEN - 1).astype(np.int64)
    ev_delta = chart["delta_ms"][sel][:n].astype(np.float32)
    coord_t = ev_time
    if NOTE_COORD == "grid":  # the note's grid time, exactly as generation's lookup tables (grid_time, grid_bar)
        gb_ev = g / GRID
        si_ev = np.clip(np.searchsorted(sec[:, 3], gb_ev, side="right") - 1, 0, len(sec) - 1)
        coord_t = sec[si_ev, 0] + (gb_ev - sec[si_ev, 3]) * sec[si_ev, 1]
    if NOTE_COORD == "grid":  # float32 relative time, as generation rounds grid_time
        ev_frame = np.clip(np.round((coord_t - start_ms).astype(np.float32) / np.float32(10.0)), 0, W - 1).astype(np.int64)
    else:
        ev_frame = np.clip(np.round((coord_t - start_ms) / 10.0), 0, W - 1).astype(np.int64)
    ev_bar = np.clip(np.floor(_measure_pos(sec, coord_t) * 16), 0, 15).astype(np.int64)
    ev_section = np.clip(np.floor(g / GRID / SECTION_BEATS).astype(np.int64) - sec0, 0, MAX_SECTIONS - 1)

    # plan targets over full sections (whole chart, not just the window)
    all_g = np.round(chart["beat"] * GRID).astype(np.int64)
    all_sec = np.floor(all_g / GRID / SECTION_BEATS).astype(np.int64) - sec0
    all_sub = subdiv_class(all_g)
    plan_rho = np.zeros(MAX_SECTIONS, dtype=np.float32)
    plan_r = np.zeros(MAX_SECTIONS, dtype=np.int64)
    for j in range(MAX_SECTIONS):
        m = all_sec == j
        if m.any():
            plan_rho[j] = m.sum() / SECTION_BEATS
            plan_r[j] = all_sub[m].max()
    plan_gap = section_gap_dists(all_g, chart["type"] <= 3, all_sec)
    bar0 = int(measure_at(sec, np.array([b0]))[0])
    # the window's measures described by all of the chart's notes, so the measures cut by the window edges get the same
    # plan rows as the song-level plan the planner predicts for generation
    bplan = bar_plan(all_g, chart["type"], bar0, sec, chart["length_beats"])
    frame_bar = measure_at(sec, beats) - bar0
    fst, fen = measure_span(sec, frame_bar + bar0)
    phase = np.clip((beats - fst) / np.maximum(fen - fst, 1e-6), 0.0, 1.0 - 1e-6)
    frame_bar[(frame_bar < 0) | (frame_bar >= MAX_BARS)] = -1
    rhint = rep_hint(mel, frame_bar, phase)

    # beat / downbeat / kiai targets from the chart's timing (mapper-set, ms-accurate)
    beat_tgt = np.zeros(W, np.float32)
    down_tgt = np.zeros(W, np.float32)
    lo_t = sec[0, 0]
    hi_t = times[-1] + 2000.0
    for b in range(int(math.ceil(beats[0])), int(math.floor(beats[-1])) + 1):
        si = int(np.clip(np.searchsorted(sec[:, 3], b, side="right") - 1, 0, len(sec) - 1))
        tb = sec[si, 0] + (b - sec[si, 3]) * sec[si, 1]
        if tb < max(lo_t, start_ms) or tb > min(hi_t, start_ms + (W - 1) * 10.0):
            continue
        f = (tb - start_ms) / 10.0
        f0 = int(math.floor(f))
        w1 = f - f0
        is_down = abs(((b - sec[si, 3]) % sec[si, 2])) < 1e-6
        for fi, wv in ((f0, 1 - w1), (f0 + 1, w1)):
            if 0 <= fi < W:
                beat_tgt[fi] = max(beat_tgt[fi], wv)
                if is_down:
                    down_tgt[fi] = max(down_tgt[fi], wv)
    beat_mask = ((t >= lo_t) & (t <= hi_t)).astype(np.float32)
    kiai_tgt = np.zeros(W, np.float32)
    for a, b2 in chart.get("kiai", np.zeros((0, 2))):
        kiai_tgt[(t >= a) & (t < b2)] = 1.0
    kiai_mask = ((t >= times[0] - 2000.0) & (t <= times[-1] + 2000.0)).astype(np.float32)

    # grid lookup tables for generation: grid index -> time, bar position, section
    G = int(math.ceil(beats[-1] * GRID)) - start_grid + 2
    gb = (start_grid + np.arange(G)) / GRID
    si = np.clip(np.searchsorted(sec[:, 3], gb, side="right") - 1, 0, len(sec) - 1)
    s = sec[si]
    gt = s[:, 0] + (gb - s[:, 3]) * s[:, 1]
    grid_bar = np.clip(np.floor(_measure_pos(sec, gt) * 16), 0, 15).astype(np.int64)
    grid_section = np.clip(np.floor(gb / SECTION_BEATS).astype(np.int64) - sec0, 0, MAX_SECTIONS - 1)

    ev_sv = sv_class(chart["sv"][sel][:n]) if "sv" in chart else np.full(n, SV_ONE, np.int64)

    return Example(
        ev_sv=ev_sv, beat_tgt=beat_tgt, down_tgt=down_tgt, beat_mask=beat_mask, kiai_tgt=kiai_tgt, kiai_mask=kiai_mask,
        grid_time=(gt - start_ms).astype(np.float32), grid_bar=grid_bar, grid_section=grid_section,
        mel=mel, beat_feat=beat_feat, frame_section=frame_section, tier=chart["tier"],
        gap=np.concatenate([gaps, [0]]).astype(np.int64), ev_gap=gaps.astype(np.int64),
        tgt_ahead=np.concatenate([ahead, [AHEAD_END]]).astype(np.int64),
        tgt_phase=np.concatenate([np.mod(g, GRID), [-100]]).astype(np.int64),
        ev_ahead=ahead.astype(np.int64),
        ev_type=ev_type, ev_len=ev_len, ev_delta=ev_delta, ev_frame=ev_frame,
        ev_phase=np.mod(g, GRID), ev_bar=ev_bar, ev_section=ev_section,
        plan_rho=plan_rho, plan_r=plan_r, plan_gap=plan_gap, bar_plan=bplan, frame_bar=frame_bar, rep_hint=rhint, ref_time=(ev_time - start_ms).astype(np.float32),
        start_grid=start_grid, start_ms=start_ms,
    )


class WindowSampler(torch.utils.data.IterableDataset):
    """Infinite random windows; charts drawn uniformly, start frames uniform over the song."""

    def __init__(self, songs: list[dict], seed: int = 0, stretch_p: float = 0.0, stretch_range: float = 0.15):
        self.songs = songs
        self.index = [(i, j) for i, s in enumerate(songs) for j in range(len(s["charts"]))]
        self.seed = seed
        self.stretch_p, self.stretch_range = stretch_p, stretch_range

    def __iter__(self):
        info = torch.utils.data.get_worker_info()
        rng = random.Random(self.seed + (info.id if info else 0) * 9973 + random.randrange(1 << 30))
        while True:
            i, j = rng.choice(self.index)
            song = self.songs[i]
            frames = len(song["mel"])
            start = rng.randrange(0, max(1, frames - WINDOW // 2))
            if self.stretch_p and rng.random() < self.stretch_p:
                r = 1.0 + rng.uniform(-self.stretch_range, self.stretch_range)
                yield make_example(*stretch(song, song["charts"][j], start, r))
            else:
                yield make_example(song, song["charts"][j], start)


def fixed_windows(songs: list[dict], n: int, seed: int = 1) -> list[Example]:
    """Deterministic evaluation windows that contain at least a few notes."""
    rng = random.Random(seed)
    index = [(i, j) for i, s in enumerate(songs) for j in range(len(s["charts"]))]
    out = []
    while len(out) < n and index:
        i, j = rng.choice(index)
        song, chart = songs[i], songs[i]["charts"][j]
        first, last = chart["time"][0], chart["time"][-1]
        lo = int(first // 10)
        hi = max(lo + 1, int(last // 10) - WINDOW)
        ex = make_example(song, chart, rng.randrange(lo, hi))
        if len(ex.ev_type) >= 8:
            out.append(ex)
    return out


def collate(batch: list[Example]) -> dict[str, torch.Tensor]:
    B = len(batch)
    N = max(1, max(len(e.ev_type) for e in batch))
    def pad(key, length, dtype, fill=0):
        out = torch.full((B, length), fill, dtype=dtype)
        for b, e in enumerate(batch):
            v = getattr(e, key)
            out[b, :len(v)] = torch.as_tensor(v, dtype=dtype)
        return out
    return {
        "mel": torch.from_numpy(np.stack([e.mel for e in batch])),
        "beat_feat": torch.from_numpy(np.stack([e.beat_feat for e in batch])),
        "frame_section": torch.from_numpy(np.stack([e.frame_section for e in batch])),
        "tier": torch.tensor([e.tier for e in batch]),
        "tgt_ahead": pad("tgt_ahead", N + 1, torch.long, -100),
        "tgt_phase": pad("tgt_phase", N + 1, torch.long, -100),
        "ev_ahead": pad("ev_ahead", N, torch.long),
        "ev_type": pad("ev_type", N, torch.long, -100),
        "ev_len": pad("ev_len", N, torch.long, -100),
        "ev_delta": pad("ev_delta", N, torch.float32),
        "ev_frame": pad("ev_frame", N, torch.long),
        "ev_phase": pad("ev_phase", N, torch.long),
        "ev_bar": pad("ev_bar", N, torch.long),
        "ev_section": pad("ev_section", N, torch.long),
        "ev_sv": pad("ev_sv", N, torch.long, -100),
        "beat_tgt": torch.from_numpy(np.stack([e.beat_tgt for e in batch])),
        "down_tgt": torch.from_numpy(np.stack([e.down_tgt for e in batch])),
        "beat_mask": torch.from_numpy(np.stack([e.beat_mask for e in batch])),
        "kiai_tgt": torch.from_numpy(np.stack([e.kiai_tgt for e in batch])),
        "kiai_mask": torch.from_numpy(np.stack([e.kiai_mask for e in batch])),
        "ev_mask": torch.stack([torch.arange(N) < len(e.ev_type) for e in batch]),
        "plan_rho": torch.from_numpy(np.stack([e.plan_rho for e in batch])),
        "plan_r": torch.from_numpy(np.stack([e.plan_r for e in batch])),
        "plan_gap": torch.from_numpy(np.stack([e.plan_gap for e in batch])),
        "bar_plan": torch.from_numpy(np.stack([e.bar_plan for e in batch])),
        "frame_bar": torch.from_numpy(np.stack([e.frame_bar for e in batch])),
        "rep_hint": torch.from_numpy(np.stack([e.rep_hint for e in batch])),
    }