python
import torch
import torch.nn as nn
class PostLNBlock(nn.Module):
"""Post-LN:サブ層 → 残差を足す → レイヤー正規化(元の Transformer)"""
def __init__(self, d_model=512, n_head=8, d_ff=2048):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head, batch_first=True)
self.ffn = nn.Sequential(nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model))
self.norm1, self.norm2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
def forward(self, x):
h = self.norm1(x + self.attn(x, x, x, need_weights=False)[0])
return self.norm2(h + self.ffn(h))
class PreLNBlock(nn.Module):
"""Pre-LN:レイヤー正規化 → サブ層 → 残差を足す(本線は正規化しない)"""
def __init__(self, d_model=512, n_head=8, d_ff=2048):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head, batch_first=True)
self.ffn = nn.Sequential(nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model))
self.norm1, self.norm2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
def forward(self, x):
y = self.norm1(x)
h = x + self.attn(y, y, y, need_weights=False)[0]
return h + self.ffn(self.norm2(h))
x = torch.randn(2, 10, 512) # [バッチ, 系列の長さ, d_model]
pre_stack = nn.Sequential(*[PreLNBlock() for _ in range(6)], nn.LayerNorm(512)) # 最後の正規化を忘れない
print(PostLNBlock()(x).shape, pre_stack(x).shape)
# PyTorch の組み込み:norm_first=False(既定)が Post-LN、True が Pre-LN
layer = nn.TransformerEncoderLayer(d_model=512, nhead=8, batch_first=True, norm_first=True)
encoder = nn.TransformerEncoder(layer, num_layers=6, norm=nn.LayerNorm(512)) # Pre-LN の最後の正規化
print(encoder(x).shape) # torch.Size([2, 10, 512])