import torch
import torch.nn as nn
import torch.nn.functional as F
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super(PositionalEncoding, self).__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
self.register_buffer('pe', pe)
def forward(self, x):
return x + self.pe[:x.size(0), :]
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1):
super(TransformerEncoderLayer, self).__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.activation = nn.ReLU()
def forward(self, src, src_mask=None, src_key_padding_mask=None):
src2 = self.norm1(src)
src2 = self.dropout1(src2)
src_out, attn_output_weights, attn_output_mask = self.self_attn(src2, src2, src2, attn_mask=src_mask,
key_padding_mask=src_key_padding_mask)
src = src + self.dropout2(src_out)
src2 = self.norm2(src)
src2 = self.dropout(src2)
src = self.linear2(self.dropout(self.activation(self.linear1(src2))))
src = src + src2
return src, attn_output_weights
class TransformerEncoder(nn.Module):
def __init__(self, encoder_layer, num_layers, d_model, vocab_size, max_len=5000):
super(TransformerEncoder, self).__init__()
self.layer = nn.ModuleList([encoder_layer for _ in range(num_layers)])
self.src_emb = nn.Embedding(vocab_size, d_model)
self.pos_encoder = PositionalEncoding(d_model, max_len)
def forward(self, src):
src = self.src_emb(src) * math.sqrt(self.d_model)
src = self.pos_encoder(src)
output = src
attn = None
for encoder in self.layer:
output, attn = encoder(output)
return output, attn
vocab_size = 10000
d_model = 512
nhead = 8
num_layers = 6
encoder_layer = TransformerEncoderLayer(d_model=d_model, nhead=nhead)
transformer_encoder = TransformerEncoder(encoder_layer, num_layers, d_model, vocab_size)
src = torch.tensor([[1, 2, 3, 4, 5, 0, 0],
[6, 7, 8, 9, 10, 0, 0]], dtype=torch.long)
output, attn = transformer_encoder(src)
print("Encoder output shape:", output.shape)
print("Attention weights shape (if you need them):", attn.shape)
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.