"""ResCapsGuard network definition. Extracted verbatim from the upstream training notebook (github.com/lab260ru/ResCapsGuard, new_capsules_changed_sinc.ipynb), cells: SincConv, Res_block, Encoder, ChanelWiseStats/View, PrimaryCapsules, RoutingMechanism, CapsuleNet. Do not edit the class bodies -- they must match the published checkpoint new_capsules_changed_sinc_layer.pth. NOTE: SincConv defaults sample_rate=64000 (a training-time quirk); kept as-is. """ from __future__ import annotations import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from torch.autograd import Variable class SincConv(nn.Module): """Sinc-based convolution Parameters ---------- in_channels : `int` Number of input channels. Must be 1. out_channels : `int` Number of filters. kernel_size : `int` Filter length. sample_rate : `int`, optional Sample rate. Defaults to 16000. Usage ----- See `torch.nn.Conv1d` Reference --------- Mirco Ravanelli, Yoshua Bengio, "Speaker Recognition from raw waveform with SincNet". https://arxiv.org/abs/1808.00158 """ @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=64000, in_channels=1, stride=1, padding=0, dilation=1, bias=False, groups=1, min_low_hz=0, min_band_hz=0): super(SincConv,self).__init__() if in_channels != 1: #msg = (f'SincConv only support one input channel ' # f'(here, in_channels = {in_channels:d}).') msg = "SincConv only support one input channel (here, in_channels = {%i})" % (in_channels) raise ValueError(msg) self.out_channels = out_channels self.kernel_size = kernel_size # Forcing the filters to be odd (i.e, perfectly symmetrics) if kernel_size%2==0: self.kernel_size=self.kernel_size+1 self.stride = stride self.padding = padding self.dilation = dilation if bias: raise ValueError('SincConv does not support bias.') if groups > 1: raise ValueError('SincConv does not support groups.') self.sample_rate = sample_rate self.min_low_hz = min_low_hz self.min_band_hz = min_band_hz # initialize filterbanks such that they are equally spaced in Mel scale low_hz = 0 high_hz = self.sample_rate / 2 - (self.min_low_hz + self.min_band_hz) # In the future we will set high hz as band_hz + low + min_band_hz + min_low_hz # Where band_hz is (high_hz - low_hz). Therefore, it is reasonable to # do diff and do not set high_hz as sr/2 mel = np.linspace(self.to_mel(low_hz), self.to_mel(high_hz), self.out_channels + 1) hz = self.to_hz(mel) # filter lower frequency (out_channels, 1) self.low_hz_ = nn.Parameter(torch.Tensor(hz[:-1]).view(-1, 1)) # learnable f1 from the paper # filter frequency band (out_channels, 1) self.band_hz_ = nn.Parameter(torch.Tensor(np.diff(hz)).view(-1, 1)) # learnable f2 (f2 = f1+diff) from the paper # len(g) = kernel_size # It is symmetric, therefore we will do computations only with left part, while creating g. # Hamming window #self.window_ = torch.hamming_window(self.kernel_size) n_lin=torch.linspace(0, (self.kernel_size/2)-1, steps=int((self.kernel_size/2))) # computing only half of the window self.window_=0.54-0.46*torch.cos(2*math.pi*n_lin/self.kernel_size) # self.window is eq. (8) # (1, kernel_size/2) n = (self.kernel_size - 1) / 2.0 self.n_ = 2*math.pi*torch.arange(-n, 0).view(1, -1) / self.sample_rate # Due to symmetry, I only need half of the time axes # self.n_ = 2 * pi * n / sr def forward(self, waveforms): """ Parameters ---------- waveforms : `torch.Tensor` (batch_size, 1, n_samples) Batch of waveforms. Returns ------- features : `torch.Tensor` (batch_size, out_channels, n_samples_out) Batch of sinc filters activations. """ self.n_ = self.n_.to(waveforms.device) # print('self.n_', self.n_) # print('--------------------') self.window_ = self.window_.to(waveforms.device) low = self.min_low_hz + torch.abs(self.low_hz_) # eq. (5) + make sure low >= min_low_hz high = torch.clamp(low + self.min_band_hz + torch.abs(self.band_hz_),self.min_low_hz,self.sample_rate/2) # eq. (6) + make sure band has length >= min_band_hz band=(high-low)[:,0] # g[0] / 2 # print('band', band) # print('low', low) # print('high', high) # print('--------------------') f_times_t_low = torch.matmul(low, self.n_) # 2 * pi * n * freq / sr f_times_t_high = torch.matmul(high, self.n_) # print('times_t_low', f_times_t_low) # print('times_t_high', f_times_t_high) # print('--------------------') # 2*f2*sinc(2*pi*f2*n) - 2*f1*sinc(2*pi*f1*n) # 2*f2*sin(2*pi*f2*n) / (2 * pi * f2 * n) - 2*f1*sin(2*pi*f1*n) / (2 * pi * f1 * n) # sin(2*pi*f2*n) / (pi n) - sin(2*pi*f1*n) / (pi n) # (2 / sr) * sin(f_times_t_high) / self.n_ - (2 / sr) * sin(f_times_t_low) / self.n_ # (1/ sr) * (sin(f_times_t_high) - sin(f_times_t_low)) / (self.n_ / 2) # sr * correct eq. (4) # because self.n_ = 2 * pi * n / sr band_pass_left=((torch.sin(f_times_t_high)-torch.sin(f_times_t_low))/(self.n_/2))*self.window_ # Equivalent of Eq.4 of the reference paper (SPEAKER RECOGNITION FROM RAW WAVEFORM WITH SINCNET). I just have expanded the sinc and simplified the terms. This way I avoid several useless computations. band_pass_center = 2*band.view(-1,1) # g[0] = 2 * (f2 - f1) = 2 * band, w[0] = 1 band_pass_right= torch.flip(band_pass_left,dims=[1]) # g[n] = g[-n] # print('band_pass_left', band_pass_left) # print('band_pass_center', band_pass_center) # print('---------------') band_pass=torch.cat([band_pass_left,band_pass_center,band_pass_right],dim=1) # create full g[n] band_pass = band_pass / (2*band[:,None]) # normalize so the max is 1 # band_pass_left = sr * correct (4) # center = freq (not scaled via division) = sr * scaled_freq # thus, after normalization we will divide all by sr and get normalized correct(4) + normalized center self.filters = (band_pass).view( self.out_channels, 1, self.kernel_size) return F.conv1d(waveforms, self.filters, stride=self.stride, padding=self.padding, dilation=self.dilation, bias=None, groups=1) # x[n] * g[n] class Res_block(nn.Module): def __init__(self, nb_filts: int, first=False): super().__init__() # for first res block in net self.first = first if not self.first: self.bn1 = nn.BatchNorm2d(num_features=nb_filts[0]) self.conv1 = nn.Conv2d(in_channels=nb_filts[0], out_channels=nb_filts[1], kernel_size=(2, 3), padding=(1, 1), stride=1) self.selu = nn.SELU(inplace=True) self.bn2 = nn.BatchNorm2d(num_features=nb_filts[1]) self.conv2 = nn.Conv2d(in_channels=nb_filts[1], out_channels=nb_filts[1], kernel_size=(2, 3), padding=(0, 1), stride=1) if nb_filts[0] != nb_filts[1]: self.downsample = True self.conv_downsample = nn.Conv2d(in_channels=nb_filts[0], out_channels=nb_filts[1], padding=(0, 1), kernel_size=(1, 3), stride=1) else: self.downsample = False self.mp = nn.MaxPool2d((1, 3)) def forward(self, x: Tensor) -> Tensor: # original sample save original_x = x if not self.first: out = self.bn1(x) out = self.selu(out) else: out = x out = self.conv1(x) out = self.bn2(out) out = self.selu(out) out = self.conv2(out) # resizing original sample in case of size diff with out if self.downsample: original_x = self.conv_downsample(original_x) # adding original sample in the end of res block out += original_x out = self.mp(out) return out class Encoder(nn.Module): def __init__(self, d_args): super().__init__() # list of some args of original model. Full list: https://github.com/clovaai/aasist/blob/main/config/AASIST.conf self.d_args = d_args filts = d_args["filts"] self.sinc_conv = SincConv(out_channels=filts[0], kernel_size=d_args["first_conv"], ) self.first_bn = nn.BatchNorm2d(num_features=1) self.selu = nn.SELU(inplace=True) self.res_encoder = nn.Sequential( Res_block(nb_filts=filts[1], first=True), Res_block(nb_filts=filts[2]), Res_block(nb_filts=filts[3]), Res_block(nb_filts=filts[4]), Res_block(nb_filts=filts[4]), Res_block(nb_filts=filts[4]) ) def forward(self, x): x = x.unsqueeze(1) x = self.sinc_conv(x) x = x.unsqueeze(dim=1) x = F.max_pool2d(torch.abs(x), (3, 3)) x = self.first_bn(x) x = self.selu(x) e = self.res_encoder(x) # [batch, filter, spec,sequence] # print(e.shape) return e class ChanelWiseStats(nn.Module): """ The class that computes mean and standart deviation in input data acrocc channels """ def __init__(self): super(ChanelWiseStats, self).__init__() def forward(self, x): x = x.view(x.data.shape[0], x.data.shape[1], x.data.shape[2]*x.data.shape[3]) mean = torch.mean(x, 2) std = torch.std(x,2) return torch.stack((mean, std), dim=1) class View(nn.Module): """ Auxiliary class """ def __init__(self, *shape): super(View, self).__init__() self.shape = shape def forward(self, input): return input.view(self.shape) class PrimaryCapsules(nn.Module): """ This class create capsules and makes forward propagation through them """ def __init__(self, num_capsules=10): super(PrimaryCapsules, self).__init__() self.num_capsules = num_capsules self.capsules = nn.ModuleList([ nn.Sequential( nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64,16, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(16), nn.ReLU(), ChanelWiseStats(), nn.Conv1d(2,8, kernel_size=5, stride=2, padding=2), nn.BatchNorm1d(8), nn.Conv1d(8, 1, kernel_size=3, stride=1, padding=1), nn.BatchNorm1d(1), View(-1, 8) ) for _ in range(num_capsules) ]) def forward(self, x): results = [capsule(x) for capsule in self.capsules] result = torch.stack(results, dim=-1) return result class RoutingMechanism(nn.Module): def __init__(self, gpu_id, num_input_capsules, num_output_capsules, data_in, data_out, num_iterations=2): super(RoutingMechanism, self).__init__() self.gpu_id = gpu_id self.num_iterations = num_iterations self.route_weights = nn.Parameter(torch.randn( num_output_capsules, num_input_capsules, data_out, data_in )) def squash(self, x, dim): squared_norm = (x ** 2).sum(dim=dim, keepdim=True) scale = squared_norm / (1 + squared_norm) return scale * x / (torch.sqrt(squared_norm)) def forward(self, x, random, dropout, random_size=0.01): # x[batch, data, in_caps] x = x.transpose(2, 1) # x[batch, in_caps, data] if random: noise = Variable(random_size * torch.randn(*self.route_weights.size())) if self.gpu_id >=0: noise = noise.cuda(self.gpu_id) route_weights = self.route_weights + noise #w_ji + rand(size(w_ji)) else: route_weights = self.route_weights priors = route_weights[:, None, :, :, :] @ x[None, :, :, :, None] #route_weights[out_caps, 1, in_caps, data_out, data_in] #x [1, batch, in_caps, data_in, 1] #priors [out_caps, batch, in_caps, data_out, 1] priors = self.squash(priors.transpose(1, 0), dim=3) #sqush(w_ij u_i) # priors[batch, out_caps, in_caps, data_out, 1] if dropout > 0.0: drop = Variable(torch.FloatTensor(*priors.size())).bernoulli(1.0-dropout) if self.gpu_id >= 0: drop = drop.cuda(self.gpu_id) priors = priors * drop logits = Variable(torch.zeros(*priors.size())) #initialization b_ij = #logits[batch,out_caps,in_caps, data_out,1] if self.gpu_id >= 0: logits = logits.cuda(self.gpu_id) num_iterations = self.num_iterations for i in range(num_iterations): #for r iterations do probs = F.softmax(logits, dim=2) #a_j = softmax(b_j) outputs = self.squash((probs*priors).sum(dim=2, keepdim=True), dim=3) #v_j=squash(a_ji * u_ji) logits = priors * outputs #b_ij = v_j*u_ji #outputs[b, out_caps, 1, data_out, 1] outputs = outputs.squeeze() if len(outputs.shape) == 3: outputs = outputs.transpose(2,1).contiguous() else: outputs = outputs.unsqueeze_(dim=0).transpose(2,1).contiguous() return outputs class CapsuleNet(nn.Module): # во время оценки отключить рандом и дропаут, модель перевести в эвал def __init__(self, num_class, gpu_id, d_args, num_capsules=3, num_iterations=3): super(CapsuleNet, self).__init__() self.num_class = num_class self.extractor = Encoder(d_args) self.fea_ext = PrimaryCapsules(num_capsules=num_capsules) self.routing_stats = RoutingMechanism(gpu_id=gpu_id, num_input_capsules=num_capsules, num_output_capsules=2, data_in=8, data_out=4, num_iterations=num_iterations) def forward(self, x, random=True, dropout=0.05, random_size=0.01): z = self.extractor(x) z = self.fea_ext(z) z = self.routing_stats(z, random, dropout, random_size=0.01) # classes = F.softmax(z, dim=-1) class_ = z.detach() class_ = class_.mean(dim=1) return z, class_