เพิ่มเมธอดให้กับคลาส MultiHeadAttention
ในแบบฝึกหัดนี้ คุณจะสร้างคลาส MultiHeadAttention ส่วนที่เหลือตั้งแต่ต้น โดยกำหนดเมธอด 4 ตัว ได้แก่
.split_heads(): แยกและแปลง input embeddings ให้กระจายไปยัง attention head แต่ละตัว.compute_attention(): คำนวณ attention weights แบบ scaled dot-product แล้วคูณด้วยเมทริกซ์ values.combine_heads(): แปลง attention weights กลับให้มีรูปร่างเดิมเหมือน input embeddingsx.forward(): เรียกใช้เมธอดอื่น ๆ เพื่อส่ง input embeddings ผ่านแต่ละขั้นตอน
torch.nn ถูก import มาในชื่อ nn, torch.nn.functional ใช้ได้ในชื่อ F และ torch ก็พร้อมใช้งานเช่นกัน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Transformer Models ด้วย PyTorch
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
self.num_heads = num_heads
self.d_model = d_model
self.head_dim = d_model // num_heads
self.query_linear = nn.Linear(d_model, d_model, bias=False)
self.key_linear = nn.Linear(d_model, d_model, bias=False)
self.value_linear = nn.Linear(d_model, d_model, bias=False)
self.output_linear = nn.Linear(d_model, d_model)
def split_heads(self, x, batch_size):
seq_length = x.size(1)
# Split the input embeddings and permute
x = x.____
return x.permute(0, 2, 1, 3)