Tạo positional encodings
Embedding cho các token là bước khởi đầu tốt, nhưng các embedding này vẫn thiếu thông tin về vị trí của từng token trong chuỗi. Để khắc phục, kiến trúc transformer sử dụng positional encodings, tức là mã hoá thông tin vị trí của mỗi token vào trong embedding.
Bạn sẽ tạo một lớp PositionalEncoding với các tham số sau:
d_model: số chiều của embedding đầu vàomax_seq_length: độ dài chuỗi tối đa (hoặc độ dài chuỗi nếu mọi chuỗi đều có cùng độ dài)
Bài tập này là một phần của khóa học
Các mô hình Transformer với PyTorch
Hướng dẫn bài tập
- Tạo một ma trận toàn số 0 có kích thước
max_seq_lengthnhând_model. - Thực hiện các phép tính sine và cosine trên
position * div_termđể tạo các giá trị embedding vị trí cho chỉ số chẵn và lẻ. - Đảm bảo
pekhông phải là tham số có thể học trong quá trình huấn luyện. - Cộng các positional embeddings đã biến đổi vào embedding token đầu vào,
x.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_seq_length):
super().__init__()
# Create a matrix of zeros of dimensions max_seq_length by d_model
pe = ____
position = torch.arange(0, max_seq_length, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model))
# Perform the sine and cosine calculations
pe[:, 0::2] = torch.____(position * div_term)
pe[:, 1::2] = torch.____(position * div_term)
# Ensure pe isn't a learnable parameter during training
self.____('____', pe.unsqueeze(0))
def forward(self, x):
# Add the positional embeddings to the token embeddings
return ____ + ____[:, :x.size(1)]
pos_encoding_layer = PositionalEncoding(d_model=512, max_seq_length=4)
output = pos_encoding_layer(token_embeddings)
print(output.shape)
print(output[0][0][:10])