deepspeech2.py 18.8 KB
Newer Older
H
huangyuxin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2021 PaddlePaddle Authors. 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.
H
huangyuxin 已提交
14
"""Deepspeech2 ASR Online Model"""
H
huangyuxin 已提交
15 16 17
from typing import Optional

import paddle
H
huangyuxin 已提交
18
import paddle.nn.functional as F
H
huangyuxin 已提交
19
from paddle import nn
H
huangyuxin 已提交
20 21
from yacs.config import CfgNode

H
huangyuxin 已提交
22
from deepspeech.models.ds2_online.conv import Conv2dSubsampling4Online
H
huangyuxin 已提交
23
from deepspeech.modules.ctc import CTCDecoder
H
huangyuxin 已提交
24 25 26 27 28
from deepspeech.utils import layer_tools
from deepspeech.utils.checkpoint import Checkpoint
from deepspeech.utils.log import Log
logger = Log(__name__).getlog()

H
huangyuxin 已提交
29
__all__ = ['DeepSpeech2ModelOnline', 'DeepSpeech2InferModeOnline']
H
huangyuxin 已提交
30 31 32 33 34 35 36


class CRNNEncoder(nn.Layer):
    def __init__(self,
                 feat_size,
                 dict_size,
                 num_conv_layers=2,
H
huangyuxin 已提交
37
                 num_rnn_layers=4,
H
huangyuxin 已提交
38
                 rnn_size=1024,
39
                 rnn_direction='forward',
H
huangyuxin 已提交
40 41
                 num_fc_layers=2,
                 fc_layers_size_list=[512, 256],
42
                 use_gru=False):
H
huangyuxin 已提交
43 44 45 46 47
        super().__init__()
        self.rnn_size = rnn_size
        self.feat_size = feat_size  # 161 for linear
        self.dict_size = dict_size
        self.num_rnn_layers = num_rnn_layers
H
huangyuxin 已提交
48
        self.num_fc_layers = num_fc_layers
49
        self.rnn_direction = rnn_direction
H
huangyuxin 已提交
50
        self.fc_layers_size_list = fc_layers_size_list
H
huangyuxin 已提交
51
        self.conv = Conv2dSubsampling4Online(feat_size, 32, dropout_rate=0.0)
H
huangyuxin 已提交
52

H
huangyuxin 已提交
53
        i_size = self.conv.output_dim
H
huangyuxin 已提交
54

H
huangyuxin 已提交
55 56 57
        self.rnn = nn.LayerList()
        self.layernorm_list = nn.LayerList()
        self.fc_layers_list = nn.LayerList()
H
huangyuxin 已提交
58
        layernorm_size = rnn_size
59 60 61 62 63 64
        for i in range(0, num_rnn_layers):
            if i == 0:
                rnn_input_size = i_size
            else:
                rnn_input_size = rnn_size
            if (use_gru == True):
H
huangyuxin 已提交
65
                self.rnn.append(
H
huangyuxin 已提交
66
                    nn.GRU(
67
                        input_size=rnn_input_size,
H
huangyuxin 已提交
68 69 70
                        hidden_size=rnn_size,
                        num_layers=1,
                        direction=rnn_direction))
71
            else:
H
huangyuxin 已提交
72
                self.rnn.append(
H
huangyuxin 已提交
73
                    nn.LSTM(
74
                        input_size=rnn_input_size,
H
huangyuxin 已提交
75 76 77
                        hidden_size=rnn_size,
                        num_layers=1,
                        direction=rnn_direction))
78 79 80
            self.layernorm_list.append(nn.LayerNorm(layernorm_size))

        fc_input_size = rnn_size
H
huangyuxin 已提交
81
        for i in range(self.num_fc_layers):
H
huangyuxin 已提交
82 83
            self.fc_layers_list.append(
                nn.Linear(fc_input_size, fc_layers_size_list[i]))
