# 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.
from typing import Dict
from torch import Tensor
from collections import OrderedDict
from omegaconf import DictConfig
from openspeech.models import OpenspeechCTCModel, register_model
from openspeech.encoders.deepspeech2 import DeepSpeech2
from openspeech.models.deepspeech2.configurations import DeepSpeech2Configs
from openspeech.tokenizers.tokenizer import Tokenizer
[docs]@register_model('deepspeech2', dataclass=DeepSpeech2Configs)
class DeepSpeech2Model(OpenspeechCTCModel):
r"""
Deep Speech2 model with configurable encoders and decoders.
Paper: https://arxiv.org/abs/1512.02595
Args:
configs (DictConfig): configuration set.
tokenizer (Tokenizer): tokenizer is in charge of preparing the inputs for a model.
Inputs:
inputs (torch.FloatTensor): A input sequence passed to encoders. Typically for inputs this will be a padded `FloatTensor` of size ``(batch, seq_length, dimension)``.
input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``
Returns:
outputs (dict): Result of model predictions that contains `y_hats`, `logits`, `output_lengths`
"""
def __init__(self, configs: DictConfig, tokenizer: Tokenizer) -> None:
super(DeepSpeech2Model, self).__init__(configs, tokenizer)
def build_model(self):
self.encoder = DeepSpeech2(
input_dim=self.configs.audio.num_mels,
num_classes=self.num_classes,
rnn_type=self.configs.model.rnn_type,
num_rnn_layers=self.configs.model.num_rnn_layers,
rnn_hidden_dim=self.configs.model.rnn_hidden_dim,
dropout_p=self.configs.model.dropout_p,
bidirectional=self.configs.model.bidirectional,
activation=self.configs.model.activation,
)
[docs] def forward(self, inputs: Tensor, input_lengths: Tensor) -> Dict[str, Tensor]:
r"""
Forward propagate a `inputs` and `targets` pair for inference.
Inputs:
inputs (torch.FloatTensor): A input sequence passed to encoders. Typically for inputs this will be a padded `FloatTensor` of size ``(batch, seq_length, dimension)``.
input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``
Returns:
outputs (dict): Result of model predictions that contains `y_hats`, `logits`, `output_lengths`
"""
return super(DeepSpeech2Model, self).forward(inputs, input_lengths)
[docs] def training_step(self, batch: tuple, batch_idx: int) -> OrderedDict:
r"""
Forward propagate a `inputs` and `targets` pair for training.
Inputs:
batch (tuple): A train batch contains `inputs`, `targets`, `input_lengths`, `target_lengths`
batch_idx (int): The index of batch
Returns:
loss (torch.Tensor): loss for training
"""
return super(DeepSpeech2Model, self).training_step(batch, batch_idx)
[docs] def validation_step(self, batch: tuple, batch_idx: int) -> OrderedDict:
r"""
Forward propagate a `inputs` and `targets` pair for validation.
Inputs:
batch (tuple): A train batch contains `inputs`, `targets`, `input_lengths`, `target_lengths`
batch_idx (int): The index of batch
Returns:
loss (torch.Tensor): loss for training
"""
return super(DeepSpeech2Model, self).validation_step(batch, batch_idx)
[docs] def test_step(self, batch: tuple, batch_idx: int) -> OrderedDict:
r"""
Forward propagate a `inputs` and `targets` pair for test.
Inputs:
batch (tuple): A train batch contains `inputs`, `targets`, `input_lengths`, `target_lengths`
batch_idx (int): The index of batch
Returns:
loss (torch.Tensor): loss for training
"""
return super(DeepSpeech2Model, self).test_step(batch, batch_idx)