model.py 15.4 KB
Newer Older
R
ranqiu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#coding=utf-8

import math

import paddle.v2 as paddle

__all__ = ["conv_seq2seq"]


def gated_conv_with_batchnorm(input,
                              size,
                              context_len,
                              context_start=None,
                              learning_rate=1.0,
R
ranqiu 已提交
15 16
                              drop_rate=0.,
                              with_bn=False):
R
ranqiu 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
    """
    Definition of the convolution block.

    :param input: The input of this block.
    :type input: LayerOutput
    :param size: The dimension of the block's output.
    :type size: int
    :param context_len: The context length of the convolution.
    :type context_len: int
    :param context_start: The start position of the context.
    :type context_start: int
    :param learning_rate: The learning rate factor of the parameters in the block.
                          The actual learning rate is the product of the global
                          learning rate and this factor.
    :type learning_rate: float
    :param drop_rate: Dropout rate.
    :type drop_rate: float
R
ranqiu 已提交
34 35 36
    :param with_bn: Whether to use batch normalization or not. False is the default
                    value.
    :type with_bn: bool
R
ranqiu 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    :return: The output of the convolution block.
    :rtype: LayerOutput
    """
    input = paddle.layer.dropout(input=input, dropout_rate=drop_rate)

    context = paddle.layer.mixed(
        size=input.size * context_len,
        input=paddle.layer.context_projection(
            input=input, context_len=context_len, context_start=context_start))

    raw_conv = paddle.layer.fc(
        input=context,
        size=size * 2,
        act=paddle.activation.Linear(),
        param_attr=paddle.attr.Param(
            initial_mean=0.,
            initial_std=math.sqrt(4.0 * (1.0 - drop_rate) / context.size),
            learning_rate=learning_rate),
        bias_attr=False)

R
ranqiu 已提交
57 58 59 60 61
    if with_bn:
        raw_conv = paddle.layer.batch_norm(
            input=raw_conv,
            act=paddle.activation.Linear(),
            param_attr=paddle.attr.Param(learning_rate=learning_rate))
R
ranqiu 已提交
62 63

    with paddle.layer.mixed(size=size) as conv:
R
ranqiu 已提交
64
        conv += paddle.layer.identity_projection(raw_conv, size=size, offset=0)
R
ranqiu 已提交
65 66 67

    with paddle.layer.mixed(size=size, act=paddle.activation.Sigmoid()) as gate:
        gate += paddle.layer.identity_projection(
R
ranqiu 已提交
68
            raw_conv, size=size, offset=size)
R
ranqiu 已提交
69 70 71 72 73 74 75 76 77 78 79

    with paddle.layer.mixed(size=size) as gated_conv:
        gated_conv += paddle.layer.dotmul_operator(conv, gate)

    return gated_conv


def encoder(token_emb,
            pos_emb,
            conv_blocks=[(256, 3)] * 5,
            num_attention=3,
R
ranqiu 已提交
80 81
            drop_rate=0.,
            with_bn=False):
R
ranqiu 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    """
    Definition of the encoder.

    :param token_emb: The embedding vector of the input token.
    :type token_emb: LayerOutput
    :param pos_emb: The embedding vector of the input token's position.
    :type pos_emb: LayerOutput
    :param conv_blocks: The scale list of the convolution blocks. Each element of
                        the list contains output dimension and context length of
                        the corresponding convolution block.
    :type conv_blocks: list of tuple
    :param num_attention: The total number of the attention modules used in the decoder.
    :type num_attention: int
    :param drop_rate: Dropout rate.
    :type drop_rate: float
R
ranqiu 已提交
97 98 99
    :param with_bn: Whether to use batch normalization or not. False is the default
                    value.
    :type with_bn: bool
R
ranqiu 已提交
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
    :return: The input token encoding.
    :rtype: LayerOutput
    """
    embedding = paddle.layer.addto(
        input=[token_emb, pos_emb],
        layer_attr=paddle.attr.Extra(drop_rate=drop_rate))

    proj_size = conv_blocks[0][0]
    block_input = paddle.layer.fc(
        input=embedding,
        size=proj_size,
        act=paddle.activation.Linear(),
        param_attr=paddle.attr.Param(
            initial_mean=0.,
            initial_std=math.sqrt((1.0 - drop_rate) / embedding.size),
            learning_rate=1.0 / (2.0 * num_attention)),
        bias_attr=True, )

    for (size, context_len) in conv_blocks:
        if block_input.size == size:
            residual = block_input
        else:
            residual = paddle.layer.fc(
                input=block_input,
                size=size,
                act=paddle.activation.Linear(),
                param_attr=paddle.attr.Param(learning_rate=1.0 /
                                             (2.0 * num_attention)),
                bias_attr=True)

        gated_conv = gated_conv_with_batchnorm(
            input=block_input,
            size=size,
            context_len=context_len,
            learning_rate=1.0 / (2.0 * num_attention),
R
ranqiu 已提交
135 136
            drop_rate=drop_rate,
            with_bn=with_bn)