H
huangyuxin 已提交
84 85
            fc_input_size = fc_layers_size_list[i]

H
huangyuxin 已提交
86 87
    @property
    def output_size(self):
H
huangyuxin 已提交
88
        return self.fc_layers_size_list[-1]
H
huangyuxin 已提交
89

90
    def forward(self, x, x_lens):
H
huangyuxin 已提交
91 92 93
        """Compute Encoder outputs

        Args:
94 95
            x (Tensor): [B, T_input, D]
            x_lens (Tensor): [B]
H
huangyuxin 已提交
96
        Returns:
97
            x (Tensor): encoder outputs, [B, T_output, D]
H
huangyuxin 已提交
98
            x_lens (Tensor): encoder length, [B]
99
            final_state_list: list of final_states for RNN layers, [num_directions, batch_size, hidden_size] * num_rnn_layers
H
huangyuxin 已提交
100
        """
H
huangyuxin 已提交
101
        # [B, T, D]
H
huangyuxin 已提交
102 103 104 105
        # convolution group
        x, x_lens = self.conv(x, x_lens)
        # convert data from convolution feature map to sequence of vectors
        #B, C, D, T = paddle.shape(x)  # not work under jit
H
huangyuxin 已提交
106
        #x = x.transpose([0, 3, 1, 2])  #[B, T, C, D]
H
huangyuxin 已提交
107
        #x = x.reshape([B, T, C * D])  #[B, T, C*D]  # not work under jit
H
huangyuxin 已提交
108
        #x = x.reshape([0, 0, -1])  #[B, T, C*D]
H
huangyuxin 已提交
109 110

        # remove padding part
111
        init_state = None
112
        final_state_list = []
113
        for i in range(0, self.num_rnn_layers):
114
            x, final_state = self.rnn[i](x, init_state, x_lens)  #[B, T, D]
115
            final_state_list.append(final_state)
H
huangyuxin 已提交
116
            x = self.layernorm_list[i](x)
H
huangyuxin 已提交
117 118 119 120

        for i in range(self.num_fc_layers):
            x = self.fc_layers_list[i](x)
            x = F.relu(x)
121
        return x, x_lens, final_state_list
122

123
    def forward_chunk(self, x, x_lens, init_state_list):
124 125 126 127 128 129 130 131 132
        """Compute Encoder outputs

        Args:
            x (Tensor): [B, feature_chunk_size, D]
            x_lens (Tensor): [B]
            init_state_list (list of Tensors): [ num_directions, batch_size, hidden_size] * num_rnn_layers
        Returns:
            x (Tensor): encoder outputs, [B, chunk_size, D]
            x_lens (Tensor): encoder length, [B]
133
            chunk_final_state_list: list of final_states for RNN layers, [num_directions, batch_size, hidden_size] * num_rnn_layers
134
        """
135 136
        x, x_lens = self.conv(x, x_lens)
        chunk_final_state_list = []
137
        for i in range(0, self.num_rnn_layers):
138 139
            x, final_state = self.rnn[i](x, init_state_list[i],
                                         x_lens)  #[B, T, D]
140
            chunk_final_state_list.append(final_state)
141 142 143 144 145
            x = self.layernorm_list[i](x)

        for i in range(self.num_fc_layers):
            x = self.fc_layers_list[i](x)
            x = F.relu(x)
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        return x, x_lens, chunk_final_state_list

    def forward_chunk_by_chunk(self, x, x_lens, decoder_chunk_size=8):
        subsampling_rate = self.conv.subsampling_rate
        receptive_field_length = self.conv.receptive_field_length
        chunk_size = (decoder_chunk_size - 1
                      ) * subsampling_rate + receptive_field_length
        chunk_stride = subsampling_rate * decoder_chunk_size
        max_len = x.shape[1]
        assert (chunk_size <= max_len)

        eouts_chunk_list = []
        eouts_chunk_lens_list = []

        padding_len = chunk_stride - (max_len - chunk_size) % chunk_stride
        padding = paddle.zeros((x.shape[0], padding_len, x.shape[2]))
