module.py 7.8 KB
Newer Older
K
KP 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# Copyright (c) 2020 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.
from typing import Dict
import os

import paddle
import paddle.nn as nn
import paddle.nn.functional as F

from paddlenlp.transformers.electra.modeling import ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel
from paddlenlp.transformers.electra.tokenizer import ElectraTokenizer
from paddlenlp.metrics import ChunkEvaluator
from paddlehub.module.module import moduleinfo
from paddlehub.module.nlp_module import TransformerModule
from paddlehub.utils.log import logger


@moduleinfo(
    name="electra-small",
31
    version="1.0.1",
W
wuzewu 已提交
32
    summary="electra-small, 12-layer, 256-hidden, 4-heads, 14M parameters. The module is executed as paddle.dygraph.",
K
KP 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    author="paddlepaddle",
    author_email="",
    type="nlp/semantic_model",
    meta=TransformerModule,
)
class Electra(nn.Layer):
    """
    Electra model
    """

    def __init__(
            self,
            task: str = None,
            load_checkpoint: str = None,
            label_map: Dict = None,
            num_classes: int = 2,
L
linjieccc 已提交
49
            suffix: bool = False,
K
KP 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62
            **kwargs,
    ):
        super(Electra, self).__init__()
        if label_map:
            self.label_map = label_map
            self.num_classes = len(label_map)
        else:
            self.num_classes = num_classes

        if task == 'sequence_classification':
            task = 'seq-cls'
            logger.warning(
                "current task name 'sequence_classification' was renamed to 'seq-cls', "
W
wuzewu 已提交
63
                "'sequence_classification' has been deprecated and will be removed in the future.", )
K
KP 已提交
64 65
        if task == 'seq-cls':
            self.model = ElectraForSequenceClassification.from_pretrained(
W
wuzewu 已提交
66
                pretrained_model_name_or_path='electra-small', num_classes=self.num_classes, **kwargs)
K
KP 已提交
67 68 69 70
            self.criterion = paddle.nn.loss.CrossEntropyLoss()
            self.metric = paddle.metric.Accuracy()
        elif task == 'token-cls':
            self.model = ElectraForTokenClassification.from_pretrained(
W
wuzewu 已提交
71
                pretrained_model_name_or_path='electra-small', num_classes=self.num_classes, **kwargs)
K
KP 已提交
72
            self.criterion = paddle.nn.loss.CrossEntropyLoss()
L
linjieccc 已提交
73
            self.metric = ChunkEvaluator(label_list=[self.label_map[i] for i in sorted(self.label_map.keys())], suffix=suffix)
74 75 76
        elif task == 'text-matching':
            self.model = ElectraModel.from_pretrained(pretrained_model_name_or_path='electra-small', **kwargs)
            self.dropout = paddle.nn.Dropout(0.1)
W
wuzewu 已提交
77
            self.classifier = paddle.nn.Linear(self.model.config['hidden_size'] * 3, 2)
78 79
            self.criterion = paddle.nn.loss.CrossEntropyLoss()
            self.metric = paddle.metric.Accuracy()
K
KP 已提交
80 81 82
        elif task is None:
            self.model = ElectraModel.from_pretrained(pretrained_model_name_or_path='electra-small', **kwargs)
        else:
W
wuzewu 已提交
83
            raise RuntimeError("Unknown task {}, task should be one in {}".format(task, self._tasks_supported))
K
KP 已提交
84 85 86 87 88 89 90 91

        self.task = task

        if load_checkpoint is not None and os.path.isfile(load_checkpoint):
            state_dict = paddle.load(load_checkpoint)
            self.set_state_dict(state_dict)
            logger.info('Loaded parameters from %s' % os.path.abspath(load_checkpoint))

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    def forward(self,
                input_ids=None,
                token_type_ids=None,
                position_ids=None,
                attention_mask=None,
                query_input_ids=None,
                query_token_type_ids=None,
                query_position_ids=None,
                query_attention_mask=None,
                title_input_ids=None,
                title_token_type_ids=None,
                title_position_ids=None,
                title_attention_mask=None,
                seq_lengths=None,
                labels=None):

        if self.task != 'text-matching':
            result = self.model(input_ids, token_type_ids, position_ids, attention_mask)
        else:
            query_result = self.model(query_input_ids, query_token_type_ids, query_position_ids, query_attention_mask)
            title_result = self.model(title_input_ids, title_token_type_ids, title_position_ids, title_attention_mask)

K
KP 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        if self.task == 'seq-cls':
            logits = result
            probs = F.softmax(logits, axis=1)
            if labels is not None:
                loss = self.criterion(logits, labels)
                correct = self.metric.compute(probs, labels)
                acc = self.metric.update(correct)
                return probs, loss, {'acc': acc}
            return probs
        elif self.task == 'token-cls':
            logits = result
            token_level_probs = F.softmax(logits, axis=-1)
            preds = token_level_probs.argmax(axis=-1)
            if labels is not None:
                loss = self.criterion(logits, labels.unsqueeze(-1))
                num_infer_chunks, num_label_chunks, num_correct_chunks = \
                    self.metric.compute(None, seq_lengths, preds, labels)
W
wuzewu 已提交
131
                self.metric.update(num_infer_chunks.numpy(), num_label_chunks.numpy(), num_correct_chunks.numpy())
K
KP 已提交
132 133 134
                _, _, f1_score = map(float, self.metric.accumulate())
                return token_level_probs, loss, {'f1_score': f1_score}
            return token_level_probs
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
        elif self.task == 'text-matching':
            query_token_embedding = query_result
            query_token_embedding = self.dropout(query_token_embedding)
            query_attention_mask = paddle.unsqueeze(
                (query_input_ids != self.model.pad_token_id).astype(query_token_embedding.dtype), axis=2)
            query_token_embedding = query_token_embedding * query_attention_mask
            query_sum_embedding = paddle.sum(query_token_embedding, axis=1)
            query_sum_mask = paddle.sum(query_attention_mask, axis=1)
            query_mean = query_sum_embedding / query_sum_mask

            title_token_embedding = title_result
            title_token_embedding = self.dropout(title_token_embedding)
            title_attention_mask = paddle.unsqueeze(
                (title_input_ids != self.model.pad_token_id).astype(title_token_embedding.dtype), axis=2)
            title_token_embedding = title_token_embedding * title_attention_mask
            title_sum_embedding = paddle.sum(title_token_embedding, axis=1)
            title_sum_mask = paddle.sum(title_attention_mask, axis=1)
            title_mean = title_sum_embedding / title_sum_mask

            sub = paddle.abs(paddle.subtract(query_mean, title_mean))
            projection = paddle.concat([query_mean, title_mean, sub], axis=-1)
            logits = self.classifier(projection)
            probs = F.softmax(logits)
            if labels is not None:
                loss = self.criterion(logits, labels)
                correct = self.metric.compute(probs, labels)
                acc = self.metric.update(correct)
                return probs, loss, {'acc': acc}
            return probs
K
KP 已提交
164 165 166 167 168 169 170 171 172
        else:
            sequence_output, pooled_output = result
            return sequence_output, pooled_output

    @staticmethod
    def get_tokenizer(*args, **kwargs):
        """
        Gets the tokenizer that is customized for this module.
        """
W
wuzewu 已提交
173
        return ElectraTokenizer.from_pretrained(pretrained_model_name_or_path='electra-small', *args, **kwargs)