Implement spatial-self attention on pytorch
- User
Implement spatial-self attention on pytorch
- Assistant
Implement spatial-self attention on pytorch
To implement spatial self-attention in PyTorch, we'll create a custom module that applies the self-attention mechanism across the spatial dimensions of an input feature map. This allows the model to capture long-range dependencies across different spatial locations, enhancing the representational power of convolutional neural networks.
Below is the implementation of a SpatialSelfAttention module, along with detailed explanations:
import torch
import torch.nn as nn
import torch.nn.functional as F
class SpatialSelfAttention(nn.Module):
def __init__(self, in_channels):
super(SpatialSelfAttention, self).__init__()
# Convolution layers to generate query, key, and value feature maps
self.query_conv = nn.Conv2d(in_channels, in_channels // 8, kernel_size=1)
self.key_conv = nn.Conv2d(in_channels, in_channels // 8, kernel_size=1)
self.value_conv = nn.Conv2d(in_channels, in_channels, kernel_size=1)
# Learnable parameter to scale the attention output
self.gamma = nn.Parameter(torch.zeros(1))
# Softmax operation to generate attention map
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
"""
Inputs:
x: Input feature maps (B x C x H x W)
Returns:
out: Output feature maps with spatial self-attention applied
attention: Attention map (B x N x N) where N = H * W
"""
batch_size, C, H, W = x.size()
# Generate query, key, and value feature maps
query = self.query_conv(x) # (B x C' x H x W)
key = self.key_conv(x) # (B x C' x H x W)
value = self.value_conv(x) # (B x C x H x W)
# Reshape and permute to multiply query and key tensors
# Flatten the spatial dimensions (H x W) to compute attention
query = query.view(batch_size, -1, H * W).permute(0, 2, 1) # (B x N x C')
key = key.view(batch_size, -1, H * W) # (B x C' x N)
# Compute energy (affinity) matrix
energy = torch.bmm(query, key) # Batch matrix multiplication (B x N x N)
# Apply softmax to get attention map
attention = self.softmax(energy) # (B x N x N)
# Reshape value tensor for multiplication with attention map
value = value.view(batch_size, -1, H * W) # (B x C x N)
# Apply attention to value
out = torch.bmm(value, attention.permute(0, 2, 1)) # (B x C x N)
# Reshape output tensor to original spatial dimensions
out = out.view(batch_size, C, H, W) # (B x C x H x W)
# Apply learnable scaling parameter and residual connection
out = self.gamma * out + x
return out, attention
Parameter Initialization:
x into query (q), key (k), and value (v) feature spaces.
self.query_conv: Projects x to queries.self.key_conv: Projects x to keys.self.value_conv: Projects x to values.self.gamma is a learnable scalar parameter initialized to zero. It balances the importance of the attention map in the final output.self.softmax applies the softmax function along the last dimension to obtain the attention weights.Forward Pass:
x is projected into query, key, and value feature maps using the convolution layers.query: Reshaped to (B, N, C') where N = H * W, and permuted to have spatial dimensions first.key: Reshaped to (B, C', N).query and key:
energy = torch.bmm(query, key) results in a tensor of shape (B, N, N), representing the attention scores between all spatial positions.attention = self.softmax(energy).(B, C, N) to align with the attention map.out = torch.bmm(value, attention.permute(0, 2, 1)).You can integrate the SpatialSelfAttention module into your neural network models as follows:
# Example usage in a CNN model
class CNNWithAttention(nn.Module):
def __init__(self, in_channels, num_classes):
super(CNNWithAttention, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=3, padding=1)
self.attention = SpatialSelfAttention(64)
self.conv2 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.fc = nn.Linear(128 * H * W, num_classes) # Adjust H and W as per your input size
def forward(self, x):
x = self.conv1(x)
x, attention_map = self.attention(x)
x = self.conv2(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
Computational Efficiency:
(H * W) x (H * W), it can be memory-intensive for large spatial dimensions.Training Stability:
gamma parameter helps in stabilizing training by initially setting the attention contribution to zero.gamma during training as it finds the attention mechanism useful.By integrating this SpatialSelfAttention module into your models, you can enhance their ability to capture contextual information across spatial dimensions, which is beneficial for tasks like image classification, segmentation, and object detection.
Not yet included in a published release.
out(B, C, H, W)self.gamma and add the original input x (residual connection):
out = self.gamma * out + x.self.gamma is zero, so the module initially performs an identity mapping, allowing the network to learn how much attention to apply during training.Return Values: