07. Transformer
07. Transformer¶
๊ฐ์¶
Transformer๋ "Attention Is All You Need" (Vaswani et al., 2017) ๋ ผ๋ฌธ์์ ์ ์๋ ์ํคํ ์ฒ๋ก, ํ๋ ๋ฅ๋ฌ๋์ ํต์ฌ์ ๋๋ค. RNN ์์ด Self-Attention๋ง์ผ๋ก ์ํ์ค๋ฅผ ์ฒ๋ฆฌํฉ๋๋ค.
ํ์ต ๋ชฉํ¶
- Self-Attention: Query, Key, Value ์ฐ์ฐ ์ดํด
- Multi-Head Attention: ์ฌ๋ฌ attention head์ ๋ณ๋ ฌ ์ฒ๋ฆฌ
- Positional Encoding: ์์น ์ ๋ณด ์ฃผ์
- Encoder-Decoder: ์ ์ฒด ์ํคํ ์ฒ ๊ตฌ์กฐ
์ํ์ ๋ฐฐ๊ฒฝ¶
1. Scaled Dot-Product Attention¶
Attention(Q, K, V) = softmax(QK^T / โd_k) V
์ฌ๊ธฐ์:
- Q (Query): ๋ฌด์์ ์ฐพ์์ง
- K (Key): ๋งค์นญํ ๋์
- V (Value): ์ค์ ๊ฐ์ ธ์ฌ ๊ฐ
- d_k: Key์ ์ฐจ์ (scaling factor)
์์ ๋ถํด:
1. QK^T: Query์ Key์ ์ ์ฌ๋ ๊ณ์ฐ โ (seq_len, seq_len)
2. / โd_k: ํฐ ๊ฐ ๋ฐฉ์ง (softmax ์์ ์ฑ)
3. softmax: ํ๋ฅ ๋ถํฌ๋ก ๋ณํ
4. ร V: ๊ฐ์ค ํ๊ท
2. Multi-Head Attention¶
MultiHead(Q, K, V) = Concat(head_1, ..., head_h) W^O
where head_i = Attention(Q W^Q_i, K W^K_i, V W^V_i)
ํน์ง:
- ์ฌ๋ฌ "๊ด์ "์์ attention ํ์ต
- ๊ฐ head๊ฐ ๋ค๋ฅธ ํจํด ํฌ์ฐฉ
- ๋ณ๋ ฌ ์ฒ๋ฆฌ ๊ฐ๋ฅ
3. Positional Encoding¶
PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
๋ชฉ์ :
- Transformer๋ ์์ ์ ๋ณด๊ฐ ์์
- ์์น ์ ๋ณด๋ฅผ ๋ช
์์ ์ผ๋ก ์ฃผ์
- Sinusoidal: ํ์ต ์์ด ์์ฑ, ์ธ์ฝ ๊ฐ๋ฅ
ํ์ผ ๊ตฌ์กฐ¶
07_Transformer/
โโโ README.md
โโโ pytorch_lowlevel/
โ โโโ attention_lowlevel.py # Attention ๊ธฐ๋ณธ ๊ตฌํ
โ โโโ multihead_attention.py # Multi-Head Attention
โ โโโ positional_encoding.py # ์์น ์ธ์ฝ๋ฉ
โ โโโ transformer_lowlevel.py # ์ ์ฒด Transformer
โโโ paper/
โ โโโ transformer_paper.py # ๋
ผ๋ฌธ ์ฌํ
โ โโโ transformer_xl.py # Transformer-XL ๋ณํ
โโโ exercises/
โโโ 01_flash_attention.md # Flash Attention ๊ตฌํ
โโโ 02_rotary_embeddings.md # RoPE ๊ตฌํ
โโโ 03_kv_cache.md # KV Cache ๊ตฌํ
ํต์ฌ ๊ฐ๋ ¶
1. Self-Attention vs Cross-Attention¶
Self-Attention:
- Q, K, V ๋ชจ๋ ๊ฐ์ ์ํ์ค์์
- Encoder, Decoder ๋ด๋ถ์์ ์ฌ์ฉ
Cross-Attention:
- Q๋ Decoder์์, K, V๋ Encoder์์
- Encoder-Decoder ์ฐ๊ฒฐ
2. Masking¶
# Padding mask: ํจ๋ฉ ํ ํฐ ๋ฌด์
padding_mask = (input_ids == pad_token_id) # (batch, seq_len)
# Causal mask: ๋ฏธ๋ ํ ํฐ ๋ชป ๋ณด๊ฒ
causal_mask = torch.triu(torch.ones(seq_len, seq_len), diagonal=1)
# ์์ผ๊ฐ ํ๋ ฌ์ -inf๋ก ์ค์
3. Feed-Forward Network¶
FFN(x) = max(0, xW_1 + b_1)W_2 + b_2
๋๋ (GELU ์ฌ์ฉ):
FFN(x) = GELU(xW_1)W_2
ํน์ง:
- Position-wise: ๊ฐ ์์น ๋
๋ฆฝ์ ์ผ๋ก ์ ์ฉ
- Expansion: ๋ณดํต 4๋ฐฐ ํ์ฅ (d_model โ 4*d_model โ d_model)
์ฐ์ต ๋ฌธ์ ¶
๊ธฐ์ด¶
- Scaled Dot-Product Attention ์ง์ ๊ตฌํ
- Positional Encoding ์๊ฐํ
- Self-Attention ํจํด ์๊ฐํ
์ค๊ธ¶
- Multi-Head Attention ๊ตฌํ
- Encoder ๋ธ๋ก ์์ฑ
- Decoder ๋ธ๋ก ์์ฑ (causal mask ํฌํจ)
๊ณ ๊ธ¶
- KV Cache๋ก autoregressive ์์ฑ ์ต์ ํ
- Flash Attention ๊ตฌํ (๋ฉ๋ชจ๋ฆฌ ํจ์จ)
- Rotary Position Embedding (RoPE) ๊ตฌํ
์ฐธ๊ณ ์๋ฃ¶
- Vaswani et al. (2017). "Attention Is All You Need"
- The Annotated Transformer
- The Illustrated Transformer