model_paddle.py 37.5 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 124 125 126 127 128 129
            shape=(1, 1, out_features),
            dtype=paddle.float32,
            default_initializer=paddle.nn.initializer.Assign(
                paddle.normal(shape=(1, 1, out_features))))

    def forward(self, input: paddle.Tensor,
                masked_position=None) -> paddle.Tensor:
        masked_position = paddle.expand_as(
            paddle.unsqueeze(masked_position, -1), input)
        masked_input = masked_fill(input, masked_position, 0) + masked_fill(
            paddle.expand_as(self.mask_feature, input), ~masked_position, 0)
P
pfZhu 已提交
130 131
        return masked_input

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

P
pfZhu 已提交
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 200 201
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
小湉湉 已提交
202 203
        p = paddle.reshape(
            self.linear_pos(pos_emb), [n_batch_pos, -1, self.h, self.d_k])
P
pfZhu 已提交
204 205 206 207 208 209 210 211 212 213 214
        # (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
小湉湉 已提交
215 216
        matrix_ac = paddle.matmul(q_with_bias_u,
                                  paddle.transpose(k, [0, 1, 3, 2]))
P
pfZhu 已提交
217 218 219

        # compute matrix b and matrix d
        # (batch, head, time1, time1)
小湉湉's avatar
小湉湉 已提交
220 221
        matrix_bd = paddle.matmul(q_with_bias_v,
                                  paddle.transpose(p, [0, 1, 3, 2]))
P
pfZhu 已提交
222 223 224 225 226 227
        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
小湉湉 已提交
228

P
pfZhu 已提交
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 262 263
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
小湉湉 已提交
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 291 292

    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 已提交
293
        """Construct an Encoder object."""
小湉湉's avatar
小湉湉 已提交
294
        super().__init__()
P
pfZhu 已提交
295
        self._output_size = attention_dim
小湉湉's avatar
小湉湉 已提交
296
        self.text_masking = text_masking
P
pfZhu 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
        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
