python
import math
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm
'''
数字の列を逆の順番に並べ替えるタスク(翻訳の代わりの、データのダウンロードがいらない小さな例)
例:入力 [3, 7, 1, 9, 4, ...] → 出力 [..., 4, 9, 1, 7, 3]
'''
# ハイパーパラメータ
seq_len = 10 # 列の長さ
vocab_size = 12 # 数字 0〜9 と、開始・終了の記号
BOS, EOS = 10, 11
d_model = 128 # 論文の base モデルは 512
nhead = 4 # 論文は 8
num_layers = 3 # 論文は 6
dim_feedforward = 512 # 論文は 2048
batch_size = 64
steps = 3000
learning_rate = 5e-4
# cudaを使えるなら'cuda', Apple Siliconなら'mps', それ以外なら'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
def make_batch(n):
src = torch.randint(0, 10, (n, seq_len))
tgt = torch.flip(src, dims=[1])
tgt_in = torch.cat([torch.full((n, 1), BOS), tgt], dim=1) # デコーダの入力(1つ右へずらす)
tgt_out = torch.cat([tgt, torch.full((n, 1), EOS)], dim=1) # 予測する正解
return src.to(device), tgt_in.to(device), tgt_out.to(device)
# 正弦波の位置エンコーディング(論文 3.5 節)
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=512):
super().__init__()
pos = torch.arange(max_len).unsqueeze(1)
div = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
pe = torch.zeros(max_len, d_model)
pe[:, 0::2] = torch.sin(pos * div)
pe[:, 1::2] = torch.cos(pos * div)
self.register_buffer('pe', pe)
def forward(self, x): # x: [B, T, d_model]
return x + self.pe[:x.size(1)]
class Seq2SeqTransformer(nn.Module):
def __init__(self):
super().__init__()
self.embed = nn.Embedding(vocab_size, d_model) # 入力と出力で埋め込みを共有する
self.pos = PositionalEncoding(d_model)
self.transformer = nn.Transformer(
d_model=d_model, nhead=nhead,
num_encoder_layers=num_layers, num_decoder_layers=num_layers,
dim_feedforward=dim_feedforward, dropout=0.1, batch_first=True)
self.out = nn.Linear(d_model, vocab_size)
def forward(self, src, tgt_in):
scale = math.sqrt(d_model) # 埋め込みに √d_model をかける(論文 3.4 節)
src_emb = self.pos(self.embed(src) * scale)
tgt_emb = self.pos(self.embed(tgt_in) * scale)
# デコーダの自己アテンションで、先の位置を見せないマスク
tgt_mask = nn.Transformer.generate_square_subsequent_mask(tgt_in.size(1)).to(src.device)
h = self.transformer(src_emb, tgt_emb, tgt_mask=tgt_mask)
return self.out(h) # ソフトマックスは損失関数の中で計算する
model = Seq2SeqTransformer().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate, betas=(0.9, 0.98), eps=1e-9)
# 学習ループ
model.train()
for step in tqdm(range(steps)):
src, tgt_in, tgt_out = make_batch(batch_size)
optimizer.zero_grad()
logits = model(src, tgt_in) # [B, T, vocab_size]
loss = criterion(logits.reshape(-1, vocab_size), tgt_out.reshape(-1))
loss.backward()
optimizer.step()
# 評価:1語ずつ予測して延ばす(貪欲法)
model.eval()
src, _, tgt_out = make_batch(1000)
with torch.no_grad():
ys = torch.full((src.size(0), 1), BOS, device=device)
for _ in range(seq_len):
next_token = model(src, ys)[:, -1].argmax(dim=-1, keepdim=True)
ys = torch.cat([ys, next_token], dim=1)
accuracy = (ys[:, 1:] == tgt_out[:, :-1]).all(dim=1).float().mean().item()
print(f"列が完全に一致した割合: {accuracy * 100:.2f}%")