model_paddle.py 37.0 KB
Newer Older
P
pfZhu 已提交
1
import argparse
小湉湉's avatar
小湉湉 已提交
2 3 4 5
import logging
import math
import os
import sys
P
pfZhu 已提交
6
from pathlib import Path
小湉湉's avatar
小湉湉 已提交
7
from typing import Dict
P
pfZhu 已提交
8
from typing import List
小湉湉's avatar
小湉湉 已提交
9
from typing import Optional
P
pfZhu 已提交
10 11 12 13 14 15
from typing import Tuple
from typing import Union

import numpy as np
import paddle
import yaml
小湉湉's avatar
小湉湉 已提交
16
from paddle import nn
P
pfZhu 已提交
17 18 19 20 21 22
pypath = '..'
for dir_name in os.listdir(pypath):
    dir_path = os.path.join(pypath, dir_name)
    if os.path.isdir(dir_path):
        sys.path.append(dir_path)

小湉湉's avatar
小湉湉 已提交
23 24 25 26 27
from paddlespeech.s2t.utils.error_rate import ErrorCalculator
from paddlespeech.t2s.modules.activation import get_activation
from paddlespeech.t2s.modules.conformer.convolution import ConvolutionModule
from paddlespeech.t2s.modules.conformer.encoder_layer import EncoderLayer
from paddlespeech.t2s.modules.masked_fill import masked_fill
P
pfZhu 已提交
28 29
from paddlespeech.t2s.modules.nets_utils import initialize
from paddlespeech.t2s.modules.tacotron2.decoder import Postnet
小湉湉's avatar
小湉湉 已提交
30 31 32
from paddlespeech.t2s.modules.transformer.embedding import PositionalEncoding
from paddlespeech.t2s.modules.transformer.embedding import ScaledPositionalEncoding
from paddlespeech.t2s.modules.transformer.embedding import RelPositionalEncoding
P
pfZhu 已提交
33
from paddlespeech.t2s.modules.transformer.subsampling import Conv2dSubsampling
小湉湉's avatar
小湉湉 已提交
34 35
from paddlespeech.t2s.modules.transformer.attention import MultiHeadedAttention
from paddlespeech.t2s.modules.transformer.attention import RelPositionMultiHeadedAttention
P
pfZhu 已提交
36
from paddlespeech.t2s.modules.transformer.positionwise_feed_forward import PositionwiseFeedForward
小湉湉's avatar
小湉湉 已提交
37 38
from paddlespeech.t2s.modules.transformer.multi_layer_conv import Conv1dLinear
from paddlespeech.t2s.modules.transformer.multi_layer_conv import MultiLayeredConv1d
P
pfZhu 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
from paddlespeech.t2s.modules.transformer.repeat import repeat
from paddlespeech.t2s.modules.layer_norm import LayerNorm


class LegacyRelPositionalEncoding(PositionalEncoding):
    """Relative positional encoding module (old version).

    Details can be found in https://github.com/espnet/espnet/pull/2816.

    See : Appendix B in https://arxiv.org/abs/1901.02860

    Args:
        d_model (int): Embedding dimension.
        dropout_rate (float): Dropout rate.
        max_len (int): Maximum input length.

    """
小湉湉's avatar
小湉湉 已提交
56

P
pfZhu 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    def __init__(self, d_model: int, dropout_rate: float, max_len: int=5000):
        """
        Args:
            d_model (int): Embedding dimension.
            dropout_rate (float): Dropout rate.
            max_len (int, optional): [Maximum input length.]. Defaults to 5000.
        """
        super().__init__(d_model, dropout_rate, max_len, reverse=True)

    def extend_pe(self, x):
        """Reset the positional encodings."""
        if self.pe is not None:
            if paddle.shape(self.pe)[1] >= paddle.shape(x)[1]:
                return
        pe = paddle.zeros((paddle.shape(x)[1], self.d_model))
        if self.reverse:
            position = paddle.arange(
小湉湉's avatar
小湉湉 已提交
74 75
                paddle.shape(x)[1] - 1, -1, -1.0,
                dtype=paddle.float32).unsqueeze(1)
P
pfZhu 已提交
76
        else:
小湉湉's avatar
小湉湉 已提交
77 78
            position = paddle.arange(
                0, paddle.shape(x)[1], dtype=paddle.float32).unsqueeze(1)
P
pfZhu 已提交
79
        div_term = paddle.exp(
小湉湉's avatar
小湉湉 已提交
80 81
            paddle.arange(0, self.d_model, 2, dtype=paddle.float32) *
            -(math.log(10000.0) / self.d_model))
P
pfZhu 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94
        pe[:, 0::2] = paddle.sin(position * div_term)
        pe[:, 1::2] = paddle.cos(position * div_term)
        pe = pe.unsqueeze(0)
        self.pe = pe

    def forward(self, x: paddle.Tensor) -> Tuple[paddle.Tensor, paddle.Tensor]:
        """Compute positional encoding.
        Args:
            x (paddle.Tensor): Input tensor (batch, time, `*`).
        Returns:
            paddle.Tensor: Encoded tensor (batch, time, `*`).
            paddle.Tensor: Positional embedding tensor (1, time, `*`).
        """
小湉湉's avatar
小湉湉 已提交
95
        self.extend_pe(x)
P
pfZhu 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109
        x = x * self.xscale
        pos_emb = self.pe[:, :paddle.shape(x)[1]]
        return self.dropout(x), self.dropout(pos_emb)


class mySequential(nn.Sequential):
    def forward(self, *inputs):
        for module in self._sub_layers.values():
            if type(inputs) == tuple:
                inputs = module(*inputs)
            else:
                inputs = module(inputs)
        return inputs

小湉湉's avatar
小湉湉 已提交
110

P
pfZhu 已提交
111 112 113 114
class NewMaskInputLayer(nn.Layer):
    __constants__ = ['out_features']
    out_features: int

小湉湉's avatar
小湉湉 已提交
115
    def __init__(self, out_features: int, device=None, dtype=None) -> None:
P
pfZhu 已提交
116
        factory_kwargs = {'device': device, 'dtype': dtype}
小湉湉's avatar
小湉湉 已提交
117
        super().__init__()
