Source code for openspeech.modules.mask_conv2d

# MIT License
#
# Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import torch
import torch.nn as nn
from torch import Tensor
from typing import Tuple


[docs]class MaskConv2d(nn.Module): r""" Masking Convolutional Neural Network Adds padding to the output of the module based on the given lengths. This is to ensure that the results of the model do not change when batch sizes change during inference. Input needs to be in the shape of (batch_size, channel, hidden_dim, seq_len) Refer to https://github.com/SeanNaren/deepspeech.pytorch/blob/master/model.py Copyright (c) 2017 Sean Naren MIT License Args: sequential (torch.nn): sequential list of convolution layer Inputs: inputs, seq_lengths - **inputs** (torch.FloatTensor): The input of size BxCxHxT - **seq_lengths** (torch.IntTensor): The actual length of each sequence in the batch Returns: output, seq_lengths - **output**: Masked output from the sequential - **seq_lengths**: Sequence length of output from the sequential """ def __init__(self, sequential: nn.Sequential) -> None: super(MaskConv2d, self).__init__() self.sequential = sequential def forward(self, inputs: Tensor, seq_lengths: Tensor) -> Tuple[Tensor, Tensor]: output = None for module in self.sequential: output = module(inputs) mask = torch.BoolTensor(output.size()).fill_(0) if output.is_cuda: mask = mask.cuda() seq_lengths = self._get_sequence_lengths(module, seq_lengths) for idx, length in enumerate(seq_lengths): length = length.item() if (mask[idx].size(2) - length) > 0: mask[idx].narrow(dim=2, start=length, length=mask[idx].size(2) - length).fill_(1) output = output.masked_fill(mask, 0) inputs = output return output, seq_lengths def _get_sequence_lengths(self, module: nn.Module, seq_lengths: Tensor) -> Tensor: r""" Calculate convolutional neural network receptive formula Args: module (torch.nn.Module): module of CNN seq_lengths (torch.IntTensor): The actual length of each sequence in the batch Returns: seq_lengths - **seq_lengths**: Sequence length of output from the module """ if isinstance(module, nn.Conv2d): numerator = seq_lengths + 2 * module.padding[1] - module.dilation[1] * (module.kernel_size[1] - 1) - 1 seq_lengths = numerator.float() / float(module.stride[1]) seq_lengths = seq_lengths.int() + 1 elif isinstance(module, nn.MaxPool2d): seq_lengths >>= 1 return seq_lengths.int()