小湉湉 已提交
320
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
321 322 323 324 325
        elif input_layer == "conv2d":
            self.embed = Conv2dSubsampling(
                idim,
                attention_dim,
                dropout_rate,
小湉湉's avatar
小湉湉 已提交
326
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
327 328 329 330
            self.conv_subsampling_factor = 4
        elif input_layer == "embed":
            self.embed = nn.Sequential(
                nn.Embedding(idim, attention_dim, padding_idx=padding_idx),
小湉湉's avatar
小湉湉 已提交
331
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
332 333 334 335 336 337 338
        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
小湉湉 已提交
339
                pos_enc_class(attention_dim, positional_dropout_rate))
P
pfZhu 已提交
340
            self.text_embed = nn.Sequential(
小湉湉's avatar
小湉湉 已提交
341 342 343 344 345 346
                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 已提交
347 348 349 350 351
            self.speech_embed = mySequential(
                NewMaskInputLayer(idim),
                nn.Linear(idim, attention_dim),
                nn.LayerNorm(attention_dim),
                nn.ReLU(),
小湉湉's avatar
小湉湉 已提交
352
                pos_enc_class(attention_dim, positional_dropout_rate))
P
pfZhu 已提交
353
            self.text_embed = nn.Sequential(
小湉湉's avatar
小湉湉 已提交
354 355 356
                nn.Embedding(
                    vocab_size, attention_dim, padding_idx=padding_idx),
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
357 358 359
        elif isinstance(input_layer, nn.Layer):
            self.embed = nn.Sequential(
                input_layer,
小湉湉's avatar
小湉湉 已提交
360
                pos_enc_class(attention_dim, positional_dropout_rate), )
P
pfZhu 已提交
361 362
        elif input_layer is None:
            self.embed = nn.Sequential(
小湉湉's avatar
小湉湉 已提交
363
                pos_enc_class(attention_dim, positional_dropout_rate))
P
pfZhu 已提交
364 365 366 367 368 369 370 371
        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
小湉湉 已提交
372 373
            encoder_selfattn_layer_args = (attention_heads, attention_dim,
                                           attention_dropout_rate, )
P
pfZhu 已提交
374 375 376
        elif selfattention_layer_type == "legacy_rel_selfattn":
            assert pos_enc_layer_type == "legacy_rel_pos"
            encoder_selfattn_layer = LegacyRelPositionMultiHeadedAttention
小湉湉's avatar
小湉湉 已提交
377 378
            encoder_selfattn_layer_args = (attention_heads, attention_dim,
                                           attention_dropout_rate, )
P
pfZhu 已提交
379
        elif selfattention_layer_type == "rel_selfattn":
小湉湉's avatar
小湉湉 已提交
380 381
            logging.info(
                "encoder self-attention layer type = relative self-attention")
P
pfZhu 已提交
382 383
            assert pos_enc_layer_type == "rel_pos"
            encoder_selfattn_layer = RelPositionMultiHeadedAttention
小湉湉's avatar
小湉湉 已提交
384 385
            encoder_selfattn_layer_args = (attention_heads, attention_dim,
                                           attention_dropout_rate, zero_triu, )
P
pfZhu 已提交
386
        else:
小湉湉's avatar
小湉湉 已提交
387 388
            raise ValueError("unknown encoder_attn_layer: " +
                             selfattention_layer_type)
P
pfZhu 已提交
389 390 391 392

        # feed-forward module definition
        if positionwise_layer_type == "linear":
            positionwise_layer = PositionwiseFeedForward
小湉湉's avatar
小湉湉 已提交
393 394
            positionwise_layer_args = (attention_dim, linear_units,
                                       dropout_rate, activation, )
P
pfZhu 已提交
395 396
        elif positionwise_layer_type == "conv1d":
            positionwise_layer = MultiLayeredConv1d
小湉湉's avatar
小湉湉 已提交
397 398 399
            positionwise_layer_args = (attention_dim, linear_units,
                                       positionwise_conv_kernel_size,
                                       dropout_rate, )
P
pfZhu 已提交
400 401
        elif positionwise_layer_type == "conv1d-linear":
            positionwise_layer = Conv1dLinear
小湉湉's avatar
小湉湉 已提交
402 403 404
            positionwise_layer_args = (attention_dim, linear_units,
                                       positionwise_conv_kernel_size,
                                       dropout_rate, )
P
pfZhu 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        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
小湉湉 已提交
423
                stochastic_depth_rate * float(1 + lnum) / num_blocks, ), )
P
pfZhu 已提交
424 425 426 427 428 429 430 431 432 433 434 435
        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
小湉湉 已提交
436
                stochastic_depth_rate * float(1 + lnum) / self.pre_speech_layer, ),
P
pfZhu 已提交
437 438 439 440 441 442
        )
        if self.normalize_before:
            self.after_norm = LayerNorm(attention_dim)

        self.intermediate_layers = intermediate_layers

小湉湉's avatar
小湉湉 已提交
443 444 445 446 447 448 449 450
    def forward(self,
                speech_pad,
                text_pad,
                masked_position,
                speech_mask=None,
                text_mask=None,
                speech_segment_pos=None,
                text_segment_pos=None):
P
pfZhu 已提交
451 452 453 454 455 456 457 458 459
        """Encode input sequence.

        """
        if masked_position is not None:
            speech_pad = self.speech_embed(speech_pad, masked_position)
        else:
            speech_pad = self.speech_embed(speech_pad)
        # pure speech input
        if -2 in np.array(text_pad):
小湉湉's avatar
小湉湉 已提交
460
            text_pad = text_pad + 3
P
pfZhu 已提交
461 462 463
            text_mask = paddle.unsqueeze(bool(text_pad), 1)
            text_segment_pos = paddle.zeros_like(text_pad)
            text_pad = self.text_embed(text_pad)
小湉湉's avatar
小湉湉 已提交
464 465 466
            text_pad = (text_pad[0] + self.segment_emb(text_segment_pos),
                        text_pad[1])
            text_segment_pos = None
P
pfZhu 已提交
467 468 469 470 471 472 473 474
        elif text_pad is not None:
            text_pad = self.text_embed(text_pad)
        segment_emb = None
        if speech_segment_pos is not None and text_segment_pos is not None and self.segment_emb:
            speech_segment_emb = self.segment_emb(speech_segment_pos)
            text_segment_emb = self.segment_emb(text_segment_pos)
            text_pad = (text_pad[0] + text_segment_emb, text_pad[1])
            speech_pad = (speech_pad[0] + speech_segment_emb, speech_pad[1])
