common.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. from typing import Type
  6. import torch
  7. import torch.nn as nn
  8. class MLPBlock(nn.Module):
  9. def __init__(
  10. self,
  11. embedding_dim: int,
  12. mlp_dim: int,
  13. act: Type[nn.Module] = nn.GELU,
  14. ) -> None:
  15. super().__init__()
  16. self.lin1 = nn.Linear(embedding_dim, mlp_dim)
  17. self.lin2 = nn.Linear(mlp_dim, embedding_dim)
  18. self.act = act()
  19. def forward(self, x: torch.Tensor) -> torch.Tensor:
  20. return self.lin2(self.act(self.lin1(x)))
  21. # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
  22. # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
  23. class LayerNorm2d(nn.Module):
  24. def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
  25. super().__init__()
  26. self.weight = nn.Parameter(torch.ones(num_channels))
  27. self.bias = nn.Parameter(torch.zeros(num_channels))
  28. self.eps = eps
  29. def forward(self, x: torch.Tensor) -> torch.Tensor:
  30. u = x.mean(1, keepdim=True)
  31. s = (x - u).pow(2).mean(1, keepdim=True)
  32. x = (x - u) / torch.sqrt(s + self.eps)
  33. x = self.weight[:, None, None] * x + self.bias[:, None, None]
  34. return x