|
|
import math |
|
|
import torch |
|
|
import torch.nn as nn |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
self.register_buffer('pe', pe) |
|
|
|
|
|
def forward(self, x): |
|
|
|
|
|
|
|
|
x = x + self.pe[:, :x.size(1)] |
|
|
return x |
|
|
|
|
|
class TransformerBlock(nn.Module): |
|
|
def __init__(self, embed_dim, num_heads, ff_dim, dropout=0.1): |
|
|
super(TransformerBlock, self).__init__() |
|
|
|
|
|
|
|
|
self.attention = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True) |
|
|
|
|
|
|
|
|
self.norm1 = nn.LayerNorm(embed_dim) |
|
|
self.norm2 = nn.LayerNorm(embed_dim) |
|
|
|
|
|
|
|
|
self.ff = nn.Sequential( |
|
|
nn.Linear(embed_dim, ff_dim), |
|
|
nn.ReLU(), |
|
|
nn.Linear(ff_dim, embed_dim) |
|
|
) |
|
|
|
|
|
self.dropout = nn.Dropout(dropout) |
|
|
|
|
|
def forward(self, x): |
|
|
|
|
|
|
|
|
attn_output, _ = self.attention(x, x, x) |
|
|
x = self.norm1(x + self.dropout(attn_output)) |
|
|
|
|
|
|
|
|
ff_output = self.ff(x) |
|
|
x = self.norm2(x + self.dropout(ff_output)) |
|
|
return x |
|
|
|
|
|
class TransformerSentimentModel(nn.Module): |
|
|
def __init__(self, vocab_size, embed_dim, num_heads, ff_dim, num_layers, output_dim, max_len=300): |
|
|
super(TransformerSentimentModel, self).__init__() |
|
|
self.embedding = nn.Embedding(vocab_size, embed_dim) |
|
|
self.pos_encoding = PositionalEncoding(embed_dim, max_len) |
|
|
self.blocks = nn.ModuleList([ |
|
|
TransformerBlock(embed_dim, num_heads, ff_dim) for _ in range(num_layers) |
|
|
]) |
|
|
|
|
|
self.dropout = nn.Dropout(0.5) |
|
|
self.fc = nn.Linear(embed_dim, output_dim) |
|
|
|
|
|
def forward(self, input_ids): |
|
|
|
|
|
x = self.embedding(input_ids) |
|
|
x = self.pos_encoding(x) |
|
|
|
|
|
for block in self.blocks: |
|
|
x = block(x) |
|
|
|
|
|
x = x[:, 0, :] |
|
|
return self.fc(self.dropout(x)) |