ernie.py 9.1 KB
Newer Older
X
xixiaoyao 已提交
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
# -*- coding: UTF-8 -*-
#   Copyright (c) 2019 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.
"""Ernie model."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

from paddle import fluid
from paddle.fluid import layers

from paddlepalm.backbone.utils.transformer import pre_process_layer, encoder
X
xixiaoyao 已提交
27
from paddlepalm.backbone.base_backbone import BaseBackbone
X
xixiaoyao 已提交
28 29


X
xixiaoyao 已提交
30 31 32 33 34
class ERNIE(BaseBackbone):
    
    def __init__(self, hidden_size, num_hidden_layers, num_attention_heads, vocab_size, \
          max_position_embeddings, sent_type_vocab_size, task_type_vocab_size, \
          hidden_act, hidden_dropout_prob, attention_probs_dropout_prob, initializer_range, phase='train'):
X
xixiaoyao 已提交
35 36 37

        # self._is_training = phase == 'train' # backbone一般不用关心运行阶段,因为outputs在任何阶段基本不会变

X
xixiaoyao 已提交
38 39 40 41 42 43
        self._emb_size = hidden_size
        self._n_layer = num_hidden_layers
        self._n_head = num_attention_heads
        self._voc_size = vocab_size
        self._max_position_seq_len = max_position_embeddings
        self._sent_types = sent_type_vocab_size
X
xixiaoyao 已提交
44

X
xixiaoyao 已提交
45
        self._task_types = task_type_vocab_size
X
xixiaoyao 已提交
46

X
xixiaoyao 已提交
47 48 49
        self._hidden_act = hidden_act
        self._prepostprocess_dropout = hidden_dropout_prob
        self._attention_dropout = attention_probs_dropout_prob
X
xixiaoyao 已提交
50 51 52 53 54 55 56 57

        self._word_emb_name = "word_embedding"
        self._pos_emb_name = "pos_embedding"
        self._sent_emb_name = "sent_embedding"
        self._task_emb_name = "task_embedding"
        self._emb_dtype = "float32"

        self._param_initializer = fluid.initializer.TruncatedNormal(
X
xixiaoyao 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
            scale=initializer_range)

    @classmethod
    def from_config(cls, config, phase='train'):
        assert 'hidden_size' in config, "{} is required to initialize ERNIE".format('hidden_size')
        assert 'num_hidden_layers' in config, "{} is required to initialize ERNIE".format('num_hidden_layers')
        assert 'num_attention_heads' in config, "{} is required to initialize ERNIE".format('num_attention_heads')
        assert 'vocab_size' in config, "{} is required to initialize ERNIE".format('vocab_size')
        assert 'max_position_embeddings' in config, "{} is required to initialize ERNIE".format('max_position_embeddings')
        assert 'sent_type_vocab_size' in config or 'type_vocab_size' in config, "{} is required to initialize ERNIE".format('sent_type_vocab_size')
        assert 'task_type_vocab_size' in config, "{} is required to initialize ERNIE".format('task_type_vocab_size')
        assert 'hidden_act' in config, "{} is required to initialize ERNIE".format('hidden_act')
        assert 'hidden_dropout_prob' in config, "{} is required to initialize ERNIE".format('hidden_dropout_prob')
        assert 'attention_probs_dropout_prob' in config, "{} is required to initialize ERNIE".format('attention_probs_dropout_prob')
        assert 'initializer_range' in config, "{} is required to initialize ERNIE".format('initializer_range')

        hidden_size = config['hidden_size']
        num_hidden_layers = config['num_hidden_layers']
        num_attention_heads = config['num_attention_heads']
        vocab_size = config['vocab_size']
        max_position_embeddings = config['max_position_embeddings']
        if 'sent_type_vocab_size' in config:
            sent_type_vocab_size = config['sent_type_vocab_size']
        else:
            sent_type_vocab_size = config['type_vocab_size']
        task_type_vocab_size = config['task_type_vocab_size']
        hidden_act = config['hidden_act']
        hidden_dropout_prob = config['hidden_dropout_prob']
        attention_probs_dropout_prob = config['attention_probs_dropout_prob']
        initializer_range = config['initializer_range']
        
        return cls(hidden_size, num_hidden_layers, num_attention_heads, vocab_size, \
          max_position_embeddings, sent_type_vocab_size, task_type_vocab_size, \
          hidden_act, hidden_dropout_prob, attention_probs_dropout_prob, initializer_range, phase=phase)
X
xixiaoyao 已提交
92 93 94

    @property
    def inputs_attr(self):
X
xixiaoyao 已提交
95 96 97
        return {"token_ids": [[-1, -1], 'int64'],
                "position_ids": [[-1, -1], 'int64'],
                "segment_ids": [[-1, -1], 'int64'],
X
xixiaoyao 已提交
98
                "input_mask": [[-1, -1, 1], 'float32'],
X
xixiaoyao 已提交
99
                "task_ids": [[-1,-1], 'int64']}
X
xixiaoyao 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

    @property
    def outputs_attr(self):
        return {"word_embedding": [[-1, -1, self._emb_size], 'float32'],
                "embedding_table": [[-1, self._voc_size, self._emb_size], 'float32'],
                "encoder_outputs": [[-1, -1, self._emb_size], 'float32'],
                "sentence_embedding": [[-1, self._emb_size], 'float32'],
                "sentence_pair_embedding": [[-1, self._emb_size], 'float32']}

    def build(self, inputs, scope_name=""):

        src_ids = inputs['token_ids']
        pos_ids = inputs['position_ids']
        sent_ids = inputs['segment_ids']
        input_mask = inputs['input_mask']
        task_ids = inputs['task_ids']

        # padding id in vocabulary must be set to 0
X
xixiaoyao 已提交
118
        emb_out = fluid.embedding(
X
xixiaoyao 已提交
119 120 121 122 123 124 125 126 127 128
            input=src_ids,
            size=[self._voc_size, self._emb_size],
            dtype=self._emb_dtype,
            param_attr=fluid.ParamAttr(
                name=scope_name+self._word_emb_name, initializer=self._param_initializer),
            is_sparse=False)

        # fluid.global_scope().find_var('backbone-word_embedding').get_tensor()
        embedding_table = fluid.default_main_program().global_block().var(scope_name+self._word_emb_name)
        
X
xixiaoyao 已提交
129
        position_emb_out = fluid.embedding(
X
xixiaoyao 已提交
130 131 132 133 134 135
            input=pos_ids,
            size=[self._max_position_seq_len, self._emb_size],
            dtype=self._emb_dtype,
            param_attr=fluid.ParamAttr(
                name=scope_name+self._pos_emb_name, initializer=self._param_initializer))

X
xixiaoyao 已提交
136
        sent_emb_out = fluid.embedding(
X
xixiaoyao 已提交
137 138 139 140 141 142 143 144 145
            sent_ids,
            size=[self._sent_types, self._emb_size],
            dtype=self._emb_dtype,
            param_attr=fluid.ParamAttr(
                name=scope_name+self._sent_emb_name, initializer=self._param_initializer))

        emb_out = emb_out + position_emb_out
        emb_out = emb_out + sent_emb_out

X
xixiaoyao 已提交
146
        task_emb_out = fluid.embedding(
X
xixiaoyao 已提交
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 202 203 204 205
            task_ids,
            size=[self._task_types, self._emb_size],
            dtype=self._emb_dtype,
            param_attr=fluid.ParamAttr(
                name=scope_name+self._task_emb_name,
                initializer=self._param_initializer))

        emb_out = emb_out + task_emb_out

        emb_out = pre_process_layer(
            emb_out, 'nd', self._prepostprocess_dropout, name=scope_name+'pre_encoder')

        self_attn_mask = fluid.layers.matmul(
            x=input_mask, y=input_mask, transpose_y=True)

        self_attn_mask = fluid.layers.scale(
            x=self_attn_mask, scale=10000.0, bias=-1.0, bias_after_scale=False)
        n_head_self_attn_mask = fluid.layers.stack(
            x=[self_attn_mask] * self._n_head, axis=1)
        n_head_self_attn_mask.stop_gradient = True

        enc_out = encoder(
            enc_input=emb_out,
            attn_bias=n_head_self_attn_mask,
            n_layer=self._n_layer,
            n_head=self._n_head,
            d_key=self._emb_size // self._n_head,
            d_value=self._emb_size // self._n_head,
            d_model=self._emb_size,
            d_inner_hid=self._emb_size * 4,
            prepostprocess_dropout=self._prepostprocess_dropout,
            attention_dropout=self._attention_dropout,
            relu_dropout=0,
            hidden_act=self._hidden_act,
            preprocess_cmd="",
            postprocess_cmd="dan",
            param_initializer=self._param_initializer,
            name=scope_name+'encoder')

        
        next_sent_feat = fluid.layers.slice(
            input=enc_out, axes=[1], starts=[0], ends=[1])
        next_sent_feat = fluid.layers.reshape(next_sent_feat, [-1, next_sent_feat.shape[-1]])
        next_sent_feat = fluid.layers.fc(
            input=next_sent_feat,
            size=self._emb_size,
            act="tanh",
            param_attr=fluid.ParamAttr(
                name=scope_name+"pooled_fc.w_0", initializer=self._param_initializer),
            bias_attr=scope_name+"pooled_fc.b_0")

        return {'embedding_table': embedding_table,
                'word_embedding': emb_out,
                'encoder_outputs': enc_out,
                'sentence_embedding': next_sent_feat,
                'sentence_pair_embedding': next_sent_feat}

    def postprocess(self, rt_outputs):
        pass
X
xixiaoyao 已提交
206 207 208 209 210 211 212 213 214



class Model(ERNIE):

    def __init__(self, config, phase):
        ERNIE.from_config(config, phase=phase)