conv.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import torch.nn as nn
  2. # --------------------- Basic modules ---------------------
  3. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  4. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  5. return conv
  6. def get_activation(act_type=None):
  7. if act_type == 'relu':
  8. return nn.ReLU(inplace=True)
  9. elif act_type == 'lrelu':
  10. return nn.LeakyReLU(0.1, inplace=True)
  11. elif act_type == 'mish':
  12. return nn.Mish(inplace=True)
  13. elif act_type == 'silu':
  14. return nn.SiLU(inplace=True)
  15. elif act_type is None:
  16. return nn.Identity()
  17. else:
  18. raise NotImplementedError
  19. def get_norm(norm_type, dim):
  20. if norm_type == 'BN':
  21. return nn.BatchNorm2d(dim)
  22. elif norm_type == 'GN':
  23. return nn.GroupNorm(num_groups=32, num_channels=dim)
  24. elif norm_type is None:
  25. return nn.Identity()
  26. else:
  27. raise NotImplementedError
  28. class BasicConv(nn.Module):
  29. def __init__(self,
  30. in_dim, # in channels
  31. out_dim, # out channels
  32. kernel_size=1, # kernel size
  33. padding=0, # padding
  34. stride=1, # padding
  35. dilation=1, # dilation
  36. act_type :str = 'lrelu', # activation
  37. norm_type :str = 'BN', # normalization
  38. depthwise :bool = False
  39. ):
  40. super(BasicConv, self).__init__()
  41. self.depthwise = depthwise
  42. use_bias = False if norm_type is not None else True
  43. if not depthwise:
  44. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=1, bias=use_bias)
  45. self.norm = get_norm(norm_type, out_dim)
  46. else:
  47. self.conv1 = get_conv2d(in_dim, in_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=in_dim, bias=use_bias)
  48. self.norm1 = get_norm(norm_type, in_dim)
  49. self.conv2 = get_conv2d(in_dim, out_dim, k=1, p=0, s=1, d=1, g=1)
  50. self.norm2 = get_norm(norm_type, out_dim)
  51. self.act = get_activation(act_type)
  52. def forward(self, x):
  53. if not self.depthwise:
  54. return self.act(self.norm(self.conv(x)))
  55. else:
  56. # Depthwise conv
  57. x = self.act(self.norm1(self.conv1(x)))
  58. # Pointwise conv
  59. x = self.act(self.norm2(self.conv2(x)))
  60. return x