Transformer Encoder – NumPy Implementation
Author: L■■ng ■■c Th■ng
1■■ Gi■i thi■u
Tài li■u này trình bày quá trình xây d■ng ki■n trúc Transformer Encoder t■ ■■u b■ng
NumPy. M■i ph■n ■■■c thi■t k■ ■■ giúp ng■■i ■■c hi■u rõ t■ng l■p và t■ng phép
toán trong m■ng Transformer, t■ Self-Attention ■■n Encoder Stack hoàn ch■nh.
2■■ Linear Layer & Softmax
Linear layer h■c phép bi■n ■■i tuy■n tính: y = XW + b. Softmax ■■■c s■ d■ng ■■
chu■n hóa giá tr■ thành phân ph■i xác su■t.
# Linear Layer NumPy
class Linear:
def __init__(self, in_features, out_features):
limit = [Link](6 / (in_features + out_features))
self.W = [Link](-limit, limit, (in_features, out_features))
self.b = [Link](out_features)
def __call__(self, x):
return x @ self.W + self.b
3■■ Self-Attention & Multi-Head Attention
C■ ch■ Attention cho phép mô hình h■c m■i quan h■ gi■a các token trong chu■i.
Multi-Head Attention m■ r■ng ■i■u này b■ng cách chia embedding thành nhi■u “■■u”
(heads) ■■ h■c các ng■ c■nh khác nhau song song.
Attention(Q, K, V) = softmax((QK■) / √d_k) V
4■■ Residual Connection & Layer Normalization
Residual Connection giúp gi■ l■i thông tin g■c, còn LayerNorm chu■n hóa các giá tr■
■■ ■n ■■nh quá trình hu■n luy■n.
class LayerNorm:
def __init__(self, d_model, eps=1e-6):
[Link] = [Link]((1, d_model))
[Link] = [Link]((1, d_model))
[Link] = eps
def __call__(self, x):
mean = [Link](axis=-1, keepdims=True)
var = ((x - mean) ** 2).mean(axis=-1, keepdims=True)
return [Link] * (x - mean) / [Link](var + [Link]) + [Link]
5■■ Feed Forward Network (FFN)
FFN là m■ng n■-ron 2 l■p áp d■ng ■■c l■p cho t■ng token: ReLU(xW■ + b■)W■ + b■.
class FeedForward:
def __init__(self, d_model, d_ff):
self.W1 = [Link](d_model, d_ff) * 0.02
self.b1 = [Link]((1, d_ff))
self.W2 = [Link](d_ff, d_model) * 0.02
self.b2 = [Link]((1, d_model))
def __call__(self, x):
return [Link](0, x @ self.W1 + self.b1) @ self.W2 + self.b2
6■■ Positional Encoding
Positional Encoding thêm thông tin v■ v■ trí c■a token trong chu■i b■ng các hàm sin và
cos.
class PositionalEncoding:
def __init__(self, seq_len, d_model):
pos = [Link](seq_len)[:, [Link]]
i = [Link](d_model)[[Link], :]
angle = pos / [Link](10000, (2 * (i//2)) / d_model)
[Link] = [Link]((seq_len, d_model))
[Link][:, 0::2] = [Link](angle[:, 0::2])
[Link][:, 1::2] = [Link](angle[:, 1::2])
def __call__(self, X):
return X + [Link][:[Link][0]]
7■■ Encoder Block
Encoder Block k■t h■p Multi-Head Attention, Feed Forward Network, và hai b■■c Add &
Norm.
class EncoderBlock:
def __init__(self, d_model, num_heads, d_ff):
[Link] = MultiHeadAttention(d_model, num_heads)
self.ln1 = LayerNorm(d_model)
[Link] = FeedForward(d_model, d_ff)
self.ln2 = LayerNorm(d_model)
def __call__(self, X):
X = self.ln1(X + [Link](X))
X = self.ln2(X + [Link](X))
return X
8■■ Transformer Encoder Stack
Transformer Encoder bao g■m nhi■u EncoderBlock x■p ch■ng cùng Positional
Encoding.
class TransformerEncoder:
def __init__(self, num_layers, d_model, num_heads, d_ff, seq_len):
self.pos_encoding = PositionalEncoding(seq_len, d_model)
[Link] = [EncoderBlock(d_model, num_heads, d_ff) for _ in range(num_layers)]
def __call__(self, X):
X = self.pos_encoding(X)
for layer in [Link]:
X = layer(X)
return X
■ S■ ■■ kh■i t■ng th■ Encoder
S■ ■■ mô t■ lu■ng d■ li■u trong Transformer Encoder: Input → Positional Encoding →
Multi-Head Attention → Add & Norm → FFN → Add & Norm → Output.