File size: 26,824 Bytes
f859cdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
#!/usr/bin/env python3
"""MidiGen v3 model, masking, binning, and loss helpers."""
from __future__ import annotations

import math
import warnings
from dataclasses import dataclass

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

try:
    from torch.nn.attention.flex_attention import (
        BlockMask,
        create_block_mask,
        flex_attention as _raw_flex_attention,
    )
    FLEX_ATTENTION_AVAILABLE = True
    # flex_attention warns and materializes full scores unless compiled.
    _flex_attention = torch.compile(_raw_flex_attention, dynamic=False)
except Exception:
    BlockMask = None
    create_block_mask = None
    _flex_attention = None
    FLEX_ATTENTION_AVAILABLE = False

_WARNED_FLEX_MASK_FALLBACK = False


# ══════════════════════════════════════════════════════════════════════════════
#  Model constants
# ══════════════════════════════════════════════════════════════════════════════

D_MODEL      = 512
N_HEADS      = 8
assert D_MODEL % N_HEADS == 0
HEAD_DIM     = D_MODEL // N_HEADS   # 64
N_LAYERS     = 16
FFN_DIM      = 1408
SEQ_LEN      = 2048
SLIDING_WINDOW = 512
DEFAULT_DROPOUT = 0.0
XPOS_SCALE_BASE = 512               # attention matrix decays as exp(-distance/XPOS_SCALE_BASE) so we get 1/3 damping at distance=512
FLEX_BLOCK_SIZE = 128

D_TIME_EMB  = 160
D_TRACK_EMB = 32
D_INST_EMB  = 64
D_PITCH_EMB = 160
D_DUR_EMB   = 96
assert D_TIME_EMB + D_TRACK_EMB + D_INST_EMB + D_PITCH_EMB + D_DUR_EMB == D_MODEL

N_TIME_BINS  = 140
SEP_BIN      = N_TIME_BINS          # <SEP> index in the time head (total outputs = N_TIME_BINS + 1)
N_DUR_BINS   = 140
TIME_CEIL_SECONDS = 6.0
DUR_CEIL_SECONDS = 6.0
TIME_LOG_NORM = math.log1p(TIME_CEIL_SECONDS)
DUR_LOG_NORM = math.log1p(DUR_CEIL_SECONDS)

N_PITCH_CLASSES = 256
N_TRACK_CLASSES = 128
N_INSTR_CLASSES = 137

TOP_P       = 0.95
TEMPERATURE = 1.0

BPM         = 120
TPQ         = 480
TICKS_PER_S = BPM / 60.0 * TPQ   # 960 ticks/s at 120 BPM


# ══════════════════════════════════════════════════════════════════════════════
#  Utility functions
# ══════════════════════════════════════════════════════════════════════════════

def build_rope_freqs(
    seq_len: int,
    head_dim: int,
    device: torch.device,
    start_pos: int = 0,
) -> torch.Tensor:
    """Returns [seq_len, head_dim] RoPE frequency cache for absolute positions."""
    half  = head_dim // 2
    theta = 1.0 / (10000 ** (torch.arange(0, half, device=device).float() / half))
    t     = torch.arange(start_pos, start_pos + seq_len, device=device).float()
    freqs = torch.outer(t, theta)           # [seq_len, half]
    return torch.cat([freqs, freqs], dim=-1)  # [seq_len, head_dim]


def build_xpos_scale(
    seq_len: int,
    device: torch.device,
    scale_base: float = XPOS_SCALE_BASE,
    start_pos: int = 0,
) -> torch.Tensor:
    """Returns uniform xPos scale [seq_len, 1] for stable absolute positions."""
    center = SEQ_LEN // 2
    pos = torch.arange(start_pos, start_pos + seq_len, device=device).float()
    return torch.exp((pos - center) / scale_base)[:, None]


def rotate_half(x: torch.Tensor) -> torch.Tensor:
    h = x.shape[-1] // 2
    return torch.cat([-x[..., h:], x[..., :h]], dim=-1)


