Sure, here's an example of a PyTorch model that uses self-attention and takes a 7x7 2D input of integers from -3 to 3:
python
import torch
import torch.nn as nn
import torch.nn.functional as F
class SelfAttention(nn.Module):
def __init__(self, input_dim):
super(SelfAttention, self).__init__()
self.query_linear = nn.Linear(input_dim, input_dim)
self.key_linear = nn.Linear(input_dim, input_dim)
self.value_linear = nn.Linear(input_dim, input_dim)
self.softmax = nn.Softmax(dim=2)
def forward(self, x):
batch_size, seq_length, input_dim = x.shape
query = self.query_linear(x).view(batch_size, seq_length, input_dim)
key = self.key_linear(x).view(batch_size, seq_length, input_dim)
value = self.value_linear(x).view(batch_size, seq_length, input_dim)
energy = torch.bmm(query, key.transpose(1, 2))
energy = energy / (input_dim ** 0.5)
attention = self.softmax(energy)
x_context = torch.bmm(attention, value)
return x_context, attention
class SmallSelfAttentionModel(nn.Module):
def __init__(self):
super(SmallSelfAttentionModel, self).__init__()
self.conv1 = nn.Conv2d(1, 64, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.conv3 = nn.Conv2d(128, 256, kernel_size=3, padding=1)
self.dropout = nn.Dropout(0.25)
self.self_attention = SelfAttention(256)
self.fc1 = nn.Linear(256 * 7 * 7, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 7 * 7)
def forward(self, x):
x = x.unsqueeze(1)
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv3(x))
x = F.max_pool2d(x, 2)
x = x.view(x.shape[0], -1)
x = self.dropout(x)
x_context, attention = self.self_attention(x.unsqueeze(1).unsqueeze(1))
x = torch.cat((x, x_context), dim=-1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Create a model instance
model = SmallSelfAttentionModel()
# Create a sample input
input_tensor = torch.randn(1, 7, 7)
for i in range(7):
for j in range(7):
input_tensor[0, i, j] = torch.randint(-3, 4, (1,))