network.py 12.3 KB
Newer Older
P
Peng Li 已提交
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 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 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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 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 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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
import math
import paddle.v2 as pd

import reader

__all__ = ["training_net", "inference_net", "feeding"]

feeding = {reader.Q_IDS_STR:reader.Q_IDS,
           reader.E_IDS_STR:reader.E_IDS,
           reader.QE_COMM_STR:reader.QE_COMM,
           reader.EE_COMM_STR:reader.EE_COMM,
           reader.LABELS_STR:reader.LABELS}

def get_embedding(name, input, word_vec_dim, wordvecs):
    """
    Defined word embedding
    
    :param name: layer name
    :type name: str
    :param input: layer input
    :type input: LayerOutput
    :param word_vec_dim: dimension of the word embeddings
    :type word_vec_dim: int
    :param wordvecs: word embedding matrix
    :type wordvecs: numpy array
    :return: embedding
    :rtype: LayerOutput
    """
    return pd.layer.embedding(
                name=name,
                input=input,
                size=word_vec_dim,
                param_attr=pd.attr.ParamAttr(name="wordvecs",
                                             is_static=True,
                                             initializer=lambda _:wordvecs))

def encoding_question(question,
                      q_lstm_dim,
                      latent_chain_dim,
                      word_vec_dim,
                      drop_rate,
                      wordvecs,
                      default_init_std,
                      default_l2_rate):
    """
    Define network for encoding question

    :param question: question token ids
    :type question: LayerOutput
    :param q_lstm_dim: dimension of the question LSTM
    :type q_lstm_dim: int
    :param latent_chain_dim: dimension of the attention layer
    :type latent_chain_dim: int
    :param word_vec_dim: dimension of the word embeddings
    :type word_vec_dim: int
    :param drop_rate: dropout rate
    :type drop_rate: float
    :param wordvecs: word embedding matrix
    :type wordvecs: numpy array
    :param default_init_std: default initial std
    :type default_init_std: float
    :param default_l2_rate: default l2 rate
    :type default_l2_rate: float
    :return: question encoding
    :rtype: LayerOutput
    """
    # word embedding
    emb = get_embedding("question_embedding", question, word_vec_dim, wordvecs)

    # question LSTM
    wx = pd.layer.fc(name="q_hidden1",
                     act=pd.activation.Linear(),
                     size=q_lstm_dim * 4,
                     input=emb,
                     param_attr=pd.attr.ParamAttr(name="_q_hidden1.w0",
                                                  initial_std=default_init_std,
                                                  l2_rate=default_l2_rate),
                     bias_attr=pd.attr.ParamAttr(name="_q_hidden1.wbias",
                                                 initial_std=0,
                                                 l2_rate=default_l2_rate))
    q_rnn = pd.layer.lstmemory(
                    name="q_rnn1",
                    input=wx,
                    bias_attr=pd.attr.ParamAttr(name="_q_rnn1.wbias",
                                                initial_std=0,
                                                l2_rate=default_l2_rate),
                    param_attr=pd.attr.ParamAttr(name="_q_rnn1.w0",
                                                 initial_std=default_init_std,
                                                 l2_rate=default_l2_rate))
    q_rnn = pd.layer.dropout(q_rnn, drop_rate)

    # self attention
    fc = pd.layer.fc(name="attention_layer1",
                     act=pd.activation.Tanh(),
                     size=latent_chain_dim,
                     input=q_rnn,
                     param_attr=pd.attr.ParamAttr(name="_attention_layer1.w0",
                                                  initial_std=default_init_std,
                                                  l2_rate=default_l2_rate),
                     bias_attr=False)
    weight = pd.layer.fc(name="attention_weight",
                         size=1,
                         act=pd.activation.SequenceSoftmax(),
                         input=fc,
                         param_attr=pd.attr.ParamAttr(
                             name="_attention_weight.w0",
                             initial_std=default_init_std,
                             l2_rate=default_l2_rate),
                         bias_attr=False)

    scaled_q_rnn = pd.layer.scaling(input=q_rnn, weight=weight)

    q_encoding = pd.layer.pooling(input=scaled_q_rnn,
                                  pooling_type=pd.pooling.Sum())
    return q_encoding

