File size: 5,977 Bytes
7e2301f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | """PhotonCodec: causal continuous VAE, 24 kHz waveform <-> 25 Hz x 64-d latents.
Encoder: causal strided conv stack (Snake activations), stride product 960.
Decoder: upsample latents 25 Hz -> 100 Hz, causal ConvNeXt stack (Vocos-style),
iSTFT head (n_fft 960, hop 240). The iSTFT window center gives ~20 ms lookahead,
which the streaming engine handles with 1-frame overlap + crossfade.
"""
from __future__ import annotations
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..config import CodecConfig
class Snake(nn.Module):
"""x + sin^2(a x) / a, per channel (BigVGAN). Helps periodic signals (singing)."""
def __init__(self, channels: int):
super().__init__()
self.log_alpha = nn.Parameter(torch.zeros(1, channels, 1))
def forward(self, x):
a = self.log_alpha.exp()
return x + torch.sin(a * x).pow(2) / (a + 1e-9)
class CausalConv1d(nn.Conv1d):
"""Conv1d padded on the left only, so output[t] depends on input[<= t]."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
k, d, s = self.kernel_size[0], self.dilation[0], self.stride[0]
self.causal_pad = (k - 1) * d + 1 - s
def forward(self, x):
return super().forward(F.pad(x, (self.causal_pad, 0)))
class ResUnit(nn.Module):
def __init__(self, ch: int, dilation: int):
super().__init__()
self.net = nn.Sequential(
Snake(ch), CausalConv1d(ch, ch, 7, dilation=dilation), Snake(ch), nn.Conv1d(ch, ch, 1)
)
def forward(self, x):
return x + self.net(x)
class EncoderBlock(nn.Module):
def __init__(self, cin: int, cout: int, stride: int):
super().__init__()
self.net = nn.Sequential(
ResUnit(cin, 1), ResUnit(cin, 3), ResUnit(cin, 9),
Snake(cin), CausalConv1d(cin, cout, 2 * stride, stride=stride),
)
def forward(self, x):
return self.net(x)
class Encoder(nn.Module):
def __init__(self, cfg: CodecConfig):
super().__init__()
ch = cfg.enc_channels
layers = [CausalConv1d(1, ch[0], 7)]
for i, s in enumerate(cfg.enc_strides):
cout = ch[i + 1] if i + 1 < len(ch) else ch[-1]
layers.append(EncoderBlock(ch[i], cout, s))
layers += [Snake(ch[-1]), CausalConv1d(ch[-1], 2 * cfg.latent_dim, 3)]
self.net = nn.Sequential(*layers)
self.hop = math.prod(cfg.enc_strides)
def forward(self, wav): # (B, 1, T) -> mean, logvar: (B, D, T // hop)
T = wav.shape[-1]
if T % self.hop:
wav = F.pad(wav, (0, self.hop - T % self.hop))
mean, logvar = self.net(wav).chunk(2, dim=1)
return mean, logvar.clamp(-12.0, 4.0)
class ConvNeXtBlock(nn.Module):
def __init__(self, dim: int):
super().__init__()
self.dw = CausalConv1d(dim, dim, 7, groups=dim)
self.norm = nn.LayerNorm(dim)
self.pw1 = nn.Linear(dim, dim * 3)
self.pw2 = nn.Linear(dim * 3, dim)
self.gamma = nn.Parameter(torch.full((dim,), 1e-2))
def forward(self, x): # (B, C, T)
y = self.dw(x).transpose(1, 2)
y = self.pw2(F.gelu(self.pw1(self.norm(y))))
return x + (self.gamma * y).transpose(1, 2)
def istft_same(spec: torch.Tensor, n_fft: int, hop: int, window: torch.Tensor) -> torch.Tensor:
"""iSTFT with 'same' padding (Vocos): L frames -> L * hop samples."""
L = spec.shape[-1]
frames = torch.fft.irfft(spec, n_fft, dim=1, norm="backward") * window[None, :, None]
out = (L - 1) * hop + n_fft
pad = (n_fft - hop) // 2
y = F.fold(frames, (1, out), (1, n_fft), stride=(1, hop))[:, 0, 0]
env = F.fold(window.square()[None, :, None].expand(1, -1, L), (1, out), (1, n_fft), stride=(1, hop))[:, 0, 0]
return (y / env.clamp(min=1e-11))[:, pad : out - pad]
class Decoder(nn.Module):
def __init__(self, cfg: CodecConfig):
super().__init__()
d, up = cfg.dec_dim, cfg.dec_upsample
self.n_fft, self.hop = cfg.n_fft, math.prod(cfg.enc_strides) // up
self.inp = CausalConv1d(cfg.latent_dim, d, 3)
self.up = nn.ConvTranspose1d(d, d, 2 * up, stride=up, padding=up // 2)
self.blocks = nn.Sequential(*[ConvNeXtBlock(d) for _ in range(cfg.dec_layers)])
self.norm = nn.LayerNorm(d)
self.out = nn.Linear(d, cfg.n_fft + 2) # log-magnitude + phase for n_fft//2+1 bins
self.register_buffer("window", torch.hann_window(cfg.n_fft), persistent=False)
def forward(self, z): # (B, D, F) -> (B, 1, F * 960)
Fn = z.shape[-1]
# ConvTranspose(k=2u, s=u, p=u/2) yields exactly Fn * u frames (one frame of lookahead).
x = self.up(self.inp(z))[..., : Fn * self.up.stride[0]]
x = self.blocks(x)
x = self.out(self.norm(x.transpose(1, 2))).transpose(1, 2)
logmag, phase = x.float().chunk(2, dim=1)
mag = logmag.exp().clamp(max=1e2)
spec = torch.polar(mag, phase)
return istft_same(spec, self.n_fft, self.hop, self.window.float())[:, None]
class PhotonCodec(nn.Module):
def __init__(self, cfg: CodecConfig):
super().__init__()
self.cfg = cfg
self.encoder = Encoder(cfg)
self.decoder = Decoder(cfg)
self.hop = self.encoder.hop
@torch.no_grad()
def encode(self, wav: torch.Tensor, sample: bool = False) -> torch.Tensor:
mean, logvar = self.encoder(wav)
return mean + torch.randn_like(mean) * (0.5 * logvar).exp() if sample else mean
def decode(self, z: torch.Tensor) -> torch.Tensor:
return self.decoder(z)
def forward(self, wav: torch.Tensor):
mean, logvar = self.encoder(wav)
z = mean + torch.randn_like(mean) * (0.5 * logvar).exp()
recon = self.decoder(z)[..., : wav.shape[-1]]
kl = 0.5 * (mean.pow(2) + logvar.exp() - 1.0 - logvar).mean()
return {"recon": recon, "z": z, "mean": mean, "logvar": logvar, "kl": kl}
|