python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
SoundStream のエンコーダ・残差ベクトル量子化(量子化器のドロップアウトつき)・デコーダを、論文の III 節と Algorithm 1 どおりに小さく実装する。
PyTorch に SoundStream の組み込みはない。識別器と損失は HiFi-GAN・MelGAN の記事の実装と同じ考え方なので省く。
"""
class CausalConv1d(nn.Conv1d):
"""過去の側だけに詰め物をする畳み込み(未来のサンプルを見ない)"""
def forward(self, x):
pad = (self.kernel_size[0] - 1) * self.dilation[0]
return super().forward(F.pad(x, (pad, 0)))
class CausalConvT1d(nn.ConvTranspose1d):
"""転置畳み込みの出力の右端(未来の側)を切り落として長さを入力 × ストライドにそろえる"""
def forward(self, x):
y = super().forward(x)
return y[..., : x.shape[-1] * self.stride[0]]
class ResidualUnit(nn.Module):
def __init__(self, ch, dilation):
super().__init__()
self.conv1 = CausalConv1d(ch, ch, 7, dilation=dilation) # 論文の図 3:幅 7・拡張率 d → 幅 1
self.conv2 = CausalConv1d(ch, ch, 1)
def forward(self, x):
return x + self.conv2(F.elu(self.conv1(F.elu(x)))) # ELU、正規化なし
class EncoderBlock(nn.Module):
def __init__(self, ch_in, ch_out, stride):
super().__init__()
self.res = nn.Sequential(*[ResidualUnit(ch_in, d) for d in (1, 3, 9)])
self.down = CausalConv1d(ch_in, ch_out, 2 * stride, stride=stride)
def forward(self, x):
return self.down(F.elu(self.res(x)))
class DecoderBlock(nn.Module):
def __init__(self, ch_in, ch_out, stride):
super().__init__()
self.up = CausalConvT1d(ch_in, ch_out, 2 * stride, stride=stride)
self.res = nn.Sequential(*[ResidualUnit(ch_out, d) for d in (1, 3, 9)])
def forward(self, x):
return self.res(self.up(F.elu(x)))
class VectorQuantizer(nn.Module):
"""1 段のベクトル量子化。コードブックは指数移動平均で更新し、使われないベクトルを入れ替える"""
def __init__(self, n_codes=1024, dim=128, decay=0.99, dead_threshold=2.0):
super().__init__()
self.decay, self.dead_threshold = decay, dead_threshold
self.register_buffer("codebook", torch.randn(n_codes, dim))
self.register_buffer("ema_count", torch.ones(n_codes))
self.register_buffer("ema_sum", self.codebook.clone())
self.register_buffer("initialized", torch.tensor(False))
def forward(self, r): # r: [N, D](フレームを並べたもの)
if self.training and not self.initialized: # 最初のバッチで k-means の初期化(ここでは数回の反復で簡略化)
centers = r[torch.randint(0, r.shape[0], (self.codebook.shape[0],))].clone()
for _ in range(10):
idx = torch.cdist(r, centers).argmin(1)
onehot = F.one_hot(idx, centers.shape[0]).type(r.dtype)
cnt = onehot.sum(0)
centers = torch.where(cnt[:, None] > 0, onehot.t() @ r / cnt.clamp(min=1)[:, None], centers)
self.codebook.copy_(centers); self.ema_sum.copy_(centers); self.initialized.fill_(True)
idx = torch.cdist(r, self.codebook).argmin(1) # いちばん近いベクトルの番号(これを送る)
q = self.codebook[idx]
if self.training: # コードブックの指数移動平均の更新
with torch.no_grad():
onehot = F.one_hot(idx, self.codebook.shape[0]).type(r.dtype)
self.ema_count.mul_(self.decay).add_(onehot.sum(0), alpha=1 - self.decay)
self.ema_sum.mul_(self.decay).add_(onehot.t() @ r, alpha=1 - self.decay)
self.codebook.copy_(self.ema_sum / self.ema_count.clamp(min=1e-5)[:, None])
dead = self.ema_count < self.dead_threshold # 使われないベクトルをバッチの中のフレームで置き換える
if dead.any():
pick = r[torch.randint(0, r.shape[0], (int(dead.sum()),))]
self.codebook[dead] = pick; self.ema_sum[dead] = pick; self.ema_count[dead] = 1.0
q_st = r + (q - r).detach() # 勾配はそのまま通す(ストレートスルー)
return q_st, idx
class ResidualVQ(nn.Module):
def __init__(self, n_q=8, **kw):
super().__init__()
self.layers = nn.ModuleList(VectorQuantizer(**kw) for _ in range(n_q))
def forward(self, y, n_q=None): # y: [B, D, S]
B, D, S_ = y.shape
if n_q is None:
# 学習:量子化器のドロップアウト(n_q を 1〜N_q から一様に選ぶ)。推論:全段
n_q = int(torch.randint(1, len(self.layers) + 1, ())) if self.training else len(self.layers)
residual = y.permute(0, 2, 1).reshape(-1, D)
y_hat, codes = torch.zeros_like(residual), []
for layer in self.layers[:n_q]: # Algorithm 1
q, idx = layer(residual)
y_hat = y_hat + q
residual = residual - q.detach()
codes.append(idx.view(B, S_))
return y_hat.view(B, S_, D).permute(0, 2, 1), torch.stack(codes, 1) # codes: [B, n_q, S]
class SoundStream(nn.Module):
def __init__(self, C=32, D=128, strides=(2, 4, 5, 8), n_q=8, n_codes=1024):
super().__init__()
enc = [CausalConv1d(1, C, 7)]
ch = C
for s in strides: # チャネルはダウンサンプリングのたびに 2 倍
enc.append(EncoderBlock(ch, ch * 2, s)); ch *= 2
enc += [nn.ELU(), CausalConv1d(ch, D, 3)]
self.encoder = nn.Sequential(*enc)
self.rvq = ResidualVQ(n_q, n_codes=n_codes, dim=D)
dec = [CausalConv1d(D, ch, 7)]
for s in reversed(strides):
dec.append(DecoderBlock(ch, ch // 2, s)); ch //= 2
dec += [nn.ELU(), CausalConv1d(ch, 1, 7)]
self.decoder = nn.Sequential(*dec)
def forward(self, x, n_q=None): # x: [B, 1, T]、T は 320 の倍数
y = self.encoder(x) # [B, D, T/320](24 kHz なら 75 フレーム/秒)
y_hat, codes = self.rvq(y, n_q)
return self.decoder(y_hat), codes
model = SoundStream()
x = torch.randn(2, 1, 24000) # 24 kHz の 1 秒
model.train()
x_hat, codes = model(x) # 段の数はランダム
print(x_hat.shape, codes.shape) # [2, 1, 24000]、[2, n_q, 75]
model.eval()
with torch.no_grad():
for n_q in (4, 8): # 推論ではほしいビットレートに合わせて段の数を選ぶ
x_hat, codes = model(x, n_q=n_q)
print(n_q, "段 =", 75 * n_q * 10 / 1000, "kbps") # 3.0 kbps、6.0 kbps