P
pfZhu 已提交
118
        self.mask_feature = paddle.create_parameter(
小湉湉's avatar
小湉湉 已提交
119 120 121 122 123
            shape=(1, 1, out_features),
            dtype=paddle.float32,
            default_initializer=paddle.nn.initializer.Assign(
                paddle.normal(shape=(1, 1, out_features))))

小湉湉's avatar
小湉湉 已提交
124 125 126 127
    def forward(self, input: paddle.Tensor, masked_pos=None) -> paddle.Tensor:
        masked_pos = paddle.expand_as(paddle.unsqueeze(masked_pos, -1), input)
        masked_input = masked_fill(input, masked_pos, 0) + masked_fill(
            paddle.expand_as(self.mask_feature, input), ~masked_pos, 0)
P
pfZhu 已提交
128 129
        return masked_input

小湉湉's avatar
小湉湉 已提交
130

P
pfZhu 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
class LegacyRelPositionMultiHeadedAttention(MultiHeadedAttention):
    """Multi-Head Attention layer with relative position encoding (old version).
    Details can be found in https://github.com/espnet/espnet/pull/2816.
    Paper: https://arxiv.org/abs/1901.02860

    Args:
        n_head (int): The number of heads.
        n_feat (int): The number of features.
        dropout_rate (float): Dropout rate.
        zero_triu (bool): Whether to zero the upper triangular part of attention matrix.
    """

    def __init__(self, n_head, n_feat, dropout_rate, zero_triu=False):
        """Construct an RelPositionMultiHeadedAttention object."""
        super().__init__(n_head, n_feat, dropout_rate)
        self.zero_triu = zero_triu
        # linear transformation for positional encoding
        self.linear_pos = nn.Linear(n_feat, n_feat, bias_attr=False)
        # these two learnable bias are used in matrix c and matrix d
        # as described in https://arxiv.org/abs/1901.02860 Section 3.3

        self.pos_bias_u = paddle.create_parameter(
            shape=(self.h, self.d_k),
            dtype='float32',
            default_initializer=paddle.nn.initializer.XavierUniform())
        self.pos_bias_v = paddle.create_parameter(
            shape=(self.h, self.d_k),
            dtype='float32',
            default_initializer=paddle.nn.initializer.XavierUniform())

    def rel_shift(self, x):
        """Compute relative positional encoding.
        Args:
            x(Tensor): Input tensor (batch, head, time1, time2).

        Returns:
            Tensor:Output tensor.
        """
        b, h, t1, t2 = paddle.shape(x)
        zero_pad = paddle.zeros((b, h, t1, 1))
        x_padded = paddle.concat([zero_pad, x], axis=-1)
        x_padded = paddle.reshape(x_padded, [b, h, t2 + 1, t1])
        # only keep the positions from 0 to time2
        x = paddle.reshape(x_padded[:, :, 1:], [b, h, t1, t2])

        if self.zero_triu:
            ones = paddle.ones((t1, t2))
            x = x * paddle.tril(ones, t2 - 1)[None, None, :, :]

        return x

    def forward(self, query, key, value, pos_emb, mask):
        """Compute 'Scaled Dot Product Attention' with rel. positional encoding.

        Args:
            query(Tensor): Query tensor (#batch, time1, size).
            key(Tensor): Key tensor (#batch, time2, size).
            value(Tensor): Value tensor (#batch, time2, size).
            pos_emb(Tensor): Positional embedding tensor (#batch, time1, size).
            mask(Tensor): Mask tensor (#batch, 1, time2) or (#batch, time1, time2).

        Returns:
            Tensor: Output tensor (#batch, time1, d_model).
        """
        q, k, v = self.forward_qkv(query, key, value)
        # (batch, time1, head, d_k)
        q = paddle.transpose(q, [0, 2, 1, 3])

        n_batch_pos = paddle.shape(pos_emb)[0]
小湉湉's avatar
小湉湉 已提交
200 201
        p = paddle.reshape(
            self.linear_pos(pos_emb), [n_batch_pos, -1, self.h, self.d_k])
P
pfZhu 已提交
202 203 204 205 206 207 208 209 210 211 212
        # (batch, head, time1, d_k)
        p = paddle.transpose(p, [0, 2, 1, 3])
        # (batch, head, time1, d_k)
        q_with_bias_u = paddle.transpose((q + self.pos_bias_u), [0, 2, 1, 3])
        # (batch, head, time1, d_k)
        q_with_bias_v = paddle.transpose((q + self.pos_bias_v), [0, 2, 1, 3])

        # compute attention score
        # first compute matrix a and matrix c
        # as described in https://arxiv.org/abs/1901.02860 Section 3.3
        # (batch, head, time1, time2)
小湉湉's avatar
小湉湉 已提交
213 214
        matrix_ac = paddle.matmul(q_with_bias_u,
                                  paddle.transpose(k, [0, 1, 3, 2]))
P
pfZhu 已提交
215 216 217

        # compute matrix b and matrix d
        # (batch, head, time1, time1)
小湉湉's avatar
小湉湉 已提交
218 219
        matrix_bd = paddle.matmul(q_with_bias_v,
                                  paddle.transpose(p, [0, 1, 3, 2]))
P
pfZhu 已提交
220 221 222 223 224 225
        matrix_bd = self.rel_shift(matrix_bd)
        # (batch, head, time1, time2)
        scores = (matrix_ac + matrix_bd) / math.sqrt(self.d_k)

        return self.forward_attention(v, scores, mask)

小湉湉's avatar
小湉湉 已提交
226

