File size: 21,269 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
"""B0: supervised hierarchical autoregressive model of a complete chart (README section 2).

A chart has three parts and the model predicts all of them:

* timing map  -- beat and downbeat activations from audio alone (grid-free encoder);
                 decoded into BPM / offset / meter sections by :mod:`chartgen.timing`;
* notes       -- per step, the next note's position on the beat grid (beats ahead, then
                 absolute 1/48 phase), then its type, length, scroll speed (SV) and residual;
* effects     -- kiai per frame; SV per note; bar lines follow the decoded sections.

The encoder never sees the beat grid, so its music representation can be replaced by the
Stage A (JEPA + VICReg) encoder. Grid information is added after the encoder for the
planner, decoder and kiai head.
"""

from __future__ import annotations

from dataclasses import dataclass

import torch
import torch.nn as nn
import torch.nn.functional as F

from .dataset import BAR_F, GRID, REP_F, MAX_EVENTS, MAX_SECTIONS, N_AHEAD, N_LEN, N_SUBDIV, N_SV, N_TYPE
from .gapstats import N_GAP_BINS, N_RATIO_BINS

N_TIERS = 5


@dataclass
class B0Config:
    n_mels: int = 128
    d_model: int = 224
    enc_layers: int = 3
    dec_layers: int = 4
    n_heads: int = 8
    d_plan: int = 128
    plan_layers: int = 2
    branch_ch: int = 96
    local_frames: int = 2  # +/- frames of high-resolution audio read by the note heads
    dropout: float = 0.1
    max_frames: int = 1024  # after 2x downsampling
    gap_plan: bool = False  # planner also predicts each section's note-gap and gap-ratio distributions (gapstats),
    #                         and the decoder is conditioned on them
    bar_plan: bool = False  # decoder memory is conditioned on a per-bar plan (dataset.bar_plan); planner input is not
    bar_plan_drop: float = 0.3  # training: probability of hiding the bar plan of a window (model also works without)
    bar_plan_corrupt: float = 0.0  # training: probability that a given bar plan is corrupted like a predicted one
    rep_hint: bool = False  # decoder memory also gets the per-bar repetition hint from the audio (dataset.rep_hint)


def _enc_layer(d, h, drop):
    return nn.TransformerEncoderLayer(d, h, 4 * d, drop, activation="gelu", batch_first=True, norm_first=True)


