python コピー
import random
import torch
import torch.nn as nn
"""
Listen, Attend and Spell の小さな実装例。
Listener:BLSTM 1 層 → pBLSTM 3 層(隣り合う 2 時刻を連結して時間を 1/2 に)
Speller:LSTM 2 層 + 内容に基づくアテンション e = <phi(s), psi(h)> + MLP の文字の分布
学習では 10% の割合で、正解の代わりにモデルの分布からサンプリングした文字を次の入力にする(論文 3.3 節)。
"""
SOS, EOS = 1, 2
class PyramidalBLSTM(nn.Module):
def __init__(self, n_in, hidden):
super().__init__()
self.rnn = nn.LSTM(2 * n_in, hidden, batch_first=True, bidirectional=True)
def forward(self, x): # x: [B, T, D]
B, T, D = x.shape
x = x[:, : T - T % 2].reshape(B, T // 2, 2 * D) # 隣り合う 2 時刻を連結 → 時間が半分
out, _ = self.rnn(x)
return out # [B, T/2, 2*hidden]
class Listener(nn.Module):
def __init__(self, n_mels=40, hidden=256):
super().__init__()
self.blstm = nn.LSTM(n_mels, hidden, batch_first=True, bidirectional=True)
self.pyramid = nn.Sequential(*[PyramidalBLSTM(2 * hidden, hidden) for _ in range(3)])
def forward(self, x):
h, _ = self.blstm(x)
return self.pyramid(h) # 時間は 1/8、[B, U, 2*hidden]
class Speller(nn.Module):
def __init__(self, n_chars=33, d_h=512, hidden=512, d_att=128):
super().__init__()
self.embed = nn.Embedding(n_chars, hidden)
self.rnn = nn.LSTM(hidden + d_h, hidden, num_layers=2, batch_first=True) # s_i = RNN(s_{i-1}, y_{i-1}, c_{i-1})
self.phi = nn.Sequential(nn.Linear(hidden, d_att), nn.ReLU(), nn.Linear(d_att, d_att))
self.psi = nn.Sequential(nn.Linear(d_h, d_att), nn.ReLU(), nn.Linear(d_att, d_att))
self.char_dist = nn.Sequential(nn.Linear(hidden + d_h, hidden), nn.ReLU(), nn.Linear(hidden, n_chars))
def step(self, y_prev, c_prev, state, h, psi_h):
inp = torch.cat([self.embed(y_prev), c_prev], -1).unsqueeze(1)
s, state = self.rnn(inp, state)
s = s.squeeze(1) # s_i
e = (psi_h @ self.phi(s).unsqueeze(-1)).squeeze(-1) # e_{i,u} = <phi(s_i), psi(h_u)>
alpha = torch.softmax(e, dim=-1) # α_{i,u}
c = (alpha.unsqueeze(-1) * h).sum(1) # c_i = Σ α_{i,u} h_u
logits = self.char_dist(torch.cat([s, c], -1)) # P(y_i | x, y_<i)
return logits, c, state, alpha
def forward(self, h, targets, sample_rate=0.1):
B = h.size(0)
psi_h = self.psi(h)
y_prev = torch.full((B,), SOS, dtype=torch.long)
c = h.new_zeros(B, h.size(-1))
state, outs = None, []
for i in range(targets.size(1)):
logits, c, state, _ = self.step(y_prev, c, state, h, psi_h)
outs.append(logits)
if self.training and random.random() < sample_rate: # 10% はモデルからサンプリング
y_prev = torch.distributions.Categorical(logits=logits).sample()
else: # それ以外は正解の文字
y_prev = targets[:, i]
return torch.stack(outs, 1) # [B, S, n_chars]
listener, speller = Listener(), Speller()
feats = torch.randn(2, 800, 40) # 8 秒分の 40 次元対数メルフィルタバンク(10 ms ごと)
targets = torch.randint(3, 33, (2, 30)) # 正解の文字(最後に EOS を置く想定)
listener.train(); speller.train()
h = listener(feats) # [2, 100, 512](時間は 1/8)
logits = speller(h, targets)
loss = nn.functional.cross_entropy(logits.reshape(-1, 33), targets.reshape(-1))
loss.backward()
listener.eval(); speller.eval() # 推論ではサンプリングをせず、ビームサーチで探す