python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
WaveGlow の流れのステップ(可逆な 1×1 畳み込み + アフィン結合層)と損失を、
論文の式(式 5〜13)どおりに小さく実装する。PyTorch に WaveGlow の組み込みはない
(NVIDIA の公式実装は GitHub の NVIDIA/waveglow)。早めの出力は省いている。
"""
class Invertible1x1Conv(nn.Module):
def __init__(self, c):
super().__init__()
W = torch.linalg.qr(torch.randn(c, c))[0] # 直交行列で初期化(可逆)
if torch.det(W) < 0:
W[:, 0] = -W[:, 0]
self.W = nn.Parameter(W)
def forward(self, x): # 学習の向き(x → z)
log_det = x.size(0) * x.size(2) * torch.logdet(self.W) # バッチ・時刻ごとに log|det W|(式 11)
return torch.einsum("ij,bjt->bit", self.W, x), log_det
def reverse(self, z): # 推論の向き:逆行列をかける
return torch.einsum("ij,bjt->bit", torch.inverse(self.W), z)
class WN(nn.Module):
"""WaveNet に似たネットワーク:幅 3 の非因果な拡張畳み込み、ゲートつき tanh、残差とスキップ"""
def __init__(self, in_ch, mel_ch, ch=64, n_layers=4):
super().__init__()
self.start = nn.Conv1d(in_ch, ch, 1)
self.convs = nn.ModuleList(nn.Conv1d(ch, 2 * ch, 3, dilation=2 ** i, padding=2 ** i) for i in range(n_layers))
self.conds = nn.ModuleList(nn.Conv1d(mel_ch, 2 * ch, 1) for _ in range(n_layers))
self.res = nn.ModuleList(nn.Conv1d(ch, ch, 1) for _ in range(n_layers))
self.skip = nn.ModuleList(nn.Conv1d(ch, ch, 1) for _ in range(n_layers))
self.end = nn.Conv1d(ch, 2 * in_ch, 1)
nn.init.zeros_(self.end.weight); nn.init.zeros_(self.end.bias) # 最初は恒等変換に近くする
def forward(self, xa, mel):
h, out = self.start(xa), 0
for conv, cond, res, skip in zip(self.convs, self.conds, self.res, self.skip):
a, b = (conv(h) + cond(mel)).chunk(2, dim=1) # メルスペクトログラムをゲートの前に足す
z = torch.tanh(a) * torch.sigmoid(b)
h, out = h + res(z), out + skip(z)
return self.end(out).chunk(2, dim=1) # (log s, t)
class AffineCoupling(nn.Module):
def __init__(self, c, mel_ch):
super().__init__()
self.wn = WN(c // 2, mel_ch)
def forward(self, x, mel):
xa, xb = x.chunk(2, dim=1) # 式 5
log_s, t = self.wn(xa, mel) # 式 6
xb = torch.exp(log_s) * xb + t # 式 7
return torch.cat([xa, xb], dim=1), log_s.sum() # 式 8、log|s|(式 9)
def reverse(self, y, mel):
xa, xb = y.chunk(2, dim=1)
log_s, t = self.wn(xa, mel) # x_a は変わらないので同じ s, t を計算できる
return torch.cat([xa, (xb - t) * torch.exp(-log_s)], dim=1) # 式 13
class TinyWaveGlow(nn.Module):
def __init__(self, mel_ch=80, group=8, n_flows=12, hop=256):
super().__init__()
self.group = group
self.up = nn.ConvTranspose1d(mel_ch, mel_ch, hop * 2, stride=hop) # メルを音声の長さへ引き伸ばす
self.convs = nn.ModuleList(Invertible1x1Conv(group) for _ in range(n_flows))
self.coups = nn.ModuleList(AffineCoupling(group, mel_ch * group) for _ in range(n_flows))
def cond(self, mel, n):
m = self.up(mel)[:, :, :n] # [B, mel_ch, T]
B, C, T = m.shape # 8 サンプルずつ束ねる(メルも同じく)
return m.view(B, C, T // self.group, self.group).permute(0, 1, 3, 2).reshape(B, C * self.group, -1)
def forward(self, audio, mel): # 学習:x → z と対数行列式
B, T = audio.shape
x = audio.view(B, T // self.group, self.group).transpose(1, 2) # squeeze:[B, 8, T/8]
c = self.cond(mel, T)
log_det = 0
for conv, coup in zip(self.convs, self.coups):
x, ld1 = conv(x)
x, ld2 = coup(x, c)
log_det = log_det + ld1 + ld2
return x, log_det
@torch.no_grad()
def infer(self, mel, n_samples, sigma=0.6): # 推論:z → x(全サンプルを並列に)
c = self.cond(mel, n_samples)
z = sigma * torch.randn(mel.size(0), self.group, n_samples // self.group)
for conv, coup in zip(reversed(self.convs), reversed(self.coups)):
z = conv.reverse(coup.reverse(z, c))
return z.transpose(1, 2).reshape(mel.size(0), -1)
def waveglow_loss(z, log_det, sigma=0.5 ** 0.5):
"""負の対数尤度(式 12 の符号を反転)。要素の数で割って平均にする"""
return (z.pow(2).sum() / (2 * sigma ** 2) - log_det) / z.numel()
model = TinyWaveGlow()
mel = torch.randn(2, 80, 63) # [バッチ, 80, フレーム]
audio = torch.rand(2, 16000) * 2 - 1 # 16,000 サンプルの区間(論文の学習と同じ長さ)
z, log_det = model(audio, mel)
loss = waveglow_loss(z, log_det)
loss.backward()
wave = model.infer(mel, 16000) # 推論は標準偏差 0.6