python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
"""
1. torchaudio の学習済みの Tacotron 2(LJ Speech で学習)で文章から音声を作る
注意:torchaudio のボコーダは論文の WaveNet ではなく WaveRNN(Griffin-Lim の版もある)。
torchaudio は版によって提供する機能が変わるので、使う版のドキュメントで確かめる
2. 論文の位置に敏感なアテンション(累積の重みを畳み込んで特徴にする)を小さく実装する
"""
# --- 1. torchaudio の Tacotron 2 ---
bundle = torchaudio.pipelines.TACOTRON2_WAVERNN_CHAR_LJSPEECH # 文字を入力にする版
processor = bundle.get_text_processor()
tacotron2 = bundle.get_tacotron2().eval() # 推論のモード(Zoneout・バッチ正規化など)
vocoder = bundle.get_vocoder().eval()
with torch.inference_mode():
tokens, lengths = processor("Hello world! Text to speech.")
spec, spec_lengths, _ = tacotron2.infer(tokens, lengths) # [バッチ, 80, フレーム]
waveforms, _ = vocoder(spec, spec_lengths)
torchaudio.save("output.wav", waveforms[0:1].cpu(), sample_rate=vocoder.sample_rate)
# --- 2. 位置に敏感なアテンション ---
class LocationSensitiveAttention(nn.Module):
def __init__(self, query_dim=1024, memory_dim=512, attn_dim=128, n_filters=32, kernel=31):
super().__init__()
self.W = nn.Linear(query_dim, attn_dim, bias=False) # デコーダの状態 s
self.V = nn.Linear(memory_dim, attn_dim, bias=False) # エンコーダの出力 h_j
self.F = nn.Conv1d(1, n_filters, kernel, padding=kernel // 2, bias=False)
self.U = nn.Linear(n_filters, attn_dim, bias=True) # 位置の特徴 f_j(バイアス b をここに含める)
self.w = nn.Linear(attn_dim, 1, bias=False)
def forward(self, s, memory, cum_weights, mask=None):
# s: [B, query_dim]、memory: [B, T, memory_dim]、cum_weights: [B, T](これまでの重みの累積)
f = self.F(cum_weights.unsqueeze(1)).transpose(1, 2) # [B, T, n_filters]
e = self.w(torch.tanh(self.W(s).unsqueeze(1) + self.V(memory) + self.U(f))).squeeze(-1)
if mask is not None:
e = e.masked_fill(~mask, float("-inf")) # 0 で埋めた文字は見ない
alpha = F.softmax(e, dim=-1) # [B, T]
context = torch.bmm(alpha.unsqueeze(1), memory).squeeze(1) # Σ α_j h_j
return context, alpha
attn = LocationSensitiveAttention()
memory = torch.randn(2, 40, 512) # 2 文、40 文字のエンコーダの出力
cum = torch.zeros(2, 40)
for step in range(3): # デコーダの 3 ステップ分
s = torch.randn(2, 1024) # 実際は LSTM の出力
context, alpha = attn(s, memory, cum)
cum = cum + alpha # 重みを累積に足して、次のステップで使う
print(context.shape, alpha.shape) # torch.Size([2, 512]) torch.Size([2, 40])