| 564 | return vit_enc_out, vit_seq_len, image_self_attn_mask, checkpoints |
| 565 | |
| 566 | def text_encode(self, text_input, text_mask, gather_idx=None, decoding_step=False): |
| 567 | assert text_mask is not None, "text_mask should not be none" |
| 568 | if decoding_step or self._is_img2txt_task: # for img2txt tasks or step-by-step decoding |
| 569 | text_self_attn_mask = text_mask |
| 570 | else: |
| 571 | text_self_attn_mask = paddle.matmul(x=paddle.transpose(text_mask, perm=[0, 2, 1]), y=text_mask) |
| 572 | |
| 573 | self_attn_mask = paddle.scale( |
| 574 | x=text_self_attn_mask, scale=1e4, bias=-1.0, bias_after_scale=False) |
| 575 | n_head_self_attn_mask = paddle.stack( |
| 576 | x=[self_attn_mask] * self._n_head, axis=1) |
| 577 | n_head_self_attn_mask.stop_gradient = True |
| 578 | |
| 579 | # text part |
| 580 | text_emb = paddle.static.nn.embedding( |
| 581 | input=text_input["text.word_embedding"], |
| 582 | size=[self._text_emb_vocab_size["text.word_embedding"], self._emb_size], |
| 583 | dtype=self._emb_dtype, |
| 584 | param_attr=paddle.ParamAttr( |
| 585 | name='text.word_embedding', |
| 586 | trainable=self._text_encoder_trainable, |
| 587 | initializer=self._param_initializer)) |
| 588 | text_emb = paddle.squeeze(text_emb, axis=2) # (batch_size, seq_len, emb_dim) |
| 589 | |
| 590 | pos_emb = paddle.static.nn.embedding( |
| 591 | input=text_input["text.pos_embedding"], |
| 592 | size=[self._text_emb_vocab_size["text.pos_embedding"], self._emb_size], |
| 593 | dtype=self._emb_dtype, |
| 594 | param_attr=paddle.ParamAttr( |
| 595 | name='text.pos_embedding', |
| 596 | trainable=self._text_encoder_trainable, |
| 597 | initializer=self._param_initializer)) |
| 598 | pos_emb = paddle.squeeze(pos_emb, axis=2) # (batch_size, seq_len, emb_dim) |
| 599 | |
| 600 | emb_out = text_emb + pos_emb |
| 601 | emb_out = text_pre_process_layer( |
| 602 | emb_out, 'nd', self._text_prepostprocess_dropout, |
| 603 | name="text.pre_encoder", trainable=self._text_encoder_trainable) |
| 604 | |
| 605 | text_enc_out, checkpoints = text_encoder( |
| 606 | enc_input=emb_out, |
| 607 | attn_bias=n_head_self_attn_mask, |
| 608 | enc_layers=self.text_enc_layers, |
| 609 | n_head=self._text_n_head, |
| 610 | d_key=self._emb_size // self._text_n_head, |
| 611 | d_value=self._emb_size // self._text_n_head, |
| 612 | d_model=self._emb_size, |
| 613 | d_inner_hid=self._emb_size * 4, |
| 614 | prepostprocess_dropout=self._text_prepostprocess_dropout, |
| 615 | attention_dropout=self._text_attention_dropout, |
| 616 | relu_dropout=0, |
| 617 | hidden_act=self._text_hidden_act, |
| 618 | preprocess_cmd="", |
| 619 | postprocess_cmd="dan", |
| 620 | param_initializer=self._param_initializer, |
| 621 | name='text.encoder', |
| 622 | caches=self.text_caches, |
| 623 | gather_idx=gather_idx, |