File size: 11,468 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
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
"""PhotonTTS: the full text(+speaker+score) -> latent model.

Per-sample backbone sequence (right-padded across the batch):

    [speaker tokens (N_s)] [text tokens (L_t)] [<audio> + clock_0] [patch_0 + clock_1] ... [patch_{P-1} + 0]
                                                     |                  |                       |
                                         h_0 -> head predicts patch_0   h_1 -> patch_1    h_P -> stop

`text_ids` already contains control tokens (mode / lang / bandwidth / style) and, for the
in-context path B, the prompt transcript followed by the target text; the prompt's latents
are the first `loss_start` frames of `latents` and are excluded from the losses.
"""

from __future__ import annotations

from dataclasses import dataclass

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

from .. import LATENT_DIM
from ..conditioning.score_clock import NONE, REST, ScoreClockEmbed, null_features
from ..conditioning.speaker_encoder import SpeakerEncoder
from ..config import PhotonConfig
from .aux_heads import CTCHead, StopHead
from .backbone import build_backbone
from .photon_head import PhotonHead


@dataclass
class PhotonBatch:
    text_ids: list[torch.Tensor]  # B x (L_t,) long
    latents: torch.Tensor  # (B, F, D), F multiple of patch, right-padded
    latent_lens: torch.Tensor  # (B,) frames, multiples of patch
    loss_start: torch.Tensor  # (B,) frame where the target region starts (multiple of patch)
    ref_latents: torch.Tensor | None = None  # (B, F_r, D)
    ref_mask: torch.Tensor | None = None  # (B, F_r) bool
    has_ref: torch.Tensor | None = None  # (B,) bool
    clock_midi: torch.Tensor | None = None  # (B, F) long
    clock_cont: torch.Tensor | None = None  # (B, F, N_CONT)
    clock_lag: torch.Tensor | None = None  # (B, F // patch) long
    ctc_targets: torch.Tensor | None = None  # (B, L_c) long, padded
    ctc_lens: torch.Tensor | None = None  # (B,)

    def to(self, device):
        mv = lambda x: x.to(device) if isinstance(x, torch.Tensor) else x
        return PhotonBatch(**{k: ([mv(t) for t in v] if isinstance(v, list) else mv(v)) for k, v in self.__dict__.items()})


