qilowoq commited on
Commit
8e73805
1 Parent(s): f5258be

Upload model

Browse files
Files changed (2) hide show
  1. AbLang_bert_model.py +72 -118
  2. pytorch_model.bin +2 -2
AbLang_bert_model.py CHANGED
@@ -1,24 +1,29 @@
1
- from transformers.models.bert.modeling_bert import BertEncoder, BertPooler, BertEmbeddings, BaseModelOutputWithPoolingAndCrossAttentions
2
  from transformers import BertModel
 
3
  import torch
4
 
5
  class BertEmbeddingsV2(BertEmbeddings):
6
  def __init__(self, config):
7
  super().__init__(config)
8
  self.pad_token_id = config.pad_token_id
9
- self.word_embeddings = torch.nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=self.pad_token_id)
10
  self.position_embeddings = torch.nn.Embedding(config.max_position_embeddings, config.hidden_size, padding_idx=0) # here padding_idx is always 0
11
- self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
12
- self.dropout = torch.nn.Dropout(config.hidden_dropout_prob)
13
 
14
- def forward(self, input_ids=None, pos_tag_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0):
 
 
 
 
 
 
 
15
  inputs_embeds = self.word_embeddings(input_ids)
16
  position_ids = self.create_position_ids_from_input_ids(input_ids)
17
  position_embeddings = self.position_embeddings(position_ids)
18
  embeddings = inputs_embeds + position_embeddings
19
  return self.dropout(self.LayerNorm(embeddings))
20
 
21
- def create_position_ids_from_input_ids(self, input_ids):
22
  mask = input_ids.ne(self.pad_token_id).int()
23
  return torch.cumsum(mask, dim=1).long() * mask
24
 
@@ -26,133 +31,82 @@ class BertEmbeddingsV2(BertEmbeddings):
26
  class BertModelV2(BertModel):
27
  def __init__(self, config):
28
  super().__init__(config)
29
- self.config = config
30
  self.embeddings = BertEmbeddingsV2(config)
31
- self.encoder = BertEncoder(config)
32
- self.pooler = BertPooler(config) if config.add_pooling_layer else None
33
- self.init_weights()
34
-
 
 
35
  def forward(
36
  self,
37
- input_ids=None,
38
- attention_mask=None,
39
- token_type_ids=None,
40
- pos_tag_ids=None,
41
- position_ids=None,
42
- head_mask=None,
43
- inputs_embeds=None,
44
- encoder_hidden_states=None,
45
- encoder_attention_mask=None,
46
- past_key_values=None,
47
- use_cache=None,
48
- output_attentions=None,
49
- output_hidden_states=None,
50
- return_dict=None,
51
- ):
52
  r"""
53
- encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
54
- Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
55
- the model is configured as a decoder.
56
- encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
57
- Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
58
- the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
59
- - 1 for tokens that are **not masked**,
60
- - 0 for tokens that are **masked**.
61
- past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
62
- Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
63
- If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
64
- (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
65
- instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
66
- use_cache (:obj:`bool`, `optional`):
67
- If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
68
- decoding (see :obj:`past_key_values`).
69
  """
70
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
71
- output_hidden_states = (
72
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
73
- )
74
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
75
-
76
- if self.config.is_decoder:
77
- use_cache = use_cache if use_cache is not None else self.config.use_cache
78
- else:
79
- use_cache = False
80
-
81
- if input_ids is not None and inputs_embeds is not None:
82
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
83
- elif input_ids is not None:
84
- input_shape = input_ids.size()
85
- batch_size, seq_length = input_shape
86
- elif inputs_embeds is not None:
87
- input_shape = inputs_embeds.size()[:-1]
88
- batch_size, seq_length = input_shape
89
- else:
90
- raise ValueError("You have to specify either input_ids or inputs_embeds")
91
-
92
- dev = input_ids.device if input_ids is not None else inputs_embeds.device
93
-
94
- # past_key_values_length
95
- past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
96
-
97
- if attention_mask is None:
98
- attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=dev)
99
- if token_type_ids is None:
100
- token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=dev)
101
 
102
- # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
103
- # ourselves in which case we just need to make it broadcastable to all heads.
104
- extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, dev)
105
-
106
- # If a 2D or 3D attention mask is provided for the cross-attention
107
- # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
108
- if self.config.is_decoder and encoder_hidden_states is not None:
109
- encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
110
- encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
111
- if encoder_attention_mask is None:
112
- encoder_attention_mask = torch.ones(encoder_hidden_shape, device=dev)
113
- encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
114
- else:
115
- encoder_extended_attention_mask = None
116
-
117
- # Prepare head mask if needed
118
- # 1.0 in head_mask indicate we keep the head
119
- # attention_probs has shape bsz x n_heads x N x N
120
- # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
121
- # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
122
- head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
123
 
124
- embedding_output = self.embeddings(
125
- input_ids=input_ids,
126
- position_ids=position_ids,
127
  token_type_ids=token_type_ids,
128
- pos_tag_ids=pos_tag_ids,
129
- inputs_embeds=inputs_embeds,
130
- past_key_values_length=past_key_values_length,
131
- )
132
- encoder_outputs = self.encoder(
133
- embedding_output,
134
- attention_mask=extended_attention_mask,
135
  head_mask=head_mask,
 
136
  encoder_hidden_states=encoder_hidden_states,
137
- encoder_attention_mask=encoder_extended_attention_mask,
138
- past_key_values=past_key_values,
139
- use_cache=use_cache,
140
  output_attentions=output_attentions,
141
  output_hidden_states=output_hidden_states,
142
  return_dict=return_dict,
143
  )
