python
import torch
import torch.nn as nn
import torch.nn.functional as F
class SubBlock(nn.Module):
"""サブブロック:1D 畳み込み → バッチ正規化 → ReLU → ドロップアウト"""
def __init__(self, c_in, c_out, k, dropout, dilation=1, stride=1):
super().__init__()
pad = dilation * (k // 2)
self.conv = nn.Conv1d(c_in, c_out, k, stride=stride, padding=pad, dilation=dilation, bias=False)
self.bn = nn.BatchNorm1d(c_out)
self.drop = nn.Dropout(dropout)
def forward(self, x):
return self.drop(F.relu(self.bn(self.conv(x))))
class JasperBlock(nn.Module):
"""R 個のサブブロック。最後のサブブロックでは、BN の出力に残差(1×1 畳み込み → BN)を足してから ReLU・ドロップアウト"""
def __init__(self, c_in, c_out, k, R, dropout):
super().__init__()
layers = []
for i in range(R - 1):
layers.append(SubBlock(c_in if i == 0 else c_out, c_out, k, dropout))
self.subs = nn.Sequential(*layers)
self.last_conv = nn.Conv1d(c_out if R > 1 else c_in, c_out, k, padding=k // 2, bias=False)
self.last_bn = nn.BatchNorm1d(c_out)
self.res = nn.Sequential(nn.Conv1d(c_in, c_out, 1, bias=False), nn.BatchNorm1d(c_out))
self.drop = nn.Dropout(dropout)
def forward(self, x):
h = self.last_bn(self.last_conv(self.subs(x)))
return self.drop(F.relu(h + self.res(x)))
class Jasper(nn.Module):
"""Jasper BxR(論文の Table 1 の 10x5 の設定。repeat=2 で B1〜B5 を 2 回ずつ)"""
def __init__(self, n_feats=64, n_labels=29, R=5, repeat=2):
super().__init__()
# (カーネル, チャネル, ドロップアウト)
cfg = [(11, 256, 0.2), (13, 384, 0.2), (17, 512, 0.2), (21, 640, 0.3), (25, 768, 0.3)]
self.conv1 = SubBlock(n_feats, 256, 11, 0.2, stride=2)
blocks, c = [], 256
for k, ch, p in cfg:
for _ in range(repeat):
blocks.append(JasperBlock(c, ch, k, R, p))
c = ch
self.blocks = nn.Sequential(*blocks)
self.conv2 = SubBlock(c, 896, 29, 0.4, dilation=2)
self.conv3 = SubBlock(896, 1024, 1, 0.4)
self.conv4 = nn.Conv1d(1024, n_labels, 1) # 文字+CTC の空白
def forward(self, feats):
# feats: (バッチ, 特徴の次元, 時刻)
x = self.conv3(self.conv2(self.blocks(self.conv1(feats))))
return self.conv4(x) # (バッチ, ラベル数, 時刻)
# 小さめの設定で CTC の損失を計算する例(R=3、各 1 回 = Jasper 5x3)
model = Jasper(R=3, repeat=1)
ctc = nn.CTCLoss(blank=0, zero_infinity=True)
feats = torch.randn(2, 64, 400) # 2 発話、64 次元、400 フレーム
targets = torch.randint(1, 29, (2, 50)) # 0 は空白なので使わない
model.train()
logits = model(feats) # (2, 29, 200)。Conv1 のストライド 2 で時刻が半分
log_probs = logits.permute(2, 0, 1).log_softmax(-1) # CTCLoss は (時刻, バッチ, ラベル数)
input_lengths = torch.full((2,), log_probs.size(0), dtype=torch.long)
target_lengths = torch.full((2,), 50, dtype=torch.long)
loss = ctc(log_probs, targets, input_lengths, target_lengths)
loss.backward()
# 推論:バッチ正規化は学習中の統計を使い、ドロップアウトは止まる。貪欲なデコードで各時刻の最大を取る
model.eval()
with torch.no_grad():
best = model(feats).argmax(dim=1) # (2, 200)。この後、連続する同じ記号と空白を取り除く