sync code
Browse files- code/.gitignore +10 -0
- code/configs/codec.yaml +13 -0
- code/configs/photon_l.yaml +12 -0
- code/configs/photon_m.yaml +12 -0
- code/configs/photon_s.yaml +17 -0
- code/configs/pilot.yaml +8 -0
- code/photontts/__init__.py +9 -0
- code/photontts/codec/__init__.py +3 -0
- code/photontts/codec/discriminators.py +66 -0
- code/photontts/codec/losses.py +63 -0
- code/photontts/codec/semantic_reg.py +24 -0
- code/photontts/codec/vae.py +158 -0
- code/photontts/conditioning/__init__.py +4 -0
- code/photontts/conditioning/score_clock.py +128 -0
- code/photontts/conditioning/speaker_encoder.py +74 -0
- code/photontts/config.py +116 -0
- code/photontts/model/__init__.py +4 -0
- code/photontts/model/aux_heads.py +52 -0
- code/photontts/model/backbone.py +37 -0
- code/photontts/model/photon.py +232 -0
- code/photontts/model/photon_head.py +132 -0
- code/photontts/text/__init__.py +3 -0
- code/photontts/text/tags.py +46 -0
- code/photontts/text/tokenizer.py +73 -0
- code/photontts/train/__init__.py +0 -0
- code/photontts/train/flow_loss.py +27 -0
- code/pyproject.toml +30 -0
- code/scripts/hf_sync.py +100 -0
- code/scripts/smoke_pretrained.py +79 -0
- code/tests/conftest.py +37 -0
- code/tests/test_codec.py +87 -0
- code/tests/test_conditioning.py +68 -0
- code/tests/test_config.py +17 -0
- code/tests/test_head.py +41 -0
- code/tests/test_photon.py +94 -0
- code/tests/test_text.py +27 -0
- code/tools/push_remote.py +95 -0
- code/tools/remote_sh.py +29 -0
code/.gitignore
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
.venv/
|
| 5 |
+
runs/
|
| 6 |
+
data/
|
| 7 |
+
*.wav
|
| 8 |
+
*.flac
|
| 9 |
+
*.safetensors
|
| 10 |
+
.env
|
code/configs/codec.yaml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PhotonCodec fallback (only trained if no existing open VAE passes the stage-1 gates).
|
| 2 |
+
codec:
|
| 3 |
+
sample_rate: 24000
|
| 4 |
+
latent_dim: 64
|
| 5 |
+
enc_channels: [32, 64, 128, 256, 512]
|
| 6 |
+
enc_strides: [2, 4, 5, 6, 4]
|
| 7 |
+
dec_dim: 512
|
| 8 |
+
dec_layers: 8
|
| 9 |
+
dec_upsample: 4
|
| 10 |
+
n_fft: 960
|
| 11 |
+
kl_weight: 0.0001
|
| 12 |
+
semantic_dim: 1024
|
| 13 |
+
semantic_weight: 1.0
|
code/configs/photon_l.yaml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Photon-L: quality tier (Qwen3-1.7B backbone, ~150M head). Target: 24 GB+ GPU.
|
| 2 |
+
name: photon-l
|
| 3 |
+
tokenizer: Qwen/Qwen3-1.7B
|
| 4 |
+
patch: 2
|
| 5 |
+
backbone:
|
| 6 |
+
pretrained: Qwen/Qwen3-1.7B
|
| 7 |
+
attn_implementation: sdpa
|
| 8 |
+
gradient_checkpointing: true
|
| 9 |
+
head: {dim: 768, layers: 8, heads: 12, n_ctx_patches: 2, noise_samples: 4, p_uncond: 0.1, ctx_noise: 0.1}
|
| 10 |
+
speaker: {n_tokens: 32, dim: 768, layers: 6, heads: 12, p_drop: 0.1, n_emotions: 0}
|
| 11 |
+
clock: {enabled: true, frame_dim: 192, p_drop: 0.3}
|
| 12 |
+
loss: {stop_weight: 0.5, ctc_weight: 0.1, ctc_upsample: 4}
|
code/configs/photon_m.yaml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Photon-M: primary model (Qwen3-0.6B backbone, ~80M head). Target: 8-12 GB consumer GPU.
|
| 2 |
+
name: photon-m
|
| 3 |
+
tokenizer: Qwen/Qwen3-0.6B
|
| 4 |
+
patch: 2
|
| 5 |
+
backbone:
|
| 6 |
+
pretrained: Qwen/Qwen3-0.6B
|
| 7 |
+
attn_implementation: sdpa
|
| 8 |
+
gradient_checkpointing: true
|
| 9 |
+
head: {dim: 512, layers: 6, heads: 8, n_ctx_patches: 2, noise_samples: 4, p_uncond: 0.1, ctx_noise: 0.1}
|
| 10 |
+
speaker: {n_tokens: 32, dim: 512, layers: 4, heads: 8, p_drop: 0.1, n_emotions: 0}
|
| 11 |
+
clock: {enabled: true, frame_dim: 128, p_drop: 0.3}
|
| 12 |
+
loss: {stop_weight: 0.5, ctc_weight: 0.1, ctc_upsample: 4}
|
code/configs/photon_s.yaml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Photon-S: edge tier (~120M backbone trained from scratch, ~25M head, 1-step after distillation).
|
| 2 |
+
# TODO(stage 7): switch to a ~16k multilingual SentencePiece vocab; bytes for now.
|
| 3 |
+
name: photon-s
|
| 4 |
+
tokenizer: bytes
|
| 5 |
+
patch: 2
|
| 6 |
+
backbone:
|
| 7 |
+
pretrained: null
|
| 8 |
+
hidden_size: 768
|
| 9 |
+
num_layers: 12
|
| 10 |
+
num_heads: 12
|
| 11 |
+
num_kv_heads: 4
|
| 12 |
+
intermediate_size: 2048
|
| 13 |
+
attn_implementation: sdpa
|
| 14 |
+
head: {dim: 320, layers: 4, heads: 5, n_ctx_patches: 2, noise_samples: 4, p_uncond: 0.1, ctx_noise: 0.1}
|
| 15 |
+
speaker: {n_tokens: 16, dim: 384, layers: 4, heads: 6, p_drop: 0.1, n_emotions: 0}
|
| 16 |
+
clock: {enabled: true, frame_dim: 64, p_drop: 0.3}
|
| 17 |
+
loss: {stop_weight: 0.5, ctc_weight: 0.1, ctc_upsample: 4}
|
code/configs/pilot.yaml
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pilot (stage 2): Photon-M architecture end-to-end on LibriTTS-R + curated singing sets.
|
| 2 |
+
name: photon-m-pilot
|
| 3 |
+
tokenizer: Qwen/Qwen3-0.6B
|
| 4 |
+
patch: 2
|
| 5 |
+
backbone: {pretrained: Qwen/Qwen3-0.6B, attn_implementation: sdpa, gradient_checkpointing: true}
|
| 6 |
+
head: {dim: 512, layers: 6, heads: 8}
|
| 7 |
+
speaker: {n_tokens: 32, dim: 512, layers: 4, heads: 8}
|
| 8 |
+
clock: {frame_dim: 128}
|
code/photontts/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PhotonTTS: causal LM over continuous latents + distilled local flow head."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.0.1"
|
| 4 |
+
|
| 5 |
+
SAMPLE_RATE = 24_000
|
| 6 |
+
HOP = 960 # 24 kHz / 960 = 25 Hz latent frames
|
| 7 |
+
LATENT_DIM = 64
|
| 8 |
+
PATCH = 2 # 2 frames per backbone step -> 12.5 Hz
|
| 9 |
+
FRAME_RATE = SAMPLE_RATE / HOP
|
code/photontts/codec/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .vae import PhotonCodec
|
| 2 |
+
|
| 3 |
+
__all__ = ["PhotonCodec"]
|
code/photontts/codec/discriminators.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Codec GAN discriminators: multi-period (HiFi-GAN) + multi-resolution complex STFT."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from torch.nn.utils.parametrizations import weight_norm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class PeriodDisc(nn.Module):
|
| 12 |
+
def __init__(self, period: int, ch: int = 32):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.period = period
|
| 15 |
+
chans = [1, ch, ch * 4, ch * 16, ch * 32]
|
| 16 |
+
self.convs = nn.ModuleList(
|
| 17 |
+
weight_norm(nn.Conv2d(chans[i], chans[i + 1], (5, 1), (3, 1), padding=(2, 0))) for i in range(4)
|
| 18 |
+
)
|
| 19 |
+
self.convs.append(weight_norm(nn.Conv2d(chans[-1], chans[-1], (5, 1), padding=(2, 0))))
|
| 20 |
+
self.post = weight_norm(nn.Conv2d(chans[-1], 1, (3, 1), padding=(1, 0)))
|
| 21 |
+
|
| 22 |
+
def forward(self, x): # (B, 1, T)
|
| 23 |
+
B, C, T = x.shape
|
| 24 |
+
if T % self.period:
|
| 25 |
+
x = F.pad(x, (0, self.period - T % self.period), mode="reflect")
|
| 26 |
+
x = x.view(B, C, -1, self.period)
|
| 27 |
+
fmaps = []
|
| 28 |
+
for c in self.convs:
|
| 29 |
+
x = F.leaky_relu(c(x), 0.1)
|
| 30 |
+
fmaps.append(x)
|
| 31 |
+
return self.post(x).flatten(1), fmaps
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class STFTDisc(nn.Module):
|
| 35 |
+
def __init__(self, n_fft: int, hop: int, ch: int = 32):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.n_fft, self.hop = n_fft, hop
|
| 38 |
+
self.register_buffer("window", torch.hann_window(n_fft), persistent=False)
|
| 39 |
+
self.convs = nn.ModuleList([
|
| 40 |
+
weight_norm(nn.Conv2d(2, ch, (3, 9), padding=(1, 4))),
|
| 41 |
+
weight_norm(nn.Conv2d(ch, ch, (3, 9), (1, 2), padding=(1, 4))),
|
| 42 |
+
weight_norm(nn.Conv2d(ch, ch, (3, 9), (1, 2), padding=(1, 4))),
|
| 43 |
+
weight_norm(nn.Conv2d(ch, ch, (3, 9), (1, 2), padding=(1, 4))),
|
| 44 |
+
weight_norm(nn.Conv2d(ch, ch, (3, 3), padding=(1, 1))),
|
| 45 |
+
])
|
| 46 |
+
self.post = weight_norm(nn.Conv2d(ch, 1, (3, 3), padding=(1, 1)))
|
| 47 |
+
|
| 48 |
+
def forward(self, x):
|
| 49 |
+
s = torch.stft(x[:, 0].float(), self.n_fft, self.hop, window=self.window, return_complex=True)
|
| 50 |
+
x = torch.stack([s.real, s.imag], 1).transpose(2, 3) # (B, 2, frames, bins)
|
| 51 |
+
fmaps = []
|
| 52 |
+
for c in self.convs:
|
| 53 |
+
x = F.leaky_relu(c(x), 0.1)
|
| 54 |
+
fmaps.append(x)
|
| 55 |
+
return self.post(x).flatten(1), fmaps
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class CodecDiscriminator(nn.Module):
|
| 59 |
+
def __init__(self, periods=(2, 3, 5, 7, 11), stfts=((2048, 512), (1024, 256), (512, 128)), ch: int = 32):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.discs = nn.ModuleList([PeriodDisc(p, ch) for p in periods] + [STFTDisc(n, h, ch) for n, h in stfts])
|
| 62 |
+
|
| 63 |
+
def forward(self, x):
|
| 64 |
+
"""Returns (list of logits, list of feature-map lists), one entry per sub-discriminator."""
|
| 65 |
+
outs = [d(x) for d in self.discs]
|
| 66 |
+
return [o[0] for o in outs], [o[1] for o in outs]
|
code/photontts/codec/losses.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Spectral and adversarial losses shared by the codec and later adversarial fine-tuning."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def mel_filterbank(sr: int, n_fft: int, n_mels: int, fmin: float = 0.0, fmax: float | None = None) -> torch.Tensor:
|
| 13 |
+
"""HTK-style triangular mel filters, (n_mels, n_fft // 2 + 1). No torchaudio/librosa dependency."""
|
| 14 |
+
fmax = fmax or sr / 2
|
| 15 |
+
hz2mel = lambda f: 2595.0 * math.log10(1.0 + f / 700.0)
|
| 16 |
+
mels = torch.linspace(hz2mel(fmin), hz2mel(fmax), n_mels + 2)
|
| 17 |
+
hz = 700.0 * (10 ** (mels / 2595.0) - 1.0)
|
| 18 |
+
bins = torch.linspace(0, sr / 2, n_fft // 2 + 1)
|
| 19 |
+
lo, ce, hi = hz[:-2, None], hz[1:-1, None], hz[2:, None]
|
| 20 |
+
up = (bins[None] - lo) / (ce - lo).clamp(min=1e-5)
|
| 21 |
+
down = (hi - bins[None]) / (hi - ce).clamp(min=1e-5)
|
| 22 |
+
return torch.clamp(torch.minimum(up, down), min=0.0)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MelSpec(nn.Module):
|
| 26 |
+
def __init__(self, sr: int = 24_000, n_fft: int = 1024, hop: int = 256, n_mels: int = 100):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.n_fft, self.hop = n_fft, hop
|
| 29 |
+
self.register_buffer("window", torch.hann_window(n_fft), persistent=False)
|
| 30 |
+
self.register_buffer("fb", mel_filterbank(sr, n_fft, n_mels), persistent=False)
|
| 31 |
+
|
| 32 |
+
def forward(self, wav): # (B, 1, T) or (B, T) -> log-mel (B, n_mels, frames)
|
| 33 |
+
if wav.dim() == 3:
|
| 34 |
+
wav = wav[:, 0]
|
| 35 |
+
s = torch.stft(wav.float(), self.n_fft, self.hop, window=self.window, return_complex=True).abs()
|
| 36 |
+
return torch.log(torch.clamp(self.fb @ s, min=1e-5))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class MultiResMelLoss(nn.Module):
|
| 40 |
+
def __init__(self, sr: int = 24_000, configs=((512, 128, 64), (1024, 256, 100), (2048, 512, 128))):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.mels = nn.ModuleList(MelSpec(sr, n, h, m) for n, h, m in configs)
|
| 43 |
+
|
| 44 |
+
def forward(self, pred, target):
|
| 45 |
+
return sum(F.l1_loss(m(pred), m(target)) for m in self.mels) / len(self.mels)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def disc_loss(real_logits, fake_logits):
|
| 49 |
+
"""Hinge loss for the discriminator."""
|
| 50 |
+
return sum(F.relu(1 - r).mean() + F.relu(1 + f).mean() for r, f in zip(real_logits, fake_logits)) / len(real_logits)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def gen_adv_loss(fake_logits):
|
| 54 |
+
return sum(F.relu(1 - f).mean() for f in fake_logits) / len(fake_logits)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def feature_matching_loss(real_fmaps, fake_fmaps):
|
| 58 |
+
loss, n = 0.0, 0
|
| 59 |
+
for rs, fs in zip(real_fmaps, fake_fmaps):
|
| 60 |
+
for r, f in zip(rs, fs):
|
| 61 |
+
loss = loss + F.l1_loss(f, r.detach()) / (r.detach().abs().mean() + 1e-5)
|
| 62 |
+
n += 1
|
| 63 |
+
return loss / max(n, 1)
|
code/photontts/codec/semantic_reg.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Semantic regularization: make VAE latents linearly predictive of frozen SSL features
|
| 2 |
+
(w2v-BERT 2.0 / WavLM). Keeps the latent space easy for the LM to model without quantization."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SemanticProjector(nn.Module):
|
| 12 |
+
def __init__(self, latent_dim: int, semantic_dim: int, hidden: int = 512):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.net = nn.Sequential(
|
| 15 |
+
nn.Conv1d(latent_dim, hidden, 3, padding=1), nn.GELU(), nn.Conv1d(hidden, semantic_dim, 1)
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
def forward(self, z: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
| 19 |
+
"""z: (B, D, F) latents. target: (B, S, Ft) SSL features at any frame rate.
|
| 20 |
+
Returns 1 - mean cosine similarity after resampling the target to the latent rate."""
|
| 21 |
+
if target.shape[-1] != z.shape[-1]:
|
| 22 |
+
target = F.interpolate(target.float(), size=z.shape[-1], mode="linear", align_corners=False)
|
| 23 |
+
pred = self.net(z)
|
| 24 |
+
return 1.0 - F.cosine_similarity(pred, target.detach().to(pred.dtype), dim=1).mean()
|
code/photontts/codec/vae.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PhotonCodec: causal continuous VAE, 24 kHz waveform <-> 25 Hz x 64-d latents.
|
| 2 |
+
|
| 3 |
+
Encoder: causal strided conv stack (Snake activations), stride product 960.
|
| 4 |
+
Decoder: upsample latents 25 Hz -> 100 Hz, causal ConvNeXt stack (Vocos-style),
|
| 5 |
+
iSTFT head (n_fft 960, hop 240). The iSTFT window center gives ~20 ms lookahead,
|
| 6 |
+
which the streaming engine handles with 1-frame overlap + crossfade.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import math
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
|
| 17 |
+
from ..config import CodecConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Snake(nn.Module):
|
| 21 |
+
"""x + sin^2(a x) / a, per channel (BigVGAN). Helps periodic signals (singing)."""
|
| 22 |
+
|
| 23 |
+
def __init__(self, channels: int):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.log_alpha = nn.Parameter(torch.zeros(1, channels, 1))
|
| 26 |
+
|
| 27 |
+
def forward(self, x):
|
| 28 |
+
a = self.log_alpha.exp()
|
| 29 |
+
return x + torch.sin(a * x).pow(2) / (a + 1e-9)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class CausalConv1d(nn.Conv1d):
|
| 33 |
+
"""Conv1d padded on the left only, so output[t] depends on input[<= t]."""
|
| 34 |
+
|
| 35 |
+
def __init__(self, *args, **kwargs):
|
| 36 |
+
super().__init__(*args, **kwargs)
|
| 37 |
+
k, d, s = self.kernel_size[0], self.dilation[0], self.stride[0]
|
| 38 |
+
self.causal_pad = (k - 1) * d + 1 - s
|
| 39 |
+
|
| 40 |
+
def forward(self, x):
|
| 41 |
+
return super().forward(F.pad(x, (self.causal_pad, 0)))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ResUnit(nn.Module):
|
| 45 |
+
def __init__(self, ch: int, dilation: int):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.net = nn.Sequential(
|
| 48 |
+
Snake(ch), CausalConv1d(ch, ch, 7, dilation=dilation), Snake(ch), nn.Conv1d(ch, ch, 1)
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def forward(self, x):
|
| 52 |
+
return x + self.net(x)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class EncoderBlock(nn.Module):
|
| 56 |
+
def __init__(self, cin: int, cout: int, stride: int):
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.net = nn.Sequential(
|
| 59 |
+
ResUnit(cin, 1), ResUnit(cin, 3), ResUnit(cin, 9),
|
| 60 |
+
Snake(cin), CausalConv1d(cin, cout, 2 * stride, stride=stride),
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def forward(self, x):
|
| 64 |
+
return self.net(x)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class Encoder(nn.Module):
|
| 68 |
+
def __init__(self, cfg: CodecConfig):
|
| 69 |
+
super().__init__()
|
| 70 |
+
ch = cfg.enc_channels
|
| 71 |
+
layers = [CausalConv1d(1, ch[0], 7)]
|
| 72 |
+
for i, s in enumerate(cfg.enc_strides):
|
| 73 |
+
cout = ch[i + 1] if i + 1 < len(ch) else ch[-1]
|
| 74 |
+
layers.append(EncoderBlock(ch[i], cout, s))
|
| 75 |
+
layers += [Snake(ch[-1]), CausalConv1d(ch[-1], 2 * cfg.latent_dim, 3)]
|
| 76 |
+
self.net = nn.Sequential(*layers)
|
| 77 |
+
self.hop = math.prod(cfg.enc_strides)
|
| 78 |
+
|
| 79 |
+
def forward(self, wav): # (B, 1, T) -> mean, logvar: (B, D, T // hop)
|
| 80 |
+
T = wav.shape[-1]
|
| 81 |
+
if T % self.hop:
|
| 82 |
+
wav = F.pad(wav, (0, self.hop - T % self.hop))
|
| 83 |
+
mean, logvar = self.net(wav).chunk(2, dim=1)
|
| 84 |
+
return mean, logvar.clamp(-12.0, 4.0)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class ConvNeXtBlock(nn.Module):
|
| 88 |
+
def __init__(self, dim: int):
|
| 89 |
+
super().__init__()
|
| 90 |
+
self.dw = CausalConv1d(dim, dim, 7, groups=dim)
|
| 91 |
+
self.norm = nn.LayerNorm(dim)
|
| 92 |
+
self.pw1 = nn.Linear(dim, dim * 3)
|
| 93 |
+
self.pw2 = nn.Linear(dim * 3, dim)
|
| 94 |
+
self.gamma = nn.Parameter(torch.full((dim,), 1e-2))
|
| 95 |
+
|
| 96 |
+
def forward(self, x): # (B, C, T)
|
| 97 |
+
y = self.dw(x).transpose(1, 2)
|
| 98 |
+
y = self.pw2(F.gelu(self.pw1(self.norm(y))))
|
| 99 |
+
return x + (self.gamma * y).transpose(1, 2)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def istft_same(spec: torch.Tensor, n_fft: int, hop: int, window: torch.Tensor) -> torch.Tensor:
|
| 103 |
+
"""iSTFT with 'same' padding (Vocos): L frames -> L * hop samples."""
|
| 104 |
+
L = spec.shape[-1]
|
| 105 |
+
frames = torch.fft.irfft(spec, n_fft, dim=1, norm="backward") * window[None, :, None]
|
| 106 |
+
out = (L - 1) * hop + n_fft
|
| 107 |
+
pad = (n_fft - hop) // 2
|
| 108 |
+
y = F.fold(frames, (1, out), (1, n_fft), stride=(1, hop))[:, 0, 0]
|
| 109 |
+
env = F.fold(window.square()[None, :, None].expand(1, -1, L), (1, out), (1, n_fft), stride=(1, hop))[:, 0, 0]
|
| 110 |
+
return (y / env.clamp(min=1e-11))[:, pad : out - pad]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class Decoder(nn.Module):
|
| 114 |
+
def __init__(self, cfg: CodecConfig):
|
| 115 |
+
super().__init__()
|
| 116 |
+
d, up = cfg.dec_dim, cfg.dec_upsample
|
| 117 |
+
self.n_fft, self.hop = cfg.n_fft, math.prod(cfg.enc_strides) // up
|
| 118 |
+
self.inp = CausalConv1d(cfg.latent_dim, d, 3)
|
| 119 |
+
self.up = nn.ConvTranspose1d(d, d, 2 * up, stride=up, padding=up // 2)
|
| 120 |
+
self.blocks = nn.Sequential(*[ConvNeXtBlock(d) for _ in range(cfg.dec_layers)])
|
| 121 |
+
self.norm = nn.LayerNorm(d)
|
| 122 |
+
self.out = nn.Linear(d, cfg.n_fft + 2) # log-magnitude + phase for n_fft//2+1 bins
|
| 123 |
+
self.register_buffer("window", torch.hann_window(cfg.n_fft), persistent=False)
|
| 124 |
+
|
| 125 |
+
def forward(self, z): # (B, D, F) -> (B, 1, F * 960)
|
| 126 |
+
Fn = z.shape[-1]
|
| 127 |
+
# ConvTranspose(k=2u, s=u, p=u/2) yields exactly Fn * u frames (one frame of lookahead).
|
| 128 |
+
x = self.up(self.inp(z))[..., : Fn * self.up.stride[0]]
|
| 129 |
+
x = self.blocks(x)
|
| 130 |
+
x = self.out(self.norm(x.transpose(1, 2))).transpose(1, 2)
|
| 131 |
+
logmag, phase = x.float().chunk(2, dim=1)
|
| 132 |
+
mag = logmag.exp().clamp(max=1e2)
|
| 133 |
+
spec = torch.polar(mag, phase)
|
| 134 |
+
return istft_same(spec, self.n_fft, self.hop, self.window.float())[:, None]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class PhotonCodec(nn.Module):
|
| 138 |
+
def __init__(self, cfg: CodecConfig):
|
| 139 |
+
super().__init__()
|
| 140 |
+
self.cfg = cfg
|
| 141 |
+
self.encoder = Encoder(cfg)
|
| 142 |
+
self.decoder = Decoder(cfg)
|
| 143 |
+
self.hop = self.encoder.hop
|
| 144 |
+
|
| 145 |
+
@torch.no_grad()
|
| 146 |
+
def encode(self, wav: torch.Tensor, sample: bool = False) -> torch.Tensor:
|
| 147 |
+
mean, logvar = self.encoder(wav)
|
| 148 |
+
return mean + torch.randn_like(mean) * (0.5 * logvar).exp() if sample else mean
|
| 149 |
+
|
| 150 |
+
def decode(self, z: torch.Tensor) -> torch.Tensor:
|
| 151 |
+
return self.decoder(z)
|
| 152 |
+
|
| 153 |
+
def forward(self, wav: torch.Tensor):
|
| 154 |
+
mean, logvar = self.encoder(wav)
|
| 155 |
+
z = mean + torch.randn_like(mean) * (0.5 * logvar).exp()
|
| 156 |
+
recon = self.decoder(z)[..., : wav.shape[-1]]
|
| 157 |
+
kl = 0.5 * (mean.pow(2) + logvar.exp() - 1.0 - logvar).mean()
|
| 158 |
+
return {"recon": recon, "z": z, "mean": mean, "logvar": logvar, "kl": kl}
|
code/photontts/conditioning/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .score_clock import Note, Score, ScoreClockEmbed, frame_features, null_features
|
| 2 |
+
from .speaker_encoder import SpeakerEncoder
|
| 3 |
+
|
| 4 |
+
__all__ = ["Note", "Score", "ScoreClockEmbed", "SpeakerEncoder", "frame_features", "null_features"]
|
code/photontts/conditioning/score_clock.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Score Clock: time-indexed conditioning that tells the AR backbone *when* things should happen.
|
| 2 |
+
|
| 3 |
+
For every 25 Hz latent frame f (covering [f/25, (f+1)/25) s) we compute features of the
|
| 4 |
+
musical score (or speech duration target) active at that wall-clock time:
|
| 5 |
+
|
| 6 |
+
midi active note (0..127), REST=128, NONE=129 (no score / dropped)
|
| 7 |
+
continuous slur, note position fraction, onset flag + sub-frame onset offset,
|
| 8 |
+
beat phase (sin, cos) + has_beat, log-F0 + voiced + has_f0,
|
| 9 |
+
speech progress + has_progress, vibrato depth/rate, breathiness + has_style
|
| 10 |
+
|
| 11 |
+
The head receives these per frame (onset accuracy at ~20-30 ms needs sub-patch resolution);
|
| 12 |
+
the backbone receives them pooled per patch (80 ms), plus an optional syllable-lag embedding
|
| 13 |
+
("emitted syllables minus scheduled syllables") so it can catch up when it drifts.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from dataclasses import dataclass, field
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn as nn
|
| 23 |
+
|
| 24 |
+
REST, NONE = 128, 129
|
| 25 |
+
N_CONT = 16
|
| 26 |
+
MAX_LAG = 8
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class Note:
|
| 31 |
+
onset: float # seconds
|
| 32 |
+
duration: float # seconds
|
| 33 |
+
midi: int # 0..127, or REST
|
| 34 |
+
slur: bool = False
|
| 35 |
+
syllable: int = -1 # index into the lyric syllables, -1 for rests / melisma continuation
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass
|
| 39 |
+
class Score:
|
| 40 |
+
notes: list[Note] = field(default_factory=list)
|
| 41 |
+
tempo_bpm: float | None = None
|
| 42 |
+
vibrato_depth: float | None = None # semitones
|
| 43 |
+
vibrato_rate: float | None = None # Hz
|
| 44 |
+
breathiness: float | None = None # 0..1
|
| 45 |
+
|
| 46 |
+
def transpose(self, semitones: int) -> "Score":
|
| 47 |
+
notes = [Note(n.onset, n.duration, n.midi if n.midi == REST else min(max(n.midi + semitones, 0), 127),
|
| 48 |
+
n.slur, n.syllable) for n in self.notes]
|
| 49 |
+
return Score(notes, self.tempo_bpm, self.vibrato_depth, self.vibrato_rate, self.breathiness)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def frame_features(
|
| 53 |
+
n_frames: int,
|
| 54 |
+
score: Score | None = None,
|
| 55 |
+
f0: torch.Tensor | None = None, # (n_frames,) Hz, 0 = unvoiced
|
| 56 |
+
total_duration: float | None = None, # speech mode duration control (seconds)
|
| 57 |
+
frame_rate: float = 25.0,
|
| 58 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 59 |
+
"""Returns midi (n_frames,) long and cont (n_frames, N_CONT) float."""
|
| 60 |
+
midi = torch.full((n_frames,), NONE, dtype=torch.long)
|
| 61 |
+
cont = torch.zeros(n_frames, N_CONT)
|
| 62 |
+
t0 = torch.arange(n_frames) / frame_rate # frame start times
|
| 63 |
+
if score is not None:
|
| 64 |
+
midi.fill_(REST)
|
| 65 |
+
for n in score.notes:
|
| 66 |
+
start_f, end_f = n.onset * frame_rate, (n.onset + n.duration) * frame_rate
|
| 67 |
+
lo, hi = max(int(math.floor(start_f)), 0), min(int(math.ceil(end_f)), n_frames)
|
| 68 |
+
if lo >= n_frames:
|
| 69 |
+
continue
|
| 70 |
+
idx = torch.arange(lo, hi)
|
| 71 |
+
mid = (idx + 0.5) / frame_rate
|
| 72 |
+
active = (mid >= n.onset) & (mid < n.onset + n.duration)
|
| 73 |
+
idx = idx[active]
|
| 74 |
+
midi[idx] = n.midi
|
| 75 |
+
cont[idx, 0] = float(n.slur)
|
| 76 |
+
cont[idx, 1] = ((idx + 0.5) / frame_rate - n.onset) / max(n.duration, 1e-3)
|
| 77 |
+
of = int(math.floor(start_f))
|
| 78 |
+
if 0 <= of < n_frames:
|
| 79 |
+
cont[of, 2] = 1.0
|
| 80 |
+
cont[of, 3] = start_f - of # sub-frame onset offset in [0, 1)
|
| 81 |
+
if score.tempo_bpm:
|
| 82 |
+
phase = 2 * math.pi * t0 * score.tempo_bpm / 60.0
|
| 83 |
+
cont[:, 4], cont[:, 5], cont[:, 6] = torch.sin(phase), torch.cos(phase), 1.0
|
| 84 |
+
if score.vibrato_depth is not None or score.vibrato_rate is not None or score.breathiness is not None:
|
| 85 |
+
cont[:, 12] = score.vibrato_depth or 0.0
|
| 86 |
+
cont[:, 13] = (score.vibrato_rate or 0.0) / 10.0
|
| 87 |
+
cont[:, 14] = score.breathiness or 0.0
|
| 88 |
+
cont[:, 15] = 1.0
|
| 89 |
+
if f0 is not None:
|
| 90 |
+
f0 = f0[:n_frames].float()
|
| 91 |
+
voiced = f0 > 0
|
| 92 |
+
cont[: len(f0), 7] = torch.where(voiced, (torch.log(f0.clamp(min=1.0)) - math.log(200.0)) / 1.0, 0.0)
|
| 93 |
+
cont[: len(f0), 8] = voiced.float()
|
| 94 |
+
cont[: len(f0), 9] = 1.0
|
| 95 |
+
if total_duration:
|
| 96 |
+
cont[:, 10] = ((t0 + 0.5 / frame_rate) / total_duration).clamp(max=1.5)
|
| 97 |
+
cont[:, 11] = 1.0
|
| 98 |
+
return midi, cont
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def null_features(n_frames: int) -> tuple[torch.Tensor, torch.Tensor]:
|
| 102 |
+
return torch.full((n_frames,), NONE, dtype=torch.long), torch.zeros(n_frames, N_CONT)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class ScoreClockEmbed(nn.Module):
|
| 106 |
+
"""Frame features -> (frame-level emb for the head, patch-level emb for the backbone)."""
|
| 107 |
+
|
| 108 |
+
def __init__(self, frame_dim: int, backbone_dim: int, patch: int):
|
| 109 |
+
super().__init__()
|
| 110 |
+
self.patch = patch
|
| 111 |
+
self.midi = nn.Embedding(NONE + 1, frame_dim)
|
| 112 |
+
self.cont = nn.Linear(N_CONT, frame_dim)
|
| 113 |
+
self.frame_mlp = nn.Sequential(nn.SiLU(), nn.Linear(frame_dim, frame_dim))
|
| 114 |
+
self.to_patch = nn.Linear(frame_dim * patch, backbone_dim)
|
| 115 |
+
self.lag = nn.Embedding(2 * MAX_LAG + 2, backbone_dim) # last index = unknown
|
| 116 |
+
nn.init.zeros_(self.to_patch.weight)
|
| 117 |
+
nn.init.zeros_(self.to_patch.bias)
|
| 118 |
+
nn.init.zeros_(self.lag.weight) # start as a no-op on the pretrained LLM
|
| 119 |
+
|
| 120 |
+
def forward(self, midi: torch.Tensor, cont: torch.Tensor, lag: torch.Tensor | None = None):
|
| 121 |
+
"""midi: (B, F) long, cont: (B, F, N_CONT); F divisible by patch.
|
| 122 |
+
Returns frame_emb (B, F, frame_dim), patch_emb (B, F // patch, backbone_dim)."""
|
| 123 |
+
frame = self.frame_mlp(self.midi(midi) + self.cont(cont.to(self.cont.weight.dtype)))
|
| 124 |
+
B, Fn, D = frame.shape
|
| 125 |
+
patch = self.to_patch(frame.reshape(B, Fn // self.patch, self.patch * D))
|
| 126 |
+
if lag is not None:
|
| 127 |
+
patch = patch + self.lag(torch.where(lag.abs() > MAX_LAG, 2 * MAX_LAG + 1, lag + MAX_LAG))
|
| 128 |
+
return frame, patch
|
code/photontts/conditioning/speaker_encoder.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transcript-free speaker/style encoder: Perceiver resampler over reference latents -> N global tokens.
|
| 2 |
+
|
| 3 |
+
Trained jointly with the TTS model (MiniMax-Speech style). An optional gradient-reversal
|
| 4 |
+
emotion adversary pushes emotion out of the timbre tokens (IndexTTS2 style).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
|
| 12 |
+
from ..config import SpeakerConfig
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class _GradReverse(torch.autograd.Function):
|
| 16 |
+
@staticmethod
|
| 17 |
+
def forward(ctx, x, scale):
|
| 18 |
+
ctx.scale = scale
|
| 19 |
+
return x.view_as(x)
|
| 20 |
+
|
| 21 |
+
@staticmethod
|
| 22 |
+
def backward(ctx, g):
|
| 23 |
+
return -ctx.scale * g, None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def grad_reverse(x, scale: float = 1.0):
|
| 27 |
+
return _GradReverse.apply(x, scale)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class CrossAttnBlock(nn.Module):
|
| 31 |
+
def __init__(self, dim: int, heads: int):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.nq, self.nkv = nn.LayerNorm(dim), nn.LayerNorm(dim)
|
| 34 |
+
self.attn = nn.MultiheadAttention(dim, heads, batch_first=True)
|
| 35 |
+
self.ff = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))
|
| 36 |
+
|
| 37 |
+
def forward(self, q, kv, kv_pad_mask):
|
| 38 |
+
h = self.nq(q)
|
| 39 |
+
kvn = self.nkv(torch.cat([kv, h], 1)) # queries also attend to themselves (Perceiver-AR trick)
|
| 40 |
+
mask = torch.cat([kv_pad_mask, torch.zeros_like(kv_pad_mask[:, : q.shape[1]])], 1)
|
| 41 |
+
q = q + self.attn(h, kvn, kvn, key_padding_mask=mask, need_weights=False)[0]
|
| 42 |
+
return q + self.ff(q)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class SpeakerEncoder(nn.Module):
|
| 46 |
+
def __init__(self, cfg: SpeakerConfig, latent_dim: int, out_dim: int):
|
| 47 |
+
super().__init__()
|
| 48 |
+
d = cfg.dim
|
| 49 |
+
self.inp = nn.Linear(latent_dim, d)
|
| 50 |
+
self.pos = nn.Conv1d(d, d, 7, padding=3, groups=d) # conv positional encoding (length-agnostic)
|
| 51 |
+
enc = nn.TransformerEncoderLayer(d, cfg.heads, 4 * d, batch_first=True, norm_first=True)
|
| 52 |
+
self.encoder = nn.TransformerEncoder(enc, num_layers=max(cfg.layers // 2, 1), enable_nested_tensor=False)
|
| 53 |
+
self.queries = nn.Parameter(torch.randn(cfg.n_tokens, d) * 0.02)
|
| 54 |
+
self.resampler = nn.ModuleList(CrossAttnBlock(d, cfg.heads) for _ in range(max(cfg.layers - cfg.layers // 2, 1)))
|
| 55 |
+
self.out = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, out_dim))
|
| 56 |
+
self.null_tokens = nn.Parameter(torch.randn(cfg.n_tokens, out_dim) * 0.02) # "no speaker" (CFG / voice design)
|
| 57 |
+
self.emotion_head = nn.Linear(d, cfg.n_emotions) if cfg.n_emotions > 0 else None
|
| 58 |
+
|
| 59 |
+
def forward(self, ref: torch.Tensor, ref_mask: torch.Tensor):
|
| 60 |
+
"""ref: (B, T, D_latent), ref_mask: (B, T) True = valid frame.
|
| 61 |
+
Returns tokens (B, N, out_dim) and optional emotion logits from a gradient-reversed branch."""
|
| 62 |
+
pad = ~ref_mask
|
| 63 |
+
x = self.inp(ref).masked_fill(pad[..., None], 0.0) # zero pads *before* the conv mixes neighbours
|
| 64 |
+
x = x + self.pos(x.transpose(1, 2)).transpose(1, 2)
|
| 65 |
+
x = x.masked_fill(pad[..., None], 0.0)
|
| 66 |
+
x = self.encoder(x, src_key_padding_mask=pad)
|
| 67 |
+
q = self.queries[None].expand(ref.shape[0], -1, -1)
|
| 68 |
+
for blk in self.resampler:
|
| 69 |
+
q = blk(q, x, pad)
|
| 70 |
+
emo = self.emotion_head(grad_reverse(q.mean(1))) if self.emotion_head is not None else None
|
| 71 |
+
return self.out(q), emo
|
| 72 |
+
|
| 73 |
+
def null(self, batch: int) -> torch.Tensor:
|
| 74 |
+
return self.null_tokens[None].expand(batch, -1, -1)
|
code/photontts/config.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Typed configs, loadable from YAML. Nested dataclasses mirror the YAML sections."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import dataclasses
|
| 6 |
+
from dataclasses import dataclass, field
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any, get_type_hints
|
| 9 |
+
|
| 10 |
+
import yaml
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class CodecConfig:
|
| 15 |
+
sample_rate: int = 24_000
|
| 16 |
+
latent_dim: int = 64
|
| 17 |
+
enc_channels: list[int] = field(default_factory=lambda: [32, 64, 128, 256, 512])
|
| 18 |
+
enc_strides: list[int] = field(default_factory=lambda: [2, 4, 5, 6, 4]) # product = 960
|
| 19 |
+
dec_dim: int = 512
|
| 20 |
+
dec_layers: int = 8
|
| 21 |
+
dec_upsample: int = 4 # 25 Hz -> 100 Hz before iSTFT
|
| 22 |
+
n_fft: int = 960 # iSTFT at 100 Hz: hop = 960 / dec_upsample = 240
|
| 23 |
+
kl_weight: float = 1e-4
|
| 24 |
+
semantic_dim: int = 0 # >0 enables semantic regularization projector
|
| 25 |
+
semantic_weight: float = 1.0
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class BackboneConfig:
|
| 30 |
+
pretrained: str | None = None # e.g. "Qwen/Qwen3-0.6B"; None -> random init from fields below
|
| 31 |
+
hidden_size: int = 1024
|
| 32 |
+
num_layers: int = 28
|
| 33 |
+
num_heads: int = 16
|
| 34 |
+
num_kv_heads: int = 8
|
| 35 |
+
intermediate_size: int = 3072
|
| 36 |
+
max_position: int = 8192
|
| 37 |
+
attn_implementation: str = "sdpa"
|
| 38 |
+
gradient_checkpointing: bool = False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class HeadConfig:
|
| 43 |
+
dim: int = 512
|
| 44 |
+
layers: int = 6
|
| 45 |
+
heads: int = 8
|
| 46 |
+
n_ctx_patches: int = 2
|
| 47 |
+
noise_samples: int = 4 # flow-matching noise draws per backbone state
|
| 48 |
+
p_uncond: float = 0.1 # CFG dropout of h_t
|
| 49 |
+
ctx_noise: float = 0.1 # noise augmentation of context patches (anti exposure-bias)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass
|
| 53 |
+
class SpeakerConfig:
|
| 54 |
+
n_tokens: int = 32
|
| 55 |
+
dim: int = 512
|
| 56 |
+
layers: int = 4
|
| 57 |
+
heads: int = 8
|
| 58 |
+
p_drop: float = 0.1 # drop whole speaker conditioning (CFG / voice design)
|
| 59 |
+
n_emotions: int = 0 # >0 enables gradient-reversal emotion adversary
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@dataclass
|
| 63 |
+
class ClockConfig:
|
| 64 |
+
enabled: bool = True
|
| 65 |
+
frame_dim: int = 128 # per-frame features fed to the head
|
| 66 |
+
p_drop: float = 0.3
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@dataclass
|
| 70 |
+
class LossConfig:
|
| 71 |
+
stop_weight: float = 0.5
|
| 72 |
+
ctc_weight: float = 0.1
|
| 73 |
+
ctc_upsample: int = 4 # CTC runs at 12.5 * 4 = 50 Hz so byte targets fit
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass
|
| 77 |
+
class PhotonConfig:
|
| 78 |
+
name: str = "photon-m"
|
| 79 |
+
codec: CodecConfig = field(default_factory=CodecConfig)
|
| 80 |
+
backbone: BackboneConfig = field(default_factory=BackboneConfig)
|
| 81 |
+
head: HeadConfig = field(default_factory=HeadConfig)
|
| 82 |
+
speaker: SpeakerConfig = field(default_factory=SpeakerConfig)
|
| 83 |
+
clock: ClockConfig = field(default_factory=ClockConfig)
|
| 84 |
+
loss: LossConfig = field(default_factory=LossConfig)
|
| 85 |
+
tokenizer: str = "bytes" # "bytes" or an HF tokenizer name
|
| 86 |
+
patch: int = 2
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _build(cls, data: dict[str, Any] | None):
|
| 90 |
+
data = dict(data or {})
|
| 91 |
+
hints = get_type_hints(cls)
|
| 92 |
+
kwargs = {}
|
| 93 |
+
for f in dataclasses.fields(cls):
|
| 94 |
+
if f.name not in data:
|
| 95 |
+
continue
|
| 96 |
+
val = data.pop(f.name)
|
| 97 |
+
typ = hints[f.name]
|
| 98 |
+
if dataclasses.is_dataclass(typ):
|
| 99 |
+
val = _build(typ, val)
|
| 100 |
+
kwargs[f.name] = val
|
| 101 |
+
if data:
|
| 102 |
+
raise ValueError(f"Unknown keys for {cls.__name__}: {sorted(data)}")
|
| 103 |
+
return cls(**kwargs)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def load_config(path: str | Path) -> PhotonConfig:
|
| 107 |
+
with open(path, encoding="utf-8") as f:
|
| 108 |
+
return _build(PhotonConfig, yaml.safe_load(f))
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def config_from_dict(d: dict[str, Any]) -> PhotonConfig:
|
| 112 |
+
return _build(PhotonConfig, d)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def to_dict(cfg) -> dict[str, Any]:
|
| 116 |
+
return dataclasses.asdict(cfg)
|
code/photontts/model/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .photon import PhotonBatch, PhotonTTS
|
| 2 |
+
from .photon_head import PhotonHead
|
| 3 |
+
|
| 4 |
+
__all__ = ["PhotonBatch", "PhotonHead", "PhotonTTS"]
|
code/photontts/model/aux_heads.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Auxiliary backbone heads: stop prediction and a byte-level CTC alignment head.
|
| 2 |
+
|
| 3 |
+
CTC runs at 12.5 Hz * ctc_upsample (default 50 Hz) because byte targets for e.g. Chinese
|
| 4 |
+
(~15 bytes/s) exceed the 12.5 Hz step rate. At inference the CTC head doubles as a
|
| 5 |
+
skip/repeat monitor (greedy decode vs. the target text).
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
|
| 14 |
+
from ..text.tokenizer import CTC_BLANK, CTC_VOCAB
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class StopHead(nn.Module):
|
| 18 |
+
def __init__(self, dim: int):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.proj = nn.Linear(dim, 1)
|
| 21 |
+
|
| 22 |
+
def forward(self, h):
|
| 23 |
+
return self.proj(h).squeeze(-1)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class CTCHead(nn.Module):
|
| 27 |
+
def __init__(self, dim: int, upsample: int = 4, vocab: int = CTC_VOCAB):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.up, self.vocab = upsample, vocab
|
| 30 |
+
self.proj = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, upsample * vocab))
|
| 31 |
+
|
| 32 |
+
def forward(self, h): # (B, T, dim) -> log-probs (B, T * up, vocab)
|
| 33 |
+
B, T, _ = h.shape
|
| 34 |
+
return self.proj(h).view(B, T * self.up, self.vocab).float().log_softmax(-1)
|
| 35 |
+
|
| 36 |
+
def loss(self, h, h_lens, targets, target_lens):
|
| 37 |
+
lp = self(h).transpose(0, 1) # (T', B, V)
|
| 38 |
+
return F.ctc_loss(lp, targets, h_lens * self.up, target_lens, blank=CTC_BLANK,
|
| 39 |
+
reduction="mean", zero_infinity=True)
|
| 40 |
+
|
| 41 |
+
@torch.no_grad()
|
| 42 |
+
def greedy(self, h) -> list[list[int]]:
|
| 43 |
+
ids = self(h).argmax(-1)
|
| 44 |
+
out = []
|
| 45 |
+
for row in ids.tolist():
|
| 46 |
+
seq, prev = [], CTC_BLANK
|
| 47 |
+
for i in row:
|
| 48 |
+
if i != prev and i != CTC_BLANK:
|
| 49 |
+
seq.append(i)
|
| 50 |
+
prev = i
|
| 51 |
+
out.append(seq)
|
| 52 |
+
return out
|
code/photontts/model/backbone.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backbone: decoder-only causal Transformer (Qwen3), pretrained or randomly initialised.
|
| 2 |
+
|
| 3 |
+
We only use it on `inputs_embeds`, so text token embeddings come from its own embedding table
|
| 4 |
+
(resized to include PhotonTTS control tokens) and audio/speaker/clock inputs are projected in.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
|
| 11 |
+
from ..config import BackboneConfig
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def build_backbone(cfg: BackboneConfig, vocab_size: int) -> nn.Module:
|
| 15 |
+
from transformers import Qwen3Config, Qwen3Model
|
| 16 |
+
|
| 17 |
+
if cfg.pretrained:
|
| 18 |
+
model = Qwen3Model.from_pretrained(cfg.pretrained, attn_implementation=cfg.attn_implementation)
|
| 19 |
+
if model.get_input_embeddings().num_embeddings < vocab_size:
|
| 20 |
+
model.resize_token_embeddings(vocab_size, mean_resizing=True)
|
| 21 |
+
else:
|
| 22 |
+
conf = Qwen3Config(
|
| 23 |
+
vocab_size=vocab_size,
|
| 24 |
+
hidden_size=cfg.hidden_size,
|
| 25 |
+
num_hidden_layers=cfg.num_layers,
|
| 26 |
+
num_attention_heads=cfg.num_heads,
|
| 27 |
+
num_key_value_heads=cfg.num_kv_heads,
|
| 28 |
+
head_dim=cfg.hidden_size // cfg.num_heads,
|
| 29 |
+
intermediate_size=cfg.intermediate_size,
|
| 30 |
+
max_position_embeddings=cfg.max_position,
|
| 31 |
+
tie_word_embeddings=False,
|
| 32 |
+
)
|
| 33 |
+
conf._attn_implementation = cfg.attn_implementation
|
| 34 |
+
model = Qwen3Model(conf)
|
| 35 |
+
if cfg.gradient_checkpointing:
|
| 36 |
+
model.gradient_checkpointing_enable()
|
| 37 |
+
return model
|
code/photontts/model/photon.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PhotonTTS: the full text(+speaker+score) -> latent model.
|
| 2 |
+
|
| 3 |
+
Per-sample backbone sequence (right-padded across the batch):
|
| 4 |
+
|
| 5 |
+
[speaker tokens (N_s)] [text tokens (L_t)] [<audio> + clock_0] [patch_0 + clock_1] ... [patch_{P-1} + 0]
|
| 6 |
+
| | |
|
| 7 |
+
h_0 -> head predicts patch_0 h_1 -> patch_1 h_P -> stop
|
| 8 |
+
|
| 9 |
+
`text_ids` already contains control tokens (mode / lang / bandwidth / style) and, for the
|
| 10 |
+
in-context path B, the prompt transcript followed by the target text; the prompt's latents
|
| 11 |
+
are the first `loss_start` frames of `latents` and are excluded from the losses.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
|
| 22 |
+
from .. import LATENT_DIM
|
| 23 |
+
from ..conditioning.score_clock import NONE, REST, ScoreClockEmbed, null_features
|
| 24 |
+
from ..conditioning.speaker_encoder import SpeakerEncoder
|
| 25 |
+
from ..config import PhotonConfig
|
| 26 |
+
from .aux_heads import CTCHead, StopHead
|
| 27 |
+
from .backbone import build_backbone
|
| 28 |
+
from .photon_head import PhotonHead
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class PhotonBatch:
|
| 33 |
+
text_ids: list[torch.Tensor] # B x (L_t,) long
|
| 34 |
+
latents: torch.Tensor # (B, F, D), F multiple of patch, right-padded
|
| 35 |
+
latent_lens: torch.Tensor # (B,) frames, multiples of patch
|
| 36 |
+
loss_start: torch.Tensor # (B,) frame where the target region starts (multiple of patch)
|
| 37 |
+
ref_latents: torch.Tensor | None = None # (B, F_r, D)
|
| 38 |
+
ref_mask: torch.Tensor | None = None # (B, F_r) bool
|
| 39 |
+
has_ref: torch.Tensor | None = None # (B,) bool
|
| 40 |
+
clock_midi: torch.Tensor | None = None # (B, F) long
|
| 41 |
+
clock_cont: torch.Tensor | None = None # (B, F, N_CONT)
|
| 42 |
+
clock_lag: torch.Tensor | None = None # (B, F // patch) long
|
| 43 |
+
ctc_targets: torch.Tensor | None = None # (B, L_c) long, padded
|
| 44 |
+
ctc_lens: torch.Tensor | None = None # (B,)
|
| 45 |
+
|
| 46 |
+
def to(self, device):
|
| 47 |
+
mv = lambda x: x.to(device) if isinstance(x, torch.Tensor) else x
|
| 48 |
+
return PhotonBatch(**{k: ([mv(t) for t in v] if isinstance(v, list) else mv(v)) for k, v in self.__dict__.items()})
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class PhotonTTS(nn.Module):
|
| 52 |
+
def __init__(self, cfg: PhotonConfig, vocab_size: int):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.cfg = cfg
|
| 55 |
+
self.patch = p = cfg.patch
|
| 56 |
+
D = cfg.codec.latent_dim
|
| 57 |
+
self.backbone = build_backbone(cfg.backbone, vocab_size)
|
| 58 |
+
H = self.backbone.config.hidden_size
|
| 59 |
+
self.hidden = H
|
| 60 |
+
self.audio_in = nn.Linear(p * D, H)
|
| 61 |
+
self.audio_bos = nn.Parameter(torch.randn(H) * 0.02)
|
| 62 |
+
self.speaker = SpeakerEncoder(cfg.speaker, D, H)
|
| 63 |
+
self.clock = ScoreClockEmbed(cfg.clock.frame_dim, H, p)
|
| 64 |
+
self.head = PhotonHead(cfg.head, D, p, H, frame_cond_dim=cfg.clock.frame_dim)
|
| 65 |
+
self.stop = StopHead(H)
|
| 66 |
+
self.ctc = CTCHead(H, cfg.loss.ctc_upsample)
|
| 67 |
+
self.n_ctx = self.head.n_ctx
|
| 68 |
+
|
| 69 |
+
# ------------------------------------------------------------------ helpers
|
| 70 |
+
def _speaker_tokens(self, ref, ref_mask, has_ref, B, device, drop_p=0.0):
|
| 71 |
+
null = self.speaker.null(B).to(device)
|
| 72 |
+
if ref is None or has_ref is None or not bool(has_ref.any()):
|
| 73 |
+
return null, None
|
| 74 |
+
tok, emo = self.speaker(ref, ref_mask)
|
| 75 |
+
keep = has_ref.clone()
|
| 76 |
+
if drop_p > 0 and self.training:
|
| 77 |
+
keep &= torch.rand(B, device=device) >= drop_p
|
| 78 |
+
return torch.where(keep[:, None, None], tok, null), emo
|
| 79 |
+
|
| 80 |
+
def _clock(self, midi, cont, lag, B, Fn, device, drop_p=0.0):
|
| 81 |
+
if midi is None:
|
| 82 |
+
m, c = null_features(Fn)
|
| 83 |
+
midi, cont = m[None].expand(B, -1).to(device), c[None].expand(B, -1, -1).to(device)
|
| 84 |
+
elif drop_p > 0 and self.training:
|
| 85 |
+
drop = torch.rand(B, device=device) < drop_p
|
| 86 |
+
midi = torch.where(drop[:, None], torch.full_like(midi, NONE), midi)
|
| 87 |
+
cont = torch.where(drop[:, None, None], torch.zeros_like(cont), cont)
|
| 88 |
+
return self.clock(midi, cont, lag)
|
| 89 |
+
|
| 90 |
+
def _windows(self, x): # (B, F, C) -> (B, P, n_ctx + patch, C): context + target frames per patch
|
| 91 |
+
x = F.pad(x, (0, 0, self.n_ctx, 0))
|
| 92 |
+
return x.unfold(1, self.n_ctx + self.patch, self.patch).permute(0, 1, 3, 2)
|
| 93 |
+
|
| 94 |
+
# ------------------------------------------------------------------ training
|
| 95 |
+
def forward(self, b: PhotonBatch) -> dict[str, torch.Tensor]:
|
| 96 |
+
cfg, p = self.cfg, self.patch
|
| 97 |
+
B, Fn, D = b.latents.shape
|
| 98 |
+
P = Fn // p
|
| 99 |
+
dev = b.latents.device
|
| 100 |
+
dtype = next(self.backbone.parameters()).dtype
|
| 101 |
+
n_patch = b.latent_lens // p # (B,)
|
| 102 |
+
ls_patch = b.loss_start // p
|
| 103 |
+
|
| 104 |
+
spk, emo = self._speaker_tokens(b.ref_latents, b.ref_mask, b.has_ref, B, dev, cfg.speaker.p_drop)
|
| 105 |
+
# Clock for P + 1 patches: the stop position must see the same kind of clock input as at
|
| 106 |
+
# inference (null / rest features), never a zero pad - a zero there would leak the length.
|
| 107 |
+
midi, cont = b.clock_midi, b.clock_cont
|
| 108 |
+
if midi is not None:
|
| 109 |
+
last = midi[:, -1:]
|
| 110 |
+
pad_val = torch.where(last == NONE, NONE, REST)
|
| 111 |
+
midi = torch.cat([midi, pad_val.expand(-1, p)], 1)
|
| 112 |
+
cont = F.pad(cont, (0, 0, 0, p))
|
| 113 |
+
lag = None if b.clock_lag is None else F.pad(b.clock_lag, (0, 1))
|
| 114 |
+
frame_emb, clock_patch = self._clock(midi, cont, lag, B, Fn + p, dev, cfg.clock.p_drop)
|
| 115 |
+
frame_emb = frame_emb[:, :Fn]
|
| 116 |
+
|
| 117 |
+
patches = b.latents.reshape(B, P, p * D)
|
| 118 |
+
audio_inp = torch.cat([self.audio_bos.expand(B, 1, -1), self.audio_in(patches)], 1) # (B, P+1, H)
|
| 119 |
+
audio_inp = audio_inp + clock_patch
|
| 120 |
+
|
| 121 |
+
embed = self.backbone.get_input_embeddings()
|
| 122 |
+
seqs, starts = [], []
|
| 123 |
+
for i in range(B):
|
| 124 |
+
txt = embed(b.text_ids[i])
|
| 125 |
+
starts.append(spk.shape[1] + txt.shape[0])
|
| 126 |
+
seqs.append(torch.cat([spk[i], txt, audio_inp[i, : n_patch[i] + 1]], 0))
|
| 127 |
+
lens = torch.tensor([s.shape[0] for s in seqs], device=dev)
|
| 128 |
+
x = nn.utils.rnn.pad_sequence(seqs, batch_first=True).to(dtype)
|
| 129 |
+
attn = (torch.arange(x.shape[1], device=dev)[None] < lens[:, None]).long()
|
| 130 |
+
h = self.backbone(inputs_embeds=x, attention_mask=attn).last_hidden_state
|
| 131 |
+
|
| 132 |
+
# gather audio-position states: (B, P+1, H)
|
| 133 |
+
j = torch.arange(P + 1, device=dev)
|
| 134 |
+
idx = (torch.tensor(starts, device=dev)[:, None] + j[None]).clamp(max=h.shape[1] - 1)
|
| 135 |
+
h_audio = h.gather(1, idx[..., None].expand(-1, -1, h.shape[-1]))
|
| 136 |
+
|
| 137 |
+
# flow matching on patches in the target region
|
| 138 |
+
flow_mask = (j[None, :P] >= ls_patch[:, None]) & (j[None, :P] < n_patch[:, None])
|
| 139 |
+
win = self._windows(b.latents)
|
| 140 |
+
fwin = self._windows(frame_emb)
|
| 141 |
+
x1, ctx = win[..., self.n_ctx :, :][flow_mask], win[..., : self.n_ctx, :][flow_mask]
|
| 142 |
+
per = self.head.loss_terms(x1.to(dtype), h_audio[:, :P][flow_mask], ctx.to(dtype),
|
| 143 |
+
frame_cond=fwin[flow_mask].to(dtype))
|
| 144 |
+
loss_flow = per.mean()
|
| 145 |
+
|
| 146 |
+
# stop: positive exactly at position P_i
|
| 147 |
+
stop_valid = (j[None] >= ls_patch[:, None]) & (j[None] <= n_patch[:, None])
|
| 148 |
+
stop_lbl = (j[None] == n_patch[:, None]).float()
|
| 149 |
+
logits = self.stop(h_audio).float()
|
| 150 |
+
loss_stop = F.binary_cross_entropy_with_logits(
|
| 151 |
+
logits[stop_valid], stop_lbl[stop_valid], pos_weight=torch.tensor(10.0, device=dev))
|
| 152 |
+
|
| 153 |
+
out = {"flow": loss_flow, "stop": loss_stop}
|
| 154 |
+
total = loss_flow + cfg.loss.stop_weight * loss_stop
|
| 155 |
+
|
| 156 |
+
if b.ctc_targets is not None and cfg.loss.ctc_weight > 0:
|
| 157 |
+
tl = n_patch - ls_patch
|
| 158 |
+
T = int(tl.max())
|
| 159 |
+
cidx = (ls_patch[:, None] + torch.arange(T, device=dev)[None]).clamp(max=P)
|
| 160 |
+
hc = h_audio.gather(1, cidx[..., None].expand(-1, -1, h.shape[-1]))
|
| 161 |
+
loss_ctc = self.ctc.loss(hc, tl, b.ctc_targets, b.ctc_lens)
|
| 162 |
+
out["ctc"] = loss_ctc
|
| 163 |
+
total = total + cfg.loss.ctc_weight * loss_ctc
|
| 164 |
+
out["loss"] = total
|
| 165 |
+
return out
|
| 166 |
+
|
| 167 |
+
# ------------------------------------------------------------------ inference
|
| 168 |
+
@torch.no_grad()
|
| 169 |
+
def generate(
|
| 170 |
+
self,
|
| 171 |
+
text_ids: torch.Tensor, # (L_t,)
|
| 172 |
+
ref_latents: torch.Tensor | None = None, # (F_r, D)
|
| 173 |
+
prompt_latents: torch.Tensor | None = None, # (F_p, D), F_p multiple of patch
|
| 174 |
+
clock_midi: torch.Tensor | None = None, # (F_total,) covering prompt + generation
|
| 175 |
+
clock_cont: torch.Tensor | None = None,
|
| 176 |
+
max_patches: int = 375, # 30 s
|
| 177 |
+
min_patches: int = 2,
|
| 178 |
+
n_steps: int = 8,
|
| 179 |
+
cfg_scale: float = 1.5,
|
| 180 |
+
temperature: float = 1.0,
|
| 181 |
+
stop_threshold: float = 0.5,
|
| 182 |
+
) -> torch.Tensor:
|
| 183 |
+
p, dev = self.patch, text_ids.device
|
| 184 |
+
dtype = next(self.backbone.parameters()).dtype
|
| 185 |
+
D = self.cfg.codec.latent_dim
|
| 186 |
+
Pp = 0 if prompt_latents is None else prompt_latents.shape[0] // p
|
| 187 |
+
total_frames = (Pp + max_patches + 1) * p
|
| 188 |
+
if clock_midi is not None:
|
| 189 |
+
pad = total_frames - clock_midi.shape[0]
|
| 190 |
+
if pad > 0:
|
| 191 |
+
m, c = null_features(pad)
|
| 192 |
+
clock_midi = torch.cat([clock_midi, m.to(dev)])
|
| 193 |
+
clock_cont = torch.cat([clock_cont, c.to(dev)])
|
| 194 |
+
clock_midi, clock_cont = clock_midi[None, :total_frames], clock_cont[None, :total_frames]
|
| 195 |
+
frame_emb, clock_patch = self._clock(clock_midi, clock_cont, None, 1, total_frames, dev)
|
| 196 |
+
frame_emb, clock_patch = frame_emb.to(dtype), clock_patch.to(dtype)
|
| 197 |
+
fpad = F.pad(frame_emb, (0, 0, self.n_ctx, 0))
|
| 198 |
+
|
| 199 |
+
if ref_latents is not None:
|
| 200 |
+
spk, _ = self.speaker(ref_latents[None].to(dtype), torch.ones(1, ref_latents.shape[0], dtype=torch.bool, device=dev))
|
| 201 |
+
else:
|
| 202 |
+
spk = self.speaker.null(1)
|
| 203 |
+
txt = self.backbone.get_input_embeddings()(text_ids)[None]
|
| 204 |
+
audio = [self.audio_bos.view(1, 1, -1)]
|
| 205 |
+
frames = []
|
| 206 |
+
if Pp:
|
| 207 |
+
pl = prompt_latents[: Pp * p].to(dtype)
|
| 208 |
+
audio.append(self.audio_in(pl.reshape(1, Pp, p * D)))
|
| 209 |
+
frames = list(pl)
|
| 210 |
+
aud = torch.cat(audio, 1) + clock_patch[:, : Pp + 1]
|
| 211 |
+
x = torch.cat([spk.to(dtype), txt.to(dtype), aud.to(dtype)], 1)
|
| 212 |
+
out = self.backbone(inputs_embeds=x, use_cache=True)
|
| 213 |
+
h, pkv = out.last_hidden_state[:, -1], out.past_key_values
|
| 214 |
+
|
| 215 |
+
n_gen = 0
|
| 216 |
+
for jj in range(Pp, Pp + max_patches):
|
| 217 |
+
if n_gen >= min_patches and torch.sigmoid(self.stop(h).float()).item() > stop_threshold:
|
| 218 |
+
break
|
| 219 |
+
ctx = torch.zeros(self.n_ctx, D, device=dev, dtype=dtype)
|
| 220 |
+
if frames:
|
| 221 |
+
prev = torch.stack(frames[-self.n_ctx :])
|
| 222 |
+
ctx[self.n_ctx - prev.shape[0] :] = prev
|
| 223 |
+
fc = fpad[:, jj * p : jj * p + self.n_ctx + p] # same window layout as training
|
| 224 |
+
patch = self.head.sample(h, ctx[None], n_steps=n_steps, cfg_scale=cfg_scale,
|
| 225 |
+
temperature=temperature, frame_cond=fc)[0]
|
| 226 |
+
frames.extend(list(patch))
|
| 227 |
+
n_gen += 1
|
| 228 |
+
nxt = self.audio_in(patch.reshape(1, 1, p * D)) + clock_patch[:, jj + 1 : jj + 2]
|
| 229 |
+
out = self.backbone(inputs_embeds=nxt, past_key_values=pkv, use_cache=True)
|
| 230 |
+
h, pkv = out.last_hidden_state[:, -1], out.past_key_values
|
| 231 |
+
gen = frames[Pp * p :]
|
| 232 |
+
return torch.stack(gen) if gen else torch.zeros(0, D, device=dev)
|
code/photontts/model/photon_head.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Photon Head: a small bidirectional local DiT that generates one patch (2 latent frames)
|
| 2 |
+
per backbone step with flow matching, conditioned on the backbone state h_t (AdaLN-Zero),
|
| 3 |
+
the previous `n_ctx_patches` patches (DiTAR-style local context), and optional per-frame
|
| 4 |
+
Score Clock features (pitch / onsets at 25 Hz).
|
| 5 |
+
|
| 6 |
+
Time conditioning takes (t, r) so the same head can later be distilled with MeanFlow /
|
| 7 |
+
shortcut objectives (r = t during standard flow-matching training; dt = t - r).
|
| 8 |
+
CFG lives here only: a learned null replaces h_t with prob p_uncond.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import math
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
|
| 19 |
+
from ..config import HeadConfig
|
| 20 |
+
from ..train.flow_loss import interpolate, sample_t
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def timestep_embedding(t: torch.Tensor, dim: int, max_period: float = 10_000.0) -> torch.Tensor:
|
| 24 |
+
half = dim // 2
|
| 25 |
+
freqs = torch.exp(-math.log(max_period) * torch.arange(half, device=t.device, dtype=torch.float32) / half)
|
| 26 |
+
args = t.float()[:, None] * 1000.0 * freqs[None]
|
| 27 |
+
return torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DiTBlock(nn.Module):
|
| 31 |
+
def __init__(self, dim: int, heads: int):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.heads = heads
|
| 34 |
+
self.n1 = nn.LayerNorm(dim, elementwise_affine=False)
|
| 35 |
+
self.qkv = nn.Linear(dim, 3 * dim)
|
| 36 |
+
self.proj = nn.Linear(dim, dim)
|
| 37 |
+
self.n2 = nn.LayerNorm(dim, elementwise_affine=False)
|
| 38 |
+
self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(approximate="tanh"), nn.Linear(4 * dim, dim))
|
| 39 |
+
self.ada = nn.Linear(dim, 6 * dim)
|
| 40 |
+
nn.init.zeros_(self.ada.weight)
|
| 41 |
+
nn.init.zeros_(self.ada.bias)
|
| 42 |
+
|
| 43 |
+
def forward(self, x, c): # x: (N, L, D), c: (N, D)
|
| 44 |
+
s1, b1, g1, s2, b2, g2 = self.ada(F.silu(c))[:, None].chunk(6, dim=-1)
|
| 45 |
+
h = self.n1(x) * (1 + s1) + b1
|
| 46 |
+
N, L, D = h.shape
|
| 47 |
+
q, k, v = self.qkv(h).view(N, L, 3, self.heads, D // self.heads).permute(2, 0, 3, 1, 4)
|
| 48 |
+
a = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(N, L, D)
|
| 49 |
+
x = x + g1 * self.proj(a)
|
| 50 |
+
h = self.n2(x) * (1 + s2) + b2
|
| 51 |
+
return x + g2 * self.mlp(h)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class PhotonHead(nn.Module):
|
| 55 |
+
def __init__(self, cfg: HeadConfig, latent_dim: int, patch: int, cond_dim: int, frame_cond_dim: int = 0):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.cfg, self.patch, self.latent_dim = cfg, patch, latent_dim
|
| 58 |
+
d = cfg.dim
|
| 59 |
+
self.n_ctx = cfg.n_ctx_patches * patch # context frames
|
| 60 |
+
self.inp = nn.Linear(latent_dim, d)
|
| 61 |
+
self.pos = nn.Parameter(torch.randn(self.n_ctx + patch, d) * 0.02)
|
| 62 |
+
self.cond = nn.Sequential(nn.Linear(cond_dim, d), nn.SiLU(), nn.Linear(d, d))
|
| 63 |
+
self.null_cond = nn.Parameter(torch.zeros(cond_dim))
|
| 64 |
+
self.t_mlp = nn.Sequential(nn.Linear(2 * 256, d), nn.SiLU(), nn.Linear(d, d))
|
| 65 |
+
self.frame_cond = nn.Linear(frame_cond_dim, d) if frame_cond_dim else None
|
| 66 |
+
self.blocks = nn.ModuleList(DiTBlock(d, cfg.heads) for _ in range(cfg.layers))
|
| 67 |
+
self.norm_out = nn.LayerNorm(d, elementwise_affine=False)
|
| 68 |
+
self.ada_out = nn.Linear(d, 2 * d)
|
| 69 |
+
self.out = nn.Linear(d, latent_dim)
|
| 70 |
+
for m in (self.ada_out, self.out):
|
| 71 |
+
nn.init.zeros_(m.weight)
|
| 72 |
+
nn.init.zeros_(m.bias)
|
| 73 |
+
|
| 74 |
+
def forward(self, x_t, t, h, ctx, r=None, frame_cond=None):
|
| 75 |
+
"""x_t: (N, patch, D) noisy target frames; t, r: (N,); h: (N, cond_dim);
|
| 76 |
+
ctx: (N, n_ctx, D) previous clean frames; frame_cond: (N, n_ctx + patch, frame_cond_dim).
|
| 77 |
+
Returns predicted velocity (N, patch, D)."""
|
| 78 |
+
r = t if r is None else r
|
| 79 |
+
dt = self.inp.weight.dtype # timesteps / noise scales are fp32; run the net in param dtype
|
| 80 |
+
x_t, ctx, h = x_t.to(dt), ctx.to(dt), h.to(dt)
|
| 81 |
+
x = self.inp(torch.cat([ctx, x_t], dim=1)) + self.pos
|
| 82 |
+
if self.frame_cond is not None and frame_cond is not None:
|
| 83 |
+
x = x + self.frame_cond(frame_cond.to(dt))
|
| 84 |
+
temb = torch.cat([timestep_embedding(t, 256), timestep_embedding(t - r, 256)], dim=-1).to(dt)
|
| 85 |
+
c = self.cond(h) + self.t_mlp(temb)
|
| 86 |
+
for blk in self.blocks:
|
| 87 |
+
x = blk(x, c)
|
| 88 |
+
s, b = self.ada_out(F.silu(c))[:, None].chunk(2, dim=-1)
|
| 89 |
+
x = self.norm_out(x) * (1 + s) + b
|
| 90 |
+
return self.out(x[:, -self.patch :])
|
| 91 |
+
|
| 92 |
+
def drop_cond(self, h: torch.Tensor, p: float) -> torch.Tensor:
|
| 93 |
+
if p <= 0 or not self.training:
|
| 94 |
+
return h
|
| 95 |
+
drop = torch.rand(h.shape[0], device=h.device) < p
|
| 96 |
+
return torch.where(drop[:, None], self.null_cond.to(h.dtype).expand_as(h), h)
|
| 97 |
+
|
| 98 |
+
def loss_terms(self, x1, h, ctx, frame_cond=None):
|
| 99 |
+
"""Flow-matching training on a flat batch of patches. Returns per-item MSE (N * K,)
|
| 100 |
+
with K = cfg.noise_samples draws per backbone state (cheap: head is small)."""
|
| 101 |
+
K = self.cfg.noise_samples
|
| 102 |
+
rep = lambda z: None if z is None else z.repeat_interleave(K, dim=0)
|
| 103 |
+
x1, h, ctx, frame_cond = rep(x1), rep(h), rep(ctx), rep(frame_cond)
|
| 104 |
+
if self.cfg.ctx_noise > 0 and self.training:
|
| 105 |
+
ctx = ctx + torch.randn_like(ctx) * self.cfg.ctx_noise * torch.rand(ctx.shape[0], 1, 1, device=ctx.device)
|
| 106 |
+
h = self.drop_cond(h, self.cfg.p_uncond)
|
| 107 |
+
t = sample_t(x1.shape[0], x1.device)
|
| 108 |
+
x_t, v = interpolate(x1, torch.randn_like(x1), t)
|
| 109 |
+
pred = self(x_t, t, h, ctx, frame_cond=frame_cond)
|
| 110 |
+
return (pred.float() - v.float()).pow(2).flatten(1).mean(1)
|
| 111 |
+
|
| 112 |
+
@torch.no_grad()
|
| 113 |
+
def sample(self, h, ctx, n_steps: int = 8, cfg_scale: float = 1.5, temperature: float = 1.0,
|
| 114 |
+
frame_cond=None, sway: float = -1.0):
|
| 115 |
+
"""Euler sampling with head-only CFG. sway < 0 front-loads steps near t=0 (F5 sway sampling)."""
|
| 116 |
+
N = h.shape[0]
|
| 117 |
+
x = torch.randn(N, self.patch, self.latent_dim, device=h.device, dtype=h.dtype) * temperature
|
| 118 |
+
ts = torch.linspace(0, 1, n_steps + 1, device=h.device)
|
| 119 |
+
if sway:
|
| 120 |
+
ts = ts + sway * (torch.cos(math.pi / 2 * ts) - 1 + ts)
|
| 121 |
+
null = self.null_cond.to(h.dtype).expand_as(h)
|
| 122 |
+
for i in range(n_steps):
|
| 123 |
+
t = ts[i].expand(N)
|
| 124 |
+
if cfg_scale != 1.0:
|
| 125 |
+
both = self(torch.cat([x, x]), torch.cat([t, t]), torch.cat([h, null]), torch.cat([ctx, ctx]),
|
| 126 |
+
frame_cond=None if frame_cond is None else torch.cat([frame_cond, frame_cond]))
|
| 127 |
+
vc, vu = both.chunk(2)
|
| 128 |
+
v = vu + cfg_scale * (vc - vu)
|
| 129 |
+
else:
|
| 130 |
+
v = self(x, t, h, ctx, frame_cond=frame_cond)
|
| 131 |
+
x = x + (ts[i + 1] - ts[i]) * v
|
| 132 |
+
return x
|
code/photontts/text/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .tokenizer import CTC_VOCAB, ByteTokenizer, HFTokenizer, build_tokenizer, ctc_targets
|
| 2 |
+
|
| 3 |
+
__all__ = ["CTC_VOCAB", "ByteTokenizer", "HFTokenizer", "build_tokenizer", "ctc_targets"]
|
code/photontts/text/tags.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Control vocabulary shared by every tokenizer: modes, languages, bandwidth, inline tags, speaker turns."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
MODES = ["speech", "sing", "rap", "whisper", "vc", "edit", "dialog"]
|
| 8 |
+
LANGS = ["en", "zh", "ja", "ko", "es", "fr", "de", "it", "pt", "ru", "ar", "hi", "nl", "pl", "tr", "vi"]
|
| 9 |
+
BANDWIDTHS = ["bw8k", "bw12k", "bw24k"]
|
| 10 |
+
PARALINGUISTIC = ["laugh", "breath", "sigh", "uh", "um", "cough", "sniff", "cry", "gasp"]
|
| 11 |
+
SPANS = ["whisper", "emph", "shout", "sing_note"] # used as <x> ... </x>
|
| 12 |
+
MAX_SPEAKERS = 8
|
| 13 |
+
|
| 14 |
+
# Structural tokens used to assemble backbone sequences.
|
| 15 |
+
STRUCTURAL = ["<pad>", "<bos_text>", "<eos_text>", "<style>", "</style>", "<ph>", "</ph>", "<audio>"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def special_tokens() -> list[str]:
|
| 19 |
+
toks = list(STRUCTURAL)
|
| 20 |
+
toks += [f"<mode:{m}>" for m in MODES]
|
| 21 |
+
toks += [f"<lang:{l}>" for l in LANGS]
|
| 22 |
+
toks += [f"<{b}>" for b in BANDWIDTHS]
|
| 23 |
+
toks += [f"<{p}>" for p in PARALINGUISTIC]
|
| 24 |
+
for s in SPANS:
|
| 25 |
+
toks += [f"<{s}>", f"</{s}>"]
|
| 26 |
+
toks += [f"[S{i}]" for i in range(1, MAX_SPEAKERS + 1)]
|
| 27 |
+
return list(dict.fromkeys(toks)) # dedupe, keep order
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
SPECIAL_TOKENS = special_tokens()
|
| 31 |
+
_SPECIAL_SET = set(SPECIAL_TOKENS)
|
| 32 |
+
_SPECIAL_RE = re.compile("(" + "|".join(re.escape(t) for t in sorted(SPECIAL_TOKENS, key=len, reverse=True)) + ")")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def split_specials(text: str) -> list[tuple[str, bool]]:
|
| 36 |
+
"""Split text into [(chunk, is_special)] keeping order."""
|
| 37 |
+
out = []
|
| 38 |
+
for part in _SPECIAL_RE.split(text):
|
| 39 |
+
if part:
|
| 40 |
+
out.append((part, part in _SPECIAL_SET))
|
| 41 |
+
return out
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def strip_tags(text: str) -> str:
|
| 45 |
+
"""Spoken content only (for CTC targets / ASR comparison): drop all control tokens."""
|
| 46 |
+
return re.sub(r"\s+", " ", _SPECIAL_RE.sub(" ", text)).strip()
|
code/photontts/text/tokenizer.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tokenizers. All expose the same interface:
|
| 2 |
+
|
| 3 |
+
tok.encode(text) -> list[int] # control tokens like <laugh> map to single ids
|
| 4 |
+
tok.vocab_size, tok.pad_id, tok.id(token_str)
|
| 5 |
+
|
| 6 |
+
ByteTokenizer: UTF-8 bytes + control tokens. Language-agnostic, used for tests and Photon-S fallback.
|
| 7 |
+
HFTokenizer: wraps a pretrained LLM tokenizer (Qwen3) with the control tokens added.
|
| 8 |
+
|
| 9 |
+
CTC targets always use bytes (`ctc_targets`), independent of the backbone tokenizer.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from .tags import SPECIAL_TOKENS, split_specials, strip_tags
|
| 15 |
+
|
| 16 |
+
CTC_BLANK = 0 # CTC vocab: 0 = blank, 1..256 = byte value + 1
|
| 17 |
+
CTC_VOCAB = 257
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def ctc_targets(text: str) -> list[int]:
|
| 21 |
+
return [b + 1 for b in strip_tags(text).encode("utf-8")]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ByteTokenizer:
|
| 25 |
+
def __init__(self):
|
| 26 |
+
self.specials = {t: 256 + i for i, t in enumerate(SPECIAL_TOKENS)}
|
| 27 |
+
self.vocab_size = 256 + len(SPECIAL_TOKENS)
|
| 28 |
+
self.pad_id = self.specials["<pad>"]
|
| 29 |
+
|
| 30 |
+
def id(self, token: str) -> int:
|
| 31 |
+
return self.specials[token]
|
| 32 |
+
|
| 33 |
+
def encode(self, text: str) -> list[int]:
|
| 34 |
+
ids: list[int] = []
|
| 35 |
+
for chunk, special in split_specials(text):
|
| 36 |
+
ids.extend([self.specials[chunk]] if special else chunk.encode("utf-8"))
|
| 37 |
+
return ids
|
| 38 |
+
|
| 39 |
+
def decode(self, ids: list[int]) -> str:
|
| 40 |
+
inv = {v: k for k, v in self.specials.items()}
|
| 41 |
+
out, buf = [], bytearray()
|
| 42 |
+
for i in ids:
|
| 43 |
+
if i < 256:
|
| 44 |
+
buf.append(i)
|
| 45 |
+
else:
|
| 46 |
+
out.append(buf.decode("utf-8", errors="replace"))
|
| 47 |
+
buf = bytearray()
|
| 48 |
+
out.append(inv.get(i, ""))
|
| 49 |
+
out.append(buf.decode("utf-8", errors="replace"))
|
| 50 |
+
return "".join(out)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class HFTokenizer:
|
| 54 |
+
def __init__(self, name: str):
|
| 55 |
+
from transformers import AutoTokenizer
|
| 56 |
+
|
| 57 |
+
self.tok = AutoTokenizer.from_pretrained(name)
|
| 58 |
+
self.tok.add_special_tokens({"additional_special_tokens": SPECIAL_TOKENS})
|
| 59 |
+
self.vocab_size = len(self.tok)
|
| 60 |
+
self.pad_id = self.tok.convert_tokens_to_ids("<pad>")
|
| 61 |
+
|
| 62 |
+
def id(self, token: str) -> int:
|
| 63 |
+
return self.tok.convert_tokens_to_ids(token)
|
| 64 |
+
|
| 65 |
+
def encode(self, text: str) -> list[int]:
|
| 66 |
+
return self.tok.encode(text, add_special_tokens=False)
|
| 67 |
+
|
| 68 |
+
def decode(self, ids: list[int]) -> str:
|
| 69 |
+
return self.tok.decode(ids)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def build_tokenizer(name: str):
|
| 73 |
+
return ByteTokenizer() if name == "bytes" else HFTokenizer(name)
|
code/photontts/train/__init__.py
ADDED
|
File without changes
|
code/photontts/train/flow_loss.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rectified-flow / conditional flow matching utilities.
|
| 2 |
+
|
| 3 |
+
Convention: x_t = (1 - t) * noise + t * data, t in [0, 1]; velocity target v = data - noise.
|
| 4 |
+
Sampling integrates dx/dt = v from t = 0 (noise) to t = 1 (data).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def sample_t(n: int, device, mean: float = 0.0, std: float = 1.0) -> torch.Tensor:
|
| 13 |
+
"""Logit-normal timesteps (SD3): concentrates training on mid-range noise levels."""
|
| 14 |
+
return torch.sigmoid(torch.randn(n, device=device) * std + mean)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def interpolate(x1: torch.Tensor, noise: torch.Tensor, t: torch.Tensor):
|
| 18 |
+
tt = t.view(-1, *([1] * (x1.dim() - 1)))
|
| 19 |
+
return (1 - tt) * noise + tt * x1, x1 - noise
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def flow_loss(pred_v: torch.Tensor, target_v: torch.Tensor, weight: torch.Tensor | None = None) -> torch.Tensor:
|
| 23 |
+
"""MSE over all but the batch dim, optionally weighted per item (e.g. loss masks)."""
|
| 24 |
+
per = (pred_v.float() - target_v.float()).pow(2).flatten(1).mean(1)
|
| 25 |
+
if weight is None:
|
| 26 |
+
return per.mean()
|
| 27 |
+
return (per * weight).sum() / weight.sum().clamp(min=1.0)
|
code/pyproject.toml
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=68"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "photontts"
|
| 7 |
+
version = "0.0.1"
|
| 8 |
+
description = "PhotonTTS: fast, human-like, zero-shot voice-cloning TTS with singing"
|
| 9 |
+
requires-python = ">=3.11"
|
| 10 |
+
dependencies = [
|
| 11 |
+
"torch>=2.4",
|
| 12 |
+
"numpy",
|
| 13 |
+
"einops",
|
| 14 |
+
"pyyaml",
|
| 15 |
+
"safetensors",
|
| 16 |
+
"transformers>=4.51",
|
| 17 |
+
"huggingface_hub>=0.30",
|
| 18 |
+
"soundfile",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
[project.optional-dependencies]
|
| 22 |
+
dev = ["pytest>=8"]
|
| 23 |
+
data = ["webdataset", "pyworld"]
|
| 24 |
+
|
| 25 |
+
[tool.setuptools.packages.find]
|
| 26 |
+
include = ["photontts*"]
|
| 27 |
+
|
| 28 |
+
[tool.pytest.ini_options]
|
| 29 |
+
testpaths = ["tests"]
|
| 30 |
+
markers = ["slow: overfit tests that train for a few hundred steps", "gpu: requires CUDA"]
|
code/scripts/hf_sync.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Back up local artifacts to the public Hugging Face repos, keeping total storage under a cap.
|
| 2 |
+
|
| 3 |
+
model repo <user>/PhotonTTS code snapshot + checkpoints (runs/<name>/ckpt-*)
|
| 4 |
+
dataset repo <user>/PhotonTTS-data latent shards, manifests, processed metadata
|
| 5 |
+
|
| 6 |
+
Usage (on the GPU box, inside tmux):
|
| 7 |
+
python scripts/hf_sync.py --runs /root/runs --data /root/data/shards --every 3600
|
| 8 |
+
|
| 9 |
+
Raw audio is never uploaded by this script. The cap counts both repos together.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import os
|
| 16 |
+
import time
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from huggingface_hub import HfApi
|
| 20 |
+
|
| 21 |
+
TB = 1000**4
|
| 22 |
+
CODE_IGNORE = ["**/__pycache__/**", "**/.pytest_cache/**", ".venv/**", "runs/**", "data/**", "*.pyc", ".git/**"]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def repo_bytes(api: HfApi, repo_id: str, repo_type: str) -> int:
|
| 26 |
+
total = 0
|
| 27 |
+
for f in api.list_repo_tree(repo_id, repo_type=repo_type, recursive=True):
|
| 28 |
+
total += getattr(f, "size", 0) or 0
|
| 29 |
+
return total
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def dir_bytes(path: Path) -> int:
|
| 33 |
+
return sum(p.stat().st_size for p in path.rglob("*") if p.is_file())
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def keep_last_checkpoints(run_dir: Path, keep: int) -> list[Path]:
|
| 37 |
+
ckpts = sorted((p for p in run_dir.glob("ckpt-*") if p.is_dir()), key=lambda p: p.stat().st_mtime)
|
| 38 |
+
return ckpts[-keep:]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def sync_once(args, api: HfApi) -> None:
|
| 42 |
+
user = api.whoami()["name"]
|
| 43 |
+
model_repo, data_repo = f"{user}/{args.model_repo}", f"{user}/{args.data_repo}"
|
| 44 |
+
used = repo_bytes(api, model_repo, "model") + repo_bytes(api, data_repo, "dataset")
|
| 45 |
+
cap = int(args.cap_tb * TB)
|
| 46 |
+
print(f"[hf_sync] used {used / TB:.3f} TB of {args.cap_tb} TB cap", flush=True)
|
| 47 |
+
|
| 48 |
+
if args.code:
|
| 49 |
+
api.upload_folder(repo_id=model_repo, folder_path=args.code, path_in_repo="code",
|
| 50 |
+
ignore_patterns=CODE_IGNORE, commit_message="sync code")
|
| 51 |
+
|
| 52 |
+
if args.runs and Path(args.runs).exists():
|
| 53 |
+
for run in sorted(p for p in Path(args.runs).iterdir() if p.is_dir()):
|
| 54 |
+
for ck in keep_last_checkpoints(run, args.keep):
|
| 55 |
+
size = dir_bytes(ck)
|
| 56 |
+
if used + size > cap:
|
| 57 |
+
print(f"[hf_sync] SKIP {ck} ({size / 1e9:.1f} GB): would exceed cap", flush=True)
|
| 58 |
+
continue
|
| 59 |
+
api.upload_folder(repo_id=model_repo, folder_path=str(ck), path_in_repo=f"runs/{run.name}/{ck.name}",
|
| 60 |
+
commit_message=f"checkpoint {run.name}/{ck.name}")
|
| 61 |
+
used += size # upper bound; HF dedupes unchanged files
|
| 62 |
+
logs = run / "logs"
|
| 63 |
+
if logs.exists():
|
| 64 |
+
api.upload_folder(repo_id=model_repo, folder_path=str(logs), path_in_repo=f"runs/{run.name}/logs",
|
| 65 |
+
commit_message=f"logs {run.name}")
|
| 66 |
+
|
| 67 |
+
if args.data and Path(args.data).exists():
|
| 68 |
+
size = dir_bytes(Path(args.data))
|
| 69 |
+
if used + size > cap:
|
| 70 |
+
print(f"[hf_sync] data dir {size / TB:.2f} TB may exceed cap; uploading anyway is refused", flush=True)
|
| 71 |
+
else:
|
| 72 |
+
# resumable, chunked, multi-worker upload designed for TB-scale folders
|
| 73 |
+
api.upload_large_folder(repo_id=data_repo, repo_type="dataset", folder_path=args.data,
|
| 74 |
+
ignore_patterns=["**/raw/**", "*.wav", "*.flac", "*.mp3", "*.opus"])
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def main():
|
| 78 |
+
ap = argparse.ArgumentParser()
|
| 79 |
+
ap.add_argument("--code", default=str(Path(__file__).resolve().parents[1]))
|
| 80 |
+
ap.add_argument("--runs", default=None)
|
| 81 |
+
ap.add_argument("--data", default=None)
|
| 82 |
+
ap.add_argument("--model-repo", default="PhotonTTS")
|
| 83 |
+
ap.add_argument("--data-repo", default="PhotonTTS-data")
|
| 84 |
+
ap.add_argument("--cap-tb", type=float, default=float(os.environ.get("PHOTON_HF_CAP_TB", 7.0)))
|
| 85 |
+
ap.add_argument("--keep", type=int, default=2, help="checkpoints per run to keep on HF")
|
| 86 |
+
ap.add_argument("--every", type=int, default=0, help="seconds between syncs; 0 = once")
|
| 87 |
+
args = ap.parse_args()
|
| 88 |
+
api = HfApi()
|
| 89 |
+
while True:
|
| 90 |
+
try:
|
| 91 |
+
sync_once(args, api)
|
| 92 |
+
except Exception as e: # never crash the sync loop on a transient HF error
|
| 93 |
+
print(f"[hf_sync] error: {e!r}", flush=True)
|
| 94 |
+
if not args.every:
|
| 95 |
+
break
|
| 96 |
+
time.sleep(args.every)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
main()
|
code/scripts/smoke_pretrained.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smoke test a real tier config on GPU: build, train steps on random latents, timed generation.
|
| 2 |
+
|
| 3 |
+
python scripts/smoke_pretrained.py --config configs/photon_m.yaml --batch 8 --seconds 20
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from photontts.config import load_config
|
| 14 |
+
from photontts.model.photon import PhotonBatch, PhotonTTS
|
| 15 |
+
from photontts.text.tokenizer import build_tokenizer, ctc_targets
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
ap = argparse.ArgumentParser()
|
| 20 |
+
ap.add_argument("--config", default="configs/photon_m.yaml")
|
| 21 |
+
ap.add_argument("--batch", type=int, default=8)
|
| 22 |
+
ap.add_argument("--seconds", type=float, default=20.0)
|
| 23 |
+
ap.add_argument("--steps", type=int, default=5)
|
| 24 |
+
args = ap.parse_args()
|
| 25 |
+
|
| 26 |
+
cfg = load_config(args.config)
|
| 27 |
+
tok = build_tokenizer(cfg.tokenizer)
|
| 28 |
+
dev = "cuda"
|
| 29 |
+
t0 = time.time()
|
| 30 |
+
model = PhotonTTS(cfg, tok.vocab_size).to(dev, torch.bfloat16)
|
| 31 |
+
n = lambda m: sum(p.numel() for p in m.parameters()) / 1e6
|
| 32 |
+
print(f"built {cfg.name} in {time.time() - t0:.1f}s | total {n(model):.0f}M | backbone {n(model.backbone):.0f}M "
|
| 33 |
+
f"| head {n(model.head):.1f}M | speaker {n(model.speaker):.1f}M | vocab {tok.vocab_size}")
|
| 34 |
+
|
| 35 |
+
B, Fn = args.batch, int(args.seconds * 25) // 2 * 2
|
| 36 |
+
text = "<mode:speech><lang:en><bw24k>" + "The quick brown fox jumps over the lazy dog. " * int(args.seconds / 3)
|
| 37 |
+
ctc = torch.tensor(ctc_targets(text))
|
| 38 |
+
b = PhotonBatch(
|
| 39 |
+
text_ids=[torch.tensor(tok.encode(text))] * B,
|
| 40 |
+
latents=torch.randn(B, Fn, 64),
|
| 41 |
+
latent_lens=torch.full((B,), Fn),
|
| 42 |
+
loss_start=torch.zeros(B, dtype=torch.long),
|
| 43 |
+
ref_latents=torch.randn(B, 250, 64), ref_mask=torch.ones(B, 250, dtype=torch.bool),
|
| 44 |
+
has_ref=torch.ones(B, dtype=torch.bool),
|
| 45 |
+
ctc_targets=ctc[None].expand(B, -1).contiguous(), ctc_lens=torch.full((B,), len(ctc)),
|
| 46 |
+
).to(dev)
|
| 47 |
+
b.latents, b.ref_latents = b.latents.bfloat16(), b.ref_latents.bfloat16()
|
| 48 |
+
opt = torch.optim.AdamW(model.parameters(), lr=1e-5)
|
| 49 |
+
model.train()
|
| 50 |
+
torch.cuda.reset_peak_memory_stats()
|
| 51 |
+
for i in range(args.steps):
|
| 52 |
+
torch.cuda.synchronize()
|
| 53 |
+
t = time.time()
|
| 54 |
+
out = model(b)
|
| 55 |
+
out["loss"].backward()
|
| 56 |
+
opt.step()
|
| 57 |
+
opt.zero_grad(set_to_none=True)
|
| 58 |
+
torch.cuda.synchronize()
|
| 59 |
+
dt = time.time() - t
|
| 60 |
+
audio_s = B * args.seconds
|
| 61 |
+
print(f"step {i}: {dt * 1000:.0f} ms | {audio_s / dt:.0f} s-audio/s | "
|
| 62 |
+
+ " ".join(f"{k}={v.item():.3f}" for k, v in out.items()))
|
| 63 |
+
print(f"peak mem {torch.cuda.max_memory_allocated() / 1e9:.1f} GB (bf16 weights, fp32 AdamW states not 8-bit yet)")
|
| 64 |
+
|
| 65 |
+
model.eval()
|
| 66 |
+
ids = torch.tensor(tok.encode("<mode:speech><lang:en>Hello from Photon."), device=dev)
|
| 67 |
+
ref = torch.randn(250, 64, device=dev, dtype=torch.bfloat16)
|
| 68 |
+
for steps, cfgs in ((8, 1.5), (2, 1.0)):
|
| 69 |
+
torch.cuda.synchronize()
|
| 70 |
+
t = time.time()
|
| 71 |
+
z = model.generate(ids, ref_latents=ref, max_patches=125, min_patches=125, n_steps=steps, cfg_scale=cfgs)
|
| 72 |
+
torch.cuda.synchronize()
|
| 73 |
+
dt = time.time() - t
|
| 74 |
+
print(f"generate {z.shape[0] / 25:.1f}s audio, {steps} head steps, cfg {cfgs}: {dt:.2f}s "
|
| 75 |
+
f"-> RTF {dt / (z.shape[0] / 25):.3f} | {dt / 125 * 1000:.1f} ms/patch (eager, no CUDA graphs)")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
main()
|
code/tests/conftest.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 8 |
+
|
| 9 |
+
from photontts.config import config_from_dict # noqa: E402
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def pytest_collection_modifyitems(config, items):
|
| 13 |
+
if not torch.cuda.is_available():
|
| 14 |
+
skip = pytest.mark.skip(reason="needs CUDA")
|
| 15 |
+
for it in items:
|
| 16 |
+
if "gpu" in it.keywords:
|
| 17 |
+
it.add_marker(skip)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.fixture
|
| 21 |
+
def device():
|
| 22 |
+
return "cuda" if torch.cuda.is_available() else "cpu"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.fixture
|
| 26 |
+
def tiny_cfg():
|
| 27 |
+
return config_from_dict({
|
| 28 |
+
"name": "tiny",
|
| 29 |
+
"tokenizer": "bytes",
|
| 30 |
+
"patch": 2,
|
| 31 |
+
"codec": {"enc_channels": [8, 16, 16, 32, 32], "dec_dim": 64, "dec_layers": 2},
|
| 32 |
+
"backbone": {"pretrained": None, "hidden_size": 128, "num_layers": 2, "num_heads": 4,
|
| 33 |
+
"num_kv_heads": 2, "intermediate_size": 256, "attn_implementation": "sdpa"},
|
| 34 |
+
"head": {"dim": 96, "layers": 2, "heads": 4, "noise_samples": 2, "p_uncond": 0.1},
|
| 35 |
+
"speaker": {"n_tokens": 4, "dim": 64, "layers": 2, "heads": 4},
|
| 36 |
+
"clock": {"frame_dim": 32},
|
| 37 |
+
})
|
code/tests/test_codec.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from photontts.codec.discriminators import CodecDiscriminator
|
| 7 |
+
from photontts.codec.losses import MultiResMelLoss, disc_loss, feature_matching_loss, gen_adv_loss
|
| 8 |
+
from photontts.codec.semantic_reg import SemanticProjector
|
| 9 |
+
from photontts.codec.vae import PhotonCodec, istft_same
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def tones(n: int, seconds: float = 1.0, sr: int = 24_000):
|
| 13 |
+
"""Harmonic tones with varying pitch: a cheap stand-in for voiced audio."""
|
| 14 |
+
t = torch.arange(int(seconds * sr)) / sr
|
| 15 |
+
out = []
|
| 16 |
+
for i in range(n):
|
| 17 |
+
f0 = 110 * 2 ** (i / 4)
|
| 18 |
+
w = sum(torch.sin(2 * math.pi * f0 * k * t) / k for k in range(1, 6))
|
| 19 |
+
out.append(0.3 * w / w.abs().max())
|
| 20 |
+
return torch.stack(out)[:, None]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_istft_same_length():
|
| 24 |
+
spec = torch.randn(2, 481, 40, dtype=torch.complex64)
|
| 25 |
+
y = istft_same(spec, 960, 240, torch.hann_window(960))
|
| 26 |
+
assert y.shape == (2, 40 * 240)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_codec_shapes(tiny_cfg):
|
| 30 |
+
codec = PhotonCodec(tiny_cfg.codec)
|
| 31 |
+
wav = torch.randn(2, 1, 24_000)
|
| 32 |
+
out = codec(wav)
|
| 33 |
+
assert out["mean"].shape == (2, 64, 25) # 25 Hz x 64-d
|
| 34 |
+
assert out["recon"].shape == wav.shape
|
| 35 |
+
assert torch.isfinite(out["kl"])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_codec_pads_partial_frames(tiny_cfg):
|
| 39 |
+
codec = PhotonCodec(tiny_cfg.codec)
|
| 40 |
+
z = codec.encode(torch.randn(1, 1, 24_000 + 100))
|
| 41 |
+
assert z.shape[-1] == 26
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_encoder_is_causal(tiny_cfg):
|
| 45 |
+
codec = PhotonCodec(tiny_cfg.codec).eval()
|
| 46 |
+
wav = torch.randn(1, 1, 24_000)
|
| 47 |
+
z1 = codec.encode(wav)
|
| 48 |
+
wav2 = wav.clone()
|
| 49 |
+
wav2[..., 12_000:] = torch.randn(1, 1, 12_000) # change the second half only
|
| 50 |
+
z2 = codec.encode(wav2)
|
| 51 |
+
# frames ending before sample 12000 (frame f covers [960f, 960(f+1))) must be unchanged
|
| 52 |
+
assert torch.allclose(z1[..., :12], z2[..., :12], atol=1e-5)
|
| 53 |
+
assert not torch.allclose(z1[..., 13:], z2[..., 13:])
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_discriminator_and_losses(tiny_cfg):
|
| 57 |
+
disc = CodecDiscriminator(ch=8)
|
| 58 |
+
real, fake = tones(2), torch.randn(2, 1, 24_000) * 0.1
|
| 59 |
+
rl, rf = disc(real)
|
| 60 |
+
fl, ff = disc(fake)
|
| 61 |
+
assert len(rl) == 8
|
| 62 |
+
for v in (disc_loss(rl, fl), gen_adv_loss(fl), feature_matching_loss(rf, ff), MultiResMelLoss()(fake, real)):
|
| 63 |
+
assert torch.isfinite(v)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_semantic_projector():
|
| 67 |
+
proj = SemanticProjector(64, 32, hidden=32)
|
| 68 |
+
loss = proj(torch.randn(2, 64, 25), torch.randn(2, 32, 50))
|
| 69 |
+
assert 0.0 <= loss.item() <= 2.0
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@pytest.mark.slow
|
| 73 |
+
def test_codec_overfits_tones(tiny_cfg, device):
|
| 74 |
+
torch.manual_seed(0)
|
| 75 |
+
codec = PhotonCodec(tiny_cfg.codec).to(device)
|
| 76 |
+
mel = MultiResMelLoss().to(device)
|
| 77 |
+
wav = tones(4).to(device)
|
| 78 |
+
opt = torch.optim.AdamW(codec.parameters(), lr=2e-3)
|
| 79 |
+
first = None
|
| 80 |
+
for step in range(300):
|
| 81 |
+
out = codec(wav)
|
| 82 |
+
loss = mel(out["recon"], wav) + 1e-4 * out["kl"]
|
| 83 |
+
opt.zero_grad()
|
| 84 |
+
loss.backward()
|
| 85 |
+
opt.step()
|
| 86 |
+
first = first if first is not None else loss.item()
|
| 87 |
+
assert loss.item() < 0.5 * first, (first, loss.item())
|
code/tests/test_conditioning.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from photontts.conditioning.score_clock import NONE, REST, Note, Score, ScoreClockEmbed, frame_features
|
| 5 |
+
from photontts.conditioning.speaker_encoder import SpeakerEncoder
|
| 6 |
+
from photontts.config import SpeakerConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_score_frames_and_onsets():
|
| 10 |
+
s = Score([Note(0.0, 0.5, 60, syllable=0), Note(0.51, 0.49, 64, slur=True, syllable=1)], tempo_bpm=120)
|
| 11 |
+
midi, cont = frame_features(25, s)
|
| 12 |
+
assert midi[0] == 60 and midi[11] == 60
|
| 13 |
+
assert midi[13] == 64 and midi[24] == 64
|
| 14 |
+
assert cont[0, 2] == 1.0 and cont[0, 3] == 0.0 # onset at frame 0
|
| 15 |
+
assert cont[12, 2] == 1.0 # 0.51 s * 25 = 12.75 -> onset in frame 12
|
| 16 |
+
assert abs(cont[12, 3].item() - 0.75) < 1e-4 # sub-frame offset
|
| 17 |
+
assert cont[13, 0] == 1.0 # slur
|
| 18 |
+
assert cont[:, 6].eq(1.0).all() # has_beat
|
| 19 |
+
assert 0 < cont[5, 1] < cont[10, 1] < 1 # note position fraction increases
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_rests_vs_none():
|
| 23 |
+
midi, _ = frame_features(10, Score([Note(0.2, 0.1, 70)]))
|
| 24 |
+
assert midi[0] == REST and midi[5] == 70
|
| 25 |
+
midi, cont = frame_features(10, None)
|
| 26 |
+
assert midi.eq(NONE).all() and cont.abs().sum() == 0
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_transpose():
|
| 30 |
+
s = Score([Note(0, 1, 60), Note(1, 1, REST)]).transpose(3)
|
| 31 |
+
assert s.notes[0].midi == 63 and s.notes[1].midi == REST
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_f0_and_progress_features():
|
| 35 |
+
f0 = torch.tensor([0.0, 200.0, 400.0, 0.0])
|
| 36 |
+
_, cont = frame_features(4, f0=f0, total_duration=0.16)
|
| 37 |
+
assert cont[:, 9].eq(1).all() and cont[0, 8] == 0 and cont[1, 8] == 1
|
| 38 |
+
assert abs(cont[1, 7].item()) < 1e-5 # log(200/200) = 0
|
| 39 |
+
assert cont[0, 10] < cont[3, 10] <= 1.0
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_clock_embed_shapes_and_init_noop():
|
| 43 |
+
emb = ScoreClockEmbed(32, 128, 2)
|
| 44 |
+
midi, cont = frame_features(10, Score([Note(0, 0.4, 60)]))
|
| 45 |
+
frame, patch = emb(midi[None], cont[None], lag=torch.zeros(1, 5, dtype=torch.long))
|
| 46 |
+
assert frame.shape == (1, 10, 32) and patch.shape == (1, 5, 128)
|
| 47 |
+
assert patch.abs().max() == 0 # zero-init: does not perturb a pretrained LLM at start
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_speaker_encoder_mask_invariance():
|
| 51 |
+
torch.manual_seed(0)
|
| 52 |
+
enc = SpeakerEncoder(SpeakerConfig(n_tokens=4, dim=64, layers=2, heads=4), 64, 128).eval()
|
| 53 |
+
ref = torch.randn(1, 50, 64)
|
| 54 |
+
a, _ = enc(ref, torch.ones(1, 50, dtype=torch.bool))
|
| 55 |
+
padded = torch.cat([ref, torch.randn(1, 20, 64) * 100], 1)
|
| 56 |
+
mask = torch.cat([torch.ones(1, 50), torch.zeros(1, 20)], 1).bool()
|
| 57 |
+
b, _ = enc(padded, mask)
|
| 58 |
+
assert a.shape == (1, 4, 128)
|
| 59 |
+
assert torch.allclose(a, b, atol=1e-4)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_speaker_emotion_adversary_reverses_grad():
|
| 63 |
+
enc = SpeakerEncoder(SpeakerConfig(n_tokens=4, dim=32, layers=2, heads=4, n_emotions=5), 64, 64)
|
| 64 |
+
ref = torch.randn(2, 30, 64, requires_grad=True)
|
| 65 |
+
_, emo = enc(ref, torch.ones(2, 30, dtype=torch.bool))
|
| 66 |
+
assert emo.shape == (2, 5)
|
| 67 |
+
emo.sum().backward()
|
| 68 |
+
assert enc.emotion_head.weight.grad is not None
|
code/tests/test_config.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
from photontts.config import load_config
|
| 4 |
+
|
| 5 |
+
CONFIGS = Path(__file__).resolve().parents[1] / "configs"
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_all_configs_load():
|
| 9 |
+
for name in ("photon_s", "photon_m", "photon_l", "pilot", "codec"):
|
| 10 |
+
cfg = load_config(CONFIGS / f"{name}.yaml")
|
| 11 |
+
assert cfg.patch == 2
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_tier_ordering():
|
| 15 |
+
s, m, l = (load_config(CONFIGS / f"photon_{t}.yaml") for t in "sml")
|
| 16 |
+
assert s.head.dim < m.head.dim < l.head.dim
|
| 17 |
+
assert s.backbone.pretrained is None and "0.6B" in m.backbone.pretrained and "1.7B" in l.backbone.pretrained
|
code/tests/test_head.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from photontts.model.photon_head import PhotonHead
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _head(tiny_cfg, cond_dim=16, frame_dim=0):
|
| 8 |
+
return PhotonHead(tiny_cfg.head, 64, 2, cond_dim, frame_cond_dim=frame_dim)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_head_shapes_and_zero_init(tiny_cfg):
|
| 12 |
+
head = _head(tiny_cfg, frame_dim=8)
|
| 13 |
+
N = 5
|
| 14 |
+
v = head(torch.randn(N, 2, 64), torch.rand(N), torch.randn(N, 16), torch.randn(N, 4, 64),
|
| 15 |
+
frame_cond=torch.randn(N, 6, 8))
|
| 16 |
+
assert v.shape == (N, 2, 64)
|
| 17 |
+
assert v.abs().max() == 0 # adaLN-zero output init
|
| 18 |
+
x = head.sample(torch.randn(N, 16), torch.randn(N, 4, 64), n_steps=3, frame_cond=torch.randn(N, 6, 8))
|
| 19 |
+
assert x.shape == (N, 2, 64)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@pytest.mark.slow
|
| 23 |
+
def test_head_overfits_fixed_conditions(tiny_cfg, device):
|
| 24 |
+
"""4 distinct conditions -> 4 fixed target patches; sampling must recover them."""
|
| 25 |
+
torch.manual_seed(0)
|
| 26 |
+
tiny_cfg.head.p_uncond = 0.0
|
| 27 |
+
tiny_cfg.head.ctx_noise = 0.0
|
| 28 |
+
head = _head(tiny_cfg).to(device)
|
| 29 |
+
cond = torch.randn(4, 16, device=device)
|
| 30 |
+
target = torch.randn(4, 2, 64, device=device)
|
| 31 |
+
ctx = torch.zeros(4, 4, 64, device=device)
|
| 32 |
+
opt = torch.optim.AdamW(head.parameters(), lr=1e-3)
|
| 33 |
+
for _ in range(1500):
|
| 34 |
+
loss = head.loss_terms(target, cond, ctx).mean()
|
| 35 |
+
opt.zero_grad()
|
| 36 |
+
loss.backward()
|
| 37 |
+
opt.step()
|
| 38 |
+
head.eval()
|
| 39 |
+
x = head.sample(cond, ctx, n_steps=16, cfg_scale=1.0, sway=0.0)
|
| 40 |
+
err = (x - target).pow(2).mean() / target.pow(2).mean()
|
| 41 |
+
assert err < 0.1, err.item()
|
code/tests/test_photon.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from photontts.conditioning.score_clock import Note, Score, frame_features
|
| 5 |
+
from photontts.model.photon import PhotonBatch, PhotonTTS
|
| 6 |
+
from photontts.text.tokenizer import ByteTokenizer, ctc_targets
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def make_batch(tok, latents_list, texts, ref=True, loss_start=None, clock=False):
|
| 10 |
+
B = len(texts)
|
| 11 |
+
Fs = [l.shape[0] for l in latents_list]
|
| 12 |
+
Fm = max(Fs)
|
| 13 |
+
lat = torch.zeros(B, Fm, 64)
|
| 14 |
+
for i, l in enumerate(latents_list):
|
| 15 |
+
lat[i, : l.shape[0]] = l
|
| 16 |
+
ctc = [torch.tensor(ctc_targets(t)) for t in texts]
|
| 17 |
+
b = PhotonBatch(
|
| 18 |
+
text_ids=[torch.tensor(tok.encode(t)) for t in texts],
|
| 19 |
+
latents=lat,
|
| 20 |
+
latent_lens=torch.tensor(Fs),
|
| 21 |
+
loss_start=torch.tensor(loss_start or [0] * B),
|
| 22 |
+
ref_latents=torch.randn(B, 30, 64) if ref else None,
|
| 23 |
+
ref_mask=torch.ones(B, 30, dtype=torch.bool) if ref else None,
|
| 24 |
+
has_ref=torch.tensor([True] * B) if ref else None,
|
| 25 |
+
ctc_targets=torch.nn.utils.rnn.pad_sequence(ctc, batch_first=True),
|
| 26 |
+
ctc_lens=torch.tensor([len(c) for c in ctc]),
|
| 27 |
+
)
|
| 28 |
+
if clock:
|
| 29 |
+
feats = [frame_features(Fm, Score([Note(0.0, Fm / 25 / 2, 60), Note(Fm / 25 / 2, Fm / 25 / 2, 67)], 100)) for _ in range(B)]
|
| 30 |
+
b.clock_midi = torch.stack([f[0] for f in feats])
|
| 31 |
+
b.clock_cont = torch.stack([f[1] for f in feats])
|
| 32 |
+
return b
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_forward_losses_finite_and_backward(tiny_cfg):
|
| 36 |
+
tok = ByteTokenizer()
|
| 37 |
+
model = PhotonTTS(tiny_cfg, tok.vocab_size)
|
| 38 |
+
b = make_batch(tok, [torch.randn(40, 64), torch.randn(24, 64)],
|
| 39 |
+
["<mode:speech><lang:en>hello there", "<mode:sing>la la"], clock=True)
|
| 40 |
+
out = model(b)
|
| 41 |
+
for k in ("loss", "flow", "stop", "ctc"):
|
| 42 |
+
assert torch.isfinite(out[k]), k
|
| 43 |
+
out["loss"].backward()
|
| 44 |
+
assert model.audio_in.weight.grad is not None
|
| 45 |
+
assert model.speaker.queries.grad is not None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_prompt_region_excluded_from_flow_loss(tiny_cfg):
|
| 49 |
+
"""Path B: changing prompt latents must not change which patches are scored (only context)."""
|
| 50 |
+
tok = ByteTokenizer()
|
| 51 |
+
torch.manual_seed(0)
|
| 52 |
+
model = PhotonTTS(tiny_cfg, tok.vocab_size)
|
| 53 |
+
b = make_batch(tok, [torch.randn(40, 64)], ["prompt text. target text"], loss_start=[20])
|
| 54 |
+
out = model(b)
|
| 55 |
+
assert torch.isfinite(out["loss"])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_generate_shapes(tiny_cfg):
|
| 59 |
+
tok = ByteTokenizer()
|
| 60 |
+
model = PhotonTTS(tiny_cfg, tok.vocab_size).eval()
|
| 61 |
+
ids = torch.tensor(tok.encode("<mode:speech>hi"))
|
| 62 |
+
z = model.generate(ids, ref_latents=torch.randn(30, 64), max_patches=5, min_patches=5, n_steps=2)
|
| 63 |
+
assert z.shape == (10, 64)
|
| 64 |
+
z = model.generate(ids, prompt_latents=torch.randn(8, 64), max_patches=3, min_patches=3, n_steps=2)
|
| 65 |
+
assert z.shape == (6, 64)
|
| 66 |
+
midi, cont = frame_features(40, Score([Note(0, 1.0, 62)]))
|
| 67 |
+
z = model.generate(ids, clock_midi=midi, clock_cont=cont, max_patches=4, min_patches=4, n_steps=2)
|
| 68 |
+
assert z.shape == (8, 64)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@pytest.mark.slow
|
| 72 |
+
def test_overfit_one_utterance_and_stop(tiny_cfg, device):
|
| 73 |
+
"""Single utterance: losses must fall, and generation must stop near the right length."""
|
| 74 |
+
torch.manual_seed(0)
|
| 75 |
+
tiny_cfg.speaker.p_drop = 0.0
|
| 76 |
+
tiny_cfg.clock.p_drop = 0.0
|
| 77 |
+
tok = ByteTokenizer()
|
| 78 |
+
model = PhotonTTS(tiny_cfg, tok.vocab_size).to(device)
|
| 79 |
+
t = torch.arange(32)[:, None] / 32
|
| 80 |
+
lat = torch.sin(2 * torch.pi * (t * 3 + torch.arange(64)[None] / 64)) # smooth structured latents
|
| 81 |
+
b = make_batch(tok, [lat], ["<mode:speech>hello world"]).to(device)
|
| 82 |
+
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
| 83 |
+
first = None
|
| 84 |
+
for _ in range(400):
|
| 85 |
+
out = model(b)
|
| 86 |
+
opt.zero_grad()
|
| 87 |
+
out["loss"].backward()
|
| 88 |
+
opt.step()
|
| 89 |
+
first = first or {k: v.item() for k, v in out.items()}
|
| 90 |
+
assert out["flow"].item() < 0.2 * first["flow"], (first, out)
|
| 91 |
+
assert out["stop"].item() < 0.2 * first["stop"]
|
| 92 |
+
model.eval()
|
| 93 |
+
z = model.generate(b.text_ids[0], ref_latents=b.ref_latents[0], max_patches=40, n_steps=8, cfg_scale=1.0)
|
| 94 |
+
assert 12 <= z.shape[0] // 2 <= 20, z.shape # true length = 16 patches
|
code/tests/test_text.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from photontts.text.tags import strip_tags
|
| 4 |
+
from photontts.text.tokenizer import CTC_VOCAB, ByteTokenizer, ctc_targets
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_byte_tokenizer_roundtrip_with_tags():
|
| 8 |
+
tok = ByteTokenizer()
|
| 9 |
+
text = "<mode:speech><lang:en>Hello <laugh> world! 你好"
|
| 10 |
+
ids = tok.encode(text)
|
| 11 |
+
assert tok.id("<laugh>") in ids
|
| 12 |
+
assert tok.id("<mode:speech>") == ids[0]
|
| 13 |
+
assert tok.decode(ids) == text
|
| 14 |
+
assert max(ids) < tok.vocab_size
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_unknown_angle_text_is_plain_bytes():
|
| 18 |
+
tok = ByteTokenizer()
|
| 19 |
+
ids = tok.encode("a <notatag> b")
|
| 20 |
+
assert all(i < 256 for i in ids)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_ctc_targets_strip_tags():
|
| 24 |
+
assert strip_tags("[S1] Hi <breath> there") == "Hi there"
|
| 25 |
+
t = ctc_targets("[S1] Hi <breath> there")
|
| 26 |
+
assert t == [b + 1 for b in b"Hi there"]
|
| 27 |
+
assert max(ctc_targets("你好")) < CTC_VOCAB
|
code/tools/push_remote.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Push the local PhotonTTS source tree to the remote marimo GPU box (/root/PhotonTTS).
|
| 2 |
+
|
| 3 |
+
MARIMO_URL=... MARIMO_TOKEN=... python tools/push_remote.py [--exec-script PATH]
|
| 4 |
+
|
| 5 |
+
Tars the repo (code only), sends it through the marimo-pair execute-code.sh script, and
|
| 6 |
+
extracts it on the remote. Credentials come from env vars only; never commit them.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import base64
|
| 12 |
+
import io
|
| 13 |
+
import os
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
import tarfile
|
| 17 |
+
import tempfile
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 21 |
+
SKIP_DIRS = {".git", ".venv", "__pycache__", ".pytest_cache", "runs", "data"}
|
| 22 |
+
DEFAULT_EXEC = Path.home() / ".claude/skills/marimo-pair/scripts/execute-code.sh"
|
| 23 |
+
REMOTE_DIR = "/root/PhotonTTS"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def build_tar() -> bytes:
|
| 27 |
+
buf = io.BytesIO()
|
| 28 |
+
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
| 29 |
+
for p in sorted(ROOT.rglob("*")):
|
| 30 |
+
rel = p.relative_to(ROOT)
|
| 31 |
+
if any(part in SKIP_DIRS for part in rel.parts) or p.is_dir() or p.suffix == ".pyc":
|
| 32 |
+
continue
|
| 33 |
+
tar.add(p, arcname=rel.as_posix())
|
| 34 |
+
return buf.getvalue()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def find_bash() -> str:
|
| 38 |
+
"""On Windows, plain 'bash' resolves to WSL; prefer Git Bash."""
|
| 39 |
+
if os.name != "nt":
|
| 40 |
+
return "bash"
|
| 41 |
+
for c in (os.environ.get("PHOTON_BASH"), r"C:\Program Files\Git\bin\bash.exe", r"C:\Program Files\Git\usr\bin\bash.exe"):
|
| 42 |
+
if c and Path(c).exists():
|
| 43 |
+
return c
|
| 44 |
+
return "bash"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
CHUNK = 20_000 # execute-code.sh passes code as one jq argument; Windows caps args at ~32K chars
|
| 48 |
+
STAGING = "/root/.photon_push.b64"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def run_remote(code: str, url: str, token: str, exec_script: Path) -> str:
|
| 52 |
+
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="ascii") as f:
|
| 53 |
+
f.write(code)
|
| 54 |
+
tmp = f.name
|
| 55 |
+
try:
|
| 56 |
+
r = subprocess.run([find_bash(), exec_script.as_posix(), "--url", url, "--token", token, Path(tmp).as_posix()],
|
| 57 |
+
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
| 58 |
+
finally:
|
| 59 |
+
os.unlink(tmp)
|
| 60 |
+
out = "\n".join(l for l in (r.stdout + r.stderr).splitlines() if not l.startswith("Warning"))
|
| 61 |
+
if r.returncode != 0 or "Traceback" in out:
|
| 62 |
+
raise RuntimeError(out)
|
| 63 |
+
return out
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def main():
|
| 67 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 68 |
+
url, token = os.environ["MARIMO_URL"], os.environ["MARIMO_TOKEN"]
|
| 69 |
+
exec_script = Path(sys.argv[sys.argv.index("--exec-script") + 1]) if "--exec-script" in sys.argv else DEFAULT_EXEC
|
| 70 |
+
payload = base64.b64encode(build_tar()).decode()
|
| 71 |
+
chunks = [payload[i : i + CHUNK] for i in range(0, len(payload), CHUNK)]
|
| 72 |
+
for i, c in enumerate(chunks):
|
| 73 |
+
mode = "w" if i == 0 else "a"
|
| 74 |
+
run_remote(f"open({STAGING!r}, {mode!r}).write({c!r})\n", url, token, exec_script)
|
| 75 |
+
code = (
|
| 76 |
+
"import base64, io, tarfile, os, shutil\n"
|
| 77 |
+
f"dst = {REMOTE_DIR!r}\n"
|
| 78 |
+
"os.makedirs(dst, exist_ok=True)\n"
|
| 79 |
+
"for name in os.listdir(dst):\n"
|
| 80 |
+
" if name not in ('runs', 'data', '.venv'):\n"
|
| 81 |
+
" p = os.path.join(dst, name)\n"
|
| 82 |
+
" shutil.rmtree(p) if os.path.isdir(p) else os.remove(p)\n"
|
| 83 |
+
f"data = base64.b64decode(open({STAGING!r}).read())\n"
|
| 84 |
+
f"assert len(data) == {len(payload) * 3 // 4 - payload[-2:].count('=')}, 'truncated push'\n"
|
| 85 |
+
"with tarfile.open(fileobj=io.BytesIO(data), mode='r:gz') as t:\n"
|
| 86 |
+
" t.extractall(dst, filter='data')\n"
|
| 87 |
+
f"os.remove({STAGING!r})\n"
|
| 88 |
+
"n = sum(len(f) for _, _, f in os.walk(dst))\n"
|
| 89 |
+
"print(f'pushed {len(data)} bytes -> {dst} ({n} files)')\n"
|
| 90 |
+
)
|
| 91 |
+
print(run_remote(code, url, token, exec_script), f"[{len(chunks)} chunks]")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
main()
|
code/tools/remote_sh.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run a shell command on the remote GPU box and print its output.
|
| 2 |
+
|
| 3 |
+
MARIMO_URL=... MARIMO_TOKEN=... python tools/remote_sh.py "cd /root/PhotonTTS && pytest -q"
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 13 |
+
from push_remote import DEFAULT_EXEC, run_remote # noqa: E402
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def main():
|
| 17 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 18 |
+
cmd = " ".join(sys.argv[1:])
|
| 19 |
+
timeout = int(os.environ.get("REMOTE_TIMEOUT", 3600))
|
| 20 |
+
code = (
|
| 21 |
+
"import subprocess\n"
|
| 22 |
+
f"r = subprocess.run({cmd!r}, shell=True, capture_output=True, text=True, timeout={timeout})\n"
|
| 23 |
+
"print(r.stdout[-20000:], r.stderr[-5000:], f'[exit {r.returncode}]')\n"
|
| 24 |
+
)
|
| 25 |
+
print(run_remote(code, os.environ["MARIMO_URL"], os.environ["MARIMO_TOKEN"], DEFAULT_EXEC))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if __name__ == "__main__":
|
| 29 |
+
main()
|