MCPcopy Create free account
hub / github.com/SooLab/CGFormer / forward

Method forward

bert/modeling_bert.py:212–263  ·  view source on GitHub ↗
(
        self,
        hidden_states,
        attention_mask=None,
        head_mask=None,
        encoder_hidden_states=None,
        encoder_attention_mask=None,
        output_attentions=False,
    )

Source from the content-addressed store, hash-verified

210 return x.permute(0, 2, 1, 3)
211
212 def forward(
213 self,
214 hidden_states,
215 attention_mask=None,
216 head_mask=None,
217 encoder_hidden_states=None,
218 encoder_attention_mask=None,
219 output_attentions=False,
220 ):
221 mixed_query_layer = self.query(hidden_states)
222
223 # If this is instantiated as a cross-attention module, the keys
224 # and values come from an encoder; the attention mask needs to be
225 # such that the encoder's padding tokens are not attended to.
226 if encoder_hidden_states is not None:
227 mixed_key_layer = self.key(encoder_hidden_states)
228 mixed_value_layer = self.value(encoder_hidden_states)
229 attention_mask = encoder_attention_mask
230 else:
231 mixed_key_layer = self.key(hidden_states)
232 mixed_value_layer = self.value(hidden_states)
233
234 query_layer = self.transpose_for_scores(mixed_query_layer)
235 key_layer = self.transpose_for_scores(mixed_key_layer)
236 value_layer = self.transpose_for_scores(mixed_value_layer)
237
238 # Take the dot product between "query" and "key" to get the raw attention scores.
239 attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
240 attention_scores = attention_scores / math.sqrt(self.attention_head_size)
241 if attention_mask is not None:
242 # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
243 attention_scores = attention_scores + attention_mask
244
245 # Normalize the attention scores to probabilities.
246 attention_probs = nn.Softmax(dim=-1)(attention_scores)
247
248 # This is actually dropping out entire tokens to attend to, which might
249 # seem a bit unusual, but is taken from the original Transformer paper.
250 attention_probs = self.dropout(attention_probs)
251
252 # Mask heads if we want to
253 if head_mask is not None:
254 attention_probs = attention_probs * head_mask
255
256 context_layer = torch.matmul(attention_probs, value_layer)
257
258 context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
259 new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
260 context_layer = context_layer.view(*new_context_layer_shape)
261
262 outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
263 return outputs
264
265
266class BertSelfOutput(nn.Module):

Callers

nothing calls this directly

Calls 1

transpose_for_scoresMethod · 0.95

Tested by

no test coverage detected