File size: 5,698 Bytes
7e2301f | 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 | """Score Clock: time-indexed conditioning that tells the AR backbone *when* things should happen.
For every 25 Hz latent frame f (covering [f/25, (f+1)/25) s) we compute features of the
musical score (or speech duration target) active at that wall-clock time:
midi active note (0..127), REST=128, NONE=129 (no score / dropped)
continuous slur, note position fraction, onset flag + sub-frame onset offset,
beat phase (sin, cos) + has_beat, log-F0 + voiced + has_f0,
speech progress + has_progress, vibrato depth/rate, breathiness + has_style
The head receives these per frame (onset accuracy at ~20-30 ms needs sub-patch resolution);
the backbone receives them pooled per patch (80 ms), plus an optional syllable-lag embedding
("emitted syllables minus scheduled syllables") so it can catch up when it drifts.
"""
from __future__ import annotations
import math
from dataclasses import dataclass, field
import torch
import torch.nn as nn
REST, NONE = 128, 129
N_CONT = 16
MAX_LAG = 8
@dataclass
class Note:
onset: float # seconds
duration: float # seconds
midi: int # 0..127, or REST
slur: bool = False
syllable: int = -1 # index into the lyric syllables, -1 for rests / melisma continuation
@dataclass
class Score:
notes: list[Note] = field(default_factory=list)
tempo_bpm: float | None = None
vibrato_depth: float | None = None # semitones
vibrato_rate: float | None = None # Hz
breathiness: float | None = None # 0..1
def transpose(self, semitones: int) -> "Score":
notes = [Note(n.onset, n.duration, n.midi if n.midi == REST else min(max(n.midi + semitones, 0), 127),
n.slur, n.syllable) for n in self.notes]
return Score(notes, self.tempo_bpm, self.vibrato_depth, self.vibrato_rate, self.breathiness)
def frame_features(
n_frames: int,
score: Score | None = None,
f0: torch.Tensor | None = None, # (n_frames,) Hz, 0 = unvoiced
total_duration: float | None = None, # speech mode duration control (seconds)
frame_rate: float = 25.0,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Returns midi (n_frames,) long and cont (n_frames, N_CONT) float."""
midi = torch.full((n_frames,), NONE, dtype=torch.long)
cont = torch.zeros(n_frames, N_CONT)
t0 = torch.arange(n_frames) / frame_rate # frame start times
if score is not None:
midi.fill_(REST)
for n in score.notes:
start_f, end_f = n.onset * frame_rate, (n.onset + n.duration) * frame_rate
lo, hi = max(int(math.floor(start_f)), 0), min(int(math.ceil(end_f)), n_frames)
if lo >= n_frames:
continue
idx = torch.arange(lo, hi)
mid = (idx + 0.5) / frame_rate
active = (mid >= n.onset) & (mid < n.onset + n.duration)
idx = idx[active]
midi[idx] = n.midi
cont[idx, 0] = float(n.slur)
cont[idx, 1] = ((idx + 0.5) / frame_rate - n.onset) / max(n.duration, 1e-3)
of = int(math.floor(start_f))
if 0 <= of < n_frames:
cont[of, 2] = 1.0
cont[of, 3] = start_f - of # sub-frame onset offset in [0, 1)
if score.tempo_bpm:
phase = 2 * math.pi * t0 * score.tempo_bpm / 60.0
cont[:, 4], cont[:, 5], cont[:, 6] = torch.sin(phase), torch.cos(phase), 1.0
if score.vibrato_depth is not None or score.vibrato_rate is not None or score.breathiness is not None:
cont[:, 12] = score.vibrato_depth or 0.0
cont[:, 13] = (score.vibrato_rate or 0.0) / 10.0
cont[:, 14] = score.breathiness or 0.0
cont[:, 15] = 1.0
if f0 is not None:
f0 = f0[:n_frames].float()
voiced = f0 > 0
cont[: len(f0), 7] = torch.where(voiced, (torch.log(f0.clamp(min=1.0)) - math.log(200.0)) / 1.0, 0.0)
cont[: len(f0), 8] = voiced.float()
cont[: len(f0), 9] = 1.0
if total_duration:
cont[:, 10] = ((t0 + 0.5 / frame_rate) / total_duration).clamp(max=1.5)
cont[:, 11] = 1.0
return midi, cont
def null_features(n_frames: int) -> tuple[torch.Tensor, torch.Tensor]:
return torch.full((n_frames,), NONE, dtype=torch.long), torch.zeros(n_frames, N_CONT)
class ScoreClockEmbed(nn.Module):
"""Frame features -> (frame-level emb for the head, patch-level emb for the backbone)."""
def __init__(self, frame_dim: int, backbone_dim: int, patch: int):
super().__init__()
self.patch = patch
self.midi = nn.Embedding(NONE + 1, frame_dim)
self.cont = nn.Linear(N_CONT, frame_dim)
self.frame_mlp = nn.Sequential(nn.SiLU(), nn.Linear(frame_dim, frame_dim))
self.to_patch = nn.Linear(frame_dim * patch, backbone_dim)
self.lag = nn.Embedding(2 * MAX_LAG + 2, backbone_dim) # last index = unknown
nn.init.zeros_(self.to_patch.weight)
nn.init.zeros_(self.to_patch.bias)
nn.init.zeros_(self.lag.weight) # start as a no-op on the pretrained LLM
def forward(self, midi: torch.Tensor, cont: torch.Tensor, lag: torch.Tensor | None = None):
"""midi: (B, F) long, cont: (B, F, N_CONT); F divisible by patch.
Returns frame_emb (B, F, frame_dim), patch_emb (B, F // patch, backbone_dim)."""
frame = self.frame_mlp(self.midi(midi) + self.cont(cont.to(self.cont.weight.dtype)))
B, Fn, D = frame.shape
patch = self.to_patch(frame.reshape(B, Fn // self.patch, self.patch * D))
if lag is not None:
patch = patch + self.lag(torch.where(lag.abs() > MAX_LAG, 2 * MAX_LAG + 1, lag + MAX_LAG))
return frame, patch
|