162
        padded_x = paddle.concat([x, padding], axis=1)
163 164
        num_chunk = (max_len + padding_len - chunk_size) / chunk_stride + 1
        num_chunk = int(num_chunk)
165
        chunk_state_list = [None] * self.num_rnn_layers
166 167 168
        for i in range(0, num_chunk):
            start = i * chunk_stride
            end = start + chunk_size
169 170 171 172 173 174 175 176
            #   end = min(start + chunk_size, max_len)
            #   if (end - start < receptive_field_length):
            #       break
            x_chunk = padded_x[:, start:end, :]

            x_len_left = paddle.where(x_lens - i * chunk_stride < 0,
                                      paddle.zeros_like(x_lens),
                                      x_lens - i * chunk_stride)
177 178 179 180
            x_chunk_len_tmp = paddle.ones_like(x_lens) * chunk_size
            x_chunk_lens = paddle.where(x_len_left < x_chunk_len_tmp,
                                        x_len_left, x_chunk_len_tmp)

181 182
            eouts_chunk, eouts_chunk_lens, chunk_state_list = self.forward_chunk(
                x_chunk, x_chunk_lens, chunk_state_list)
183 184 185 186

            eouts_chunk_list.append(eouts_chunk)
            eouts_chunk_lens_list.append(eouts_chunk_lens)

187
        return eouts_chunk_list, eouts_chunk_lens_list, chunk_state_list
H
huangyuxin 已提交
188 189


H
huangyuxin 已提交
190 191
class DeepSpeech2ModelOnline(nn.Layer):
    """The DeepSpeech2 network structure for online.
H
huangyuxin 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    :param audio_data: Audio spectrogram data layer.
    :type audio_data: Variable
    :param text_data: Transcription text data layer.
    :type text_data: Variable
    :param audio_len: Valid sequence length data layer.
    :type audio_len: Variable
    :param masks: Masks data layer to reset padding.
    :type masks: Variable
    :param dict_size: Dictionary size for tokenized transcription.
    :type dict_size: int
    :param num_conv_layers: Number of stacking convolution layers.
    :type num_conv_layers: int
    :param num_rnn_layers: Number of stacking RNN layers.
    :type num_rnn_layers: int
    :param rnn_size: RNN layer size (dimension of RNN cells).
    :type rnn_size: int
    :param use_gru: Use gru if set True. Use simple rnn if set False.
    :type use_gru: bool
    :type share_weights: bool
    :return: A tuple of an output unnormalized log probability layer (
             before softmax) and a ctc cost layer.
H
huangyuxin 已提交
214
    :rtype: tuple of LayerOutput
H
huangyuxin 已提交
215 216 217 218 219 220 221
    """

    @classmethod
    def params(cls, config: Optional[CfgNode]=None) -> CfgNode:
        default = CfgNode(
            dict(
                num_conv_layers=2,  #Number of stacking convolution layers.
H
huangyuxin 已提交
222
                num_rnn_layers=4,  #Number of stacking RNN layers.
H
huangyuxin 已提交
223
                rnn_layer_size=1024,  #RNN layer size (number of RNN cells).
H
huangyuxin 已提交
224
                num_fc_layers=2,
H
huangyuxin 已提交
225
                fc_layers_size_list=[512, 256],
H
huangyuxin 已提交
226 227 228 229 230 231 232 233 234 235 236 237
                use_gru=True,  #Use gru if set True. Use simple rnn if set False.
            ))
        if config is not None:
            config.merge_from_other_cfg(default)
        return default

    def __init__(self,
                 feat_size,
                 dict_size,
                 num_conv_layers=2,
                 num_rnn_layers=3,
                 rnn_size=1024,
238
                 rnn_direction='forward',
H
huangyuxin 已提交
239 240
                 num_fc_layers=2,
                 fc_layers_size_list=[512, 256],
241
                 use_gru=False):