def encoding_evidence(evidence,
                      qe_comm,
                      ee_comm,
                      q_encoding,
                      e_lstm_dim,
                      word_vec_dim,
                      com_vec_dim,
                      drop_rate,
                      wordvecs,
                      default_init_std,
                      default_l2_rate):
    """
    Define network for encoding evidence

    :param qe_comm: qe.ecomm features
    :type qe_comm: LayerOutput
    :param ee_comm: ee.ecomm features
    :type ee_comm: LayerOutput
    :param q_encoding: question encoding, a fixed-length vector
    :type q_encoding: LayerOutput
    :param e_lstm_dim: dimension of the evidence LSTMs
    :type e_lstm_dim: int
    :param word_vec_dim: dimension of the word embeddings
    :type word_vec_dim: int
    :param com_vec_dim: dimension of the qe.comm and ee.comm feature embeddings
    :type com_vec_dim: int
    :param drop_rate: dropout rate
    :type drop_rate: float
    :param wordvecs: word embedding matrix
    :type wordvecs: numpy array
    :param default_init_std: default initial std
    :type default_init_std: float
    :param default_l2_rate: default l2 rate
    :type default_l2_rate: float
    :return: evidence encoding
    :rtype: LayerOutput
    """
    def lstm(idx, reverse, inputs):
        """LSTM wrapper"""
        bias_attr = pd.attr.ParamAttr(name="_e_hidden%d.wbias" % idx,
                                      initial_std=0,
                                      l2_rate=default_l2_rate)
        with pd.layer.mixed(name="e_hidden%d" % idx,
                            size=e_lstm_dim * 4,
                            bias_attr=bias_attr) as wx:
            for i, input in enumerate(inputs):
                param_attr=pd.attr.ParamAttr(name="_e_hidden%d.w%d" % (idx, i),
                                             initial_std=default_init_std,
                                             l2_rate=default_l2_rate)
                wx += pd.layer.full_matrix_projection(
                        input=input, param_attr=param_attr)
        
        e_rnn = pd.layer.lstmemory(
                    name="e_rnn%d" % idx,
                    input=wx,
                    reverse=reverse,
                    bias_attr=pd.attr.ParamAttr(name="_e_rnn%d.wbias" % idx,
                                                initial_std=0,
                                                l2_rate=default_l2_rate),
                    param_attr=pd.attr.ParamAttr(name="_e_rnn%d.w0" % idx,
                                                 initial_std=default_init_std,
                                                 l2_rate=default_l2_rate))
        e_rnn = pd.layer.dropout(e_rnn, drop_rate)
        return e_rnn

    # share word embeddings with question
    emb = get_embedding("evidence_embedding", evidence, word_vec_dim, wordvecs)

    # copy q_encoding len(evidence) times
    q_encoding_expand = pd.layer.expand(input=q_encoding, expand_as=evidence)

    # feature embeddings
    comm_initial_std = 1/math.sqrt(64.0)
    qe_comm_emb = pd.layer.embedding(
                    name="qe_comm",
                    input=qe_comm,
                    size=com_vec_dim,
                    param_attr=pd.attr.ParamAttr(name="_cw_embedding.w0",
                                                 initial_std=comm_initial_std,
                                                 l2_rate=default_l2_rate))

    ee_comm_emb = pd.layer.embedding(
                    name="ee_comm",
                    input=ee_comm,
                    size=com_vec_dim,
                    param_attr=pd.attr.ParamAttr(name="_eecom_embedding.w0",
                                                 initial_std=comm_initial_std,
                                                 l2_rate=default_l2_rate))

    # evidence LSTMs
    first_layer_extra_inputs = [q_encoding_expand, qe_comm_emb, ee_comm_emb]
    e_rnn1 = lstm(1, False, [emb] + first_layer_extra_inputs)
    e_rnn2 = lstm(2, True,  [e_rnn1])
    e_rnn3 = lstm(3, False, [e_rnn2, e_rnn1]) # with cross layer links

    return e_rnn3

