RawTFNet / _net.py
korallll's picture
Make the repo self-contained: Arena wrapper code, arena_entry.yaml, portable weight/parity paths
8e69893 verified
Raw History Blame Contribute Delete
17.1 kB
"""Self-contained port of RawTFNet (full, width=32) for Arena inference.
Ported verbatim from https://github.com/swagshaw/RawTFNet-Pytorch
(model_scripts/rawtfnet.py + blocks/frontend.py + blocks/classifier.py).
Only the modules the full `RawTFNet` actually instantiates are kept; the
`torchinfo` dependency and unused variants (RawTFNet_small, Frontend_S/L/SE,
SepECA blocks, ECA, C2DLayer) are dropped. Math is untouched.
Architecture: SincConv front-end -> DWS Res2Net-SE conv blocks (DWS_Frontend_SE)
-> TfSepNet(depth=10, width=32) classifier. Output: per-utterance 2-logit tensor
(index 1 == bona fide).
"""
from __future__ import annotations
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# --------------------------------------------------------------------------- #
# Front-end blocks (from blocks/frontend.py) #
# --------------------------------------------------------------------------- #
class SeparableConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, bias=False, pointwise=False):
super().__init__()
self.conv2d = nn.Conv2d(in_channels=in_channels, out_channels=in_channels,
kernel_size=kernel_size, stride=stride,
groups=in_channels, padding=padding,
dilation=dilation, bias=bias)
if pointwise:
self.pointwise = nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
kernel_size=1, stride=1, padding=0, bias=bias)
else:
self.pointwise = nn.Identity()
def forward(self, x):
x = self.conv2d(x)
x = self.pointwise(x)
return x
class SincConv(nn.Module):
"""From https://github.com/clovaai/aasist (AASIST.py)."""
@staticmethod
def to_mel(hz):
return 2595 * np.log10(1 + hz / 700)
@staticmethod
def to_hz(mel):
return 700 * (10 ** (mel / 2595) - 1)
def __init__(self, out_channels, kernel_size, sample_rate=16000,
in_channels=1, stride=1, padding=0, dilation=1, bias=False,
groups=1, mask=False):
super().__init__()
if in_channels != 1:
raise ValueError(
"SincConv only support one input channel (here, in_channels = {%i})" % in_channels)
self.out_channels = out_channels
self.kernel_size = kernel_size
self.sample_rate = sample_rate
if kernel_size % 2 == 0:
self.kernel_size = self.kernel_size + 1
self.stride = stride
self.padding = padding
self.dilation = dilation
self.mask = mask
if bias:
raise ValueError('SincConv does not support bias.')
if groups > 1:
raise ValueError('SincConv does not support groups.')
NFFT = 512
f = int(self.sample_rate / 2) * np.linspace(0, 1, int(NFFT / 2) + 1)
fmel = self.to_mel(f)
fmelmax = np.max(fmel)
fmelmin = np.min(fmel)
filbandwidthsmel = np.linspace(fmelmin, fmelmax, self.out_channels + 1)
filbandwidthsf = self.to_hz(filbandwidthsmel)
self.mel = filbandwidthsf
self.hsupp = torch.arange(-(self.kernel_size - 1) / 2,
(self.kernel_size - 1) / 2 + 1)
self.band_pass = torch.zeros(self.out_channels, self.kernel_size)
for i in range(len(self.mel) - 1):
fmin = self.mel[i]
fmax = self.mel[i + 1]
hHigh = (2 * fmax / self.sample_rate) * np.sinc(2 * fmax * self.hsupp / self.sample_rate)
hLow = (2 * fmin / self.sample_rate) * np.sinc(2 * fmin * self.hsupp / self.sample_rate)
hideal = hHigh - hLow
self.band_pass[i, :] = torch.Tensor(np.hamming(self.kernel_size)) * torch.Tensor(hideal)
def forward(self, x, mask=False):
band_pass_filter = self.band_pass.clone().to(x.device)
if mask:
A = int(np.random.uniform(0, 20))
A0 = random.randint(0, band_pass_filter.shape[0] - A)
band_pass_filter[A0:A0 + A, :] = 0
self.filters = band_pass_filter.view(self.out_channels, 1, self.kernel_size)
return F.conv1d(x, self.filters, stride=self.stride, padding=self.padding,
dilation=self.dilation, bias=None, groups=1)
class Conv2DBlock_S(nn.Module):
"""ResNet-style block (AASIST), used as the first front-end block."""
def __init__(self, in_channels: int, out_channels: int, is_first_block: bool = False):
super().__init__()
self.normalizer = None
if not is_first_block:
self.normalizer = nn.Sequential(
nn.BatchNorm2d(num_features=in_channels),
nn.SELU(inplace=True),
)
self.layers = nn.Sequential(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(2, 5), padding=(1, 2), stride=1),
nn.BatchNorm2d(num_features=out_channels),
nn.SELU(inplace=True),
nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=(2, 3), padding=(0, 1), stride=1),
)
self.downsampler = None
if in_channels != out_channels:
self.downsampler = nn.Sequential(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, padding=(0, 1), kernel_size=(1, 3), stride=1)
)
self.pooling = nn.MaxPool2d(kernel_size=(1, 6))
def forward(self, x):
identity = x
if self.downsampler is not None:
identity = self.downsampler(identity)
if self.normalizer is not None:
x = self.normalizer(x)
x = self.layers(x)
x = x + identity
x = self.pooling(x)
return x
class SELayer(nn.Module):
def __init__(self, channels, channel_reduction=8):
super().__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(channels, channels // channel_reduction),
nn.ReLU(inplace=True),
nn.Linear(channels // channel_reduction, channels),
nn.Sigmoid(),
)
def forward(self, x):
b, c, _, _ = x.size()
y = self.avg_pool(x).view(b, c)
y = self.fc(y).view(b, c, 1, 1)
return x * y
class DWS_Conv2DBlock_SE(nn.Module):
"""Depthwise-separable Res2Net-SE block."""
def __init__(self, in_channels: int, out_channels: int, scale: int = 8, channel_reduction: int = 8):
super().__init__()
self.scale = scale
self.sub_channels = out_channels // scale
self.hidden_channels = self.sub_channels * scale
relu = nn.ReLU(inplace=True)
self.normalizer = nn.Sequential(
nn.BatchNorm2d(num_features=in_channels),
nn.SELU(inplace=True),
)
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels=in_channels, out_channels=self.hidden_channels, kernel_size=(1, 7), padding=(0, 3)),
nn.BatchNorm2d(num_features=self.hidden_channels),
relu,
)
self.conv2 = []
for _ in range(2, scale + 1):
self.conv2.append(nn.Sequential(
SeparableConv2d(in_channels=self.sub_channels, out_channels=self.sub_channels, kernel_size=(3, 9), padding=(1, 4)),
nn.BatchNorm2d(num_features=self.sub_channels),
relu,
))
self.conv2 = nn.ModuleList(self.conv2)
self.conv3 = nn.Sequential(
nn.Conv2d(in_channels=self.hidden_channels, out_channels=out_channels, kernel_size=(1, 7), padding=(0, 3)),
nn.BatchNorm2d(num_features=out_channels),
relu,
)
self.se_module = SELayer(channels=out_channels, channel_reduction=channel_reduction)
self.downsampler = None
if in_channels != out_channels:
self.downsampler = nn.Sequential(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, padding=(0, 3), kernel_size=(1, 7), stride=1)
)
self.pooling = nn.MaxPool2d(kernel_size=(1, 6))
def forward(self, x):
identity = x
if self.downsampler is not None:
identity = self.downsampler(identity)
x = self.normalizer(x)
x = self.conv1(x)
x_sub = torch.split(x, split_size_or_sections=self.sub_channels, dim=1)
y_sub = [x_sub[0]]
for i in range(1, self.scale):
if i == 1:
y_i = self.conv2[i - 1](x_sub[i])
else:
y_i = self.conv2[i - 1](x_sub[i] + y_sub[i - 1])
y_sub.append(y_i)
y = torch.cat(y_sub, dim=1)
y = self.conv3(y)
y = self.se_module(y)
y = y + identity
y = self.pooling(y)
return y
class DWS_Frontend_SE(nn.Module):
"""Sinc front-end of the full RawTFNet."""
def __init__(self, sinc_kernel_size=128, sample_rate=16000):
super().__init__()
self.sinc_layer = SincConv(in_channels=1, out_channels=70, kernel_size=sinc_kernel_size, sample_rate=sample_rate)
self.bn = nn.BatchNorm2d(num_features=1)
self.selu = nn.SELU(inplace=True)
self.conv_blocks = nn.Sequential(
Conv2DBlock_S(in_channels=1, out_channels=32, is_first_block=True),
DWS_Conv2DBlock_SE(in_channels=32, out_channels=32),
DWS_Conv2DBlock_SE(in_channels=32, out_channels=64),
DWS_Conv2DBlock_SE(in_channels=64, out_channels=64),
)
def forward(self, x):
x = x.unsqueeze(dim=1)
x = self.sinc_layer(x)
x = x.unsqueeze(dim=1)
x = F.max_pool2d(torch.abs(x), (3, 3))
x = self.bn(x)
LFM = self.selu(x)
HFM = self.conv_blocks(LFM)
return HFM
# --------------------------------------------------------------------------- #
# Classifier blocks (from blocks/classifier.py) #
# --------------------------------------------------------------------------- #
class ShuffleLayer(nn.Module):
def __init__(self, group=10):
super().__init__()
self.group = group
def forward(self, x):
b, c, f, t = x.data.size()
assert c % self.group == 0
group_channels = c // self.group
x = x.reshape(b, group_channels, self.group, f, t)
x = x.permute(0, 2, 1, 3, 4)
x = x.reshape(b, c, f, t)
return x
class AdaResNorm(nn.Module):
def __init__(self, c, grad=False, id_norm=None, eps=1e-5):
super().__init__()
self.grad = grad
self.id_norm = id_norm
self.eps = torch.Tensor(1, c, 1, 1)
self.eps.data.fill_(eps)
if self.grad:
self.rho = nn.Parameter(torch.Tensor(1, c, 1, 1))
self.rho.data.fill_(0.5)
self.gamma = nn.Parameter(torch.ones(1, c, 1, 1))
self.beta = nn.Parameter(torch.zeros(1, c, 1, 1))
else:
self.rho = torch.Tensor(1, c, 1, 1)
self.rho.data.fill_(0.5)
def forward(self, x):
self.eps = self.eps.to(x.device)
self.rho = self.rho.to(x.device)
identity = x
ifn_mean = x.mean((1, 3), keepdim=True)
ifn_var = x.var((1, 3), keepdim=True)
ifn = (x - ifn_mean) / (ifn_var + self.eps).sqrt()
res_norm = self.rho * identity + (1 - self.rho) * ifn
if self.grad:
return self.gamma * res_norm + self.beta
return res_norm
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=False, use_bn=False, use_relu=False):
super().__init__()
self.use_bn = use_bn
self.use_relu = use_relu
if self.use_bn:
self.bn = nn.BatchNorm2d(out_channels)
if self.use_relu:
self.activation = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
kernel_size=kernel_size, stride=stride, padding=padding,
dilation=dilation, groups=groups, bias=bias)
def forward(self, x):
x = self.conv(x)
if self.use_bn:
x = self.bn(x)
if self.use_relu:
x = self.activation(x)
return x
class TimeFreqSepConvs(nn.Module):
def __init__(self, in_channels, out_channels, dropout_rate=0.2, shuffle=False, shuffle_groups=10):
super().__init__()
self.transition = in_channels != out_channels
self.shuffle = shuffle
self.half_channels = out_channels // 2
if self.transition:
self.trans_conv = ConvBlock(in_channels=in_channels, out_channels=out_channels, kernel_size=1, use_bn=True, use_relu=True)
self.freq_dw_conv = ConvBlock(in_channels=self.half_channels, out_channels=self.half_channels, kernel_size=(3, 1), padding=(1, 0), groups=self.half_channels, use_bn=True, use_relu=True)
self.temp_dw_conv = ConvBlock(in_channels=self.half_channels, out_channels=self.half_channels, kernel_size=(1, 3), padding=(0, 1), groups=self.half_channels, use_bn=True, use_relu=True)
self.freq_pw_conv = ConvBlock(in_channels=self.half_channels, out_channels=self.half_channels, kernel_size=1, use_bn=True, use_relu=True)
self.temp_pw_conv = ConvBlock(in_channels=self.half_channels, out_channels=self.half_channels, kernel_size=1, use_bn=True, use_relu=True)
self.dropout = nn.Dropout(p=dropout_rate)
self.shuffle_layer = ShuffleLayer(group=shuffle_groups)
def forward(self, x):
if self.transition:
x = self.trans_conv(x)
if self.shuffle:
x = self.shuffle_layer(x)
x1, x2 = torch.split(x, self.half_channels, dim=1)
identity1 = x1
identity2 = x2
x1 = self.freq_dw_conv(x1)
x1 = x1.mean(2, keepdim=True)
x1 = self.freq_pw_conv(x1)
x1 = self.dropout(x1)
x1 = x1 + identity1
x2 = self.temp_dw_conv(x2)
x2 = x2.mean(3, keepdim=True)
x2 = self.temp_pw_conv(x2)
x2 = self.dropout(x2)
x2 = x2 + identity2
x = torch.cat((x1, x2), dim=1)
return x
defaultcfg = {
18: ['CONV', 'N', 1, 1, 'N', 'M', 1.5, 1.5, 'N', 'M', 2, 2, 'N', 2.5, 2.5, 2.5, 'N'],
10: ['N', 1, 1, 'N', 'M', 1.5, 1.5, 'N', 'M', 2, 2, 'N', 2.5, 2.5, 2.5, 'N'],
}
class TfSepNet(nn.Module):
def __init__(self, depth=18, width=40, dropout_rate=0.2, shuffle=True, shuffle_groups=10):
super().__init__()
cfg = defaultcfg[depth]
self.width = width
self.dropout_rate = dropout_rate
self.shuffle = shuffle
self.shuffle_groups = shuffle_groups
self.feature = self.make_layers(cfg)
i = -1
while isinstance(cfg[i], str):
i -= 1
self.classifier = nn.Conv2d(round(cfg[i] * self.width), 2, 1, bias=True)
def make_layers(self, cfg):
layers = []
vt = 2
for v in cfg:
if v == 'CONV':
layers += [nn.Conv2d(32, 2 * self.width, 5, stride=2, bias=False, padding=1)]
elif v == 'N':
layers += [AdaResNorm(c=round(vt * self.width), grad=True)]
elif v == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
elif v != vt:
layers += [TimeFreqSepConvs(in_channels=round(vt * self.width), out_channels=round(v * self.width),
dropout_rate=self.dropout_rate, shuffle=self.shuffle, shuffle_groups=self.shuffle_groups)]
vt = v
else:
layers += [TimeFreqSepConvs(in_channels=round(vt * self.width), out_channels=round(vt * self.width),
dropout_rate=self.dropout_rate, shuffle=self.shuffle, shuffle_groups=self.shuffle_groups)]
return nn.Sequential(*layers)
def forward(self, x):
x = self.feature(x)
y = self.classifier(x)
y = y.mean((-1, -2), keepdim=False)
y = y.squeeze()
return y
# --------------------------------------------------------------------------- #
# Full model #
# --------------------------------------------------------------------------- #
class RawTFNet(nn.Module):
def __init__(self, sample_rate: int = 16000):
super().__init__()
self.front_end = DWS_Frontend_SE(sinc_kernel_size=128, sample_rate=sample_rate)
self.classifier = TfSepNet(depth=10, width=32, dropout_rate=0.2, shuffle=True, shuffle_groups=8)
def forward(self, x):
x = self.front_end(x)
x = self.classifier(x)
return x
# Alias mirroring the reference wrappers' `TestModel` convention.
Model = RawTFNet