Transformer Architectureは、人工知能・機械学習分野における重要な概念・技術です。
Transformer Architecture(トランスフォーマー)は、2017 年に Google の研究者が論文「Attention Is All You Need」で発表した、ニューラルネットワークの革新的なアーキテクチャです。従来の RNN や CNN に代わって Self-Attention メカニズムを中心に据え、並列処理能力・長距離依存の学習・スケーラビリティに優れます。現代の大規模言語モデル(GPT、BERT、Llama、Claude、Gemini)、画像認識(ViT)、音声認識(Whisper)など、ほぼすべての AI 分野の基盤技術となっています。
Input → Encoder → Context → Decoder → Output
全トークン間の関連度を計算:
Attention(Q, K, V) = softmax(QK^T / √d_k) × V
動作:
複数の Attention を並列実行:
効果:
Transformer は並列処理のため、位置情報を別途付加:
位置ごとの非線形変換:
FFN(x) = max(0, xW_1 + b_1)W_2 + b_2
安定した学習のための正規化:
勾配消失を防ぐスキップ接続:
output = LayerNorm(x + Sublayer(x))
| モデル | 年 | パラメータ |
|---|---|---|
| GPT-1 | 2018 | 117M |
| GPT-2 | 2019 | 1.5B |
| GPT-3 | 2020 | 175B |
| GPT-4 | 2023 | ~1.7T(推定) |
デコーダーのみ、用途: 生成、対話
O(n² × d)
import torch
import torch.nn as nn
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
self.d_model = d_model
self.num_heads = num_heads
self.d_k = d_model // num_heads
self.q_linear = nn.Linear(d_model, d_model)
self.k_linear = nn.Linear(d_model, d_model)
self.v_linear = nn.Linear(d_model, d_model)
self.out = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
B = q.size(0)
Q = self.q_linear(q).view(B, -1, self.num_heads, self.d_k).transpose(1, 2)
K = self.k_linear(k).view(B, -1, self.num_heads, self.d_k).transpose(1, 2)
V = self.v_linear(v).view(B, -1, self.num_heads, self.d_k).transpose(1, 2)
scores = torch.matmul(Q, K.transpose(-2, -1)) / (self.d_k ** 0.5)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attn = torch.softmax(scores, dim=-1)
out = torch.matmul(attn, V)
out = out.transpose(1, 2).contiguous().view(B, -1, self.d_model)
return self.out(out)