def apply_rope(
    x: torch.Tensor,
    freqs: torch.Tensor,
    scale: torch.Tensor | None = None,
) -> torch.Tensor:
    """x: [B, H, T, D], freqs: [T, D], scale: optional [T, 1]."""
    cos = freqs.cos().to(dtype=x.dtype)[None, None]
    sin = freqs.sin().to(dtype=x.dtype)[None, None]
    out = x * cos + rotate_half(x) * sin
    if scale is not None:
        out = out * scale.to(dtype=x.dtype)[None, None]
    return out


def _sample_top_p(logits: torch.Tensor, p: float, temperature: float) -> torch.Tensor:
    """Top-P (nucleus) sampling. logits: [..., V] β†’ sampled indices [...]."""
    logits = logits / temperature
    probs  = F.softmax(logits, dim=-1)
    sorted_probs, sorted_idx = probs.sort(dim=-1, descending=True)
    cum = sorted_probs.cumsum(dim=-1)
    sorted_probs[cum - sorted_probs > p] = 0.0
    sorted_probs /= sorted_probs.sum(dim=-1, keepdim=True).clamp(min=1e-8)
    flat_p   = sorted_probs.reshape(-1, sorted_probs.shape[-1])
    sampled  = torch.multinomial(flat_p, 1).reshape(*logits.shape[:-1])   # [...]
    flat_idx = sorted_idx.reshape(-1, sorted_idx.shape[-1])
    bi       = torch.arange(sampled.numel(), device=logits.device)
    return flat_idx[bi, sampled.reshape(-1)].reshape(sampled.shape)


def _seconds_to_bin(
    x: torch.Tensor,
    n_bins: int,
    ceil_seconds: float = TIME_CEIL_SECONDS,
) -> torch.Tensor:
    """Map raw seconds to integer bins [0, n_bins - 1] with the model's log time scale."""
    log_norm = math.log1p(ceil_seconds)
    return (torch.log1p(x.clamp(0.0, ceil_seconds)) / log_norm * (n_bins - 1)).round().long()