class PhotonTTS(nn.Module):
    def __init__(self, cfg: PhotonConfig, vocab_size: int):
        super().__init__()
        self.cfg = cfg
        self.patch = p = cfg.patch
        D = cfg.codec.latent_dim
        self.backbone = build_backbone(cfg.backbone, vocab_size)
        H = self.backbone.config.hidden_size
        self.hidden = H
        self.audio_in = nn.Linear(p * D, H)
        self.audio_bos = nn.Parameter(torch.randn(H) * 0.02)
        self.speaker = SpeakerEncoder(cfg.speaker, D, H)
        self.clock = ScoreClockEmbed(cfg.clock.frame_dim, H, p)
        self.head = PhotonHead(cfg.head, D, p, H, frame_cond_dim=cfg.clock.frame_dim)
        self.stop = StopHead(H)
        self.ctc = CTCHead(H, cfg.loss.ctc_upsample)
        self.n_ctx = self.head.n_ctx

    # ------------------------------------------------------------------ helpers
    def _speaker_tokens(self, ref, ref_mask, has_ref, B, device, drop_p=0.0):
        null = self.speaker.null(B).to(device)
        if ref is None or has_ref is None or not bool(has_ref.any()):
            return null, None
        tok, emo = self.speaker(ref, ref_mask)
        keep = has_ref.clone()
        if drop_p > 0 and self.training:
            keep &= torch.rand(B, device=device) >= drop_p
        return torch.where(keep[:, None, None], tok, null), emo

    def _clock(self, midi, cont, lag, B, Fn, device, drop_p=0.0):
        if midi is None:
            m, c = null_features(Fn)
            midi, cont = m[None].expand(B, -1).to(device), c[None].expand(B, -1, -1).to(device)
        elif drop_p > 0 and self.training:
            drop = torch.rand(B, device=device) < drop_p
            midi = torch.where(drop[:, None], torch.full_like(midi, NONE), midi)
            cont = torch.where(drop[:, None, None], torch.zeros_like(cont), cont)
        return self.clock(midi, cont, lag)

    def _windows(self, x):  # (B, F, C) -> (B, P, n_ctx + patch, C): context + target frames per patch
        x = F.pad(x, (0, 0, self.n_ctx, 0))
        return x.unfold(1, self.n_ctx + self.patch, self.patch).permute(0, 1, 3, 2)

    # ------------------------------------------------------------------ training
    def forward(self, b: PhotonBatch) -> dict[str, torch.Tensor]:
        cfg, p = self.cfg, self.patch
        B, Fn, D = b.latents.shape
        P = Fn // p
        dev = b.latents.device
        dtype = next(self.backbone.parameters()).dtype
        n_patch = b.latent_lens // p  # (B,)
        ls_patch = b.loss_start // p

        spk, emo = self._speaker_tokens(b.ref_latents, b.ref_mask, b.has_ref, B, dev, cfg.speaker.p_drop)
        # Clock for P + 1 patches: the stop position must see the same kind of clock input as at
        # inference (null / rest features), never a zero pad - a zero there would leak the length.
        midi, cont = b.clock_midi, b.clock_cont
        if midi is not None:
            last = midi[:, -1:]
            pad_val = torch.where(last == NONE, NONE, REST)
            midi = torch.cat([midi, pad_val.expand(-1, p)], 1)
            cont = F.pad(cont, (0, 0, 0, p))
        lag = None if b.clock_lag is None else F.pad(b.clock_lag, (0, 1))
        frame_emb, clock_patch = self._clock(midi, cont, lag, B, Fn + p, dev, cfg.clock.p_drop)
        frame_emb = frame_emb[:, :Fn]

        patches = b.latents.reshape(B, P, p * D)
        audio_inp = torch.cat([self.audio_bos.expand(B, 1, -1), self.audio_in(patches)], 1)  # (B, P+1, H)
        audio_inp = audio_inp + clock_patch

        embed = self.backbone.get_input_embeddings()
        seqs, starts = [], []
        for i in range(B):
            txt = embed(b.text_ids[i])
            starts.append(spk.shape[1] + txt.shape[0])
            seqs.append(torch.cat([spk[i], txt, audio_inp[i, : n_patch[i] + 1]], 0))
        lens = torch.tensor([s.shape[0] for s in seqs], device=dev)
        x = nn.utils.rnn.pad_sequence(seqs, batch_first=True).to(dtype)
        attn = (torch.arange(x.shape[1], device=dev)[None] < lens[:, None]).long()
        h = self.backbone(inputs_embeds=x, attention_mask=attn).last_hidden_state

        # gather audio-position states: (B, P+1, H)
        j = torch.arange(P + 1, device=dev)
        idx = (torch.tensor(starts, device=dev)[:, None] + j[None]).clamp(max=h.shape[1] - 1)
        h_audio = h.gather(1, idx[..., None].expand(-1, -1, h.shape[-1]))

        # flow matching on patches in the target region
        flow_mask = (j[None, :P] >= ls_patch[:, None]) & (j[None, :P] < n_patch[:, None])
        win = self._windows(b.latents)
        fwin = self._windows(frame_emb)
        x1, ctx = win[..., self.n_ctx :, :][flow_mask], win[..., : self.n_ctx, :][flow_mask]
        per = self.head.loss_terms(x1.to(dtype), h_audio[:, :P][flow_mask], ctx.to(dtype),
                                   frame_cond=fwin[flow_mask].to(dtype))
        loss_flow = per.mean()

        # stop: positive exactly at position P_i
        stop_valid = (j[None] >= ls_patch[:, None]) & (j[None] <= n_patch[:, None])
        stop_lbl = (j[None] == n_patch[:, None]).float()
        logits = self.stop(h_audio).float()
        loss_stop = F.binary_cross_entropy_with_logits(
            logits[stop_valid], stop_lbl[stop_valid], pos_weight=torch.tensor(10.0, device=dev))

        out = {"flow": loss_flow, "stop": loss_stop}
        total = loss_flow + cfg.loss.stop_weight * loss_stop

        if b.ctc_targets is not None and cfg.loss.ctc_weight > 0:
            tl = n_patch - ls_patch
            T = int(tl.max())
            cidx = (ls_patch[:, None] + torch.arange(T, device=dev)[None]).clamp(max=P)
            hc = h_audio.gather(1, cidx[..., None].expand(-1, -1, h.shape[-1]))
            loss_ctc = self.ctc.loss(hc, tl, b.ctc_targets, b.ctc_lens)
            out["ctc"] = loss_ctc
            total = total + cfg.loss.ctc_weight * loss_ctc
        out["loss"] = total
        return out

    # ------------------------------------------------------------------ inference
    @torch.no_grad()
    def generate(
        self,
        text_ids: torch.Tensor,  # (L_t,)
        ref_latents: torch.Tensor | None = None,  # (F_r, D)
        prompt_latents: torch.Tensor | None = None,  # (F_p, D), F_p multiple of patch
        clock_midi: torch.Tensor | None = None,  # (F_total,) covering prompt + generation
        clock_cont: torch.Tensor | None = None,
        max_patches: int = 375,  # 30 s
        min_patches: int = 2,
        n_steps: int = 8,
        cfg_scale: float = 1.5,
        temperature: float = 1.0,
        stop_threshold: float = 0.5,
    ) -> torch.Tensor:
        p, dev = self.patch, text_ids.device
        dtype = next(self.backbone.parameters()).dtype
        D = self.cfg.codec.latent_dim
        Pp = 0 if prompt_latents is None else prompt_latents.shape[0] // p
        total_frames = (Pp + max_patches + 1) * p
        if clock_midi is not None:
            pad = total_frames - clock_midi.shape[0]
            if pad > 0:
                m, c = null_features(pad)
                clock_midi = torch.cat([clock_midi, m.to(dev)])
                clock_cont = torch.cat([clock_cont, c.to(dev)])
            clock_midi, clock_cont = clock_midi[None, :total_frames], clock_cont[None, :total_frames]
        frame_emb, clock_patch = self._clock(clock_midi, clock_cont, None, 1, total_frames, dev)
        frame_emb, clock_patch = frame_emb.to(dtype), clock_patch.to(dtype)
        fpad = F.pad(frame_emb, (0, 0, self.n_ctx, 0))

        if ref_latents is not None:
            spk, _ = self.speaker(ref_latents[None].to(dtype), torch.ones(1, ref_latents.shape[0], dtype=torch.bool, device=dev))
        else:
            spk = self.speaker.null(1)
        txt = self.backbone.get_input_embeddings()(text_ids)[None]
        audio = [self.audio_bos.view(1, 1, -1)]
        frames = []
        if Pp:
            pl = prompt_latents[: Pp * p].to(dtype)
            audio.append(self.audio_in(pl.reshape(1, Pp, p * D)))
            frames = list(pl)
        aud = torch.cat(audio, 1) + clock_patch[:, : Pp + 1]
        x = torch.cat([spk.to(dtype), txt.to(dtype), aud.to(dtype)], 1)
        out = self.backbone(inputs_embeds=x, use_cache=True)
        h, pkv = out.last_hidden_state[:, -1], out.past_key_values

        n_gen = 0
        for jj in range(Pp, Pp + max_patches):
            if n_gen >= min_patches and torch.sigmoid(self.stop(h).float()).item() > stop_threshold:
                break
            ctx = torch.zeros(self.n_ctx, D, device=dev, dtype=dtype)
            if frames:
                prev = torch.stack(frames[-self.n_ctx :])
                ctx[self.n_ctx - prev.shape[0] :] = prev
            fc = fpad[:, jj * p : jj * p + self.n_ctx + p]  # same window layout as training
            patch = self.head.sample(h, ctx[None], n_steps=n_steps, cfg_scale=cfg_scale,
                                     temperature=temperature, frame_cond=fc)[0]
            frames.extend(list(patch))
            n_gen += 1
            nxt = self.audio_in(patch.reshape(1, 1, p * D)) + clock_patch[:, jj + 1 : jj + 2]
            out = self.backbone(inputs_embeds=nxt, past_key_values=pkv, use_cache=True)
            h, pkv = out.last_hidden_state[:, -1], out.past_key_values
        gen = frames[Pp * p :]
        return torch.stack(gen) if gen else torch.zeros(0, D, device=dev)