| 35 | self.use_ext_encoder = False |
| 36 | |
| 37 | def forward( |
| 38 | self, |
| 39 | input_ids=None, |
| 40 | attention_mask=None, |
| 41 | token_type_ids=None, |
| 42 | position_ids=None, |
| 43 | head_mask=None, |
| 44 | inputs_embeds=None, |
| 45 | encoder_hidden_states=None, |
| 46 | encoder_attention_mask=None, |
| 47 | ): |
| 48 | if input_ids is not None and inputs_embeds is not None: |
| 49 | raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") |
| 50 | elif input_ids is not None: |
| 51 | input_shape = input_ids.size() |
| 52 | elif inputs_embeds is not None: |
| 53 | input_shape = inputs_embeds.size()[:-1] |
| 54 | else: |
| 55 | raise ValueError("You have to specify either input_ids or inputs_embeds") |
| 56 | |
| 57 | device = input_ids.device if input_ids is not None else inputs_embeds.device |
| 58 | |
| 59 | if attention_mask is None: |
| 60 | attention_mask = torch.ones(input_shape, device=device) |
| 61 | if token_type_ids is None: |
| 62 | token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) |
| 63 | |
| 64 | if self.use_ext_encoder: |
| 65 | # if attention_mask.dim() == 3: |
| 66 | # extended_attention_mask = attention_mask |
| 67 | # elif attention_mask.dim() == 2: |
| 68 | # extended_attention_mask = attention_mask[:, None, :].repeat(1, input_shape[1], 1) |
| 69 | # else: |
| 70 | # raise ValueError( |
| 71 | # "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( |
| 72 | # input_shape, attention_mask.shape |
| 73 | # ) |
| 74 | # ) |
| 75 | assert attention_mask.dim() == 2 |
| 76 | extended_attention_mask = attention_mask.view(-1, 1, 1, attention_mask.size(-1)) |
| 77 | m_2 = extended_attention_mask.transpose(-1, -2) |
| 78 | extended_attention_mask = extended_attention_mask * m_2 |
| 79 | extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility |
| 80 | seq_lens = torch.sum(attention_mask, 1, dtype=torch.int32).cuda() |
| 81 | else: |
| 82 | # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] |
| 83 | # ourselves in which case we just need to make it broadcastable to all heads. |
| 84 | if attention_mask.dim() == 3: |
| 85 | extended_attention_mask = attention_mask[:, None, :, :] |
| 86 | elif attention_mask.dim() == 2: |
| 87 | extended_attention_mask = attention_mask[:, None, None, :] |
| 88 | else: |
| 89 | raise ValueError( |
| 90 | "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( |
| 91 | input_shape, attention_mask.shape |
| 92 | ) |
| 93 | ) |
| 94 | # Since attention_mask is 1.0 for positions we want to attend and 0.0 for |