DTDNN_layers.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. """ Some implementations are adapted from https://github.com/yuyq96/D-TDNN
  3. """
  4. import torch
  5. import torch.nn.functional as F
  6. import torch.utils.checkpoint as cp
  7. from torch import nn
  8. def get_nonlinear(config_str, channels):
  9. nonlinear = nn.Sequential()
  10. for name in config_str.split('-'):
  11. if name == 'relu':
  12. nonlinear.add_module('relu', nn.ReLU(inplace=True))
  13. elif name == 'prelu':
  14. nonlinear.add_module('prelu', nn.PReLU(channels))
  15. elif name == 'batchnorm':
  16. nonlinear.add_module('batchnorm', nn.BatchNorm1d(channels))
  17. elif name == 'batchnorm_':
  18. nonlinear.add_module('batchnorm',
  19. nn.BatchNorm1d(channels, affine=False))
  20. else:
  21. raise ValueError('Unexpected module ({}).'.format(name))
  22. return nonlinear
  23. def statistics_pooling(x, dim=-1, keepdim=False, unbiased=True, eps=1e-2):
  24. mean = x.mean(dim=dim)
  25. std = x.std(dim=dim, unbiased=unbiased)
  26. stats = torch.cat([mean, std], dim=-1)
  27. if keepdim:
  28. stats = stats.unsqueeze(dim=dim)
  29. return stats
  30. class StatsPool(nn.Module):
  31. def forward(self, x):
  32. return statistics_pooling(x)
  33. class TDNNLayer(nn.Module):
  34. def __init__(self,
  35. in_channels,
  36. out_channels,
  37. kernel_size,
  38. stride=1,
  39. padding=0,
  40. dilation=1,
  41. bias=False,
  42. config_str='batchnorm-relu'):
  43. super(TDNNLayer, self).__init__()
  44. if padding < 0:
  45. assert kernel_size % 2 == 1, 'Expect equal paddings, but got even kernel size ({})'.format(
  46. kernel_size)
  47. padding = (kernel_size - 1) // 2 * dilation
  48. self.linear = nn.Conv1d(
  49. in_channels,
  50. out_channels,
  51. kernel_size,
  52. stride=stride,
  53. padding=padding,
  54. dilation=dilation,
  55. bias=bias)
  56. self.nonlinear = get_nonlinear(config_str, out_channels)
  57. def forward(self, x):
  58. x = self.linear(x)
  59. x = self.nonlinear(x)
  60. return x
  61. class CAMLayer(nn.Module):
  62. def __init__(self,
  63. bn_channels,
  64. out_channels,
  65. kernel_size,
  66. stride,
  67. padding,
  68. dilation,
  69. bias,
  70. reduction=2):
  71. super(CAMLayer, self).__init__()
  72. self.linear_local = nn.Conv1d(
  73. bn_channels,
  74. out_channels,
  75. kernel_size,
  76. stride=stride,
  77. padding=padding,
  78. dilation=dilation,
  79. bias=bias)
  80. self.linear1 = nn.Conv1d(bn_channels, bn_channels // reduction, 1)
  81. self.relu = nn.ReLU(inplace=True)
  82. self.linear2 = nn.Conv1d(bn_channels // reduction, out_channels, 1)
  83. self.sigmoid = nn.Sigmoid()
  84. def forward(self, x):
  85. y = self.linear_local(x)
  86. context = x.mean(-1, keepdim=True) + self.seg_pooling(x)
  87. context = self.relu(self.linear1(context))
  88. m = self.sigmoid(self.linear2(context))
  89. return y * m
  90. def seg_pooling(self, x, seg_len=100, stype='avg'):
  91. if stype == 'avg':
  92. seg = F.avg_pool1d(
  93. x, kernel_size=seg_len, stride=seg_len, ceil_mode=True)
  94. elif stype == 'max':
  95. seg = F.max_pool1d(
  96. x, kernel_size=seg_len, stride=seg_len, ceil_mode=True)
  97. else:
  98. raise ValueError('Wrong segment pooling type.')
  99. shape = seg.shape
  100. seg = seg.unsqueeze(-1).expand(*shape,
  101. seg_len).reshape(*shape[:-1], -1)
  102. seg = seg[..., :x.shape[-1]]
  103. return seg
  104. class CAMDenseTDNNLayer(nn.Module):
  105. def __init__(self,
  106. in_channels,
  107. out_channels,
  108. bn_channels,
  109. kernel_size,
  110. stride=1,
  111. dilation=1,
  112. bias=False,
  113. config_str='batchnorm-relu',
  114. memory_efficient=False):
  115. super(CAMDenseTDNNLayer, self).__init__()
  116. assert kernel_size % 2 == 1, 'Expect equal paddings, but got even kernel size ({})'.format(
  117. kernel_size)
  118. padding = (kernel_size - 1) // 2 * dilation
  119. self.memory_efficient = memory_efficient
  120. self.nonlinear1 = get_nonlinear(config_str, in_channels)
  121. self.linear1 = nn.Conv1d(in_channels, bn_channels, 1, bias=False)
  122. self.nonlinear2 = get_nonlinear(config_str, bn_channels)
  123. self.cam_layer = CAMLayer(
  124. bn_channels,
  125. out_channels,
  126. kernel_size,
  127. stride=stride,
  128. padding=padding,
  129. dilation=dilation,
  130. bias=bias)
  131. def bn_function(self, x):
  132. return self.linear1(self.nonlinear1(x))
  133. def forward(self, x):
  134. if self.training and self.memory_efficient:
  135. x = cp.checkpoint(self.bn_function, x)
  136. else:
  137. x = self.bn_function(x)
  138. x = self.cam_layer(self.nonlinear2(x))
  139. return x
  140. class CAMDenseTDNNBlock(nn.ModuleList):
  141. def __init__(self,
  142. num_layers,
  143. in_channels,
  144. out_channels,
  145. bn_channels,
  146. kernel_size,
  147. stride=1,
  148. dilation=1,
  149. bias=False,
  150. config_str='batchnorm-relu',
  151. memory_efficient=False):
  152. super(CAMDenseTDNNBlock, self).__init__()
  153. for i in range(num_layers):
  154. layer = CAMDenseTDNNLayer(
  155. in_channels=in_channels + i * out_channels,
  156. out_channels=out_channels,
  157. bn_channels=bn_channels,
  158. kernel_size=kernel_size,
  159. stride=stride,
  160. dilation=dilation,
  161. bias=bias,
  162. config_str=config_str,
  163. memory_efficient=memory_efficient)
  164. self.add_module('tdnnd%d' % (i + 1), layer)
  165. def forward(self, x):
  166. for layer in self:
  167. x = torch.cat([x, layer(x)], dim=1)
  168. return x
  169. class TransitLayer(nn.Module):
  170. def __init__(self,
  171. in_channels,
  172. out_channels,
  173. bias=True,
  174. config_str='batchnorm-relu'):
  175. super(TransitLayer, self).__init__()
  176. self.nonlinear = get_nonlinear(config_str, in_channels)
  177. self.linear = nn.Conv1d(in_channels, out_channels, 1, bias=bias)
  178. def forward(self, x):
  179. x = self.nonlinear(x)
  180. x = self.linear(x)
  181. return x
  182. class DenseLayer(nn.Module):
  183. def __init__(self,
  184. in_channels,
  185. out_channels,
  186. bias=False,
  187. config_str='batchnorm-relu'):
  188. super(DenseLayer, self).__init__()
  189. self.linear = nn.Conv1d(in_channels, out_channels, 1, bias=bias)
  190. self.nonlinear = get_nonlinear(config_str, out_channels)
  191. def forward(self, x):
  192. if len(x.shape) == 2:
  193. x = self.linear(x.unsqueeze(dim=-1)).squeeze(dim=-1)
  194. else:
  195. x = self.linear(x)
  196. x = self.nonlinear(x)
  197. return x
  198. class BasicResBlock(nn.Module):
  199. expansion = 1
  200. def __init__(self, in_planes, planes, stride=1):
  201. super(BasicResBlock, self).__init__()
  202. self.conv1 = nn.Conv2d(
  203. in_planes,
  204. planes,
  205. kernel_size=3,
  206. stride=(stride, 1),
  207. padding=1,
  208. bias=False)
  209. self.bn1 = nn.BatchNorm2d(planes)
  210. self.conv2 = nn.Conv2d(
  211. planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
  212. self.bn2 = nn.BatchNorm2d(planes)
  213. self.shortcut = nn.Sequential()
  214. if stride != 1 or in_planes != self.expansion * planes:
  215. self.shortcut = nn.Sequential(
  216. nn.Conv2d(
  217. in_planes,
  218. self.expansion * planes,
  219. kernel_size=1,
  220. stride=(stride, 1),
  221. bias=False), nn.BatchNorm2d(self.expansion * planes))
  222. def forward(self, x):
  223. out = F.relu(self.bn1(self.conv1(x)))
  224. out = self.bn2(self.conv2(out))
  225. out += self.shortcut(x)
  226. out = F.relu(out)
  227. return out