Transformers ແລະ GPT
Attention: ໃຫ້ແຕ່ລະຄຳເລືອກເອງວ່າຈະສົນໃຈຄຳໃດ.
Transformer ແທນ LSTM ດ້ວຍ self-attention: ແຕ່ລະ token ສ້າງ query, key ແລະ value ແລ້ວໃຫ້ນ້ຳໜັກກັບ token ອື່ນຕາມຄວາມຄ້າຍຂອງ query–key. GPT ແມ່ນ Transformer ທີ່ມີ causal mask ຈຶ່ງທາຍຄຳຖັດໄປໄດ້.
ໂຄດຕົວຢ່າງຄິດໄລ່ attention ຂອງ 4 ຄຳ ແລະ ສະແດງຕາຕະລາງນ້ຳໜັກ: ສ່ວນເທິງຂວາເປັນ 0 ເພາະ mask ບໍ່ໃຫ້ເບິ່ງອະນາຄົດ.
Attention(Q, K, V) = softmax( Q·Kᵀ / √d + mask ) · V
mask[i, j] = −∞ ຖ້າ j > i
| ສ່ວນ | ໜ້າທີ່ |
|---|---|
| Multi-head attention | ຫຼາຍ head ເບິ່ງຄວາມສຳພັນຫຼາຍແບບພ້ອມກັນ |
| Positional encoding | ບອກລຳດັບຂອງ token |
| Layer norm + skip | ໃຫ້ຊ້ອນຫຼາຍຊັ້ນໄດ້ຢ່າງສະຖຽນ |
| Encoder / Decoder | BERT = encoder, GPT = decoder, T5 = ທັງສອງ |
ສິ່ງທີ່ຄວນຈື່
- Attention ເບິ່ງທຸກຄຳພ້ອມກັນ ຈຶ່ງຝຶກແບບຂະໜານໄດ້ ແລະ ຈື່ບໍລິບົດຍາວໄດ້
- ChatGPT ແມ່ນ GPT ຂະໜາດໃຫຍ່ + ການຝຶກຕາມຄຳສັ່ງ (RLHF)
import torch
torch.manual_seed(0)
tokens = ["the", "cat", "sat", "down"]
d = 8
x = torch.randn(len(tokens), d) # token embeddings
Wq, Wk, Wv = (torch.randn(d, d) / d ** 0.5 for _ in range(3))
Q, K, V = x @ Wq, x @ Wk, x @ Wv
scores = Q @ K.T / d ** 0.5 # how much each token looks at each other
mask = torch.triu(torch.ones(len(tokens), len(tokens)), diagonal=1).bool()
scores = scores.masked_fill(mask, float("-inf")) # causal mask: no peeking at the future
weights = torch.softmax(scores, dim=-1)
out = weights @ V
print("attention weights (row = query token):")
print(" " + "".join(f"{t:>7}" for t in tokens))
for t, row in zip(tokens, weights):
print(f"{t:>6}" + "".join(f"{w:7.2f}" for w in row))
print("output shape:", tuple(out.shape))
ຜົນລັບ
attention weights (row = query token):
the cat sat down
the 1.00 0.00 0.00 0.00
cat 0.40 0.60 0.00 0.00
sat 0.38 0.59 0.04 0.00
down 0.09 0.13 0.68 0.10
output shape: (4, 8)
- #GenerativeAI
- #DeepLearning
- #PythonສຳລັບຄົນLaos
- #AI
- #ບອກຕໍ່ຄວາມຮູ້