import torch
from torch import nn
class TransformerBlock(nn.Module):
def __init__(self, embed_size, heads):
super(TransformerBlock, self).__init__()
self.attention = nn.MultiheadAttention(embed_dim=embed_size, num_heads=heads)
self.norm1 = nn.LayerNorm(embed_size)
self.norm2 = nn.LayerNorm(embed_size)
self.feed_forward = nn.Sequential(
nn.Linear(embed_size, embed_size),
nn.ReLU(),
nn.Linear(embed_size, embed_size)
)
def forward(self, value, key, query, mask):
attention_out, _ = self.attention(query, key, value, attn_mask=mask)
x = self.norm1(attention_out + query)
forward_out = self.feed_forward(x)
out = self.norm2(forward_out + x)
return out
# Instantiate the TransformerBlock
model = TransformerBlock(embed_size=512, heads=8)
# Assuming we have input tensors 'value', 'key', 'query', 'mask'
# out = model(value, key, query, mask)
Please note that you need to define your input tensors value, key, query, mask based on your specific task. The transformer model is very customizable and can be extended depending on your needs. You can add more layers, use different sizes, etc.
This transformer block can be used as a building block for creating larger transformer models. For example, the actual Transformer model used in "Attention is All You Need" consists of multiple such blocks stacked on top of each other, both in the encoder and in the decoder.