R
ranqiu 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

        with paddle.layer.mixed(size=size) as block_output:
            block_output += paddle.layer.identity_projection(residual)
            block_output += paddle.layer.identity_projection(gated_conv)

        # halve the variance of the sum
        block_output = paddle.layer.slope_intercept(
            input=block_output, slope=math.sqrt(0.5))

        block_input = block_output

    emb_dim = embedding.size
    encoded_vec = paddle.layer.fc(
        input=block_output,
        size=emb_dim,
        act=paddle.activation.Linear(),
        param_attr=paddle.attr.Param(learning_rate=1.0 / (2.0 * num_attention)),
        bias_attr=True)

    encoded_sum = paddle.layer.addto(input=[encoded_vec, embedding])

    # halve the variance of the sum
Y
yangyaming 已提交
159 160
    encoded_sum = paddle.layer.slope_intercept(
        input=encoded_sum, slope=math.sqrt(0.5))
R
ranqiu 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

    return encoded_vec, encoded_sum


def attention(decoder_state, cur_embedding, encoded_vec, encoded_sum):
    """
    Definition of the attention.

    :param decoder_state: The hidden state of the decoder.
    :type decoder_state: LayerOutput
    :param cur_embedding: The embedding vector of the current token.
    :type cur_embedding: LayerOutput
    :param encoded_vec: The source token encoding.
    :type encoded_vec: LayerOutput
    :param encoded_sum: The sum of the source token's encoding and embedding.
    :type encoded_sum: LayerOutput
R
ranqiu 已提交
177
    :return: A context vector and the attention weight.
R
ranqiu 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    :rtype: LayerOutput
    """
    residual = decoder_state

    state_size = decoder_state.size
    emb_dim = cur_embedding.size
    with paddle.layer.mixed(size=emb_dim, bias_attr=True) as state_summary:
        state_summary += paddle.layer.full_matrix_projection(decoder_state)
        state_summary += paddle.layer.identity_projection(cur_embedding)

    # halve the variance of the sum
    state_summary = paddle.layer.slope_intercept(
        input=state_summary, slope=math.sqrt(0.5))

    expanded = paddle.layer.expand(input=state_summary, expand_as=encoded_vec)

R
ranqiu 已提交
194
    m = paddle.layer.dot_prod(input1=expanded, input2=encoded_vec)
R
ranqiu 已提交
195

196 197 198 199
    attention_weight = paddle.layer.fc(input=m,
                                       size=1,
                                       act=paddle.activation.SequenceSoftmax(),
                                       bias_attr=False)
R
ranqiu 已提交
200 201 202 203 204 205

    scaled = paddle.layer.scaling(weight=attention_weight, input=encoded_sum)

    attended = paddle.layer.pooling(
        input=scaled, pooling_type=paddle.pooling.Sum())

206 207 208 209
    attended_proj = paddle.layer.fc(input=attended,
                                    size=state_size,
                                    act=paddle.activation.Linear(),
                                    bias_attr=True)
R
ranqiu 已提交
210 211 212 213 214 215

    attention_result = paddle.layer.addto(input=[attended_proj, residual])

    # halve the variance of the sum
    attention_result = paddle.layer.slope_intercept(
        input=attention_result, slope=math.sqrt(0.5))
R
ranqiu 已提交
216
    return attention_result, attention_weight
R
ranqiu 已提交
217 218 219 220 221 222 223 224


def decoder(token_emb,
            pos_emb,
            encoded_vec,
            encoded_sum,
            dict_size,
            conv_blocks=[(256, 3)] * 3,
R
ranqiu 已提交
225 226
            drop_rate=0.,
            with_bn=False):
