[ASR]add squeezeformer model (#2755)
* add squeezeformer model * change CodeStyle, test=asr * change CodeStyle, test=asr * fix subsample rate error, test=asr * merge classes as required, test=asr * change CodeStyle, test=asr * fix missing code, test=asr * split code to new file, test=asr * remove rel_shift, test=asrpull/3056/head
parent
9bf5471613
commit
31a4562ae8
@ -0,0 +1,98 @@
|
||||
############################################
|
||||
# Network Architecture #
|
||||
############################################
|
||||
cmvn_file:
|
||||
cmvn_file_type: "json"
|
||||
# encoder related
|
||||
encoder: squeezeformer
|
||||
encoder_conf:
|
||||
encoder_dim: 256 # dimension of attention
|
||||
output_size: 256 # dimension of output
|
||||
attention_heads: 4
|
||||
num_blocks: 12 # the number of encoder blocks
|
||||
reduce_idx: 5
|
||||
recover_idx: 11
|
||||
feed_forward_expansion_factor: 8
|
||||
input_dropout_rate: 0.1
|
||||
feed_forward_dropout_rate: 0.1
|
||||
attention_dropout_rate: 0.1
|
||||
adaptive_scale: true
|
||||
cnn_module_kernel: 31
|
||||
normalize_before: false
|
||||
activation_type: 'swish'
|
||||
pos_enc_layer_type: 'rel_pos'
|
||||
time_reduction_layer_type: 'stream'
|
||||
causal: true
|
||||
use_dynamic_chunk: true
|
||||
use_dynamic_left_chunk: false
|
||||
|
||||
# decoder related
|
||||
decoder: transformer
|
||||
decoder_conf:
|
||||
attention_heads: 4
|
||||
linear_units: 2048
|
||||
num_blocks: 6
|
||||
dropout_rate: 0.1 # sublayer output dropout
|
||||
positional_dropout_rate: 0.1
|
||||
self_attention_dropout_rate: 0.0
|
||||
src_attention_dropout_rate: 0.0
|
||||
# hybrid CTC/attention
|
||||
model_conf:
|
||||
ctc_weight: 0.3
|
||||
lsm_weight: 0.1 # label smoothing option
|
||||
length_normalized_loss: false
|
||||
init_type: 'kaiming_uniform' # !Warning: need to convergence
|
||||
|
||||
###########################################
|
||||
# Data #
|
||||
###########################################
|
||||
|
||||
train_manifest: data/manifest.train
|
||||
dev_manifest: data/manifest.dev
|
||||
test_manifest: data/manifest.test
|
||||
|
||||
|
||||
###########################################
|
||||
# Dataloader #
|
||||
###########################################
|
||||
|
||||
vocab_filepath: data/lang_char/vocab.txt
|
||||
spm_model_prefix: ''
|
||||
unit_type: 'char'
|
||||
preprocess_config: conf/preprocess.yaml
|
||||
feat_dim: 80
|
||||
stride_ms: 10.0
|
||||
window_ms: 25.0
|
||||
sortagrad: 0 # Feed samples from shortest to longest ; -1: enabled for all epochs, 0: disabled, other: enabled for 'other' epochs
|
||||
batch_size: 32
|
||||
maxlen_in: 512 # if input length > maxlen-in, batchsize is automatically reduced
|
||||
maxlen_out: 150 # if output length > maxlen-out, batchsize is automatically reduced
|
||||
minibatches: 0 # for debug
|
||||
batch_count: auto
|
||||
batch_bins: 0
|
||||
batch_frames_in: 0
|
||||
batch_frames_out: 0
|
||||
batch_frames_inout: 0
|
||||
num_workers: 2
|
||||
subsampling_factor: 1
|
||||
num_encs: 1
|
||||
|
||||
###########################################
|
||||
# Training #
|
||||
###########################################
|
||||
n_epoch: 240
|
||||
accum_grad: 1
|
||||
global_grad_clip: 5.0
|
||||
dist_sampler: True
|
||||
optim: adam
|
||||
optim_conf:
|
||||
lr: 0.001
|
||||
weight_decay: 1.0e-6
|
||||
scheduler: warmuplr
|
||||
scheduler_conf:
|
||||
warmup_steps: 25000
|
||||
lr_decay: 1.0
|
||||
log_interval: 100
|
||||
checkpoint:
|
||||
kbest_n: 50
|
||||
latest_n: 5
|
@ -0,0 +1,93 @@
|
||||
############################################
|
||||
# Network Architecture #
|
||||
############################################
|
||||
cmvn_file:
|
||||
cmvn_file_type: "json"
|
||||
# encoder related
|
||||
encoder: squeezeformer
|
||||
encoder_conf:
|
||||
encoder_dim: 256 # dimension of attention
|
||||
output_size: 256 # dimension of output
|
||||
attention_heads: 4
|
||||
num_blocks: 12 # the number of encoder blocks
|
||||
reduce_idx: 5
|
||||
recover_idx: 11
|
||||
feed_forward_expansion_factor: 8
|
||||
input_dropout_rate: 0.1
|
||||
feed_forward_dropout_rate: 0.1
|
||||
attention_dropout_rate: 0.1
|
||||
adaptive_scale: true
|
||||
cnn_module_kernel: 31
|
||||
normalize_before: false
|
||||
activation_type: 'swish'
|
||||
pos_enc_layer_type: 'rel_pos'
|
||||
time_reduction_layer_type: 'conv1d'
|
||||
|
||||
# decoder related
|
||||
decoder: transformer
|
||||
decoder_conf:
|
||||
attention_heads: 4
|
||||
linear_units: 2048
|
||||
num_blocks: 6
|
||||
dropout_rate: 0.1
|
||||
positional_dropout_rate: 0.1
|
||||
self_attention_dropout_rate: 0.0
|
||||
src_attention_dropout_rate: 0.0
|
||||
|
||||
# hybrid CTC/attention
|
||||
model_conf:
|
||||
ctc_weight: 0.3
|
||||
lsm_weight: 0.1 # label smoothing option
|
||||
length_normalized_loss: false
|
||||
init_type: 'kaiming_uniform' # !Warning: need to convergence
|
||||
|
||||
###########################################
|
||||
# Data #
|
||||
###########################################
|
||||
train_manifest: data/manifest.train
|
||||
dev_manifest: data/manifest.dev
|
||||
test_manifest: data/manifest.test
|
||||
|
||||
###########################################
|
||||
# Dataloader #
|
||||
###########################################
|
||||
vocab_filepath: data/lang_char/vocab.txt
|
||||
spm_model_prefix: ''
|
||||
unit_type: 'char'
|
||||
preprocess_config: conf/preprocess.yaml
|
||||
feat_dim: 80
|
||||
stride_ms: 10.0
|
||||
window_ms: 25.0
|
||||
sortagrad: 0 # Feed samples from shortest to longest ; -1: enabled for all epochs, 0: disabled, other: enabled for 'other' epochs
|
||||
batch_size: 32
|
||||
maxlen_in: 512 # if input length > maxlen-in, batchsize is automatically reduced
|
||||
maxlen_out: 150 # if output length > maxlen-out, batchsize is automatically reduced
|
||||
minibatches: 0 # for debug
|
||||
batch_count: auto
|
||||
batch_bins: 0
|
||||
batch_frames_in: 0
|
||||
batch_frames_out: 0
|
||||
batch_frames_inout: 0
|
||||
num_workers: 2
|
||||
subsampling_factor: 1
|
||||
num_encs: 1
|
||||
|
||||
###########################################
|
||||
# Training #
|
||||
###########################################
|
||||
n_epoch: 150
|
||||
accum_grad: 8
|
||||
global_grad_clip: 5.0
|
||||
dist_sampler: False
|
||||
optim: adam
|
||||
optim_conf:
|
||||
lr: 0.002
|
||||
weight_decay: 1.0e-6
|
||||
scheduler: warmuplr
|
||||
scheduler_conf:
|
||||
warmup_steps: 25000
|
||||
lr_decay: 1.0
|
||||
log_interval: 100
|
||||
checkpoint:
|
||||
kbest_n: 50
|
||||
latest_n: 5
|
@ -0,0 +1,62 @@
|
||||
from typing import Optional
|
||||
from typing import Union
|
||||
|
||||
import paddle
|
||||
import paddle.nn.functional as F
|
||||
from paddle.nn.layer.conv import _ConvNd
|
||||
|
||||
__all__ = ['Conv2DValid']
|
||||
|
||||
|
||||
class Conv2DValid(_ConvNd):
|
||||
"""
|
||||
Conv2d operator for VALID mode padding.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
in_channels: int,
|
||||
out_channels: int,
|
||||
kernel_size: int,
|
||||
stride: int=1,
|
||||
padding: Union[str, int]=0,
|
||||
dilation: int=1,
|
||||
groups: int=1,
|
||||
padding_mode: str='zeros',
|
||||
weight_attr=None,
|
||||
bias_attr=None,
|
||||
data_format="NCHW",
|
||||
valid_trigx: bool=False,
|
||||
valid_trigy: bool=False) -> None:
|
||||
super(Conv2DValid, self).__init__(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
False,
|
||||
2,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
padding_mode=padding_mode,
|
||||
dilation=dilation,
|
||||
groups=groups,
|
||||
weight_attr=weight_attr,
|
||||
bias_attr=bias_attr,
|
||||
data_format=data_format)
|
||||
self.valid_trigx = valid_trigx
|
||||
self.valid_trigy = valid_trigy
|
||||
|
||||
def _conv_forward(self,
|
||||
input: paddle.Tensor,
|
||||
weight: paddle.Tensor,
|
||||
bias: Optional[paddle.Tensor]):
|
||||
validx, validy = 0, 0
|
||||
if self.valid_trigx:
|
||||
validx = (input.shape[-2] *
|
||||
(self._stride[-2] - 1) - 1 + self._kernel_size[-2]) // 2
|
||||
if self.valid_trigy:
|
||||
validy = (input.shape[-1] *
|
||||
(self._stride[-1] - 1) - 1 + self._kernel_size[-1]) // 2
|
||||
return F.conv2d(input, weight, bias, self._stride, (validx, validy),
|
||||
self._dilation, self._groups)
|
||||
|
||||
def forward(self, input: paddle.Tensor) -> paddle.Tensor:
|
||||
return self._conv_forward(input, self.weight, self.bias)
|
@ -0,0 +1,263 @@
|
||||
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
|
||||
# Copyright 2019 Mobvoi Inc. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# Modified from wenet(https://github.com/wenet-e2e/wenet)
|
||||
"""Subsampling layer definition."""
|
||||
from typing import Tuple
|
||||
|
||||
import paddle
|
||||
import paddle.nn.functional as F
|
||||
from paddle import nn
|
||||
|
||||
from paddlespeech.s2t import masked_fill
|
||||
from paddlespeech.s2t.modules.align import Conv1D
|
||||
from paddlespeech.s2t.modules.conv2d import Conv2DValid
|
||||
from paddlespeech.s2t.utils.log import Log
|
||||
|
||||
logger = Log(__name__).getlog()
|
||||
|
||||
__all__ = [
|
||||
"TimeReductionLayerStream", "TimeReductionLayer1D", "TimeReductionLayer2D"
|
||||
]
|
||||
|
||||
|
||||
class TimeReductionLayer1D(nn.Layer):
|
||||
"""
|
||||
Modified NeMo,
|
||||
Squeezeformer Time Reduction procedure.
|
||||
Downsamples the audio by `stride` in the time dimension.
|
||||
Args:
|
||||
channel (int): input dimension of
|
||||
MultiheadAttentionMechanism and PositionwiseFeedForward
|
||||
out_dim (int): Output dimension of the module.
|
||||
kernel_size (int): Conv kernel size for
|
||||
depthwise convolution in convolution module
|
||||
stride (int): Downsampling factor in time dimension.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
channel: int,
|
||||
out_dim: int,
|
||||
kernel_size: int=5,
|
||||
stride: int=2):
|
||||
super(TimeReductionLayer1D, self).__init__()
|
||||
|
||||
self.channel = channel
|
||||
self.out_dim = out_dim
|
||||
self.kernel_size = kernel_size
|
||||
self.stride = stride
|
||||
self.padding = max(0, self.kernel_size - self.stride)
|
||||
|
||||
self.dw_conv = Conv1D(
|
||||
in_channels=channel,
|
||||
out_channels=channel,
|
||||
kernel_size=kernel_size,
|
||||
stride=stride,
|
||||
padding=self.padding,
|
||||
groups=channel, )
|
||||
|
||||
self.pw_conv = Conv1D(
|
||||
in_channels=channel,
|
||||
out_channels=out_dim,
|
||||
kernel_size=1,
|
||||
stride=1,
|
||||
padding=0,
|
||||
groups=1, )
|
||||
|
||||
self.init_weights()
|
||||
|
||||
def init_weights(self):
|
||||
dw_max = self.kernel_size**-0.5
|
||||
pw_max = self.channel**-0.5
|
||||
self.dw_conv._param_attr = paddle.nn.initializer.Uniform(
|
||||
low=-dw_max, high=dw_max)
|
||||
self.dw_conv._bias_attr = paddle.nn.initializer.Uniform(
|
||||
low=-dw_max, high=dw_max)
|
||||
self.pw_conv._param_attr = paddle.nn.initializer.Uniform(
|
||||
low=-pw_max, high=pw_max)
|
||||
self.pw_conv._bias_attr = paddle.nn.initializer.Uniform(
|
||||
low=-pw_max, high=pw_max)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
xs,
|
||||
xs_lens: paddle.Tensor,
|
||||
mask: paddle.Tensor=paddle.ones((0, 0, 0), dtype=paddle.bool),
|
||||
mask_pad: paddle.Tensor=paddle.ones((0, 0, 0),
|
||||
dtype=paddle.bool), ):
|
||||
xs = xs.transpose([0, 2, 1]) # [B, C, T]
|
||||
xs = masked_fill(xs, mask_pad.equal(0), 0.0)
|
||||
|
||||
xs = self.dw_conv(xs)
|
||||
xs = self.pw_conv(xs)
|
||||
|
||||
xs = xs.transpose([0, 2, 1]) # [B, T, C]
|
||||
|
||||
B, T, D = xs.shape
|
||||
mask = mask[:, ::self.stride, ::self.stride]
|
||||
mask_pad = mask_pad[:, :, ::self.stride]
|
||||
L = mask_pad.shape[-1]
|
||||
# For JIT exporting, we remove F.pad operator.
|
||||
if L - T < 0:
|
||||
xs = xs[:, :L - T, :]
|
||||
else:
|
||||
dummy_pad = paddle.zeros([B, L - T, D], dtype=paddle.float32)
|
||||
xs = paddle.concat([xs, dummy_pad], axis=1)
|
||||
|
||||
xs_lens = (xs_lens + 1) // 2
|
||||
return xs, xs_lens, mask, mask_pad
|
||||
|
||||
|
||||
class TimeReductionLayer2D(nn.Layer):
|
||||
def __init__(self, kernel_size: int=5, stride: int=2, encoder_dim: int=256):
|
||||
super(TimeReductionLayer2D, self).__init__()
|
||||
self.encoder_dim = encoder_dim
|
||||
self.kernel_size = kernel_size
|
||||
self.dw_conv = Conv2DValid(
|
||||
in_channels=encoder_dim,
|
||||
out_channels=encoder_dim,
|
||||
kernel_size=(kernel_size, 1),
|
||||
stride=stride,
|
||||
valid_trigy=True)
|
||||
self.pw_conv = Conv2DValid(
|
||||
in_channels=encoder_dim,
|
||||
out_channels=encoder_dim,
|
||||
kernel_size=1,
|
||||
stride=1,
|
||||
valid_trigx=False,
|
||||
valid_trigy=False)
|
||||
|
||||
self.kernel_size = kernel_size
|
||||
self.stride = stride
|
||||
self.init_weights()
|
||||
|
||||
def init_weights(self):
|
||||
dw_max = self.kernel_size**-0.5
|
||||
pw_max = self.encoder_dim**-0.5
|
||||
self.dw_conv._param_attr = paddle.nn.initializer.Uniform(
|
||||
low=-dw_max, high=dw_max)
|
||||
self.dw_conv._bias_attr = paddle.nn.initializer.Uniform(
|
||||
low=-dw_max, high=dw_max)
|
||||
self.pw_conv._param_attr = paddle.nn.initializer.Uniform(
|
||||
low=-pw_max, high=pw_max)
|
||||
self.pw_conv._bias_attr = paddle.nn.initializer.Uniform(
|
||||
low=-pw_max, high=pw_max)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
xs: paddle.Tensor,
|
||||
xs_lens: paddle.Tensor,
|
||||
mask: paddle.Tensor=paddle.ones((0, 0, 0), dtype=paddle.bool),
|
||||
mask_pad: paddle.Tensor=paddle.ones((0, 0, 0), dtype=paddle.bool),
|
||||
) -> Tuple[paddle.Tensor, paddle.Tensor, paddle.Tensor, paddle.Tensor]:
|
||||
xs = masked_fill(xs, mask_pad.transpose([0, 2, 1]).equal(0), 0.0)
|
||||
xs = xs.unsqueeze(1)
|
||||
padding1 = self.kernel_size - self.stride
|
||||
xs = F.pad(
|
||||
xs, (0, 0, 0, 0, 0, padding1, 0, 0), mode='constant', value=0.)
|
||||
xs = self.dw_conv(xs.transpose([0, 3, 2, 1]))
|
||||
xs = self.pw_conv(xs).transpose([0, 3, 2, 1]).squeeze(1)
|
||||
tmp_length = xs.shape[1]
|
||||
xs_lens = (xs_lens + 1) // 2
|
||||
padding2 = max(0, (xs_lens.max() - tmp_length).item())
|
||||
batch_size, hidden = xs.shape[0], xs.shape[-1]
|
||||
dummy_pad = paddle.zeros(
|
||||
[batch_size, padding2, hidden], dtype=paddle.float32)
|
||||
xs = paddle.concat([xs, dummy_pad], axis=1)
|
||||
mask = mask[:, ::2, ::2]
|
||||
mask_pad = mask_pad[:, :, ::2]
|
||||
return xs, xs_lens, mask, mask_pad
|
||||
|
||||
|
||||
class TimeReductionLayerStream(nn.Layer):
|
||||
"""
|
||||
Squeezeformer Time Reduction procedure.
|
||||
Downsamples the audio by `stride` in the time dimension.
|
||||
Args:
|
||||
channel (int): input dimension of
|
||||
MultiheadAttentionMechanism and PositionwiseFeedForward
|
||||
out_dim (int): Output dimension of the module.
|
||||
kernel_size (int): Conv kernel size for
|
||||
depthwise convolution in convolution module
|
||||
stride (int): Downsampling factor in time dimension.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
channel: int,
|
||||
out_dim: int,
|
||||
kernel_size: int=1,
|
||||
stride: int=2):
|
||||
super(TimeReductionLayerStream, self).__init__()
|
||||
|
||||
self.channel = channel
|
||||
self.out_dim = out_dim
|
||||
self.kernel_size = kernel_size
|
||||
self.stride = stride
|
||||
|
||||
self.dw_conv = Conv1D(
|
||||
in_channels=channel,
|
||||
out_channels=channel,
|
||||
kernel_size=kernel_size,
|
||||
stride=stride,
|
||||
padding=0,
|
||||
groups=channel)
|
||||
|
||||
self.pw_conv = Conv1D(
|
||||
in_channels=channel,
|
||||
out_channels=out_dim,
|
||||
kernel_size=1,
|
||||
stride=1,
|
||||
padding=0,
|
||||
groups=1)
|
||||
self.init_weights()
|
||||
|
||||
def init_weights(self):
|
||||
dw_max = self.kernel_size**-0.5
|
||||
pw_max = self.channel**-0.5
|
||||
self.dw_conv._param_attr = paddle.nn.initializer.Uniform(
|
||||
low=-dw_max, high=dw_max)
|
||||
self.dw_conv._bias_attr = paddle.nn.initializer.Uniform(
|
||||
low=-dw_max, high=dw_max)
|
||||
self.pw_conv._param_attr = paddle.nn.initializer.Uniform(
|
||||
low=-pw_max, high=pw_max)
|
||||
self.pw_conv._bias_attr = paddle.nn.initializer.Uniform(
|
||||
low=-pw_max, high=pw_max)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
xs,
|
||||
xs_lens: paddle.Tensor,
|
||||
mask: paddle.Tensor=paddle.ones([0, 0, 0], dtype=paddle.bool),
|
||||
mask_pad: paddle.Tensor=paddle.ones([0, 0, 0], dtype=paddle.bool)):
|
||||
xs = xs.transpose([0, 2, 1]) # [B, C, T]
|
||||
xs = masked_fill(xs, mask_pad.equal(0), 0.0)
|
||||
|
||||
xs = self.dw_conv(xs)
|
||||
xs = self.pw_conv(xs)
|
||||
|
||||
xs = xs.transpose([0, 2, 1]) # [B, T, C]
|
||||
|
||||
B, T, D = xs.shape
|
||||
mask = mask[:, ::self.stride, ::self.stride]
|
||||
mask_pad = mask_pad[:, :, ::self.stride]
|
||||
L = mask_pad.shape[-1]
|
||||
# For JIT exporting, we remove F.pad operator.
|
||||
if L - T < 0:
|
||||
xs = xs[:, :L - T, :]
|
||||
else:
|
||||
dummy_pad = paddle.zeros([B, L - T, D], dtype=paddle.float32)
|
||||
xs = paddle.concat([xs, dummy_pad], axis=1)
|
||||
|
||||
xs_lens = (xs_lens + 1) // 2
|
||||
return xs, xs_lens, mask, mask_pad
|
Loading…
Reference in new issue