144
- sequence_output = encoder_outputs[0]
145
- pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
 
 
 
 
 
 
146
 
147
  if not return_dict:
148
- return (sequence_output, pooled_output) + encoder_outputs[1:]
 
149
 
150
- return BaseModelOutputWithPoolingAndCrossAttentions(
151
- last_hidden_state=sequence_output,
152
- pooler_output=pooled_output,
153
- past_key_values=encoder_outputs.past_key_values,
154
- hidden_states=encoder_outputs.hidden_states,
155
- attentions=encoder_outputs.attentions,
156
- cross_attentions=encoder_outputs.cross_attentions,
157
  )
158
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.models.bert.modeling_bert import BertEncoder, BertPooler, BertEmbeddings, BertForMaskedLM, MaskedLMOutput
2
  from transformers import BertModel
3
+ from typing import List, Optional, Tuple, Union
4
  import torch
5
 
6
  class BertEmbeddingsV2(BertEmbeddings):
7
  def __init__(self, config):
8
  super().__init__(config)
9
  self.pad_token_id = config.pad_token_id
 
10
  self.position_embeddings = torch.nn.Embedding(config.max_position_embeddings, config.hidden_size, padding_idx=0) # here padding_idx is always 0
 
 
11
 
12
+ def forward(
13
+ self,
14
+ input_ids: torch.LongTensor,
15
+ token_type_ids: Optional[torch.LongTensor] = None,
16
+ position_ids: Optional[torch.LongTensor] = None,
17
+ inputs_embeds: Optional[torch.FloatTensor] = None,
18
+ past_key_values_length: int = 0,
19
+ ) -> torch.Tensor:
20
  inputs_embeds = self.word_embeddings(input_ids)
21
  position_ids = self.create_position_ids_from_input_ids(input_ids)
22
  position_embeddings = self.position_embeddings(position_ids)
23
  embeddings = inputs_embeds + position_embeddings
24
  return self.dropout(self.LayerNorm(embeddings))
25
 
26
+ def create_position_ids_from_input_ids(self, input_ids: torch.LongTensor) -> torch.Tensor:
27
  mask = input_ids.ne(self.pad_token_id).int()
28
  return torch.cumsum(mask, dim=1).long() * mask
29
 
 
31
  class BertModelV2(BertModel):
32
  def __init__(self, config):
33
  super().__init__(config)
 
34
  self.embeddings = BertEmbeddingsV2(config)
35
+
36
+
37
+ class BertForMaskedLMV2(BertForMaskedLM):
38
+ def __init__(self, config):
39
+ super().__init__(config)
40
+
41
  def forward(
42
  self,
43
+ input_ids: Optional[torch.Tensor] = None,
44
+ attention_mask: Optional[torch.Tensor] = None,
45
+ token_type_ids: Optional[torch.Tensor] = None,
46
+ position_ids: Optional[torch.Tensor] = None,
47
+ head_mask: Optional[torch.Tensor] = None,
48
+ inputs_embeds: Optional[torch.Tensor] = None,
49
+ encoder_hidden_states: Optional[torch.Tensor] = None,
50
+ encoder_attention_mask: Optional[torch.Tensor] = None,
51
+ labels: Optional[torch.Tensor] = None,
52
+ output_attentions: Optional[bool] = None,
53
+ output_hidden_states: Optional[bool] = None,
54
+ return_dict: Optional[bool] = None,
55
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
 
 
56
  r"""
57
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
58
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
59
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
60
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
 
 
 
 
 
 
 
 
 
 
 
 
61
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
+ outputs = self.bert(
66
+ input_ids,
67
+ attention_mask=attention_mask,
68
  token_type_ids=token_type_ids,
69
+ position_ids=position_ids,
 
 
 
 
 
 
70
  head_mask=head_mask,
71
+ inputs_embeds=inputs_embeds,
72
  encoder_hidden_states=encoder_hidden_states,
73
+ encoder_attention_mask=encoder_attention_mask,
 
 
74
  output_attentions=output_attentions,
75
  output_hidden_states=output_hidden_states,
76
  return_dict=return_dict,
77
  )
78
+
79
+ sequence_output = outputs[0]
80
+ prediction_scores = sequence_output[:, :, 0:24]
81
+
82
+ masked_lm_loss = None
83
+ if labels is not None:
84
+ loss_fct = torch.nn.CrossEntropyLoss() # -100 index = padding token
85
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
86
 
87
  if not return_dict:
88
+ output = (prediction_scores,) + outputs[2:]
89
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
90
 
91
+ return MaskedLMOutput(
92
+ loss=masked_lm_loss,
93
+ logits=prediction_scores,
94
+ hidden_states=outputs.hidden_states,
95
+ attentions=outputs.attentions,
 
 
96
  )
97
+
98
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
99
+ input_shape = input_ids.shape
100
+ effective_batch_size = input_shape[0]
101
+
102
+ # add a dummy token
103
+ if self.config.pad_token_id is None:
104
+ raise ValueError("The PAD token should be defined for generation")
105
+
106
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
107
+ dummy_token = torch.full(
108
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
109
+ )
110
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
111
+
112
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
pytorch_model.bin CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c448ef288a9c3d3e622ad6ebf5168eba5fa7e44afc5d280971ba72319269a436
3
- size 340860389
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1df129a33dc579997effd90fb6ff33b8bcd2f2619fc2726cc524e02f71f4f3e
3
+ size 343223341