File size: 1,766 Bytes
f356d7c | 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 | import torch
from .layernorm import LayerNorm
from .multi_head_attention import MultiHeadAttention
from .projection import FeedForwardNetwork
class EncoderLayer(torch.nn.Module):
def __init__(self, d_model: int, num_heads: int, d_ff: int = 2048):
"""
Initializes the EncoderLayer module.
Args:
d_model (int): The dimensionality of the input and output.
num_heads (int): The number of heads in the multi-head attention.
d_ff (int, optional): The dimensionality of the inner-layer of the
feed-forward network. Defaults to 2048.
"""
super().__init__()
self.mha = MultiHeadAttention(
d_model=d_model, num_heads=num_heads
)
self.layer_norm_1 = LayerNorm(d_model)
self.ffn = FeedForwardNetwork(d_model=d_model, d_ff=d_ff)
self.layer_norm_2 = LayerNorm(d_model)
def forward(self, in_embeddings: torch.Tensor) -> torch.Tensor:
"""
Forward pass for the EncoderLayer.
Args:
in_embeddings (torch.Tensor): The input tensor of shape
(batch_size, seq_len, d_model).
Returns:
torch.Tensor: The output tensor of the same shape as the input.
"""
# Multi-Head Attention sub-layer
mha_out = self.mha(in_embeddings, in_embeddings, in_embeddings)
# print(mha_out.min(), mha_out.max())
# Residual connection and layer normalization
norm_out_1 = self.layer_norm_1(mha_out + in_embeddings)
# Feed-Forward Network sub-layer
ffn_out = self.ffn(norm_out_1)
# Residual connection and layer normalization
output = self.layer_norm_2(ffn_out + norm_out_1)
return output
|