Positional encodings बनाना
Tokens को embed करना एक अच्छी शुरुआत है, लेकिन इन embeddings में अभी भी सीक्वेंस में हर token की पोजिशन की जानकारी नहीं है. इसे ठीक करने के लिए, transformer आर्किटेक्चर positional encodings का उपयोग करता है. इससे हर token की positional जानकारी embeddings में शामिल हो जाती है.
आप एक PositionalEncoding क्लास बनाएँगे, जिसमें ये पैरामीटर होंगे:
d_model: इनपुट embeddings का dimensionalitymax_seq_length: अधिकतम sequence length (या sequence length, यदि हर sequence की लंबाई समान हो)
यह अभ्यास पाठ्यक्रम का हिस्सा है
PyTorch के साथ Transformer Models
अभ्यास निर्देश
max_seq_lengthबाईd_modelआयामों वाला zeros का एक मैट्रिक्स बनाएँ.- सम और विषम पोजिशनल एम्बेडिंग मान बनाने के लिए
position * div_termपर sine और cosine की गणनाएँ करें. - सुनिश्चित करें कि
peट्रेनिंग के दौरान learnable पैरामीटर न हो. - ट्रांसफॉर्म किए गए पोजिशनल एम्बेडिंग्स को इनपुट token embeddings
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])