H
huangyuxin 已提交
242 243 244 245 246 247
        super().__init__()
        self.encoder = CRNNEncoder(
            feat_size=feat_size,
            dict_size=dict_size,
            num_conv_layers=num_conv_layers,
            num_rnn_layers=num_rnn_layers,
248
            rnn_direction=rnn_direction,
H
huangyuxin 已提交
249 250
            num_fc_layers=num_fc_layers,
            fc_layers_size_list=fc_layers_size_list,
H
huangyuxin 已提交
251
            rnn_size=rnn_size,
252
            use_gru=use_gru)
H
huangyuxin 已提交
253
        assert (self.encoder.output_size == fc_layers_size_list[-1])
H
huangyuxin 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274

        self.decoder = CTCDecoder(
            odim=dict_size,  # <blank> is in  vocab
            enc_n_units=self.encoder.output_size,
            blank_id=0,  # first token is <blank>
            dropout_rate=0.0,
            reduction=True,  # sum
            batch_average=True)  # sum / batch_size

    def forward(self, audio, audio_len, text, text_len):
        """Compute Model loss

        Args:
            audio (Tenosr): [B, T, D]
            audio_len (Tensor): [B]
            text (Tensor): [B, U]
            text_len (Tensor): [B]

        Returns:
            loss (Tenosr): [1]
        """
275
        eouts, eouts_len, final_state_list = self.encoder(audio, audio_len)
H
huangyuxin 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        loss = self.decoder(eouts, eouts_len, text, text_len)
        return loss

    @paddle.no_grad()
    def decode(self, audio, audio_len, vocab_list, decoding_method,
               lang_model_path, beam_alpha, beam_beta, beam_size, cutoff_prob,
               cutoff_top_n, num_processes):
        # init once
        # decoders only accept string encoded in utf-8
        self.decoder.init_decode(
            beam_alpha=beam_alpha,
            beam_beta=beam_beta,
            lang_model_path=lang_model_path,
            vocab_list=vocab_list,
            decoding_method=decoding_method)

292 293 294 295 296 297
        eouts, eouts_len, final_state_list = self.encoder(audio, audio_len)
        probs = self.decoder.softmax(eouts)
        return self.decoder.decode_probs(
            probs.numpy(), eouts_len, vocab_list, decoding_method,
            lang_model_path, beam_alpha, beam_beta, beam_size, cutoff_prob,
            cutoff_top_n, num_processes)
