Lavender825 commited on
Commit
7dfbd5c
·
1 Parent(s): 0222c13

Guard BERT embedding inputs during forward

Browse files
Files changed (2) hide show
  1. src/inference.py +2 -2
  2. src/models.py +38 -18
src/inference.py CHANGED
@@ -201,7 +201,7 @@ class AspectPredictor:
201
  review_text,
202
  max_length=self._max_inference_length(),
203
  truncation=True,
204
- padding="max_length",
205
  return_tensors="pt",
206
  )
207
  input_ids = self._prepare_input_ids(enc["input_ids"]).to(self.device)
@@ -245,7 +245,7 @@ class AspectPredictor:
245
  [r["review_text"] for r in chunk],
246
  max_length=self._max_inference_length(),
247
  truncation=True,
248
- padding="max_length",
249
  return_tensors="pt",
250
  )
251
  input_ids = self._prepare_input_ids(enc["input_ids"]).to(self.device)
 
201
  review_text,
202
  max_length=self._max_inference_length(),
203
  truncation=True,
204
+ padding=True,
205
  return_tensors="pt",
206
  )
207
  input_ids = self._prepare_input_ids(enc["input_ids"]).to(self.device)
 
245
  [r["review_text"] for r in chunk],
246
  max_length=self._max_inference_length(),
247
  truncation=True,
248
+ padding=True,
249
  return_tensors="pt",
250
  )
251
  input_ids = self._prepare_input_ids(enc["input_ids"]).to(self.device)
src/models.py CHANGED
@@ -60,6 +60,40 @@ def _load_bert_model(bert_name: str):
60
  return model
61
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  # ---------------------------------------------------------------------------
64
  # Shared helpers
65
  # ---------------------------------------------------------------------------
@@ -363,12 +397,7 @@ class BertMetaFusionACSAModel(nn.Module):
363
  overall_labels: Optional[torch.Tensor] = None,
364
  output_attentions: bool = False,
365
  ):
366
- bert_out = self.bert(
367
- input_ids=input_ids,
368
- attention_mask=attention_mask,
369
- output_attentions=output_attentions,
370
- return_dict=True,
371
- )
372
  text_vec = bert_out.last_hidden_state[:, 0, :] # [CLS]
373
 
374
  meta_vec = self.meta_mlp(meta_features) # (B, meta_hidden)
@@ -491,12 +520,7 @@ class GatedAspectSemanticMetaFusionACSAModel(nn.Module):
491
  overall_labels: Optional[torch.Tensor] = None,
492
  output_attentions: bool = False,
493
  ):
494
- bert_out = self.bert(
495
- input_ids=input_ids,
496
- attention_mask=attention_mask,
497
- output_attentions=output_attentions,
498
- return_dict=True,
499
- )
500
  text_vec = bert_out.last_hidden_state[:, 0, :]
501
  B = text_vec.size(0)
502
  meta_tokens = self.meta_tokenizer(meta_features)
@@ -589,10 +613,7 @@ class BertACSAModel(nn.Module):
589
  def forward(self, input_ids, attention_mask,
590
  labels: Optional[torch.Tensor] = None,
591
  output_attentions: bool = False):
592
- bert_out = self.bert(
593
- input_ids=input_ids, attention_mask=attention_mask,
594
- output_attentions=output_attentions, return_dict=True,
595
- )
596
  text_vec = bert_out.last_hidden_state[:, 0, :]
597
  logits = self.heads(text_vec)
598
  loss = _aspect_loss(logits, labels, self.class_weights) if labels is not None else None
@@ -622,8 +643,7 @@ class BertOverallModel(nn.Module):
622
  self.num_classes = num_classes
623
 
624
  def forward(self, input_ids, attention_mask, labels=None, output_attentions=False):
625
- out = self.bert(input_ids=input_ids, attention_mask=attention_mask,
626
- output_attentions=output_attentions, return_dict=True)
627
  logits = self.classifier(out.last_hidden_state[:, 0, :])
628
  loss = F.cross_entropy(logits, labels) if labels is not None else None
629
  return {
 
60
  return model
61
 
62
 
63
+ def _safe_bert_forward(bert, input_ids, attention_mask, output_attentions=False):
64
+ embeddings = getattr(bert, "embeddings", None)
65
+ word_embeddings = getattr(embeddings, "word_embeddings", None)
66
+ position_embeddings = getattr(embeddings, "position_embeddings", None)
67
+ token_type_embeddings = getattr(embeddings, "token_type_embeddings", None)
68
+
69
+ if word_embeddings is not None:
70
+ vocab_size = int(word_embeddings.num_embeddings)
71
+ if vocab_size > 0:
72
+ input_ids = input_ids.clamp(min=0, max=vocab_size - 1)
73
+
74
+ if position_embeddings is not None:
75
+ max_pos = int(position_embeddings.num_embeddings)
76
+ if max_pos > 0 and input_ids.size(1) > max_pos:
77
+ input_ids = input_ids[:, :max_pos]
78
+ attention_mask = attention_mask[:, :max_pos]
79
+
80
+ token_type_ids = torch.zeros_like(input_ids)
81
+ if token_type_embeddings is not None:
82
+ type_size = int(token_type_embeddings.num_embeddings)
83
+ if type_size <= 0:
84
+ token_type_ids = None
85
+ elif type_size == 1:
86
+ token_type_ids = token_type_ids.clamp(max=0)
87
+
88
+ return bert(
89
+ input_ids=input_ids,
90
+ attention_mask=attention_mask,
91
+ token_type_ids=token_type_ids,
92
+ output_attentions=output_attentions,
93
+ return_dict=True,
94
+ )
95
+
96
+
97
  # ---------------------------------------------------------------------------
98
  # Shared helpers
99
  # ---------------------------------------------------------------------------
 
397
  overall_labels: Optional[torch.Tensor] = None,
398
  output_attentions: bool = False,
399
  ):
400
+ bert_out = _safe_bert_forward(self.bert, input_ids, attention_mask, output_attentions)
 
 
 
 
 
401
  text_vec = bert_out.last_hidden_state[:, 0, :] # [CLS]
402
 
403
  meta_vec = self.meta_mlp(meta_features) # (B, meta_hidden)
 
520
  overall_labels: Optional[torch.Tensor] = None,
521
  output_attentions: bool = False,
522
  ):
523
+ bert_out = _safe_bert_forward(self.bert, input_ids, attention_mask, output_attentions)
 
 
 
 
 
524
  text_vec = bert_out.last_hidden_state[:, 0, :]
525
  B = text_vec.size(0)
526
  meta_tokens = self.meta_tokenizer(meta_features)
 
613
  def forward(self, input_ids, attention_mask,
614
  labels: Optional[torch.Tensor] = None,
615
  output_attentions: bool = False):
616
+ bert_out = _safe_bert_forward(self.bert, input_ids, attention_mask, output_attentions)
 
 
 
617
  text_vec = bert_out.last_hidden_state[:, 0, :]
618
  logits = self.heads(text_vec)
619
  loss = _aspect_loss(logits, labels, self.class_weights) if labels is not None else None
 
643
  self.num_classes = num_classes
644
 
645
  def forward(self, input_ids, attention_mask, labels=None, output_attentions=False):
646
+ out = _safe_bert_forward(self.bert, input_ids, attention_mask, output_attentions)
 
647
  logits = self.classifier(out.last_hidden_state[:, 0, :])
648
  loss = F.cross_entropy(logits, labels) if labels is not None else None
649
  return {