MCPcopy Create free account
hub / github.com/modelscope/modelscope / forward

Method forward

modelscope/models/nlp/bert/backbone.py:393–461  ·  view source on GitHub ↗
(
        self,
        hidden_states,
        attention_mask=None,
        head_mask=None,
        encoder_hidden_states=None,
        encoder_attention_mask=None,
        past_key_value=None,
        output_attentions=False,
    )

Source from the content-addressed store, hash-verified

391 self.output = BertOutput(config)
392
393 def forward(
394 self,
395 hidden_states,
396 attention_mask=None,
397 head_mask=None,
398 encoder_hidden_states=None,
399 encoder_attention_mask=None,
400 past_key_value=None,
401 output_attentions=False,
402 ):
403 # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
404 self_attn_past_key_value = past_key_value[:
405 2] if past_key_value is not None else None
406 self_attention_outputs = self.attention(
407 hidden_states,
408 attention_mask,
409 head_mask,
410 output_attentions=output_attentions,
411 past_key_value=self_attn_past_key_value,
412 )
413 attention_output = self_attention_outputs[0]
414
415 # if decoder, the last output is tuple of self-attn cache
416 if self.is_decoder:
417 outputs = self_attention_outputs[1:-1]
418 present_key_value = self_attention_outputs[-1]
419 else:
420 outputs = self_attention_outputs[
421 1:] # add self attentions if we output attention weights
422
423 cross_attn_present_key_value = None
424 if self.is_decoder and encoder_hidden_states is not None:
425 if not hasattr(self, 'crossattention'):
426 raise ValueError(
427 f'If `encoder_hidden_states` are passed, {self} has to be instantiated '
428 f'with cross-attention layers by setting `config.add_cross_attention=True`'
429 )
430
431 # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
432 cross_attn_past_key_value = past_key_value[
433 -2:] if past_key_value is not None else None
434 cross_attention_outputs = self.crossattention(
435 attention_output,
436 attention_mask,
437 head_mask,
438 encoder_hidden_states,
439 encoder_attention_mask,
440 cross_attn_past_key_value,
441 output_attentions,
442 )
443 attention_output = cross_attention_outputs[0]
444 outputs = outputs + cross_attention_outputs[
445 1:-1] # add cross attentions if we output attention weights
446
447 # add cross-attn cache to positions 3,4 of present_key_value tuple
448 cross_attn_present_key_value = cross_attention_outputs[-1]
449 present_key_value = present_key_value + cross_attn_present_key_value
450

Callers

nothing calls this directly

Calls 2

attentionMethod · 0.45

Tested by

no test coverage detected