H
huangyuxin 已提交
298
    """
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    @paddle.no_grad()
    def decode_by_chunk(self, eouts_prefix, eouts_len_prefix, chunk_state_list,
                        audio_chunk, audio_len_chunk, vocab_list,
                        decoding_method, lang_model_path, beam_alpha, beam_beta,
                        beam_size, cutoff_prob, cutoff_top_n, num_processes):
        # init once
        # decoders only accept string encoded in utf-8
        self.decoder.init_decode(
            beam_alpha=beam_alpha,
            beam_beta=beam_beta,
            lang_model_path=lang_model_path,
            vocab_list=vocab_list,
            decoding_method=decoding_method)

        eouts_chunk, eouts_chunk_len, final_state_list = self.encoder.forward_chunk(
            audio_chunk, audio_len_chunk, chunk_state_list)
        if eouts_prefix is not None:
            eouts = paddle.concat([eouts_prefix, eouts_chunk], axis=1)
            eouts_len = paddle.add_n([eouts_len_prefix, eouts_chunk_len])
        else:
            eouts = eouts_chunk
            eouts_len = eouts_chunk_len

        probs = self.decoder.softmax(eouts)
        return self.decoder.decode_probs(
            probs.numpy(), eouts_len, vocab_list, decoding_method,
            lang_model_path, beam_alpha, beam_beta, beam_size, cutoff_prob,
            cutoff_top_n, num_processes), eouts, eouts_len, final_state_list

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    @paddle.no_grad()
    def decode_chunk_by_chunk(self, audio, audio_len, vocab_list,
                              decoding_method, lang_model_path, beam_alpha,
                              beam_beta, beam_size, cutoff_prob, cutoff_top_n,
                              num_processes):
        # init once
        # decoders only accept string encoded in utf-8
        self.decoder.init_decode(
            beam_alpha=beam_alpha,
            beam_beta=beam_beta,
            lang_model_path=lang_model_path,
            vocab_list=vocab_list,
            decoding_method=decoding_method)

        eouts_chunk_list, eouts_chunk_len_list, final_state_list = self.encoder.forward_chunk_by_chunk(
            audio, audio_len)
        eouts = paddle.concat(eouts_chunk_list, axis=1)
        eouts_len = paddle.add_n(eouts_chunk_len_list)

H
huangyuxin 已提交
347 348 349 350 351
        probs = self.decoder.softmax(eouts)
        return self.decoder.decode_probs(
            probs.numpy(), eouts_len, vocab_list, decoding_method,
            lang_model_path, beam_alpha, beam_beta, beam_size, cutoff_prob,
            cutoff_top_n, num_processes)
H
huangyuxin 已提交
352
    """
353 354 355 356 357 358
    """
    decocd_prob,
    decode_prob_chunk_by_chunk
    decode_prob_by_chunk
    is only used for test
    """
H
huangyuxin 已提交
359
    """
360 361 362 363 364 365 366
    @paddle.no_grad()
    def decode_prob(self, audio, audio_len):
        eouts, eouts_len, final_state_list = self.encoder(audio, audio_len)
        probs = self.decoder.softmax(eouts)
        return probs, eouts, eouts_len, final_state_list

    @paddle.no_grad()
367
    def decode_prob_chunk_by_chunk(self, audio, audio_len, decoder_chunk_size):
368
        eouts_chunk_list, eouts_chunk_len_list, final_state_list = self.encoder.forward_chunk_by_chunk(
369
            audio, audio_len, decoder_chunk_size)
370 371 372 373 374
        eouts = paddle.concat(eouts_chunk_list, axis=1)
        eouts_len = paddle.add_n(eouts_chunk_len_list)
        probs = self.decoder.softmax(eouts)
        return probs, eouts, eouts_len, final_state_list

375 376 377 378 379 380 381 382 383 384 385 386 387
    @paddle.no_grad()
    def decode_prob_by_chunk(self, audio, audio_len, eouts_prefix,
                             eouts_lens_prefix, chunk_state_list):
        eouts_chunk, eouts_chunk_lens, final_state_list = self.encoder.forward_chunk(
            audio, audio_len, chunk_state_list)
        if eouts_prefix is not None:
            eouts = paddle.concat([eouts_prefix, eouts_chunk], axis=1)
            eouts_lens = paddle.add_n([eouts_lens_prefix, eouts_chunk_lens])
        else:
            eouts = eouts_chunk
            eouts_lens = eouts_chunk_lens
        probs = self.decoder.softmax(eouts)
        return probs, eouts, eouts_lens, final_state_list
H
huangyuxin 已提交
388
    """
389