def notes_to_input_bins(notes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    """Convert raw note rows to categorical input bins for embedding."""
    is_sep = notes[:, :, 0] < 0.0
    time_bins = _seconds_to_bin(notes[:, :, 0], N_TIME_BINS)
    time_bins = torch.where(is_sep, time_bins.new_full(time_bins.shape, SEP_BIN), time_bins)

    track_bins = notes[:, :, 1].round().long().clamp(0, N_TRACK_CLASSES - 1)
    track_bins = torch.where(is_sep, track_bins.new_zeros(track_bins.shape), track_bins)

    inst_bins = notes[:, :, 2].round().long().clamp(0, N_INSTR_CLASSES - 1)
    inst_bins = torch.where(is_sep, inst_bins.new_zeros(inst_bins.shape), inst_bins)

    pitch_bins = notes[:, :, 3].round().long().clamp(0, N_PITCH_CLASSES - 1)
    pitch_bins = torch.where(is_sep, pitch_bins.new_zeros(pitch_bins.shape), pitch_bins)

    dur_bins = _seconds_to_bin(notes[:, :, 4], N_DUR_BINS, DUR_CEIL_SECONDS)
    dur_bins = torch.where(is_sep, dur_bins.new_zeros(dur_bins.shape), dur_bins)
    return time_bins, track_bins, inst_bins, pitch_bins, dur_bins


# ══════════════════════════════════════════════════════════════════════════════
#  Model components
# ══════════════════════════════════════════════════════════════════════════════

@dataclass
class AttentionContext:
    bool_mask: torch.Tensor | None = None
    block_mask: BlockMask | None = None
    is_causal: bool = True


def _causal_sliding_bool_mask(
    q_len: int,
    key_len: int,
    device: torch.device,
    window: int = SLIDING_WINDOW,
) -> torch.Tensor:
    q_pos = key_len - q_len + torch.arange(q_len, device=device)
    k_pos = torch.arange(key_len, device=device)
    distance = q_pos[:, None] - k_pos[None, :]
    return (distance >= 0) & (distance < int(window))


def _build_doc_attention_context(
    doc_ids: torch.Tensor | None,
    *,
    device: torch.device,
    seq_len: int,
    prefer_flex: bool = True,
) -> AttentionContext | None:
    if doc_ids is None:
        return None

    doc_ids = doc_ids.to(device=device)
    if prefer_flex and FLEX_ATTENTION_AVAILABLE and create_block_mask is not None and device.type == "cuda":
        try:
            def doc_mask_mod(
                b: torch.Tensor,
                h: torch.Tensor,
                q_idx: torch.Tensor,
                kv_idx: torch.Tensor,
            ) -> torch.Tensor:
                distance = q_idx - kv_idx
                return (
                    (distance >= 0)
                    & (distance < SLIDING_WINDOW)
                    & (doc_ids[b, q_idx] == doc_ids[b, kv_idx])
                )

            return AttentionContext(
                block_mask=create_block_mask(
                    doc_mask_mod,
                    B=doc_ids.shape[0],
                    H=None,
                    Q_LEN=seq_len,
                    KV_LEN=seq_len,
                    device=device,
                    BLOCK_SIZE=FLEX_BLOCK_SIZE,
                    _compile=True,
                ),
                is_causal=False,
            )
        except Exception as exc:
            global _WARNED_FLEX_MASK_FALLBACK
            if not _WARNED_FLEX_MASK_FALLBACK:
                warnings.warn(
                    "flex_attention block-mask creation failed; falling back to "
                    f"SDPA with a dense bool mask. Error: {type(exc).__name__}: {exc}",
                    RuntimeWarning,
                    stacklevel=2,
                )
                _WARNED_FLEX_MASK_FALLBACK = True

    causal_window = _causal_sliding_bool_mask(seq_len, seq_len, device)
    same_doc = doc_ids[:, :, None] == doc_ids[:, None, :]
    return AttentionContext(
        bool_mask=same_doc[:, None, :, :] & causal_window[None, None, :, :],
        is_causal=False,
    )


class NoteEmbedder(nn.Module):
    """Maps float note tensors [B, T, 5] to categorical embeddings."""

    def __init__(self):
        super().__init__()
        self.sep_embedding = nn.Parameter(torch.zeros(D_MODEL))
        self.time_embed  = nn.Embedding(N_TIME_BINS + 1, D_TIME_EMB)
        self.track_embed = nn.Embedding(N_TRACK_CLASSES, D_TRACK_EMB)
        self.inst_embed  = nn.Embedding(N_INSTR_CLASSES, D_INST_EMB)
        self.pitch_embed = nn.Embedding(N_PITCH_CLASSES, D_PITCH_EMB)
        self.dur_embed   = nn.Embedding(N_DUR_BINS, D_DUR_EMB)

    def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        """Returns (emb [B, T, D_MODEL], is_sep [B, T])."""
        is_sep = x[:, :, 0] < 0.0
        time_b, track_b, inst_b, pitch_b, dur_b = notes_to_input_bins(x)
        emb = torch.cat([
            self.time_embed(time_b),
            self.track_embed(track_b),
            self.inst_embed(inst_b),
            self.pitch_embed(pitch_b),
            self.dur_embed(dur_b),
        ], dim=-1)
        emb = torch.where(is_sep[:, :, None], self.sep_embedding[None, None, :], emb)
        return emb, is_sep


class CausalSelfAttention(nn.Module):

    def __init__(self, dropout: float = DEFAULT_DROPOUT):
        super().__init__()
        self.qkv  = nn.Linear(D_MODEL, 3 * D_MODEL, bias=False)
        self.proj = nn.Linear(D_MODEL, D_MODEL, bias=False)
        self.dropout_p = float(dropout)

    def forward(
        self,
        x: torch.Tensor,
        rope_freqs: torch.Tensor,
        xpos_scale: torch.Tensor,
        attn_context: AttentionContext | None = None,
        kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None,
        use_cache: bool = False,
    ) -> torch.Tensor | tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
        B, T, _ = x.shape
        q, k, v = self.qkv(x).reshape(B, T, 3, N_HEADS, HEAD_DIM).unbind(2)
        q = apply_rope(q.transpose(1, 2), rope_freqs, 1.0 / xpos_scale)   # [B, H, T, D]
        k = apply_rope(k.transpose(1, 2), rope_freqs, xpos_scale)
        v = v.transpose(1, 2)

        past_len = 0
        if kv_cache is not None:
            past_k, past_v = kv_cache
            past_len = past_k.shape[-2]
            k = torch.cat([past_k, k], dim=-2)
            v = torch.cat([past_v, v], dim=-2)

        if kv_cache is not None and use_cache and k.shape[-2] > SLIDING_WINDOW:
            k = k[:, :, -SLIDING_WINDOW:, :]
            v = v[:, :, -SLIDING_WINDOW:, :]
            past_len = max(0, k.shape[-2] - T)

        key_len = k.shape[-2]
        if attn_context is not None:
            if key_len != T:
                raise ValueError("document masking is not supported with a non-empty KV cache")
            if attn_context.block_mask is not None:
                if _flex_attention is None:
                    raise RuntimeError("attention context has a block mask but flex_attention is unavailable")
                out = _flex_attention(q, k, v, block_mask=attn_context.block_mask)
                out = self.proj(out.transpose(1, 2).reshape(B, T, D_MODEL))
                if use_cache:
                    return out, (k, v)
                return out
            elif attn_context.bool_mask is not None:
                attn_mask = attn_context.bool_mask
                is_causal = attn_context.is_causal
            else:
                raise RuntimeError("attention context has no usable mask")
        elif past_len:
            attn_mask = _causal_sliding_bool_mask(T, key_len, x.device)[None, None, :, :]
            is_causal = False
        else:
            attn_mask = _causal_sliding_bool_mask(T, key_len, x.device)[None, None, :, :]
            is_causal = False
        out = F.scaled_dot_product_attention(
            q,
            k,
            v,
            attn_mask=attn_mask,
            dropout_p=self.dropout_p if self.training else 0.0,
            is_causal=is_causal,
        )
        out = self.proj(out.transpose(1, 2).reshape(B, T, D_MODEL))
        if use_cache:
            if k.shape[-2] > SLIDING_WINDOW:
                k = k[:, :, -SLIDING_WINDOW:, :]
                v = v[:, :, -SLIDING_WINDOW:, :]
            return out, (k, v)
        return out


class RMSNorm(nn.Module):

    def __init__(self, dim: int, eps: float = 1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(dim))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        rms = x.pow(2).mean(dim=-1, keepdim=True).add(self.eps).rsqrt()
        return x * rms * self.weight


class SwiGLUFeedForward(nn.Module):

    def __init__(self, dropout: float = DEFAULT_DROPOUT):
        super().__init__()
        self.gate = nn.Linear(D_MODEL, FFN_DIM)
        self.up   = nn.Linear(D_MODEL, FFN_DIM)
        self.down = nn.Linear(FFN_DIM, D_MODEL)
        self.drop = nn.Dropout(dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.down(self.drop(F.silu(self.gate(x)) * self.up(x)))


class TransformerBlock(nn.Module):

    def __init__(self, dropout: float = DEFAULT_DROPOUT, *, attention_dropout: float | None = None):
        super().__init__()
        self.norm1 = RMSNorm(D_MODEL)
        self.attn  = CausalSelfAttention(dropout if attention_dropout is None else attention_dropout)
        self.norm2 = RMSNorm(D_MODEL)
        self.ffn   = SwiGLUFeedForward(dropout)
        self.drop = nn.Dropout(dropout)

    def forward(
        self,
        x: torch.Tensor,
        rope_freqs: torch.Tensor,
        xpos_scale: torch.Tensor,
        attn_context: AttentionContext | None = None,
        kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None,
        use_cache: bool = False,
    ) -> torch.Tensor | tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
        attn_out = self.attn(self.norm1(x), rope_freqs, xpos_scale, attn_context, kv_cache, use_cache)
        new_cache = None
        if use_cache:
            attn_tensor, new_cache = attn_out
        else:
            attn_tensor = attn_out
        x = x + self.drop(attn_tensor)
        x = x + self.drop(self.ffn(self.norm2(x)))
        if use_cache:
            return x, new_cache
        return x


class CascadedHead(nn.Module):
    """Intra-event categorical output head: Time -> Track -> Instrument -> Pitch -> Duration."""

    def __init__(self):
        super().__init__()
        self.time_head          = nn.Linear(D_MODEL, N_TIME_BINS + 1)
        self.time_to_track_embed = nn.Embedding(N_TIME_BINS + 1, D_MODEL)
        self.track_head         = nn.Linear(D_MODEL, N_TRACK_CLASSES)
        self.track_to_inst_embed = nn.Embedding(N_TRACK_CLASSES, D_MODEL)
        self.inst_head          = nn.Linear(D_MODEL, N_INSTR_CLASSES)
        self.inst_to_pitch_embed = nn.Embedding(N_INSTR_CLASSES, D_MODEL)
        self.pitch_head         = nn.Linear(D_MODEL, N_PITCH_CLASSES)
        self.pitch_to_dur_embed = nn.Embedding(N_PITCH_CLASSES, D_MODEL)
        self.dur_head           = nn.Linear(D_MODEL, N_DUR_BINS)

    def forward(
        self,
        h: torch.Tensor,
        tgt_time_bin: torch.Tensor,
        tgt_track_bin: torch.Tensor,
        tgt_inst_bin: torch.Tensor,
        tgt_pitch_bin: torch.Tensor,
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:

        time_logits = self.time_head(h)
        c_track = h + self.time_to_track_embed(tgt_time_bin.clamp(0, SEP_BIN))
        track_logits = self.track_head(c_track)

        track_for_inst = tgt_track_bin.clamp(0, N_TRACK_CLASSES - 1)
        c_inst = c_track + self.track_to_inst_embed(track_for_inst)
        inst_logits = self.inst_head(c_inst)

        inst_for_pitch = tgt_inst_bin.clamp(0, N_INSTR_CLASSES - 1)
        c_pitch = c_inst + self.inst_to_pitch_embed(inst_for_pitch)
        pitch_logits = self.pitch_head(c_pitch)

        pitch_for_dur = tgt_pitch_bin.clamp(0, N_PITCH_CLASSES - 1)
        c_dur = c_pitch + self.pitch_to_dur_embed(pitch_for_dur)
        dur_logits = self.dur_head(c_dur)
        return time_logits, track_logits, inst_logits, pitch_logits, dur_logits


class MidiTransformer(nn.Module):

    def __init__(self, dropout: float = DEFAULT_DROPOUT, *, attention_dropout: float | None = None):
        super().__init__()
        self.dropout = float(dropout)
        self.attention_dropout = self.dropout if attention_dropout is None else float(attention_dropout)
        if not 0.0 <= self.attention_dropout <= 1.0:
            raise ValueError("attention_dropout must be between 0 and 1")
        self.embedder = NoteEmbedder()
        self.drop     = nn.Dropout(dropout)
        self.blocks   = nn.ModuleList([
            TransformerBlock(dropout, attention_dropout=self.attention_dropout) for _ in range(N_LAYERS)
        ])
        self.norm     = RMSNorm(D_MODEL)
        self.head     = CascadedHead()
        self._init_weights()

    def _init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, std=0.02)
                if m.bias is not None:
                    nn.init.zeros_(m.bias)
            elif isinstance(m, nn.Embedding):
                nn.init.normal_(m.weight, std=0.02)
            elif isinstance(m, RMSNorm):
                nn.init.ones_(m.weight)
        nn.init.normal_(self.embedder.sep_embedding, std=0.02)

    def _encode(
        self,
        x: torch.Tensor,
        doc_ids: torch.Tensor | None = None,
        kv_cache: list[tuple[torch.Tensor, torch.Tensor] | None] | None = None,
        start_pos: int = 0,
        use_cache: bool = False,
    ) -> torch.Tensor | tuple[torch.Tensor, list[tuple[torch.Tensor, torch.Tensor]]]:
        """x: [B, T, 5] -> h: [B, T, D_MODEL]. Optionally returns updated KV cache."""
        emb, _ = self.embedder(x)
        h = self.drop(emb)
        freqs = build_rope_freqs(x.shape[1], HEAD_DIM, x.device, start_pos=start_pos)
        xpos_scale = build_xpos_scale(x.shape[1], x.device, start_pos=start_pos)
        new_cache: list[tuple[torch.Tensor, torch.Tensor]] = []
        if kv_cache is None:
            kv_cache = [None] * len(self.blocks)
        attn_context = _build_doc_attention_context(
            doc_ids,
            device=x.device,
            seq_len=x.shape[1],
            prefer_flex=not (self.training and self.attention_dropout > 0.0),
        )
        for idx, block in enumerate(self.blocks):
            if use_cache:
                h, layer_cache = block(h, freqs, xpos_scale, attn_context, kv_cache[idx], use_cache=True)
                new_cache.append(layer_cache)
            else:
                h = block(h, freqs, xpos_scale, attn_context)
        h = self.norm(h)
        if use_cache:
            return h, new_cache
        return h

    def forward(
        self,
        x:       torch.Tensor,   # [B, T, 5]  inputs
        targets: torch.Tensor,   # [B, T, 5]  next-step targets
        doc_ids: torch.Tensor | None = None,
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
        h = self._encode(x, doc_ids)
        tgt_time, tgt_track, tgt_inst, tgt_pitch, _ = bin_targets(targets)
        return self.head(h, tgt_time, tgt_track, tgt_inst, tgt_pitch)

    @torch.no_grad()
    def generate(
        self,
        seed: torch.Tensor,
        n_notes: int,
        top_p: float = TOP_P,
        temperature: float = TEMPERATURE,
    ) -> list[tuple]:
        """seed: [1, T, 5]. Returns integer (time, track, instrument, pitch, duration) bins."""
        self.eval()
        device = seed.device
        ctx    = seed[:, -SEQ_LEN:, :].clone()
        notes: list[tuple[int, int, int, int, int]] = []
        h, kv_cache = self._encode(ctx, start_pos=0, use_cache=True)
        h_last = h[:, -1:, :]   # [1, 1, D_MODEL]
        next_pos = ctx.shape[1]

        for _ in range(n_notes):
            # Time
            time_logits = self.head.time_head(h_last)
            time_bin    = _sample_top_p(time_logits, top_p, temperature).item()
            if int(time_bin) == SEP_BIN:
                break

            # Track
            tb        = torch.tensor([[int(time_bin)]], dtype=torch.long, device=device)
            c_track   = h_last + self.head.time_to_track_embed(tb)
            track_bin = int(_sample_top_p(self.head.track_head(c_track), top_p, temperature).item())

            # Instrument
            tr        = torch.tensor([[track_bin]], dtype=torch.long, device=device)
            c_inst    = c_track + self.head.track_to_inst_embed(tr)
            inst_bin  = int(_sample_top_p(self.head.inst_head(c_inst), top_p, temperature).item())

            # Pitch
            it        = torch.tensor([[inst_bin]], dtype=torch.long, device=device)
            c_pitch   = c_inst + self.head.inst_to_pitch_embed(it)
            pitch_logits = self.head.pitch_head(c_pitch)
            pitch_bin = int(_sample_top_p(pitch_logits, top_p, temperature).item())

            # Duration
            pt        = torch.tensor([[pitch_bin]], dtype=torch.long, device=device)
            c_dur     = c_pitch + self.head.pitch_to_dur_embed(pt)
            dur_bin   = int(_sample_top_p(self.head.dur_head(c_dur), top_p, temperature).item())

            note = (int(time_bin), track_bin, inst_bin, pitch_bin, dur_bin)
            notes.append(note)

            next_tok = torch.tensor(
                [[[
                    _bin_to_seconds(note[0]),
                    float(note[1]),
                    float(note[2]),
                    float(note[3]),
                    _bin_to_seconds(note[4], N_DUR_BINS, DUR_CEIL_SECONDS),
                ]]],
                dtype=torch.float32, device=device,
            )
            h, kv_cache = self._encode(
                next_tok,
                kv_cache=kv_cache,
                start_pos=next_pos,
                use_cache=True,
            )
            h_last = h[:, -1:, :]
            next_pos += 1

        return notes


# ══════════════════════════════════════════════════════════════════════════════
#  Loss function
# ══════════════════════════════════════════════════════════════════════════════

def bin_targets(targets: torch.Tensor):
    """targets: [B, T, 5] -> (time, track, instrument, pitch, duration) bins, all [B, T] int64."""
    is_sep     = targets[:, :, 0] < 0.0

    time_bins  = _seconds_to_bin(targets[:, :, 0], N_TIME_BINS)
    time_bins  = torch.where(is_sep, time_bins.new_full(time_bins.shape, SEP_BIN), time_bins)

    track_bins = targets[:, :, 1].round().long().clamp(0, N_TRACK_CLASSES - 1)
    track_bins = torch.where(is_sep, track_bins.new_full(track_bins.shape, -100), track_bins)

    inst_bins = targets[:, :, 2].round().long().clamp(0, N_INSTR_CLASSES - 1)
    inst_bins = torch.where(is_sep, inst_bins.new_full(inst_bins.shape, -100), inst_bins)

    pitch_bins = targets[:, :, 3].round().long().clamp(0, N_PITCH_CLASSES - 1)
    pitch_bins = torch.where(is_sep, pitch_bins.new_full(pitch_bins.shape, -100), pitch_bins)

    dur_bins   = _seconds_to_bin(targets[:, :, 4], N_DUR_BINS, DUR_CEIL_SECONDS)
    dur_bins   = torch.where(is_sep, dur_bins.new_full(dur_bins.shape, -100), dur_bins)

    return time_bins, track_bins, inst_bins, pitch_bins, dur_bins


_CE = nn.CrossEntropyLoss(
    ignore_index=-100,
    reduction="none",
)


def compute_loss(
    time_l, track_l, inst_l, pitch_l, dur_l,
    time_b, track_b, inst_b, pitch_b, dur_b,
    loss_mask: torch.Tensor | None = None,
):
    if loss_mask is None:
        loss_mask = torch.ones_like(time_b, dtype=torch.bool)
    else:
        loss_mask = loss_mask.to(device=time_b.device, dtype=torch.bool)

    def f(logits, bins):
        flat_bins = bins.reshape(-1)
        flat_loss = _CE(logits.reshape(-1, logits.shape[-1]), flat_bins)
        active = loss_mask.reshape(-1) & (flat_bins != -100)
        denom = active.sum().clamp(min=1)
        return flat_loss[active].sum() / denom

    return (
        f(time_l, time_b)
        + f(track_l, track_b)
        + f(inst_l, inst_b)
        + f(pitch_l, pitch_b)
        + f(dur_l, dur_b)
    )


def document_ids_and_loss_mask(chunk: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Return token document ids and active target mask for a packed chunk.

    SEP belongs to the document before it. The token after a SEP starts a new
    document, so the SEP -> next-track transition is masked out of the loss.
    """
    is_sep = chunk[:, 0] < 0.0
    doc_ids = np.concatenate(([0], np.cumsum(is_sep[:-1], dtype=np.int64))).astype(np.int64)
    loss_mask = doc_ids[:-1] == doc_ids[1:]
    return doc_ids[:-1], loss_mask


def _bin_to_seconds(
    bin_idx: int,
    n_bins: int = N_TIME_BINS,
    ceil_seconds: float = TIME_CEIL_SECONDS,
) -> float:
    """Map a time/duration bin [0, n_bins - 1] to seconds via inverse log-norm."""
    log_norm = math.log1p(ceil_seconds)
    return min(math.exp((bin_idx / (n_bins - 1)) * log_norm) - 1.0, ceil_seconds)