class Frontend(nn.Module):
    """Multi-scale temporal CNN over log-Mel. Returns 100 fps and 50 fps features."""

    def __init__(self, c: B0Config):
        super().__init__()
        self.norm = nn.LayerNorm(c.n_mels)
        self.branches = nn.ModuleList(
            nn.Sequential(nn.Conv1d(c.n_mels, c.branch_ch, k, padding=k // 2), nn.GELU()) for k in (3, 9, 27)
        )
        self.hires_dim = 3 * c.branch_ch
        self.down = nn.Conv1d(self.hires_dim, c.d_model, 4, stride=2, padding=1)

    def forward(self, mel):
        x = self.norm(mel).transpose(1, 2)
        hi = torch.cat([b(x) for b in self.branches], 1)
        lo = self.down(hi)
        return hi.transpose(1, 2), lo.transpose(1, 2)


class B0(nn.Module):
    def __init__(self, c: B0Config = B0Config()):
        super().__init__()
        self.c = c
        d = c.d_model
        self.frontend = Frontend(c)
        hd = self.frontend.hires_dim
        self.enc_pos = nn.Parameter(torch.zeros(1, c.max_frames, d))
        self.encoder = nn.TransformerEncoder(_enc_layer(d, c.n_heads, c.dropout), c.enc_layers, enable_nested_tensor=False)
        self.enc_norm = nn.LayerNorm(d)
        self.beat_proj = nn.Linear(4, d)

        # frame-level heads (100 fps)
        self.timing_head = nn.Sequential(nn.Linear(hd + d, d), nn.GELU(), nn.Linear(d, 2))  # beat, downbeat
        self.kiai_head = nn.Sequential(nn.Linear(hd + d, d // 2), nn.GELU(), nn.Linear(d // 2, 1))

        # section planner
        self.plan_in = nn.Linear(d, c.d_plan)
        self.plan_tier = nn.Embedding(N_TIERS, c.d_plan)
        self.plan_pos = nn.Parameter(torch.zeros(1, MAX_SECTIONS, c.d_plan))
        self.planner = nn.TransformerEncoder(_enc_layer(c.d_plan, 4, c.dropout), c.plan_layers, enable_nested_tensor=False)
        self.rho_head = nn.Linear(c.d_plan, 1)
        self.r_head = nn.Linear(c.d_plan, N_SUBDIV)
        self.plan_r_emb = nn.Embedding(N_SUBDIV, d)
        self.plan_rho_proj = nn.Linear(1, d)
        if c.gap_plan:
            self.gap_head = nn.Linear(c.d_plan, N_GAP_BINS)
            self.ratio_head = nn.Linear(c.d_plan, N_RATIO_BINS)
            self.plan_gap_proj = nn.Linear(N_GAP_BINS + N_RATIO_BINS, d)
            nn.init.zeros_(self.plan_gap_proj.weight)  # starts as B0: fine-tuning from a B0 checkpoint is a no-op at step 0
            nn.init.zeros_(self.plan_gap_proj.bias)
        if c.rep_hint:
            self.rep_proj = nn.Linear(REP_F, d)
            nn.init.zeros_(self.rep_proj.weight)
            nn.init.zeros_(self.rep_proj.bias)
        if c.bar_plan:
            self.bar_plan_proj = nn.Linear(BAR_F + 1, d)  # + "plan given" flag
            nn.init.zeros_(self.bar_plan_proj.weight)
            nn.init.zeros_(self.bar_plan_proj.bias)

        # decoder
        self.bos = nn.Parameter(torch.zeros(1, 1, d))
        self.tier_emb = nn.Embedding(N_TIERS, d)
        self.ahead_emb = nn.Embedding(N_AHEAD, d)
        self.type_emb = nn.Embedding(N_TYPE, d)
        self.len_emb = nn.Embedding(N_LEN, d)
        self.sv_emb = nn.Embedding(N_SV, d)
        self.phase_emb = nn.Embedding(GRID, d)
        self.bar_emb = nn.Embedding(16, d)
        self.audio_proj = nn.Linear(d, d)
        self.dec_pos = nn.Parameter(torch.zeros(1, MAX_EVENTS + 1, d))
        layer = nn.TransformerDecoderLayer(d, c.n_heads, 4 * d, c.dropout, activation="gelu", batch_first=True, norm_first=True)
        self.decoder = nn.TransformerDecoder(layer, c.dec_layers)
        self.dec_norm = nn.LayerNorm(d)
        self.ahead_head = nn.Linear(d, N_AHEAD)
        self.phase_head = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, GRID))

        self.local_proj = nn.Linear((2 * c.local_frames + 1) * hd, d)
        self.note_mlp = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.LayerNorm(d))
        self.type_head = nn.Linear(d, N_TYPE)
        self.len_head = nn.Linear(d, N_LEN)
        self.sv_head = nn.Linear(d, N_SV)
        self.delta_head = nn.Linear(d, 1)

        for p in (self.enc_pos, self.plan_pos, self.dec_pos, self.bos):
            nn.init.normal_(p, std=0.02)

    # ---- encoder ---------------------------------------------------------------
    def encode(self, mel):
        """Grid-free music representation."""
        hi, lo = self.frontend(mel.float())
        T = lo.shape[1]
        mem = self.enc_norm(self.encoder(lo + self.enc_pos[:, :T]))
        return hi, mem

    def with_grid(self, mem, beat_feat):
        return mem + self.beat_proj(beat_feat[:, ::2][:, : mem.shape[1]])

    def _up(self, x, W):
        return x.repeat_interleave(2, 1)[:, :W]

    def timing_logits(self, hi, mem):
        return self.timing_head(torch.cat([hi, self._up(mem, hi.shape[1])], -1))  # [B, W, 2]

    def kiai_logits(self, hi, mem_g):
        return self.kiai_head(torch.cat([hi, self._up(mem_g, hi.shape[1])], -1)).squeeze(-1)

    # ---- planner -----------------------------------------------------------------
    def plan(self, mem_g, frame_section, tier):
        return self.plan_full(mem_g, frame_section, tier)[:3]

    def plan_full(self, mem_g, frame_section, tier):
        """(log1p density, subdivision logits, section mask, gap logits, ratio logits); the last two are None
        without gap_plan."""
        fs = frame_section[:, ::2][:, : mem_g.shape[1]]
        onehot = F.one_hot((fs + 1).clamp(min=0), MAX_SECTIONS + 1)[..., 1:].float()  # [B, T, S]
        count = onehot.sum(1)
        pooled = torch.einsum("bts,btd->bsd", onehot, mem_g) / count.clamp(min=1).unsqueeze(-1)
        h = self.plan_in(pooled) + self.plan_pos + self.plan_tier(tier)[:, None]
        h = self.planner(h)
        gl, rl = (self.gap_head(h), self.ratio_head(h)) if self.c.gap_plan else (None, None)
        return self.rho_head(h).squeeze(-1), self.r_head(h), count > 0, gl, rl

    @staticmethod
    def gap_probs(gap_logits, ratio_logits):
        return torch.cat([torch.softmax(gap_logits.float(), -1), torch.softmax(ratio_logits.float(), -1)], -1)

    def with_rep_hint(self, mem_g, rep_hint, frame_bar):
        if not getattr(self.c, "rep_hint", False) or rep_hint is None:
            return mem_g
        e = self.rep_proj(rep_hint.to(mem_g.dtype))
        fb = frame_bar[:, ::2][:, : mem_g.shape[1]]
        g = torch.gather(e, 1, fb.clamp(min=0).unsqueeze(-1).expand(-1, -1, e.shape[-1]))
        return mem_g + g * (fb >= 0).unsqueeze(-1).to(g.dtype)

    @staticmethod
    def corrupt_bar_plan(bp, p):
        """Make a human bar plan look like a predicted one (for windows chosen with probability p):
        density noise, gap histogram blended toward the window mean, triplet / 1/8 / big / roll / sustain shares
        shrunk, 5% of play flags flipped. Roll start and sustain are not gated by play (rolls can start or run in a
        measure without hit notes)."""
        from .dataset import GAP0, SUSTAIN
        from .gapstats import N_GAP_BINS
        B, n, _ = bp.shape
        sel = (torch.rand(B, 1, 1, device=bp.device) < p).float()
        play = bp[..., :1]
        x = bp.clone()
        x[..., 1:2] = bp[..., 1:2] * torch.exp(0.25 * torch.randn_like(bp[..., 1:2]))
        x[..., 2:6] = bp[..., 2:6] * torch.rand(B, 1, 4, device=bp.device)
        x[..., SUSTAIN] = bp[..., SUSTAIN] * (0.5 + 0.5 * torch.rand(B, 1, device=bp.device))
        g = bp[..., GAP0:GAP0 + N_GAP_BINS]
        gm = (g * play).sum(1, keepdim=True) / play.sum(1, keepdim=True).clamp(min=1)
        a = 0.6 * torch.rand(B, 1, 1, device=bp.device)
        x[..., GAP0:GAP0 + N_GAP_BINS] = ((1 - a) * g + a * gm) * play
        flip = (torch.rand(B, n, 1, device=bp.device) < 0.05).float()
        x[..., :1] = play * (1 - flip) + (1 - play) * flip
        hit_cols = [1, 2, 4, 5] + list(range(GAP0, GAP0 + N_GAP_BINS))
        x[..., hit_cols] = x[..., hit_cols] * x[..., :1]  # measures without hit notes carry no hit-note features
        x[..., :1] = x[..., :1].clamp(max=1)
        return sel * x + (1 - sel) * bp

    def with_bar_plan(self, mem_g, bar_plan, frame_bar, given=None):
        """Decoder memory + the plan of the bar each (50 fps) frame belongs to. given: [B] bool, False = no plan."""
        if not self.c.bar_plan or bar_plan is None:
            return mem_g
        B = bar_plan.shape[0]
        given = torch.ones(B, dtype=torch.bool, device=mem_g.device) if given is None else given
        bp = bar_plan.float() * given[:, None, None]
        flag = given[:, None, None].float().expand(-1, bp.shape[1], 1)
        e = self.bar_plan_proj(torch.cat([bp, flag], -1).to(mem_g.dtype))  # [B, MAX_BARS, d]
        fb = frame_bar[:, ::2][:, : mem_g.shape[1]]
        g = torch.gather(e, 1, fb.clamp(min=0).unsqueeze(-1).expand(-1, -1, e.shape[-1]))
        return mem_g + g * (fb >= 0).unsqueeze(-1).to(g.dtype)

    def plan_embedding(self, rho, r, gap=None):
        e = self.plan_r_emb(r) + self.plan_rho_proj(torch.log1p(rho.clamp(min=0)).unsqueeze(-1))
        if self.c.gap_plan and gap is not None:
            e = e + self.plan_gap_proj(gap.to(e.dtype))
        return e

    # ---- decoder -----------------------------------------------------------------
    def _gather(self, x, idx):
        return torch.gather(x, 1, idx.unsqueeze(-1).expand(-1, -1, x.shape[-1]))

    def event_tokens(self, mem_g, plan_emb, tier, ev):
        frames50 = (ev["ev_frame"] // 2).clamp(max=mem_g.shape[1] - 1)
        x = (self.ahead_emb(ev["ev_ahead"].clamp(0, N_AHEAD - 1)) + self.type_emb(ev["ev_type"].clamp(min=0))
             + self.len_emb(ev["ev_len"].clamp(min=0)) + self.sv_emb(ev["ev_sv"].clamp(min=0))
             + self.phase_emb(ev["ev_phase"]) + self.bar_emb(ev["ev_bar"])
             + self.audio_proj(self._gather(mem_g, frames50)) + self._gather(plan_emb, ev["ev_section"]))
        B = x.shape[0]
        x = torch.cat([self.bos.expand(B, -1, -1), x], 1) + self.tier_emb(tier)[:, None]
        return x + self.dec_pos[:, : x.shape[1]]

    def decode(self, tokens, mem_g, key_padding):
        L = tokens.shape[1]
        causal = torch.triu(torch.ones(L, L, dtype=torch.bool, device=tokens.device), 1)
        return self.dec_norm(self.decoder(tokens, mem_g, tgt_mask=causal, tgt_key_padding_mask=key_padding))

    def local_audio(self, hi, frames):
        k = self.c.local_frames
        offs = torch.arange(-k, k + 1, device=frames.device)
        idx = (frames.unsqueeze(-1) + offs).clamp(0, hi.shape[1] - 1)
        B, N, K = idx.shape
        g = torch.gather(hi, 1, idx.reshape(B, N * K, 1).expand(-1, -1, hi.shape[-1]))
        return self.local_proj(g.reshape(B, N, K * hi.shape[-1]))

    def phase_logits(self, h, next_ahead):
        return self.phase_head(h + self.ahead_emb(next_ahead.clamp(0, N_AHEAD - 1)))

    def note_heads(self, h, hi, plan_emb, next_ahead, next_phase, next_bar, next_frame, next_section):
        q = (h + self.ahead_emb(next_ahead.clamp(0, N_AHEAD - 1)) + self.phase_emb(next_phase) + self.bar_emb(next_bar)
             + self.local_audio(hi, next_frame) + self._gather(plan_emb, next_section))
        q = self.note_mlp(q)
        return self.type_head(q), self.len_head(q), self.sv_head(q), self.delta_head(q).squeeze(-1)

    def forward(self, batch, plan_source: str = "target"):
        hi, mem = self.encode(batch["mel"])
        mem_g = self.with_grid(mem, batch["beat_feat"])
        timing = self.timing_logits(hi, mem)
        kiai = self.kiai_logits(hi, mem_g)
        rho_pred, r_logits, sec_mask, gap_logits, ratio_logits = self.plan_full(mem_g, batch["frame_section"], batch["tier"])
        if plan_source == "target":
            plan_emb = self.plan_embedding(batch["plan_rho"], batch["plan_r"], batch.get("plan_gap"))
        else:
            gp = self.gap_probs(gap_logits, ratio_logits).detach() if gap_logits is not None else None
            plan_emb = self.plan_embedding(rho_pred.detach().expm1().clamp(min=0), r_logits.argmax(-1), gp)
        mem_g = self.with_rep_hint(mem_g, batch.get("rep_hint"), batch["frame_bar"])
        if self.c.bar_plan:
            given = torch.ones(mem_g.shape[0], dtype=torch.bool, device=mem_g.device)
            bp = batch["bar_plan"]
            if self.training:
                given = torch.rand(mem_g.shape[0], device=mem_g.device) >= self.c.bar_plan_drop
                if getattr(self.c, "bar_plan_corrupt", 0.0) > 0:
                    bp = self.corrupt_bar_plan(bp.float(), self.c.bar_plan_corrupt)
            mem_g = self.with_bar_plan(mem_g, bp, batch["frame_bar"], given)
        tokens = self.event_tokens(mem_g, plan_emb, batch["tier"], batch)
        pad = torch.cat([torch.zeros_like(batch["ev_mask"][:, :1]), ~batch["ev_mask"]], 1)
        h = self.decode(tokens, mem_g, pad)
        type_logits, len_logits, sv_logits, delta = self.note_heads(
            h[:, :-1], hi, plan_emb, batch["ev_ahead"], batch["ev_phase"], batch["ev_bar"], batch["ev_frame"], batch["ev_section"])
        return {"ahead_logits": self.ahead_head(h), "phase_logits": self.phase_logits(h, batch["tgt_ahead"]),
                "type_logits": type_logits, "len_logits": len_logits,
                "sv_logits": sv_logits, "delta": delta, "rho_pred": rho_pred, "r_logits": r_logits,
                "sec_mask": sec_mask, "timing_logits": timing, "kiai_logits": kiai,
                "gap_logits": gap_logits, "ratio_logits": ratio_logits}


DEFAULT_WEIGHTS = {"note": 1.0, "length": 0.5, "timing": 0.05, "plan": 0.5, "beat": 1.0, "kiai": 0.3, "sv": 0.3, "gap": 0.5}


def b0_loss(out, batch, weights: dict[str, float], type_class_weight: torch.Tensor | None = None):
    m = batch["ev_mask"]
    L = {}
    L["pos"] = F.cross_entropy(out["ahead_logits"].flatten(0, 1).float(), batch["tgt_ahead"].flatten(), ignore_index=-100) + \
        F.cross_entropy(out["phase_logits"].flatten(0, 1).float(), batch["tgt_phase"].flatten(), ignore_index=-100)
    L["note"] = F.cross_entropy(out["type_logits"].flatten(0, 1).float(), batch["ev_type"].flatten(),
                                weight=type_class_weight, ignore_index=-100)
    # length only for rolls and balloons (type >= 4): hit notes always have length 0, so a loss over every note teaches the
    # head that length 0 is almost always right, and a roll then gets no body at generation
    # Divided by the number of ALL notes, so each roll gets the same gradient as before and the term stays small next to
    # position and type (they share the note query); averaging over rolls only made it ~200x larger.
    is_roll = batch["ev_type"] >= 4
    len_tgt = torch.where(is_roll, batch["ev_len"], torch.full_like(batch["ev_len"], -100))
    n_ev = (batch["ev_type"] != -100).sum().clamp(min=1)
    L["length"] = F.cross_entropy(out["len_logits"].flatten(0, 1).float(), len_tgt.flatten(), ignore_index=-100, reduction="sum") / n_ev
    L["sv"] = F.cross_entropy(out["sv_logits"].flatten(0, 1).float(), batch["ev_sv"].flatten(), ignore_index=-100)
    L["timing"] = (F.huber_loss(out["delta"].float(), batch["ev_delta"], reduction="none", delta=5.0) * m).sum() / m.sum().clamp(min=1)
    sm = out["sec_mask"]
    rho_t = torch.log1p(batch["plan_rho"])
    L["plan"] = ((out["rho_pred"].float() - rho_t) ** 2 * sm).sum() / sm.sum().clamp(min=1) + \
        (F.cross_entropy(out["r_logits"].float().transpose(1, 2), batch["plan_r"], reduction="none") * sm).sum() / sm.sum().clamp(min=1)
    if out.get("gap_logits") is not None:  # soft cross-entropy to each section's gap / ratio distribution
        from .gapstats import N_GAP_BINS
        tg = batch["plan_gap"].float()
        lg = 0.0
        for logits, t in ((out["gap_logits"], tg[..., :N_GAP_BINS]), (out["ratio_logits"], tg[..., N_GAP_BINS:])):
            mm = sm & (t.sum(-1) > 0)
            ce = -(t * torch.log_softmax(logits.float(), -1)).sum(-1)
            lg = lg + (ce * mm).sum() / mm.sum().clamp(min=1)
        L["gap"] = lg
    bm = batch["beat_mask"]
    tl = out["timing_logits"].float()
    pw = torch.tensor(8.0, device=tl.device)  # beats are ~2% of frames
    beat_l = F.binary_cross_entropy_with_logits(tl[..., 0], batch["beat_tgt"], pos_weight=pw, reduction="none")
    down_l = F.binary_cross_entropy_with_logits(tl[..., 1], batch["down_tgt"], pos_weight=pw * 4, reduction="none")
    L["beat"] = ((beat_l + down_l) * bm).sum() / bm.sum().clamp(min=1)
    km = batch["kiai_mask"]
    L["kiai"] = (F.binary_cross_entropy_with_logits(out["kiai_logits"].float(), batch["kiai_tgt"], reduction="none") * km).sum() / km.sum().clamp(min=1)
    w = {**DEFAULT_WEIGHTS, **weights}
    total = L["pos"] + sum(w[k] * L[k] for k in ("note", "length", "sv", "timing", "plan", "beat", "kiai", "gap") if k in L)
    return total, {k: v.detach() for k, v in L.items()}


class DecodeCache:
    """Incremental decoding for B0's event decoder: keys and values of past events per layer, and
    the cross-attention keys and values of the music memory (computed once). Gives the same
    outputs as decode() on the full prefix (eval mode), at O(L) instead of O(L^2) per step."""

    def __init__(self, model: B0, mem_g):
        self.model, self.layers = model, list(model.decoder.layers)
        self.k, self.v, self.ck, self.cv = [], [], [], []
        for layer in self.layers:
            a = layer.multihead_attn
            d = a.embed_dim
            w, b = a.in_proj_weight, a.in_proj_bias
            self.ck.append(self._heads(F.linear(mem_g, w[d:2 * d], b[d:2 * d]), a.num_heads))
            self.cv.append(self._heads(F.linear(mem_g, w[2 * d:], b[2 * d:]), a.num_heads))
            self.k.append(None)
            self.v.append(None)

    @staticmethod
    def _heads(x, h):
        B, L, D = x.shape
        return x.view(B, L, h, D // h).transpose(1, 2)

    def step(self, x):
        """x: [B, n, d] new tokens (n >= 1, appended after the cached ones). Returns dec_norm output [B, n, d]."""
        for i, layer in enumerate(self.layers):
            sa = layer.self_attn
            h, d = sa.num_heads, sa.embed_dim
            q, k, v = F.linear(layer.norm1(x), sa.in_proj_weight, sa.in_proj_bias).chunk(3, -1)
            q, k, v = self._heads(q, h), self._heads(k, h), self._heads(v, h)
            n = q.shape[2]
            if self.k[i] is not None:
                k, v = torch.cat([self.k[i], k], 2), torch.cat([self.v[i], v], 2)
            self.k[i], self.v[i] = k, v
            L = k.shape[2]
            mask = None
            if n > 1:  # causal within the new block
                mask = torch.ones(n, L, dtype=torch.bool, device=x.device).tril(L - n)
            o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
            x = x + sa.out_proj(o.transpose(1, 2).reshape(x.shape[0], n, d))
            ca = layer.multihead_attn
            q = self._heads(F.linear(layer.norm2(x), ca.in_proj_weight[:d], ca.in_proj_bias[:d]), h)
            o = F.scaled_dot_product_attention(q, self.ck[i], self.cv[i])
            x = x + ca.out_proj(o.transpose(1, 2).reshape(x.shape[0], n, d))
            x = x + layer._ff_block(layer.norm3(x))
        return self.model.dec_norm(x)