python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Tacotron の部品(論文の 3 章と Table 1)を小さく実装する例
PyTorch・torchaudio には Tacotron(1)の組み込みはない(torchaudio にあるのは Tacotron 2)
1. プリネット:全結合 → ReLU → ドロップアウト を 2 回
2. CBHG:畳み込みのバンク → 最大値プーリング → 畳み込みの射影 → 残差 → ハイウェイ層 → 双方向 GRU
"""
class Prenet(nn.Module):
def __init__(self, in_dim, sizes=(256, 128), p=0.5):
super().__init__()
dims = [in_dim, *sizes]
self.layers = nn.ModuleList(nn.Linear(a, b) for a, b in zip(dims[:-1], dims[1:]))
self.p = p
def forward(self, x):
for layer in self.layers:
# self.training に従う(model.eval() でドロップアウトが止まる)
x = F.dropout(F.relu(layer(x)), self.p, self.training)
return x
class BatchNormConv1d(nn.Module):
def __init__(self, in_ch, out_ch, k, act):
super().__init__()
self.conv = nn.Conv1d(in_ch, out_ch, k, padding=k // 2, bias=False)
self.bn = nn.BatchNorm1d(out_ch) # 論文:すべての畳み込みにバッチ正規化
self.act = act
def forward(self, x): # x: [バッチ, チャネル, 時間]
T = x.size(-1)
y = self.conv(x)[..., :T] # 幅が偶数のときに長さをそろえる
y = self.bn(y)
return self.act(y) if self.act is not None else y
class Highway(nn.Module):
def __init__(self, dim):
super().__init__()
self.H = nn.Linear(dim, dim)
self.T = nn.Linear(dim, dim)
def forward(self, x):
t = torch.sigmoid(self.T(x)) # 変換ゲート
return t * F.relu(self.H(x)) + (1 - t) * x
class CBHG(nn.Module):
def __init__(self, in_dim, K=16, bank_ch=128, proj=(128, 128), n_highway=4, gru=128):
super().__init__()
self.bank = nn.ModuleList(
BatchNormConv1d(in_dim, bank_ch, k, nn.ReLU()) for k in range(1, K + 1))
self.pool = nn.MaxPool1d(kernel_size=2, stride=1, padding=1)
self.proj1 = BatchNormConv1d(K * bank_ch, proj[0], 3, nn.ReLU())
self.proj2 = BatchNormConv1d(proj[0], proj[1], 3, None) # 最後は線形(活性化なし)
# 残差を足すため、射影の出力の次元は入力と同じにする
self.pre_highway = nn.Linear(proj[1], gru) if proj[1] != gru else nn.Identity()
self.highways = nn.ModuleList(Highway(gru) for _ in range(n_highway))
self.gru = nn.GRU(gru, gru, batch_first=True, bidirectional=True)
def forward(self, x): # x: [バッチ, 時間, in_dim]
T = x.size(1)
h = x.transpose(1, 2)
h = torch.cat([conv(h) for conv in self.bank], dim=1) # 1〜K の幅を並べて連結
h = self.pool(h)[..., :T] # ストライド 1:時間の長さを変えない
h = self.proj2(self.proj1(h))
h = h.transpose(1, 2) + x # 残差接続(入力の列に足す)
h = self.pre_highway(h)
for hw in self.highways:
h = hw(h)
out, _ = self.gru(h) # [バッチ, 時間, 2 × gru]
return out
# エンコーダ:文字の埋め込み(256)→ プリネット → CBHG(K = 16)
embed = nn.Embedding(num_embeddings=70, embedding_dim=256)
prenet = Prenet(256)
cbhg = CBHG(in_dim=128, K=16, proj=(128, 128))
chars = torch.randint(0, 70, (2, 40)) # 2 文、40 文字
memory = cbhg(prenet(embed(chars)))
print(memory.shape) # torch.Size([2, 40, 256])
# 推論のときはバッチ正規化とドロップアウトを推論のモードにする
cbhg.eval()
prenet.eval()