import torch from torch import nn EPSILON = 1e-5 # input dim = b, c, d class LayerNorm(nn.Module): def __init__(self, d): super().__init__() self.gamma = nn.Parameter(torch.ones(d)) self.beta = nn.Parameter(torch.zeros(d)) def forward(self, input): mean = torch.mean(input, dim=2, keepdim=True) variance = torch.var(input, dim=2, keepdim=True, unbiased=False) x = (input - mean) / torch.sqrt(variance + EPSILON) logits = (x * self.gamma) + self.beta return logits # input = torch.randn(2,3,4) # print(input) # LN = LayerNorm(input.shape[2]) # output = LN.forward(input) # print(output)