R
ranqiu 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    """
    Definition of the decoder.

    :param token_emb: The embedding vector of the input token.
    :type token_emb: LayerOutput
    :param pos_emb: The embedding vector of the input token's position.
    :type pos_emb: LayerOutput
    :param encoded_vec: The source token encoding.
    :type encoded_vec: LayerOutput
    :param encoded_sum: The sum of the source token's encoding and embedding.
    :type encoded_sum: LayerOutput
    :param dict_size: The size of the target dictionary.
    :type dict_size: int
    :param conv_blocks: The scale list of the convolution blocks. Each element
                        of the list contains output dimension and context length
                        of the corresponding convolution block.
    :type conv_blocks: list of tuple
    :param drop_rate: Dropout rate.
    :type drop_rate: float
R
ranqiu 已提交
246 247 248 249
    :param with_bn: Whether to use batch normalization or not. False is the default
                    value.
    :type with_bn: bool
    :return: The probability of the predicted token and the attention weights.
R
ranqiu 已提交
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
    :rtype: LayerOutput
    """

    def attention_step(decoder_state, cur_embedding, encoded_vec, encoded_sum):
        conditional = attention(
            decoder_state=decoder_state,
            cur_embedding=cur_embedding,
            encoded_vec=encoded_vec,
            encoded_sum=encoded_sum)
        return conditional

    embedding = paddle.layer.addto(
        input=[token_emb, pos_emb],
        layer_attr=paddle.attr.Extra(drop_rate=drop_rate))

    proj_size = conv_blocks[0][0]
    block_input = paddle.layer.fc(
        input=embedding,
        size=proj_size,
        act=paddle.activation.Linear(),
        param_attr=paddle.attr.Param(
            initial_mean=0.,
            initial_std=math.sqrt((1.0 - drop_rate) / embedding.size)),
        bias_attr=True, )

R
ranqiu 已提交
275
    weight = []
R
ranqiu 已提交
276 277 278 279
    for (size, context_len) in conv_blocks:
        if block_input.size == size:
            residual = block_input
        else:
280 281 282 283
            residual = paddle.layer.fc(input=block_input,
                                       size=size,
                                       act=paddle.activation.Linear(),
                                       bias_attr=True)
R
ranqiu 已提交
284 285 286 287 288 289

        decoder_state = gated_conv_with_batchnorm(
            input=block_input,
            size=size,
            context_len=context_len,
            context_start=0,
R
ranqiu 已提交
290 291
            drop_rate=drop_rate,
            with_bn=with_bn)
R
ranqiu 已提交
292 293 294 295 296 297 298 299

        group_inputs = [
            decoder_state,
            embedding,
            paddle.layer.StaticInput(input=encoded_vec),
            paddle.layer.StaticInput(input=encoded_sum),
        ]

R
ranqiu 已提交
300
        conditional, attention_weight = paddle.layer.recurrent_group(
R
ranqiu 已提交
301
            step=attention_step, input=group_inputs)
R
ranqiu 已提交
302
        weight.append(attention_weight)
R
ranqiu 已提交
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

        block_output = paddle.layer.addto(input=[conditional, residual])

        # halve the variance of the sum
        block_output = paddle.layer.slope_intercept(
            input=block_output, slope=math.sqrt(0.5))

        block_input = block_output

    out_emb_dim = embedding.size
    block_output = paddle.layer.fc(
        input=block_output,
        size=out_emb_dim,
        act=paddle.activation.Linear(),
        layer_attr=paddle.attr.Extra(drop_rate=drop_rate))

    decoder_out = paddle.layer.fc(
        input=block_output,
        size=dict_size,
        act=paddle.activation.Softmax(),
        param_attr=paddle.attr.Param(
            initial_mean=0.,
            initial_std=math.sqrt((1.0 - drop_rate) / block_output.size)),
        bias_attr=True)

R
ranqiu 已提交
328
    return decoder_out, weight
R
ranqiu 已提交
329 330 331 332 333 334 335 336