小湉湉's avatar
小湉湉 已提交
475 476
            segment_emb = paddle.concat(
                [speech_segment_emb, text_segment_emb], axis=1)
P
pfZhu 已提交
477 478 479 480 481 482
        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
小湉湉 已提交
483
            masks = paddle.concat([speech_mask, text_mask], axis=-1)
P
pfZhu 已提交
484 485 486 487 488
        else:
            xs = speech_pad[0]
            xs_pos_emb = speech_pad[1]
            masks = speech_mask

小湉湉's avatar
小湉湉 已提交
489
        xs, masks = self.encoders((xs, xs_pos_emb), masks)
P
pfZhu 已提交
490 491 492 493 494 495

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

小湉湉's avatar
小湉湉 已提交
496
        return xs, masks  #, segment_emb
P
pfZhu 已提交
497 498 499


class MLMDecoder(MLMEncoder):
小湉湉's avatar
小湉湉 已提交
500
    def forward(self, xs, masks, masked_position=None, segment_emb=None):
P
pfZhu 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        """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).

        """
        emb, mlm_position = None, None
        if not self.training:
            masked_position = None
        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
小湉湉 已提交
525 526
                if (self.intermediate_layers is not None and
                        layer_idx + 1 in self.intermediate_layers):
P
pfZhu 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
                    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
小湉湉 已提交
542
def pad_to_longformer_att_window(text, max_len, max_tlen, attention_window):
P
pfZhu 已提交
543 544 545 546
    round = max_len % attention_window
    if round != 0:
        max_tlen += (attention_window - round)
        n_batch = paddle.shape(text)[0]
小湉湉's avatar
小湉湉 已提交
547 548 549
        text_pad = paddle.zeros(
            shape=(n_batch, max_tlen, *paddle.shape(text[0])[1:]),
            dtype=text.dtype)
P
pfZhu 已提交
550
        for i in range(n_batch):
小湉湉's avatar
小湉湉 已提交
551
            text_pad[i, :paddle.shape(text[i])[0]] = text[i]
P
pfZhu 已提交
552
    else:
小湉湉's avatar
小湉湉 已提交
553
        text_pad = text[:, :max_tlen]
P
pfZhu 已提交
554 555
    return text_pad, max_tlen

小湉湉's avatar
小湉湉 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578

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 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591

        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
小湉湉 已提交
592
                token_list, sym_space, sym_blank, report_cer, report_wer)
P
pfZhu 已提交
593 594 595 596 597 598
        else:
            self.error_calculator = None

        self.mlm_weight = 1.0
        self.mlm_prob = mlm_prob
        self.mlm_layer = 12
小湉湉's avatar
小湉湉 已提交
599
        self.finetune_wo_mlm = True
P
pfZhu 已提交
600 601 602 603
        self.max_span = 50
        self.min_span = 4
        self.mean_phn_span = mean_phn_span
        self.masking_schema = masking_schema
小湉湉's avatar
小湉湉 已提交
604 605 606
        if self.decoder is None or not (hasattr(self.decoder,
                                                'output_layer') and
                                        self.decoder.output_layer is not None):
P
pfZhu 已提交
607 608
            self.sfc = nn.Linear(self.encoder._output_size, odim)
        else:
小湉湉's avatar
小湉湉 已提交
609
            self.sfc = None
P
pfZhu 已提交
610
        if text_masking:
小湉湉's avatar
小湉湉 已提交
611 612 613 614
            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 已提交
615 616 617 618 619 620
            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
小湉湉 已提交
621
            self.l1_loss_func = nn.MSELoss()
P
pfZhu 已提交
622 623
        else:
            self.l1_loss_func = nn.L1Loss(reduction='none')
小湉湉's avatar
小湉湉 已提交
624 625 626 627 628 629 630 631
        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 已提交
632 633

    def collect_feats(self,
小湉湉's avatar
小湉湉 已提交
634 635 636 637 638 639 640 641 642 643
                      speech,
                      speech_lengths,
                      text,
                      text_lengths,
                      masked_position,
                      speech_mask,
                      text_mask,
                      speech_segment_pos,
                      text_segment_pos,
                      y_masks=None) -> Dict[str, paddle.Tensor]:
P
pfZhu 已提交
644 645
        return {"feats": speech, "feats_lengths": speech_lengths}

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

    def inference(
小湉湉's avatar
小湉湉 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
            self,
            speech,
            text,
            masked_position,
            speech_mask,
            text_mask,
            speech_segment_pos,
            text_segment_pos,
            span_boundary,
            y_masks=None,
            speech_lengths=None,
            text_lengths=None,
            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 已提交
699 700 701 702 703 704 705
        batch = dict(
            speech_pad=speech,
            text_pad=text,
            masked_position=masked_position,
            speech_mask=speech_mask,
            text_mask=text_mask,
            speech_segment_pos=speech_segment_pos,
小湉湉's avatar
小湉湉 已提交
706
            text_segment_pos=text_segment_pos, )
P
pfZhu 已提交
707 708 709 710

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

小湉湉's avatar
小湉湉 已提交
711
        outs = [batch['speech_pad'][:, :span_boundary[0]]]
P
pfZhu 已提交
712 713
        z_cache = None
        if use_teacher_forcing:
小湉湉's avatar
小湉湉 已提交
714
            before, zs, _, _ = self.forward(
P
pfZhu 已提交
715 716 717
                batch, speech_segment_pos, y_masks=y_masks)
            if zs is None:
                zs = before
小湉湉's avatar
小湉湉 已提交
718 719
            outs += [zs[0][span_boundary[0]:span_boundary[1]]]
            outs += [batch['speech_pad'][:, span_boundary[1]:]]
P
pfZhu 已提交
720
            return dict(feat_gen=outs)
小湉湉's avatar
小湉湉 已提交
721
        return None
P
pfZhu 已提交
722

小湉湉's avatar
小湉湉 已提交
723 724
    def _add_first_frame_and_remove_last_frame(
            self, ys: paddle.Tensor) -> paddle.Tensor:
P
pfZhu 已提交
725
        ys_in = paddle.concat(
小湉湉's avatar
小湉湉 已提交
726 727 728 729 730 731
            [
                paddle.zeros(
                    shape=(paddle.shape(ys)[0], 1, paddle.shape(ys)[2]),
                    dtype=ys.dtype), ys[:, :-1]
            ],
            axis=1)
P
pfZhu 已提交
732 733 734
        return ys_in


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


小湉湉's avatar
小湉湉 已提交
762 763 764 765 766 767
class MLMDualMaksingModel(MLMModel):
    def _calc_mlm_loss(self,
                       before_outs: paddle.Tensor,
                       after_outs: paddle.Tensor,
                       text_outs: paddle.Tensor,
                       batch):
P
pfZhu 已提交
768 769 770 771
        xs_pad = batch['speech_pad']
        text_pad = batch['text_pad']
        masked_position = batch['masked_position']
        text_masked_position = batch['text_masked_position']
小湉湉's avatar
小湉湉 已提交
772 773 774 775 776 777
        mlm_loss_position = masked_position > 0
        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 已提交
778
        if after_outs is not None:
小湉湉's avatar
小湉湉 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791
            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(
            mlm_loss_position, [-1]))) / paddle.sum((mlm_loss_position) + 1e-10)

        loss_text = paddle.sum((self.text_mlm_loss(
            paddle.reshape(text_outs, (-1, self.vocab_size)),
            paddle.reshape(text_pad, (-1))) * paddle.reshape(
                text_masked_position,
                (-1)))) / paddle.sum((text_masked_position) + 1e-10)
P
pfZhu 已提交
792 793
        return loss_mlm, loss_text

小湉湉's avatar
小湉湉 已提交
794
    def forward(self, batch, speech_segment_pos, y_masks=None):
P
pfZhu 已提交
795 796 797
        # feats: (Batch, Length, Dim)
        # -> encoder_out: (Batch, Length2, Dim2)
        speech_pad_placeholder = batch['speech_pad']
小湉湉's avatar
小湉湉 已提交
798
        encoder_out, h_masks = self.encoder(**batch)  # segment_emb