P
pfZhu 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
class MLMEncoder(nn.Layer):
    """Conformer encoder module.

    Args:
        idim (int): Input dimension.
        attention_dim (int): Dimension of attention.
        attention_heads (int): The number of heads of multi head attention.
        linear_units (int): The number of units of position-wise feed forward.
        num_blocks (int): The number of decoder blocks.
        dropout_rate (float): Dropout rate.
        positional_dropout_rate (float): Dropout rate after adding positional encoding.
        attention_dropout_rate (float): Dropout rate in attention.
        input_layer (Union[str, paddle.nn.Layer]): Input layer type.
        normalize_before (bool): Whether to use layer_norm before the first block.
        concat_after (bool): Whether to concat attention layer's input and output.
            if True, additional linear will be applied.
            i.e. x -> x + linear(concat(x, att(x)))
            if False, no additional linear will be applied. i.e. x -> x + att(x)
        positionwise_layer_type (str): "linear", "conv1d", or "conv1d-linear".
        positionwise_conv_kernel_size (int): Kernel size of positionwise conv1d layer.
        macaron_style (bool): Whether to use macaron style for positionwise layer.
        pos_enc_layer_type (str): Encoder positional encoding layer type.
        selfattention_layer_type (str): Encoder attention layer type.
        activation_type (str): Encoder activation function type.
        use_cnn_module (bool): Whether to use convolution module.
        zero_triu (bool): Whether to zero the upper triangular part of attention matrix.
        cnn_module_kernel (int): Kernerl size of convolution module.
        padding_idx (int): Padding idx for input_layer=embed.
        stochastic_depth_rate (float): Maximum probability to skip the encoder layer.
        intermediate_layers (Union[List[int], None]): indices of intermediate CTC layer.
            indices start from 1.
            if not None, intermediate outputs are returned (which changes return type
            signature.)

    """
小湉湉's avatar
小湉湉 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

    def __init__(self,
                 idim,
                 vocab_size=0,
                 pre_speech_layer: int=0,
                 attention_dim=256,
                 attention_heads=4,
                 linear_units=2048,
                 num_blocks=6,
                 dropout_rate=0.1,
                 positional_dropout_rate=0.1,
                 attention_dropout_rate=0.0,
                 input_layer="conv2d",
                 normalize_before=True,
                 concat_after=False,
                 positionwise_layer_type="linear",
                 positionwise_conv_kernel_size=1,
                 macaron_style=False,
                 pos_enc_layer_type="abs_pos",
                 pos_enc_class=None,
                 selfattention_layer_type="selfattn",
                 activation_type="swish",
                 use_cnn_module=False,
                 zero_triu=False,
                 cnn_module_kernel=31,
                 padding_idx=-1,
                 stochastic_depth_rate=0.0,
                 intermediate_layers=None,
                 text_masking=False):
P
pfZhu 已提交
291
        """Construct an Encoder object."""
小湉湉's avatar
小湉湉 已提交
292
        super().__init__()
P
pfZhu 已提交
293
        self._output_size = attention_dim
小湉湉's avatar
小湉湉 已提交
294
        self.text_masking = text_masking
