lm_interface.py 2.5 KB
Newer Older
H
Hui Zhang 已提交
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
Hui Zhang 已提交
14
# Modified from espnet(https://github.com/espnet/espnet)
H
Hui Zhang 已提交
15 16 17
"""Language model interface."""
import argparse

18 19
from paddlespeech.s2t.decoders.scorers.scorer_interface import ScorerInterface
from paddlespeech.s2t.utils.dynamic_import import dynamic_import
H
Hui Zhang 已提交
20

H
Hui Zhang 已提交
21

H
Hui Zhang 已提交
22
class LMInterface(ScorerInterface):
H
Hui Zhang 已提交
23
    """LM Interface model implementation."""
H
Hui Zhang 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

    @staticmethod
    def add_arguments(parser):
        """Add arguments to command line argument parser."""
        return parser

    @classmethod
    def build(cls, n_vocab: int, **kwargs):
        """Initialize this class with python-level args.

        Args:
            idim (int): The number of vocabulary.

        Returns:
            LMinterface: A new instance of LMInterface.

        """
        args = argparse.Namespace(**kwargs)
        return cls(n_vocab, args)

    def forward(self, x, t):
        """Compute LM loss value from buffer sequences.

        Args:
            x (torch.Tensor): Input ids. (batch, len)
            t (torch.Tensor): Target ids. (batch, len)

        Returns:
            tuple[torch.Tensor, torch.Tensor, torch.Tensor]: Tuple of
                loss to backward (scalar),
                negative log-likelihood of t: -log p(t) (scalar) and
                the number of elements in x (scalar)

        Notes:
            The last two return values are used
            in perplexity: p(t)^{-n} = exp(-log p(t) / n)

        """
        raise NotImplementedError("forward method is not implemented")


predefined_lms = {
66
    "transformer": "paddlespeech.s2t.models.lm.transformer:TransformerLM",
H
Hui Zhang 已提交
67 68
}

H
Hui Zhang 已提交
69

H
Hui Zhang 已提交
70 71 72 73 74 75 76 77 78 79 80
def dynamic_import_lm(module):
    """Import LM class dynamically.

    Args:
        module (str): module_name:class_name or alias in `predefined_lms`

    Returns:
        type: LM class

    """
    model_class = dynamic_import(module, predefined_lms)
H
Hui Zhang 已提交
81 82
    assert issubclass(model_class,
                      LMInterface), f"{module} does not implement LMInterface"
H
Hui Zhang 已提交
83
    return model_class