def define_data(dict_dim, label_num):
    """
    Define data layers

    :param dict_dim: number of words in the vocabulary
    :type dict_dim: int
    :param label_num: label numbers, BIO:3, BIO2:4
    :type label_num: int
    :return: data layers
    :rtype: tuple of LayerOutput
    """
    question = pd.layer.data(
                    name=reader.Q_IDS_STR,
                    type=pd.data_type.integer_value_sequence(dict_dim))

    evidence = pd.layer.data(
                    name=reader.E_IDS_STR,
                    type=pd.data_type.integer_value_sequence(dict_dim))

    qe_comm = pd.layer.data(
                    name=reader.QE_COMM_STR,
                    type=pd.data_type.integer_value_sequence(2))

    ee_comm = pd.layer.data(
                    name=reader.EE_COMM_STR,
                    type=pd.data_type.integer_value_sequence(2))

    label = pd.layer.data(
                    name=reader.LABELS_STR,
                    type=pd.data_type.integer_value_sequence(label_num),
                    layer_attr=pd.attr.ExtraAttr(device=-1))

    return question, evidence, qe_comm, ee_comm, label

def define_common_network(conf):
    """
    Define common network

    :param conf: network conf
    :return: CRF features, golden labels
    :rtype: tuple
    """
    # define data layers
    question, evidence, qe_comm, ee_comm, label = \
            define_data(conf.dict_dim, conf.label_num)
    
    # encode question
    q_encoding = encoding_question(question,
                                   conf.q_lstm_dim,
                                   conf.latent_chain_dim,
                                   conf.word_vec_dim,
                                   conf.drop_rate,
                                   conf.wordvecs,
                                   conf.default_init_std,
                                   conf.default_l2_rate)

    # encode evidence
    e_encoding = encoding_evidence(evidence,
                                   qe_comm,
                                   ee_comm,
                                   q_encoding,
                                   conf.e_lstm_dim,
                                   conf.word_vec_dim,
                                   conf.com_vec_dim,
                                   conf.drop_rate,
                                   conf.wordvecs,
                                   conf.default_init_std,
                                   conf.default_l2_rate)

    # pre-compute CRF features
    crf_feats = pd.layer.fc(name="output",
                            act=pd.activation.Linear(),
                            input=e_encoding,
                            size=conf.label_num,
                            param_attr=pd.attr.ParamAttr(
                                name="_output.w0",
                                initial_std=conf.default_init_std,
                                l2_rate=conf.default_l2_rate),
                            bias_attr=False)
    return crf_feats, label

def training_net(conf):
    """
    Define training network

    :param conf: network conf
    :return: CRF cost
    :rtype: LayerOutput
    """
    e_encoding, label = define_common_network(conf)
    crf = pd.layer.crf(
            input=e_encoding,
            label=label,
            size=conf.label_num,
            param_attr=pd.attr.ParamAttr(
                name="_crf.w0",
                initial_std=conf.default_init_std,
                l2_rate=conf.default_l2_rate),
            layer_attr=pd.attr.ExtraAttr(device=-1))

    return crf

def inference_net(conf):
    """
    Define training network

    :param conf: network conf
    :return: CRF viberbi decoding result
    :rtype: LayerOutput
    """
    e_encoding, label = define_common_network(conf)
    ret = pd.layer.crf_decoding(
            input=e_encoding,
            size=conf.label_num,
            param_attr=pd.attr.ParamAttr(name="_crf.w0"),
            layer_attr=pd.attr.ExtraAttr(device=-1))

    return ret