Transformer
Transformer Architecture
A neural network architecture based on self-attention. The foundation of GPT, BERT, and Claude. Proposed in 2017 in "Attention Is All You Need."
Transformer Architecture
A neural network architecture based on self-attention. The foundation of GPT, BERT, and Claude. Proposed in 2017 in "Attention Is All You Need."
The Transformer is a deep learning architecture proposed in Google's 2017 paper "Attention Is All You Need" and is a core structure underlying modern AI. It processes sequences using only attention mechanisms, without RNNs or CNNs, which enables parallel computation and effectively captures long-range dependencies.
Its key components are Self-Attention (learning relationships between all positions in the input sequence), Multi-Head Attention (performing attention from multiple perspectives simultaneously), Positional Encoding (injecting order information), and the Feed-Forward Network (non-linear transformation). The encoder-decoder structure is the original form, but variants such as BERT (encoder only) and GPT (decoder only) are widely used.
With the emergence of the Transformer, a paradigm shift has occurred not only in NLP but in all fields, including computer vision (ViT), speech (Whisper), and multimodal (CLIP). Recent LLMs such as GPT-4, Claude, and Gemini are all Transformer-based, and, in line with scaling laws, they have the characteristic that performance improves as model size and data are increased.
Implementing a Transformer directly is rare in practice, but understanding its structure is a great help for model selection, hyperparameter tuning, and performance optimization. In particular, it is worth knowing the limitation on processing long sequences caused by attention complexity (O(n²)) and the techniques for overcoming it (Flash Attention, Sparse Attention, etc.).
# Transformer 핵심 구조 이해를 위한 간단한 Self-Attention 구현
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class SelfAttention(nn.Module):
"""Scaled Dot-Product Self-Attention"""
def __init__(self, d_model, n_heads):
super().__init__()
self.d_model = d_model
self.n_heads = n_heads
self.d_k = d_model // n_heads
# Query, Key, Value 선형 변환
self.W_q = nn.Linear(d_model, d_model)
self.W_k = nn.Linear(d_model, d_model)
self.W_v = nn.Linear(d_model, d_model)
self.W_o = nn.Linear(d_model, d_model)
def forward(self, x, mask=None):
batch_size, seq_len, _ = x.shape
# Q, K, V 계산 및 헤드 분리
Q = self.W_q(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
K = self.W_k(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
V = self.W_v(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
# Scaled Dot-Product Attention
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-inf'))
attn_weights = F.softmax(scores, dim=-1)
context = torch.matmul(attn_weights, V)
# 헤드 결합 및 출력 변환
context = context.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)
return self.W_o(context)
# 사용 예시
d_model, n_heads, seq_len, batch_size = 512, 8, 100, 32
attention = SelfAttention(d_model, n_heads)
x = torch.randn(batch_size, seq_len, d_model)
output = attention(x) # [32, 100, 512]
print(f"Input: {x.shape} → Output: {output.shape}")
"We're going to use a Transformer-based model, and the input can go up to 10K tokens. Standard attention is O(n²), so memory will blow up, so we need to consider efficient implementations like Flash Attention or Longformer. I think we should start by profiling how large a batch size we can handle on an A100 80GB."
"The key reason the Transformer replaced the RNN is parallelization. An RNN has to process sequentially, but the Transformer's Self-Attention can compute all positions simultaneously. Also, because it connects long-range dependencies directly through a single attention step, it also alleviates the gradient vanishing problem."
"GPT uses only the Transformer's decoder, and BERT uses only the encoder. Decoder-based models are advantageous for generation tasks, and encoder-based models for understanding tasks. Our task is classification, so we'll go with the BERT family, and if we add a summarization feature later, let's review an encoder-decoder structure like T5."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
| Structure | Representative Models | Features | Suitable Tasks |
|---|---|---|---|
| Encoder-only | BERT, RoBERTa | Bidirectional context | Classification, NER, QA |
| Decoder-only | GPT, Claude, Llama | Autoregressive generation | Text generation, dialogue |
| Encoder-decoder | T5, BART | seq2seq | Translation, summarization |
💡 Practical tip: Most recent LLMs use a decoder-only structure. GPT-4, Claude, and Gemini all belong to this family. Understanding tasks can also be solved through prompting, so decoder-based models are used for general purposes in practice.
Standard Self-Attention uses memory proportional to the square of the sequence length. When processing long documents, use efficient implementations such as Flash Attention or Sparse Attention, or consider linear-complexity models such as Longformer or BigBird.
Learned positional embeddings degrade sharply in performance when they exceed the lengths seen during training. This can be improved with relative positional encodings such as RoPE and ALiBi, but length generalization is still a major research challenge for the Transformer.
During inference, the KV cache grows in proportion to batch size and sequence length. In large-scale serving, reducing the cache size with Grouped Query Attention (GQA) or Multi-Query Attention (MQA) is essential.