P
pfZhu 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
        if self.text_masking:
            self.text_masking_layer = NewMaskInputLayer(attention_dim)
        activation = get_activation(activation_type)
        if pos_enc_layer_type == "abs_pos":
            pos_enc_class = PositionalEncoding
        elif pos_enc_layer_type == "scaled_abs_pos":
            pos_enc_class = ScaledPositionalEncoding
        elif pos_enc_layer_type == "rel_pos":
            assert selfattention_layer_type == "rel_selfattn"
            pos_enc_class = RelPositionalEncoding
        elif pos_enc_layer_type == "legacy_rel_pos":
            pos_enc_class = LegacyRelPositionalEncoding
            assert selfattention_layer_type == "legacy_rel_selfattn"
        else:
            raise ValueError("unknown pos_enc_layer: " + pos_enc_layer_type)

        self.conv_subsampling_factor = 1
        if input_layer == "linear":
            self.embed = nn.Sequential(
                nn.Linear(idim, attention_dim),
                nn.LayerNorm(attention_dim),
                nn.Dropout(dropout_rate),
                nn.ReLU(),
小湉湉's avatar
小湉湉 已提交
318
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
319 320 321 322 323
        elif input_layer == "conv2d":
            self.embed = Conv2dSubsampling(
                idim,
                attention_dim,
                dropout_rate,
小湉湉's avatar
小湉湉 已提交
324
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
325 326 327 328
            self.conv_subsampling_factor = 4
        elif input_layer == "embed":
            self.embed = nn.Sequential(
                nn.Embedding(idim, attention_dim, padding_idx=padding_idx),
小湉湉's avatar
小湉湉 已提交
329
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
330 331 332 333 334 335 336
        elif input_layer == "mlm":
            self.segment_emb = None
            self.speech_embed = mySequential(
                NewMaskInputLayer(idim),
                nn.Linear(idim, attention_dim),
                nn.LayerNorm(attention_dim),
                nn.ReLU(),
小湉湉's avatar
小湉湉 已提交
337
                pos_enc_class(attention_dim, positional_dropout_rate))
P
pfZhu 已提交
338
            self.text_embed = nn.Sequential(
小湉湉's avatar
小湉湉 已提交
339 340 341 342 343 344
                nn.Embedding(
                    vocab_size, attention_dim, padding_idx=padding_idx),
                pos_enc_class(attention_dim, positional_dropout_rate), )
        elif input_layer == "sega_mlm":
            self.segment_emb = nn.Embedding(
                500, attention_dim, padding_idx=padding_idx)
P
pfZhu 已提交
345 346 347 348 349
            self.speech_embed = mySequential(
                NewMaskInputLayer(idim),
                nn.Linear(idim, attention_dim),
                nn.LayerNorm(attention_dim),
                nn.ReLU(),
小湉湉's avatar
小湉湉 已提交
350
                pos_enc_class(attention_dim, positional_dropout_rate))
P
pfZhu 已提交
351
            self.text_embed = nn.Sequential(
小湉湉's avatar
小湉湉 已提交
352 353 354
                nn.Embedding(
                    vocab_size, attention_dim, padding_idx=padding_idx),
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
355 356 357
        elif isinstance(input_layer, nn.Layer):
            self.embed = nn.Sequential(
                input_layer,
小湉湉's avatar
小湉湉 已提交
358
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
359 360
        elif input_layer is None:
            self.embed = nn.Sequential(
小湉湉's avatar
小湉湉 已提交
361
                pos_enc_class(attention_dim, positional_dropout_rate))
P
pfZhu 已提交
362 363 364 365 366 367 368 369
        else:
            raise ValueError("unknown input_layer: " + input_layer)
        self.normalize_before = normalize_before

        # self-attention module definition
        if selfattention_layer_type == "selfattn":
            logging.info("encoder self-attention layer type = self-attention")
            encoder_selfattn_layer = MultiHeadedAttention
小湉湉's avatar
小湉湉 已提交
370 371
            encoder_selfattn_layer_args = (attention_heads, attention_dim,
                                           attention_dropout_rate, )
P
pfZhu 已提交
372 373 374
        elif selfattention_layer_type == "legacy_rel_selfattn":
            assert pos_enc_layer_type == "legacy_rel_pos"
            encoder_selfattn_layer = LegacyRelPositionMultiHeadedAttention
小湉湉's avatar
小湉湉 已提交
375 376
            encoder_selfattn_layer_args = (attention_heads, attention_dim,
                                           attention_dropout_rate, )
P
pfZhu 已提交
377
        elif selfattention_layer_type == "rel_selfattn":
小湉湉's avatar
小湉湉 已提交
378 379
            logging.info(
                "encoder self-attention layer type = relative self-attention")
P
pfZhu 已提交
380 381
            assert pos_enc_layer_type == "rel_pos"
            encoder_selfattn_layer = RelPositionMultiHeadedAttention
小湉湉's avatar
小湉湉 已提交
382 383
            encoder_selfattn_layer_args = (attention_heads, attention_dim,
                                           attention_dropout_rate, zero_triu, )
P
pfZhu 已提交
384
        else:
小湉湉's avatar
小湉湉 已提交
385 386
            raise ValueError("unknown encoder_attn_layer: " +
                             selfattention_layer_type)
P
pfZhu 已提交
387 388 389 390

        # feed-forward module definition
        if positionwise_layer_type == "linear":
            positionwise_layer = PositionwiseFeedForward
小湉湉's avatar
小湉湉 已提交
391 392
            positionwise_layer_args = (attention_dim, linear_units,
                                       dropout_rate, activation, )
P
pfZhu 已提交
393 394
        elif positionwise_layer_type == "conv1d":
            positionwise_layer = MultiLayeredConv1d
小湉湉's avatar
小湉湉 已提交
395 396 397
            positionwise_layer_args = (attention_dim, linear_units,
                                       positionwise_conv_kernel_size,
                                       dropout_rate, )
P
pfZhu 已提交
398 399
        elif positionwise_layer_type == "conv1d-linear":
            positionwise_layer = Conv1dLinear
小湉湉's avatar
小湉湉 已提交
400 401 402
            positionwise_layer_args = (attention_dim, linear_units,
                                       positionwise_conv_kernel_size,
                                       dropout_rate, )
P
pfZhu 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
        else:
            raise NotImplementedError("Support only linear or conv1d.")

        # convolution module definition
        convolution_layer = ConvolutionModule
        convolution_layer_args = (attention_dim, cnn_module_kernel, activation)

        self.encoders = repeat(
            num_blocks,
            lambda lnum: EncoderLayer(
                attention_dim,
                encoder_selfattn_layer(*encoder_selfattn_layer_args),
                positionwise_layer(*positionwise_layer_args),
                positionwise_layer(*positionwise_layer_args) if macaron_style else None,
                convolution_layer(*convolution_layer_args) if use_cnn_module else None,
                dropout_rate,
                normalize_before,
                concat_after,
小湉湉's avatar
小湉湉 已提交
421
                stochastic_depth_rate * float(1 + lnum) / num_blocks, ), )
P
pfZhu 已提交
422 423 424 425 426 427 428 429 430 431 432 433
        self.pre_speech_layer = pre_speech_layer
        self.pre_speech_encoders = repeat(
            self.pre_speech_layer,
            lambda lnum: EncoderLayer(
                attention_dim,
                encoder_selfattn_layer(*encoder_selfattn_layer_args),
                positionwise_layer(*positionwise_layer_args),
                positionwise_layer(*positionwise_layer_args) if macaron_style else None,
                convolution_layer(*convolution_layer_args) if use_cnn_module else None,
                dropout_rate,
                normalize_before,
                concat_after,
小湉湉's avatar
小湉湉 已提交
434
                stochastic_depth_rate * float(1 + lnum) / self.pre_speech_layer, ),
P
pfZhu 已提交
435 436 437 438 439 440
        )
        if self.normalize_before:
            self.after_norm = LayerNorm(attention_dim)

        self.intermediate_layers = intermediate_layers

小湉湉's avatar
小湉湉 已提交
441 442 443
    def forward(self,
                speech_pad,
                text_pad,
小湉湉's avatar
小湉湉 已提交
444
                masked_pos,
小湉湉's avatar
小湉湉 已提交
445 446
                speech_mask=None,
                text_mask=None,
小湉湉's avatar
小湉湉 已提交
447 448
                speech_seg_pos=None,
                text_seg_pos=None):
P
pfZhu 已提交
449 450 451
        """Encode input sequence.

        """
小湉湉's avatar
小湉湉 已提交
452 453
        if masked_pos is not None:
            speech_pad = self.speech_embed(speech_pad, masked_pos)
P
pfZhu 已提交
454 455 456 457
        else:
            speech_pad = self.speech_embed(speech_pad)
        # pure speech input
        if -2 in np.array(text_pad):
小湉湉's avatar
小湉湉 已提交
458
            text_pad = text_pad + 3
P
pfZhu 已提交
459
            text_mask = paddle.unsqueeze(bool(text_pad), 1)
小湉湉's avatar
小湉湉 已提交
460
            text_seg_pos = paddle.zeros_like(text_pad)
P
pfZhu 已提交
461
            text_pad = self.text_embed(text_pad)
小湉湉's avatar
小湉湉 已提交
462
            text_pad = (text_pad[0] + self.segment_emb(text_seg_pos),
小湉湉's avatar
小湉湉 已提交
463
                        text_pad[1])
小湉湉's avatar
小湉湉 已提交
464
            text_seg_pos = None
P
pfZhu 已提交
465 466
        elif text_pad is not None:
            text_pad = self.text_embed(text_pad)
小湉湉's avatar
小湉湉 已提交
467 468 469 470 471
        if speech_seg_pos is not None and text_seg_pos is not None and self.segment_emb:
            speech_seg_emb = self.segment_emb(speech_seg_pos)
            text_seg_emb = self.segment_emb(text_seg_pos)
            text_pad = (text_pad[0] + text_seg_emb, text_pad[1])
            speech_pad = (speech_pad[0] + speech_seg_emb, speech_pad[1])
P
pfZhu 已提交
472 473 474 475 476 477
        if self.pre_speech_encoders:
            speech_pad, _ = self.pre_speech_encoders(speech_pad, speech_mask)

        if text_pad is not None:
            xs = paddle.concat([speech_pad[0], text_pad[0]], axis=1)
            xs_pos_emb = paddle.concat([speech_pad[1], text_pad[1]], axis=1)
小湉湉's avatar
小湉湉 已提交
478
            masks = paddle.concat([speech_mask, text_mask], axis=-1)
P
pfZhu 已提交
479 480 481 482 483
        else:
            xs = speech_pad[0]
            xs_pos_emb = speech_pad[1]
            masks = speech_mask

小湉湉's avatar
小湉湉 已提交
484
        xs, masks = self.encoders((xs, xs_pos_emb), masks)
P
pfZhu 已提交
485 486 487 488 489 490

        if isinstance(xs, tuple):
            xs = xs[0]
        if self.normalize_before:
            xs = self.after_norm(xs)

小湉湉's avatar
小湉湉 已提交
491
        return xs, masks
P
pfZhu 已提交
492 493 494


class MLMDecoder(MLMEncoder):
小湉湉's avatar
小湉湉 已提交
495
    def forward(self, xs, masks, masked_pos=None, segment_emb=None):
P
pfZhu 已提交
496 497 498 499 500 501 502 503 504 505 506 507
        """Encode input sequence.

        Args:
            xs (paddle.Tensor): Input tensor (#batch, time, idim).
            masks (paddle.Tensor): Mask tensor (#batch, time).

        Returns:
            paddle.Tensor: Output tensor (#batch, time, attention_dim).
            paddle.Tensor: Mask tensor (#batch, time).

        """
        if not self.training:
小湉湉's avatar
小湉湉 已提交
508
            masked_pos = None
P
pfZhu 已提交
509 510 511 512 513 514 515 516 517 518
        xs = self.embed(xs)
        if segment_emb:
            xs = (xs[0] + segment_emb, xs[1])
        if self.intermediate_layers is None:
            xs, masks = self.encoders(xs, masks)
        else:
            intermediate_outputs = []
            for layer_idx, encoder_layer in enumerate(self.encoders):
                xs, masks = encoder_layer(xs, masks)

小湉湉's avatar
小湉湉 已提交
519 520
                if (self.intermediate_layers is not None and
                        layer_idx + 1 in self.intermediate_layers):
P
pfZhu 已提交
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
                    encoder_output = xs
                    # intermediate branches also require normalization.
                    if self.normalize_before:
                        encoder_output = self.after_norm(encoder_output)
                    intermediate_outputs.append(encoder_output)
        if isinstance(xs, tuple):
            xs = xs[0]
        if self.normalize_before:
            xs = self.after_norm(xs)

        if self.intermediate_layers is not None:
            return xs, masks, intermediate_outputs
        return xs, masks


小湉湉's avatar
小湉湉 已提交
536
def pad_to_longformer_att_window(text, max_len, max_tlen, attention_window):
P
pfZhu 已提交
537 538 539 540
    round = max_len % attention_window
    if round != 0:
        max_tlen += (attention_window - round)
        n_batch = paddle.shape(text)[0]
小湉湉's avatar
小湉湉 已提交
541 542 543
        text_pad = paddle.zeros(
            shape=(n_batch, max_tlen, *paddle.shape(text[0])[1:]),
            dtype=text.dtype)
P
pfZhu 已提交
544
        for i in range(n_batch):
小湉湉's avatar
小湉湉 已提交
545
            text_pad[i, :paddle.shape(text[i])[0]] = text[i]
P
pfZhu 已提交
546
    else:
小湉湉's avatar
小湉湉 已提交
547
        text_pad = text[:, :max_tlen]
P
pfZhu 已提交
548 549
    return text_pad, max_tlen

小湉湉's avatar
小湉湉 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572

class MLMModel(nn.Layer):
    def __init__(self,
                 token_list: Union[Tuple[str, ...], List[str]],
                 odim: int,
                 encoder: nn.Layer,
                 decoder: Optional[nn.Layer],
                 postnet_layers: int=0,
                 postnet_chans: int=0,
                 postnet_filts: int=0,
                 ignore_id: int=-1,
                 lsm_weight: float=0.0,
                 length_normalized_loss: bool=False,
                 report_cer: bool=True,
                 report_wer: bool=True,
                 sym_space: str="<space>",
                 sym_blank: str="<blank>",
                 masking_schema: str="span",
                 mean_phn_span: int=3,
                 mlm_prob: float=0.25,
                 dynamic_mlm_prob=False,
                 decoder_seg_pos=False,
                 text_masking=False):
P
pfZhu 已提交
573 574 575 576 577 578 579 580 581 582 583 584 585

        super().__init__()
        # note that eos is the same as sos (equivalent ID)
        self.odim = odim
        self.ignore_id = ignore_id
        self.token_list = token_list.copy()

        self.encoder = encoder

        self.decoder = decoder
        self.vocab_size = encoder.text_embed[0]._num_embeddings
        if report_cer or report_wer:
            self.error_calculator = ErrorCalculator(
小湉湉's avatar
小湉湉 已提交
586
                token_list, sym_space, sym_blank, report_cer, report_wer)
P
pfZhu 已提交
587 588 589 590 591 592
        else:
            self.error_calculator = None

        self.mlm_weight = 1.0
        self.mlm_prob = mlm_prob
        self.mlm_layer = 12
小湉湉's avatar
小湉湉 已提交
593
        self.finetune_wo_mlm = True
P
pfZhu 已提交
594 595 596 597
        self.max_span = 50
        self.min_span = 4
        self.mean_phn_span = mean_phn_span
        self.masking_schema = masking_schema
小湉湉's avatar
小湉湉 已提交
598 599 600
        if self.decoder is None or not (hasattr(self.decoder,
                                                'output_layer') and
                                        self.decoder.output_layer is not None):
P
pfZhu 已提交
601 602
            self.sfc = nn.Linear(self.encoder._output_size, odim)
        else:
小湉湉's avatar
小湉湉 已提交
603
            self.sfc = None
P
pfZhu 已提交
604
        if text_masking:
小湉湉's avatar
小湉湉 已提交
605 606 607 608
            self.text_sfc = nn.Linear(
                self.encoder.text_embed[0]._embedding_dim,
                self.vocab_size,
                weight_attr=self.encoder.text_embed[0]._weight_attr)
P
pfZhu 已提交
609 610 611 612 613 614
            self.text_mlm_loss = nn.CrossEntropyLoss(ignore_index=ignore_id)
        else:
            self.text_sfc = None
            self.text_mlm_loss = None
        self.decoder_seg_pos = decoder_seg_pos
        if lsm_weight > 50:
小湉湉's avatar
小湉湉 已提交
615
            self.l1_loss_func = nn.MSELoss()
P
pfZhu 已提交
616 617
        else:
            self.l1_loss_func = nn.L1Loss(reduction='none')
小湉湉's avatar
小湉湉 已提交
618 619 620 621 622 623 624 625
        self.postnet = (None if postnet_layers == 0 else Postnet(
            idim=self.encoder._output_size,
            odim=odim,
            n_layers=postnet_layers,
            n_chans=postnet_chans,
            n_filts=postnet_filts,
            use_batch_norm=True,
            dropout_rate=0.5, ))
P
pfZhu 已提交
626 627

    def collect_feats(self,
小湉湉's avatar
小湉湉 已提交
628
                      speech,
小湉湉's avatar
小湉湉 已提交
629
                      speech_lens,
小湉湉's avatar
小湉湉 已提交
630
                      text,
小湉湉's avatar
小湉湉 已提交
631 632
                      text_lens,
                      masked_pos,
小湉湉's avatar
小湉湉 已提交
633 634
                      speech_mask,
                      text_mask,
小湉湉's avatar
小湉湉 已提交
635 636
                      speech_seg_pos,
                      text_seg_pos,
小湉湉's avatar
小湉湉 已提交
637
                      y_masks=None) -> Dict[str, paddle.Tensor]:
小湉湉's avatar
小湉湉 已提交
638
        return {"feats": speech, "feats_lens": speech_lens}
P
pfZhu 已提交
639

小湉湉's avatar
小湉湉 已提交
640
    def forward(self, batch, speech_seg_pos, y_masks=None):
P
pfZhu 已提交
641 642 643 644
        # feats: (Batch, Length, Dim)
        # -> encoder_out: (Batch, Length2, Dim2)
        speech_pad_placeholder = batch['speech_pad']
        if self.decoder is not None:
小湉湉's avatar
小湉湉 已提交
645 646
            ys_in = self._add_first_frame_and_remove_last_frame(
                batch['speech_pad'])
P
pfZhu 已提交
647 648
        encoder_out, h_masks = self.encoder(**batch)
        if self.decoder is not None:
小湉湉's avatar
小湉湉 已提交
649 650
            zs, _ = self.decoder(ys_in, y_masks, encoder_out,
                                 bool(h_masks),
小湉湉's avatar
小湉湉 已提交
651
                                 self.encoder.segment_emb(speech_seg_pos))
P
pfZhu 已提交
652 653
            speech_hidden_states = zs
        else:
小湉湉's avatar
小湉湉 已提交
654 655
            speech_hidden_states = encoder_out[:, :paddle.shape(batch[
                'speech_pad'])[1], :]
P
pfZhu 已提交
656
        if self.sfc is not None:
小湉湉's avatar
小湉湉 已提交
657 658 659
            before_outs = paddle.reshape(
                self.sfc(speech_hidden_states),
                (paddle.shape(speech_hidden_states)[0], -1, self.odim))
P
pfZhu 已提交
660 661 662
        else:
            before_outs = speech_hidden_states
        if self.postnet is not None:
小湉湉's avatar
小湉湉 已提交
663 664 665
            after_outs = before_outs + paddle.transpose(
                self.postnet(paddle.transpose(before_outs, [0, 2, 1])),
                (0, 2, 1))
P
pfZhu 已提交
666 667
        else:
            after_outs = None
小湉湉's avatar
小湉湉 已提交
668
        return before_outs, after_outs, speech_pad_placeholder, batch[
小湉湉's avatar
小湉湉 已提交
669
            'masked_pos']
P
pfZhu 已提交
670 671

    def inference(
小湉湉's avatar
小湉湉 已提交
672 673 674
            self,
            speech,
            text,
小湉湉's avatar
小湉湉 已提交
675
            masked_pos,
小湉湉's avatar
小湉湉 已提交
676 677
            speech_mask,
            text_mask,
小湉湉's avatar
小湉湉 已提交
678 679 680
            speech_seg_pos,
            text_seg_pos,
            span_bdy,
小湉湉's avatar
小湉湉 已提交
681
            y_masks=None,
小湉湉's avatar
小湉湉 已提交
682 683
            speech_lens=None,
            text_lens=None,
小湉湉's avatar
小湉湉 已提交
684 685 686 687 688 689 690 691 692
            feats: Optional[paddle.Tensor]=None,
            spembs: Optional[paddle.Tensor]=None,
            sids: Optional[paddle.Tensor]=None,
            lids: Optional[paddle.Tensor]=None,
            threshold: float=0.5,
            minlenratio: float=0.0,
            maxlenratio: float=10.0,
            use_teacher_forcing: bool=False, ) -> Dict[str, paddle.Tensor]:

P
pfZhu 已提交
693 694 695
        batch = dict(
            speech_pad=speech,
            text_pad=text,
小湉湉's avatar
小湉湉 已提交
696
            masked_pos=masked_pos,
P
pfZhu 已提交
697 698
            speech_mask=speech_mask,
            text_mask=text_mask,
小湉湉's avatar
小湉湉 已提交
699 700
            speech_seg_pos=speech_seg_pos,
            text_seg_pos=text_seg_pos, )
P
pfZhu 已提交
701 702 703 704

        # # inference with teacher forcing
        # hs, h_masks = self.encoder(**batch)

小湉湉's avatar
小湉湉 已提交
705
        outs = [batch['speech_pad'][:, :span_bdy[0]]]
P
pfZhu 已提交
706 707
        z_cache = None
        if use_teacher_forcing:
小湉湉's avatar
小湉湉 已提交
708
            before, zs, _, _ = self.forward(
小湉湉's avatar
小湉湉 已提交
709
                batch, speech_seg_pos, y_masks=y_masks)
P
pfZhu 已提交
710 711
            if zs is None:
                zs = before
小湉湉's avatar
小湉湉 已提交
712 713
            outs += [zs[0][span_bdy[0]:span_bdy[1]]]
            outs += [batch['speech_pad'][:, span_bdy[1]:]]
P
pfZhu 已提交
714
            return dict(feat_gen=outs)
小湉湉's avatar
小湉湉 已提交
715
        return None
P
pfZhu 已提交
716

小湉湉's avatar
小湉湉 已提交
717 718
    def _add_first_frame_and_remove_last_frame(
            self, ys: paddle.Tensor) -> paddle.Tensor:
P
pfZhu 已提交
719
        ys_in = paddle.concat(
小湉湉's avatar
小湉湉 已提交
720 721 722 723 724 725
            [
                paddle.zeros(
                    shape=(paddle.shape(ys)[0], 1, paddle.shape(ys)[2]),
                    dtype=ys.dtype), ys[:, :-1]
            ],
            axis=1)
P
pfZhu 已提交
726 727 728
        return ys_in


小湉湉's avatar
小湉湉 已提交
729
class MLMEncAsDecoderModel(MLMModel):
小湉湉's avatar
小湉湉 已提交
730
    def forward(self, batch, speech_seg_pos, y_masks=None):
P
pfZhu 已提交
731 732 733
        # feats: (Batch, Length, Dim)
        # -> encoder_out: (Batch, Length2, Dim2)
        speech_pad_placeholder = batch['speech_pad']
小湉湉's avatar
小湉湉 已提交
734
        encoder_out, h_masks = self.encoder(**batch)  # segment_emb
P
pfZhu 已提交
735 736 737 738
        if self.decoder is not None:
            zs, _ = self.decoder(encoder_out, h_masks)
        else:
            zs = encoder_out
小湉湉's avatar
小湉湉 已提交
739
        speech_hidden_states = zs[:, :paddle.shape(batch['speech_pad'])[1], :]
P
pfZhu 已提交
740
        if self.sfc is not None:
小湉湉's avatar
小湉湉 已提交
741 742 743
            before_outs = paddle.reshape(
                self.sfc(speech_hidden_states),
                (paddle.shape(speech_hidden_states)[0], -1, self.odim))
P
pfZhu 已提交
744 745 746
        else:
            before_outs = speech_hidden_states
        if self.postnet is not None:
小湉湉's avatar
小湉湉 已提交
747 748 749
            after_outs = before_outs + paddle.transpose(
                self.postnet(paddle.transpose(before_outs, [0, 2, 1])),
                [0, 2, 1])
P
pfZhu 已提交
750 751
        else:
            after_outs = None
小湉湉's avatar
小湉湉 已提交
752
        return before_outs, after_outs, speech_pad_placeholder, batch[
小湉湉's avatar
小湉湉 已提交
753
            'masked_pos']
P
pfZhu 已提交
754 755


小湉湉's avatar
小湉湉 已提交
756 757 758 759 760 761
class MLMDualMaksingModel(MLMModel):
    def _calc_mlm_loss(self,
                       before_outs: paddle.Tensor,
                       after_outs: paddle.Tensor,
                       text_outs: paddle.Tensor,
                       batch):
P
pfZhu 已提交
762 763
        xs_pad = batch['speech_pad']
        text_pad = batch['text_pad']
小湉湉's avatar
小湉湉 已提交
764 765 766
        masked_pos = batch['masked_pos']
        text_masked_pos = batch['text_masked_pos']
        mlm_loss_pos = masked_pos > 0
小湉湉's avatar
小湉湉 已提交
767 768 769 770 771
        loss = paddle.sum(
            self.l1_loss_func(
                paddle.reshape(before_outs, (-1, self.odim)),
                paddle.reshape(xs_pad, (-1, self.odim))),
            axis=-1)
P
pfZhu 已提交
772
        if after_outs is not None:
小湉湉's avatar
小湉湉 已提交
773 774 775 776 777 778
            loss += paddle.sum(
                self.l1_loss_func(
                    paddle.reshape(after_outs, (-1, self.odim)),
                    paddle.reshape(xs_pad, (-1, self.odim))),
                axis=-1)
        loss_mlm = paddle.sum((loss * paddle.reshape(
小湉湉's avatar
小湉湉 已提交
779
            mlm_loss_pos, [-1]))) / paddle.sum((mlm_loss_pos) + 1e-10)
小湉湉's avatar
小湉湉 已提交
780 781 782 783

        loss_text = paddle.sum((self.text_mlm_loss(
            paddle.reshape(text_outs, (-1, self.vocab_size)),
            paddle.reshape(text_pad, (-1))) * paddle.reshape(
小湉湉's avatar
小湉湉 已提交
784
                text_masked_pos, (-1)))) / paddle.sum((text_masked_pos) + 1e-10)
P
pfZhu 已提交
785 786
        return loss_mlm, loss_text

小湉湉's avatar
小湉湉 已提交
787
    def forward(self, batch, speech_seg_pos, y_masks=None):
P
pfZhu 已提交
788 789
        # feats: (Batch, Length, Dim)
        # -> encoder_out: (Batch, Length2, Dim2)
小湉湉's avatar
小湉湉 已提交
790
        encoder_out, h_masks = self.encoder(**batch)  # segment_emb
P
pfZhu 已提交
791 792 793 794
        if self.decoder is not None:
            zs, _ = self.decoder(encoder_out, h_masks)
        else:
            zs = encoder_out
小湉湉's avatar
小湉湉 已提交
795
        speech_hidden_states = zs[:, :paddle.shape(batch['speech_pad'])[1], :]
P
pfZhu 已提交
796
        if self.text_sfc:
小湉湉's avatar
小湉湉 已提交
797 798 799 800 801
            text_hiddent_states = zs[:, paddle.shape(batch['speech_pad'])[
                1]:, :]
            text_outs = paddle.reshape(
                self.text_sfc(text_hiddent_states),
                (paddle.shape(text_hiddent_states)[0], -1, self.vocab_size))
P
pfZhu 已提交
802
        if self.sfc is not None:
小湉湉's avatar
小湉湉 已提交
803 804 805
            before_outs = paddle.reshape(
                self.sfc(speech_hidden_states),
                (paddle.shape(speech_hidden_states)[0], -1, self.odim))
P
pfZhu 已提交
806 807 808
        else:
            before_outs = speech_hidden_states
        if self.postnet is not None:
小湉湉's avatar
小湉湉 已提交
809 810 811
            after_outs = before_outs + paddle.transpose(
                self.postnet(paddle.transpose(before_outs, [0, 2, 1])),
                [0, 2, 1])
P
pfZhu 已提交
812 813
        else:
            after_outs = None
小湉湉's avatar
小湉湉 已提交
814
        return before_outs, after_outs, text_outs, None  #, speech_pad_placeholder, batch['masked_pos'],batch['text_masked_pos']
小湉湉's avatar
小湉湉 已提交
815

P
pfZhu 已提交
816 817

def build_model_from_file(config_file, model_file):
小湉湉's avatar
小湉湉 已提交
818

P
pfZhu 已提交
819
    state_dict = paddle.load(model_file)
小湉湉's avatar
小湉湉 已提交
820 821
    model_class = MLMDualMaksingModel if 'conformer_combine_vctk_aishell3_dual_masking' in config_file \
        else MLMEncAsDecoderModel
P
pfZhu 已提交
822 823 824 825 826 827 828 829 830 831 832

    # 构建模型
    args = yaml.safe_load(Path(config_file).open("r", encoding="utf-8"))
    args = argparse.Namespace(**args)

    model = build_model(args, model_class)

    model.set_state_dict(state_dict)
    return model, args


小湉湉's avatar
小湉湉 已提交
833 834
def build_model(args: argparse.Namespace,
                model_class=MLMEncAsDecoderModel) -> MLMModel:
P
pfZhu 已提交
835 836 837 838 839 840 841 842 843 844 845 846 847
    if isinstance(args.token_list, str):
        with open(args.token_list, encoding="utf-8") as f:
            token_list = [line.rstrip() for line in f]

        # Overwriting token_list to keep it as "portable".
        args.token_list = list(token_list)
    elif isinstance(args.token_list, (tuple, list)):
        token_list = list(args.token_list)
    else:
        raise RuntimeError("token_list must be str or list")
    vocab_size = len(token_list)
    logging.info(f"Vocabulary size: {vocab_size }")

小湉湉's avatar
小湉湉 已提交
848
    odim = 80
P
pfZhu 已提交
849 850 851 852

    pos_enc_class = ScaledPositionalEncoding if args.use_scaled_pos_enc else PositionalEncoding

    if "conformer" == args.encoder:
小湉湉's avatar
小湉湉 已提交
853 854
        conformer_self_attn_layer_type = args.encoder_conf[
            'selfattention_layer_type']
P
pfZhu 已提交
855 856 857 858 859 860 861 862
        conformer_pos_enc_layer_type = args.encoder_conf['pos_enc_layer_type']
        conformer_rel_pos_type = "legacy"
        if conformer_rel_pos_type == "legacy":
            if conformer_pos_enc_layer_type == "rel_pos":
                conformer_pos_enc_layer_type = "legacy_rel_pos"
                logging.warning(
                    "Fallback to conformer_pos_enc_layer_type = 'legacy_rel_pos' "
                    "due to the compatibility. If you want to use the new one, "
小湉湉's avatar
小湉湉 已提交
863
                    "please use conformer_pos_enc_layer_type = 'latest'.")
P
pfZhu 已提交
864 865 866 867 868 869
            if conformer_self_attn_layer_type == "rel_selfattn":
                conformer_self_attn_layer_type = "legacy_rel_selfattn"
                logging.warning(
                    "Fallback to "
                    "conformer_self_attn_layer_type = 'legacy_rel_selfattn' "
                    "due to the compatibility. If you want to use the new one, "
小湉湉's avatar
小湉湉 已提交
870
                    "please use conformer_pos_enc_layer_type = 'latest'.")
P
pfZhu 已提交
871 872 873 874 875
        elif conformer_rel_pos_type == "latest":
            assert conformer_pos_enc_layer_type != "legacy_rel_pos"
            assert conformer_self_attn_layer_type != "legacy_rel_selfattn"
        else:
            raise ValueError(f"Unknown rel_pos_type: {conformer_rel_pos_type}")
小湉湉's avatar
小湉湉 已提交
876 877 878 879 880 881 882 883
        args.encoder_conf[
            'selfattention_layer_type'] = conformer_self_attn_layer_type
        args.encoder_conf['pos_enc_layer_type'] = conformer_pos_enc_layer_type
        if "conformer" == args.decoder:
            args.decoder_conf[
                'selfattention_layer_type'] = conformer_self_attn_layer_type
            args.decoder_conf[
                'pos_enc_layer_type'] = conformer_pos_enc_layer_type
P
pfZhu 已提交
884 885 886 887

    # Encoder
    encoder_class = MLMEncoder

小湉湉's avatar
小湉湉 已提交
888 889
    if 'text_masking' in args.model_conf.keys() and args.model_conf[
            'text_masking']:
P
pfZhu 已提交
890 891 892
        args.encoder_conf['text_masking'] = True
    else:
        args.encoder_conf['text_masking'] = False
小湉湉's avatar
小湉湉 已提交
893 894 895 896 897 898

    encoder = encoder_class(
        args.input_size,
        vocab_size=vocab_size,
        pos_enc_class=pos_enc_class,
        **args.encoder_conf)
P
pfZhu 已提交
899 900 901 902 903 904 905

    # Decoder
    if args.decoder != 'no_decoder':
        decoder_class = MLMDecoder
        decoder = decoder_class(
            idim=0,
            input_layer=None,
小湉湉's avatar
小湉湉 已提交
906
            **args.decoder_conf, )
P
pfZhu 已提交
907 908 909 910 911 912 913 914 915
    else:
        decoder = None

    # Build model
    model = model_class(
        odim=odim,
        encoder=encoder,
        decoder=decoder,
        token_list=token_list,
小湉湉's avatar
小湉湉 已提交
916
        **args.model_conf, )
P
pfZhu 已提交
917 918 919 920 921 922

    # Initialize
    if args.init is not None:
        initialize(model, args.init)

    return model