def conv_seq2seq(src_dict_size,
                 trg_dict_size,
                 pos_size,
                 emb_dim,
                 enc_conv_blocks=[(256, 3)] * 5,
                 dec_conv_blocks=[(256, 3)] * 3,
R
ranqiu 已提交
337 338
                 drop_rate=0.,
                 with_bn=False,
R
ranqiu 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
                 is_infer=False):
    """
    Definition of convolutional sequence-to-sequence network.

    :param src_dict_size: The size of the source dictionary.
    :type src_dict_size: int
    :param trg_dict_size: The size of the target dictionary.
    :type trg_dict_size: int
    :param pos_size: The total number of the position indexes, which means
                     the maximum value of the index is pos_size - 1.
    :type pos_size: int
    :param emb_dim: The dimension of the embedding vector.
    :type emb_dim: int
    :param enc_conv_blocks: The scale list of the encoder's convolution blocks. Each element
                            of the list contains output dimension and context length of the
                            corresponding convolution block.
    :type enc_conv_blocks: list of tuple
    :param dec_conv_blocks: The scale list of the decoder's convolution blocks. Each element
                            of the list contains output dimension and context length of the
                            corresponding convolution block.
    :type dec_conv_blocks: list of tuple
    :param drop_rate: Dropout rate.
    :type drop_rate: float
R
ranqiu 已提交
362 363
    :param with_bn: Whether to use batch normalization or not. False is the default value.
    :type with_bn: bool
R
ranqiu 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    :param is_infer: Whether infer or not.
    :type is_infer: bool
    :return: Cost or output layer.
    :rtype: LayerOutput
    """
    src = paddle.layer.data(
        name='src_word',
        type=paddle.data_type.integer_value_sequence(src_dict_size))
    src_pos = paddle.layer.data(
        name='src_word_pos',
        type=paddle.data_type.integer_value_sequence(pos_size +
                                                     1))  # one for padding

    src_emb = paddle.layer.embedding(
        input=src,
        size=emb_dim,
        name='src_word_emb',
381 382
        param_attr=paddle.attr.Param(
            initial_mean=0., initial_std=0.1))
R
ranqiu 已提交
383 384 385 386
    src_pos_emb = paddle.layer.embedding(
        input=src_pos,
        size=emb_dim,
        name='src_pos_emb',
387 388
        param_attr=paddle.attr.Param(
            initial_mean=0., initial_std=0.1))
R
ranqiu 已提交
389 390 391 392 393 394 395

    num_attention = len(dec_conv_blocks)
    encoded_vec, encoded_sum = encoder(
        token_emb=src_emb,
        pos_emb=src_pos_emb,
        conv_blocks=enc_conv_blocks,
        num_attention=num_attention,
R
ranqiu 已提交
396 397
        drop_rate=drop_rate,
        with_bn=with_bn)
R
ranqiu 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411

    trg = paddle.layer.data(
        name='trg_word',
        type=paddle.data_type.integer_value_sequence(trg_dict_size +
                                                     1))  # one for padding
    trg_pos = paddle.layer.data(
        name='trg_word_pos',
        type=paddle.data_type.integer_value_sequence(pos_size +
                                                     1))  # one for padding

    trg_emb = paddle.layer.embedding(
        input=trg,
        size=emb_dim,
        name='trg_word_emb',
412 413
        param_attr=paddle.attr.Param(
            initial_mean=0., initial_std=0.1))
R
ranqiu 已提交
414 415 416 417
    trg_pos_emb = paddle.layer.embedding(
        input=trg_pos,
        size=emb_dim,
        name='trg_pos_emb',
418 419
        param_attr=paddle.attr.Param(
            initial_mean=0., initial_std=0.1))
R
ranqiu 已提交
420

R
ranqiu 已提交
421
    decoder_out, weight = decoder(
R
ranqiu 已提交
422 423 424 425 426 427
        token_emb=trg_emb,
        pos_emb=trg_pos_emb,
        encoded_vec=encoded_vec,
        encoded_sum=encoded_sum,
        dict_size=trg_dict_size,
        conv_blocks=dec_conv_blocks,
R
ranqiu 已提交
428 429
        drop_rate=drop_rate,
        with_bn=with_bn)
R
ranqiu 已提交
430 431

    if is_infer:
R
ranqiu 已提交
432
        return decoder_out, weight
R
ranqiu 已提交
433 434 435 436 437 438 439 440

    trg_next_word = paddle.layer.data(
        name='trg_next_word',
        type=paddle.data_type.integer_value_sequence(trg_dict_size))
    cost = paddle.layer.classification_cost(
        input=decoder_out, label=trg_next_word)

    return cost