การสร้าง Positional Encoding
การทำ embedding ให้กับโทเค็นเป็นจุดเริ่มต้นที่ดี แต่ embedding เหล่านี้ยังขาดข้อมูลเกี่ยวกับตำแหน่งของแต่ละโทเค็นในลำดับ เพื่อแก้ปัญหานี้ สถาปัตยกรรม Transformer จึงใช้ positional encoding ซึ่งทำหน้าที่เข้ารหัสข้อมูลตำแหน่งของแต่ละโทเค็นลงใน embedding
ให้สร้างคลาส PositionalEncoding โดยมีพารามิเตอร์ดังนี้:
d_model: จำนวนมิติของ embedding อินพุตmax_seq_length: ความยาวลำดับสูงสุด (หรือความยาวลำดับจริง หากทุกลำดับมีความยาวเท่ากัน)
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Transformer Models ด้วย PyTorch
คำแนะนำการฝึกหัด
- สร้างเมทริกซ์ของศูนย์ที่มีขนาด
max_seq_lengthคูณd_model - คำนวณค่า sine และ cosine จาก
position * div_termเพื่อสร้างค่า positional embedding ที่ตำแหน่งคู่และคี่ - ตรวจสอบให้แน่ใจว่า
peไม่ใช่พารามิเตอร์ที่เรียนรู้ได้ในระหว่างการฝึก - บวก positional embedding ที่แปลงแล้วเข้ากับ embedding ของโทเค็นอินพุต
x
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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])