P
pfZhu 已提交
799 800 801 802
        if self.decoder is not None:
            zs, _ = self.decoder(encoder_out, h_masks)
        else:
            zs = encoder_out
小湉湉's avatar
小湉湉 已提交
803
        speech_hidden_states = zs[:, :paddle.shape(batch['speech_pad'])[1], :]
P
pfZhu 已提交
804
        if self.text_sfc:
小湉湉's avatar
小湉湉 已提交
805 806 807 808 809
            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 已提交
810
        if self.sfc is not None:
小湉湉's avatar
小湉湉 已提交
811 812 813
            before_outs = paddle.reshape(
                self.sfc(speech_hidden_states),
                (paddle.shape(speech_hidden_states)[0], -1, self.odim))
P
pfZhu 已提交
814 815 816
        else:
            before_outs = speech_hidden_states
        if self.postnet is not None:
小湉湉's avatar
小湉湉 已提交
817 818 819
            after_outs = before_outs + paddle.transpose(
                self.postnet(paddle.transpose(before_outs, [0, 2, 1])),
                [0, 2, 1])
P
pfZhu 已提交
820 821
        else:
            after_outs = None
小湉湉's avatar
小湉湉 已提交
822 823
        return before_outs, after_outs, text_outs, None  #, speech_pad_placeholder, batch['masked_position'],batch['text_masked_position']

P
pfZhu 已提交
824 825

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

P
pfZhu 已提交
827
    state_dict = paddle.load(model_file)
小湉湉's avatar
小湉湉 已提交
828 829
    model_class = MLMDualMaksingModel if 'conformer_combine_vctk_aishell3_dual_masking' in config_file \
        else MLMEncAsDecoderModel
P
pfZhu 已提交
830 831 832 833 834 835 836 837 838 839 840

    # 构建模型
    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
小湉湉 已提交
841 842
def build_model(args: argparse.Namespace,
                model_class=MLMEncAsDecoderModel) -> MLMModel:
P
pfZhu 已提交
843 844 845 846 847 848 849 850 851 852 853 854 855
    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
小湉湉 已提交
856
    odim = 80
P
pfZhu 已提交
857 858 859 860

    pos_enc_class = ScaledPositionalEncoding if args.use_scaled_pos_enc else PositionalEncoding

    if "conformer" == args.encoder:
小湉湉's avatar
小湉湉 已提交
861 862
        conformer_self_attn_layer_type = args.encoder_conf[
            'selfattention_layer_type']
P
pfZhu 已提交
863 864 865 866 867 868 869 870
        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
小湉湉 已提交
871
                    "please use conformer_pos_enc_layer_type = 'latest'.")
P
pfZhu 已提交
872 873 874 875 876 877
            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
小湉湉 已提交
878
                    "please use conformer_pos_enc_layer_type = 'latest'.")
P
pfZhu 已提交
879 880 881 882 883
        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
小湉湉 已提交
884 885 886 887 888 889 890 891
        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 已提交
892 893 894 895

    # Encoder
    encoder_class = MLMEncoder

小湉湉's avatar
小湉湉 已提交
896 897
    if 'text_masking' in args.model_conf.keys() and args.model_conf[
            'text_masking']:
P
pfZhu 已提交
898 899 900
        args.encoder_conf['text_masking'] = True
    else:
        args.encoder_conf['text_masking'] = False
小湉湉's avatar
小湉湉 已提交
901 902 903 904 905 906

    encoder = encoder_class(
        args.input_size,
        vocab_size=vocab_size,
        pos_enc_class=pos_enc_class,
        **args.encoder_conf)
P
pfZhu 已提交
907 908 909 910 911 912 913

    # Decoder
    if args.decoder != 'no_decoder':
        decoder_class = MLMDecoder
        decoder = decoder_class(
            idim=0,
            input_layer=None,
小湉湉's avatar
小湉湉 已提交
914
            **args.decoder_conf, )
P
pfZhu 已提交
915 916 917 918 919 920 921 922 923
    else:
        decoder = None

    # Build model
    model = model_class(
        odim=odim,
        encoder=encoder,
        decoder=decoder,
        token_list=token_list,
小湉湉's avatar
小湉湉 已提交
924
        **args.model_conf, )
P
pfZhu 已提交
925 926 927 928 929 930

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

    return model