scorer_interface.py 6.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
"""Scorer interface module."""
H
Hui Zhang 已提交
16
import warnings
H
Hui Zhang 已提交
17 18 19 20 21 22 23 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
from typing import Any
from typing import List
from typing import Tuple

import paddle


class ScorerInterface:
    """Scorer interface for beam search.

    The scorer performs scoring of the all tokens in vocabulary.

    Examples:
        * Search heuristics
            * :class:`scorers.length_bonus.LengthBonus`
        * Decoder networks of the sequence-to-sequence models
            * :class:`transformer.decoder.Decoder`
            * :class:`rnn.decoders.Decoder`
        * Neural language models
            * :class:`lm.transformer.TransformerLM`
            * :class:`lm.default.DefaultRNNLM`
            * :class:`lm.seq_rnn.SequentialRNNLM`

    """

    def init_state(self, x: paddle.Tensor) -> Any:
        """Get an initial state for decoding (optional).

        Args:
            x (paddle.Tensor): The encoded feature tensor

        Returns: initial state

        """
        return None

H
Hui Zhang 已提交
53
    def select_state(self, state: Any, i: int, new_id: int=None) -> Any:
H
Hui Zhang 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66
        """Select state with relative ids in the main beam search.

        Args:
            state: Decoder state for prefix tokens
            i (int): Index to select a state in the main beam search
            new_id (int): New label index to select a state if necessary

        Returns:
            state: pruned state

        """
        return None if state is None else state[i]

H
Hui Zhang 已提交
67 68
    def score(self, y: paddle.Tensor, state: Any,
              x: paddle.Tensor) -> Tuple[paddle.Tensor, Any]:
H
Hui Zhang 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        """Score new token (required).

        Args:
            y (paddle.Tensor): 1D paddle.int64 prefix tokens.
            state: Scorer state for prefix tokens
            x (paddle.Tensor): The encoder feature that generates ys.

        Returns:
            tuple[paddle.Tensor, Any]: Tuple of
                scores for next token that has a shape of `(n_vocab)`
                and next state for ys

        """
        raise NotImplementedError

    def final_score(self, state: Any) -> float:
        """Score eos (optional).

        Args:
            state: Scorer state for prefix tokens

        Returns:
            float: final score

        """
        return 0.0


class BatchScorerInterface(ScorerInterface):
    """Batch scorer interface."""

    def batch_init_state(self, x: paddle.Tensor) -> Any:
        """Get an initial state for decoding (optional).

        Args:
            x (paddle.Tensor): The encoded feature tensor

        Returns: initial state

        """
        return self.init_state(x)

H
Hui Zhang 已提交
111 112 113 114
    def batch_score(self,
                    ys: paddle.Tensor,
                    states: List[Any],
                    xs: paddle.Tensor) -> Tuple[paddle.Tensor, List[Any]]:
H
Hui Zhang 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        """Score new token batch (required).

        Args:
            ys (paddle.Tensor): paddle.int64 prefix tokens (n_batch, ylen).
            states (List[Any]): Scorer states for prefix tokens.
            xs (paddle.Tensor):
                The encoder feature that generates ys (n_batch, xlen, n_feat).

        Returns:
            tuple[paddle.Tensor, List[Any]]: Tuple of
                batchfied scores for next token with shape of `(n_batch, n_vocab)`
                and next state list for ys.

        """
        warnings.warn(
H
Hui Zhang 已提交
130 131
            "{} batch score is implemented through for loop not parallelized".
            format(self.__class__.__name__))
H
Hui Zhang 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        scores = list()
        outstates = list()
        for i, (y, state, x) in enumerate(zip(ys, states, xs)):
            score, outstate = self.score(y, state, x)
            outstates.append(outstate)
            scores.append(score)
        scores = paddle.cat(scores, 0).view(ys.shape[0], -1)
        return scores, outstates


class PartialScorerInterface(ScorerInterface):
    """Partial scorer interface for beam search.

    The partial scorer performs scoring when non-partial scorer finished scoring,
    and receives pre-pruned next tokens to score because it is too heavy to score
    all the tokens.

H
Hui Zhang 已提交
149 150
    Score sub-set of tokens, not all.

H
Hui Zhang 已提交
151 152
    Examples:
         * Prefix search for connectionist-temporal-classification models
H
Hui Zhang 已提交
153
             * :class:`decoders.scorers.ctc.CTCPrefixScorer`
H
Hui Zhang 已提交
154 155 156

    """

H
Hui Zhang 已提交
157 158 159 160 161
    def score_partial(self,
                      y: paddle.Tensor,
                      next_tokens: paddle.Tensor,
                      state: Any,
                      x: paddle.Tensor) -> Tuple[paddle.Tensor, Any]:
H
Hui Zhang 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
        """Score new token (required).

        Args:
            y (paddle.Tensor): 1D prefix token
            next_tokens (paddle.Tensor): paddle.int64 next token to score
            state: decoder state for prefix tokens
            x (paddle.Tensor): The encoder feature that generates ys

        Returns:
            tuple[paddle.Tensor, Any]:
                Tuple of a score tensor for y that has a shape `(len(next_tokens),)`
                and next state for ys

        """
        raise NotImplementedError


class BatchPartialScorerInterface(BatchScorerInterface, PartialScorerInterface):
    """Batch partial scorer interface for beam search."""

    def batch_score_partial(
H
Hui Zhang 已提交
183 184 185 186 187
            self,
            ys: paddle.Tensor,
            next_tokens: paddle.Tensor,
            states: List[Any],
            xs: paddle.Tensor, ) -> Tuple[paddle.Tensor, Any]:
H
Hui Zhang 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        """Score new token (required).

        Args:
            ys (paddle.Tensor): paddle.int64 prefix tokens (n_batch, ylen).
            next_tokens (paddle.Tensor): paddle.int64 tokens to score (n_batch, n_token).
            states (List[Any]): Scorer states for prefix tokens.
            xs (paddle.Tensor):
                The encoder feature that generates ys (n_batch, xlen, n_feat).

        Returns:
            tuple[paddle.Tensor, Any]:
                Tuple of a score tensor for ys that has a shape `(n_batch, n_vocab)`
                and next states for ys
        """
        raise NotImplementedError