H
huangyuxin 已提交
390 391 392 393 394 395 396 397 398
    @classmethod
    def from_pretrained(cls, dataloader, config, checkpoint_path):
        """Build a DeepSpeech2Model model from a pretrained model.
        Parameters
        ----------
        dataloader: paddle.io.DataLoader

        config: yacs.config.CfgNode
            model configs
H
huangyuxin 已提交
399

H
huangyuxin 已提交
400 401
        checkpoint_path: Path or str
            the path of pretrained model checkpoint, without extension name
H
huangyuxin 已提交
402

H
huangyuxin 已提交
403 404 405 406 407 408 409 410 411 412
        Returns
        -------
        DeepSpeech2Model
            The model built from pretrained result.
        """
        model = cls(feat_size=dataloader.collate_fn.feature_size,
                    dict_size=dataloader.collate_fn.vocab_size,
                    num_conv_layers=config.model.num_conv_layers,
                    num_rnn_layers=config.model.num_rnn_layers,
                    rnn_size=config.model.rnn_layer_size,
413
                    rnn_direction=config.model.rnn_direction,
H
huangyuxin 已提交
414 415
                    num_fc_layers=config.model.num_fc_layers,
                    fc_layers_size_list=config.model.fc_layers_size_list,
416
                    use_gru=config.model.use_gru)
H
huangyuxin 已提交
417 418 419 420 421 422 423
        infos = Checkpoint().load_parameters(
            model, checkpoint_path=checkpoint_path)
        logger.info(f"checkpoint info: {infos}")
        layer_tools.summary(model)
        return model


H
huangyuxin 已提交
424
class DeepSpeech2InferModelOnline(DeepSpeech2ModelOnline):
H
huangyuxin 已提交
425 426 427 428 429 430
    def __init__(self,
                 feat_size,
                 dict_size,
                 num_conv_layers=2,
                 num_rnn_layers=3,
                 rnn_size=1024,
431
                 rnn_direction='forward',
H
huangyuxin 已提交
432 433
                 num_fc_layers=2,
                 fc_layers_size_list=[512, 256],
434
                 use_gru=False):
H
huangyuxin 已提交
435 436 437 438 439 440
        super().__init__(
            feat_size=feat_size,
            dict_size=dict_size,
            num_conv_layers=num_conv_layers,
            num_rnn_layers=num_rnn_layers,
            rnn_size=rnn_size,
441
            rnn_direction=rnn_direction,
H
huangyuxin 已提交
442 443
            num_fc_layers=num_fc_layers,
            fc_layers_size_list=fc_layers_size_list,
444
            use_gru=use_gru)
H
huangyuxin 已提交
445 446 447 448 449 450 451 452 453 454 455

    def forward(self, audio, audio_len):
        """export model function

        Args:
            audio (Tensor): [B, T, D]
            audio_len (Tensor): [B]

        Returns:
            probs: probs after softmax
        """
456 457 458 459
        eouts, eouts_len, final_state_list = self.encoder(audio, audio_len)
        probs = self.decoder.softmax(eouts)
        return probs

460 461 462
    def forward_chunk(self, audio_chunk, audio_chunk_lens):
        eouts_chunkt, eouts_chunk_lens, final_state_list = self.encoder.forward_chunk(
            audio_chunk, audio_chunk_lens)
H
huangyuxin 已提交
463 464
        probs = self.decoder.softmax(eouts)
        return probs
465 466

    def forward(self, eouts_chunk_prefix, eouts_chunk_lens_prefix, audio_chunk,
467
                audio_chunk_lens, chunk_state_list):
468 469 470 471 472 473 474 475 476
        """export model function

        Args:
            audio_chunk (Tensor): [B, T, D]
            audio_chunk_len (Tensor): [B]

        Returns:
            probs: probs after softmax
        """
477 478
        eouts_chunk, eouts_chunk_lens, final_state_list = self.encoder.forward_chunk(
            audio_chunk, audio_chunk_lens, chunk_state_list)
479 480 481 482 483
        eouts_chunk_new_prefix = paddle.concat(
            [eouts_chunk_prefix, eouts_chunk], axis=1)
        eouts_chunk_lens_new_prefix = paddle.add(eouts_chunk_lens_prefix,
                                                 eouts_chunk_lens)
        probs_chunk = self.decoder.softmax(eouts_chunk_new_prefix)
484
        return probs_chunk, eouts_chunk_new_prefix, eouts_chunk_lens_new_prefix, final_state_list