1""" 2/* Copyright (c) 2023 Amazon 3 Written by Jan Buethe */ 4/* 5 Redistribution and use in source and binary forms, with or without 6 modification, are permitted provided that the following conditions 7 are met: 8 9 - Redistributions of source code must retain the above copyright 10 notice, this list of conditions and the following disclaimer. 11 12 - Redistributions in binary form must reproduce the above copyright 13 notice, this list of conditions and the following disclaimer in the 14 documentation and/or other materials provided with the distribution. 15 16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27*/ 28""" 29 30 31import torch 32from torch import nn 33import torch.nn.functional as F 34 35from utils.complexity import _conv1d_flop_count 36 37class SilkFeatureNet(nn.Module): 38 39 def __init__(self, 40 feature_dim=47, 41 num_channels=256, 42 lookahead=False): 43 44 super(SilkFeatureNet, self).__init__() 45 46 self.feature_dim = feature_dim 47 self.num_channels = num_channels 48 self.lookahead = lookahead 49 50 self.conv1 = nn.Conv1d(feature_dim, num_channels, 3) 51 self.conv2 = nn.Conv1d(num_channels, num_channels, 3, dilation=2) 52 53 self.gru = nn.GRU(num_channels, num_channels, batch_first=True) 54 55 def flop_count(self, rate=200): 56 count = 0 57 for conv in self.conv1, self.conv2: 58 count += _conv1d_flop_count(conv, rate) 59 60 count += 2 * (3 * self.gru.input_size * self.gru.hidden_size + 3 * self.gru.hidden_size * self.gru.hidden_size) * rate 61 62 return count 63 64 65 def forward(self, features, state=None): 66 """ features shape: (batch_size, num_frames, feature_dim) """ 67 68 batch_size = features.size(0) 69 70 if state is None: 71 state = torch.zeros((1, batch_size, self.num_channels), device=features.device) 72 73 74 features = features.permute(0, 2, 1) 75 if self.lookahead: 76 c = torch.tanh(self.conv1(F.pad(features, [1, 1]))) 77 c = torch.tanh(self.conv2(F.pad(c, [2, 2]))) 78 else: 79 c = torch.tanh(self.conv1(F.pad(features, [2, 0]))) 80 c = torch.tanh(self.conv2(F.pad(c, [4, 0]))) 81 82 c = c.permute(0, 2, 1) 83 84 c, _ = self.gru(c, state) 85 86 return c