ChuckLind commited on
Commit
c892da4
·
1 Parent(s): c119de7

Sync from 0bb0e6d in FinetuningBert on GitHub (#7)

Browse files

- Sync from 66b3fde in FinetuningBert on GitHub (026c61a877cdec918ece3e1411b8b785afb653b1)
- Fix trust_remote_code loading + multi-label dependency head indexing (9d0eccc9a093e4984899a51245dcc1005c291b4f)

BertForJointParsing.py CHANGED
@@ -7,12 +7,22 @@ from typing import Any, Dict, List, Literal, Optional, Tuple, Union
7
  from transformers import BertPreTrainedModel, BertModel, BertTokenizerFast
8
  from transformers.models.bert.modeling_bert import BertOnlyMLMHead
9
  from transformers.utils import ModelOutput
10
- from .BertForSyntaxParsing import BertSyntaxParsingHead, SyntaxLabels, SyntaxLogitsOutput, parse_logits as syntax_parse_logits
11
- from .BertForPrefixMarking import BertPrefixMarkingHead, parse_logits as prefix_parse_logits, encode_sentences_for_bert_for_prefix_marking, get_prefixes_from_str
12
- from .BertForMorphTagging import BertMorphTaggingHead, MorphLogitsOutput, MorphLabels, parse_logits as morph_parse_logits
 
 
 
 
 
 
 
13
 
14
  import warnings
15
 
 
 
 
16
  @dataclass
17
  class JointParsingOutput(ModelOutput):
18
  loss: Optional[torch.FloatTensor] = None
@@ -45,7 +55,7 @@ class BertForJointParsing(BertPreTrainedModel):
45
  "cls.predictions.decoder.bias": "cls.predictions.bias",
46
  }
47
 
48
- def __init__(self, config, do_syntax=None, do_ner=None, do_prefix=None, do_lex=None, do_morph=None, syntax_head_size=64):
49
  super().__init__(config)
50
 
51
  self.bert = BertModel(config, add_pooling_layer=False)
@@ -95,7 +105,7 @@ class BertForJointParsing(BertPreTrainedModel):
95
  position_ids: Optional[torch.Tensor] = None,
96
  prefix_class_id_options: Optional[torch.Tensor] = None,
97
  labels: Optional[Union[SyntaxLabels, MorphLabels, torch.Tensor]] = None,
98
- labels_type: Optional[Literal['syntax', 'ner', 'prefix', 'lex', 'morph']] = None,
99
  head_mask: Optional[torch.Tensor] = None,
100
  inputs_embeds: Optional[torch.Tensor] = None,
101
  output_attentions: Optional[bool] = None,
@@ -109,7 +119,8 @@ class BertForJointParsing(BertPreTrainedModel):
109
  if labels is not None and labels_type is None:
110
  raise ValueError("Cannot specify labels without labels_type")
111
 
112
- if labels_type == 'seg' and prefix_class_id_options is None:
 
113
  raise ValueError('Cannot calculate prefix logits without prefix_class_id_options')
114
 
115
  if compute_syntax_mst is not None and self.syntax is None:
@@ -144,13 +155,13 @@ class BertForJointParsing(BertPreTrainedModel):
144
  morph_logits = None
145
 
146
  # Calculate the syntax
147
- if self.syntax is not None and (labels is None or labels_type == 'syntax'):
148
  # apply the syntax head
149
  loss, syntax_logits = self.syntax(hidden_states, extended_attention_mask, labels, compute_syntax_mst)
150
  logits = syntax_logits
151
 
152
  # Calculate the NER
153
- if self.ner is not None and (labels is None or labels_type == 'ner'):
154
  ner_logits = self.ner(hidden_states)
155
  logits = ner_logits
156
  if labels is not None:
@@ -158,19 +169,19 @@ class BertForJointParsing(BertPreTrainedModel):
158
  loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
159
 
160
  # Calculate the segmentation
161
- if self.prefix is not None and (labels is None or labels_type == 'prefix'):
162
  loss, prefix_logits = self.prefix(hidden_states, prefix_class_id_options, labels)
163
  logits = prefix_logits
164
 
165
  # Calculate the lexeme
166
- if self.lex is not None and (labels is None or labels_type == 'lex'):
167
  lex_logits = self.lex(hidden_states)
168
  logits = lex_logits
169
  if labels is not None:
170
  loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
171
  loss = loss_fct(lex_logits.view(-1, self.config.vocab_size), labels.view(-1))
172
 
173
- if self.morph is not None and (labels is None or labels_type == 'morph'):
174
  loss, morph_logits = self.morph(hidden_states, labels)
175
  logits = morph_logits
176
 
@@ -215,7 +226,7 @@ class BertForJointParsing(BertPreTrainedModel):
215
  final_output = [dict(text=sentence, tokens=combine_token_wordpieces(ids, offsets, tokenizer)) for sentence, ids, offsets in zip(sentences, input_ids, offset_mapping)]
216
  # Syntax logits: each sentence gets a dict(tree: List[dict(word,dep_head,dep_head_idx,dep_func)], root_idx: int)
217
  if output.syntax_logits is not None:
218
- for sent_idx,parsed in enumerate(syntax_parse_logits(input_ids, sentences, tokenizer, output.syntax_logits)):
219
  merge_token_list(final_output[sent_idx]['tokens'], parsed['tree'], 'syntax')
220
  final_output[sent_idx]['root_idx'] = parsed['root_idx']
221
 
@@ -404,7 +415,7 @@ def convert_output_to_ud(output_sentences, model_cfg, style: Literal['htb', 'iah
404
  for pre in get_prefixes_from_str(word['seg'][0], model_cfg.prefix_cfg, greedy=True):
405
  # pos - just take the first valid pos that appears in the predicted prefixes list.
406
  pos = next((pos for pos in ud_prefixes_to_pos[pre] if pos in word['morph']['prefixes']), ud_prefixes_to_pos[pre][0])
407
- dep, func = ud_get_prefix_dep(pre, word, word_idx)
408
  intermediate_output.append(dict(word=pre, lex=pre, pos=pos, dep=dep, func=func, feats='_'))
409
 
410
  # if there was an implicit heh, add it in dependent on the method
@@ -464,7 +475,6 @@ def convert_output_to_ud(output_sentences, model_cfg, style: Literal['htb', 'iah
464
  # if the function is obj, then add a את pointing to the next word
465
  elif func == 'obj' and s_lex != 'את':
466
  intermediate_output.append(dict(word='_את_', lex='את', pos='ADP', dep=len(intermediate_output) + 2, func='case', feats='_', absolute_dep=True))
467
-
468
  # add the main suffix in
469
  intermediate_output.append(dict(word=suf, lex='הוא', pos='PRON', dep=dep, func=func, feats='|'.join(f'{k}={v}' for k,v in word['morph']['suffix_feats'].items())))
470
  if entry_to_assign_suf_dep:
@@ -512,13 +522,32 @@ def normalize_dep_rel(dep, style: Literal['htb', 'iahlt']):
512
  return dep
513
 
514
 
515
- def ud_get_prefix_dep(pre, word, word_idx):
516
  does_follow_main = False
 
 
517
 
 
 
 
 
 
 
518
  # shin goes to the main word for verbs, otherwise follows the word
519
- if pre.endswith('ש'):
520
- does_follow_main = word['morph']['pos'] != 'VERB' and word['syntax']['dep_head_idx'] > word_idx
521
- func = 'mark'
 
 
 
 
 
 
 
 
 
 
 
522
  # vuv goes to the main word if the function is in the list, otherwise follows
523
  elif pre == 'ו':
524
  does_follow_main = word['syntax']['dep_func'] not in ["conj", "acl:recl", "parataxis", "root", "acl", "amod", "list", "appos", "dep", "flatccomp"]
@@ -534,4 +563,8 @@ def ud_get_prefix_dep(pre, word, word_idx):
534
  if pre == 'ה':
535
  func = 'det' if 'DET' in word['morph']['prefixes'] else 'mark'
536
 
 
 
 
 
537
  return (word['syntax']['dep_head_idx'] if does_follow_main else word_idx), func
 
7
  from transformers import BertPreTrainedModel, BertModel, BertTokenizerFast
8
  from transformers.models.bert.modeling_bert import BertOnlyMLMHead
9
  from transformers.utils import ModelOutput
10
+ # transformers' get_imports() strips the try body but keeps the except body, so the absolute
11
+ # imports have to sit in the try or trust_remote_code demands them as pip packages
12
+ try:
13
+ from BertForSyntaxParsing import BertSyntaxParsingHead, SyntaxLabels, SyntaxLogitsOutput, parse_logits as syntax_parse_logits
14
+ from BertForPrefixMarking import BertPrefixMarkingHead, parse_logits as prefix_parse_logits, encode_sentences_for_bert_for_prefix_marking, get_prefixes_from_str
15
+ from BertForMorphTagging import BertMorphTaggingHead, MorphLogitsOutput, MorphLabels, parse_logits as morph_parse_logits
16
+ except ImportError:
17
+ from .BertForSyntaxParsing import BertSyntaxParsingHead, SyntaxLabels, SyntaxLogitsOutput, parse_logits as syntax_parse_logits
18
+ from .BertForPrefixMarking import BertPrefixMarkingHead, parse_logits as prefix_parse_logits, encode_sentences_for_bert_for_prefix_marking, get_prefixes_from_str
19
+ from .BertForMorphTagging import BertMorphTaggingHead, MorphLogitsOutput, MorphLabels, parse_logits as morph_parse_logits
20
 
21
  import warnings
22
 
23
+ INDEX_TO_LABELS = ['syntax', 'ner', 'prefix', 'lex', 'morph']
24
+ LABELS_TO_INDEX = {k:i for i,k in enumerate(INDEX_TO_LABELS)}
25
+
26
  @dataclass
27
  class JointParsingOutput(ModelOutput):
28
  loss: Optional[torch.FloatTensor] = None
 
55
  "cls.predictions.decoder.bias": "cls.predictions.bias",
56
  }
57
 
58
+ def __init__(self, config, do_syntax=None, do_ner=None, do_prefix=None, do_lex=None, do_morph=None, syntax_head_size=128):
59
  super().__init__(config)
60
 
61
  self.bert = BertModel(config, add_pooling_layer=False)
 
105
  position_ids: Optional[torch.Tensor] = None,
106
  prefix_class_id_options: Optional[torch.Tensor] = None,
107
  labels: Optional[Union[SyntaxLabels, MorphLabels, torch.Tensor]] = None,
108
+ labels_type: Optional[torch.Tensor] = None,
109
  head_mask: Optional[torch.Tensor] = None,
110
  inputs_embeds: Optional[torch.Tensor] = None,
111
  output_attentions: Optional[bool] = None,
 
119
  if labels is not None and labels_type is None:
120
  raise ValueError("Cannot specify labels without labels_type")
121
 
122
+ labels_type_str = INDEX_TO_LABELS[labels_type.detach().cpu().item()] if labels_type is not None else None
123
+ if labels_type_str == 'seg' and prefix_class_id_options is None:
124
  raise ValueError('Cannot calculate prefix logits without prefix_class_id_options')
125
 
126
  if compute_syntax_mst is not None and self.syntax is None:
 
155
  morph_logits = None
156
 
157
  # Calculate the syntax
158
+ if self.syntax is not None and (labels is None or labels_type_str == 'syntax'):
159
  # apply the syntax head
160
  loss, syntax_logits = self.syntax(hidden_states, extended_attention_mask, labels, compute_syntax_mst)
161
  logits = syntax_logits
162
 
163
  # Calculate the NER
164
+ if self.ner is not None and (labels is None or labels_type_str == 'ner'):
165
  ner_logits = self.ner(hidden_states)
166
  logits = ner_logits
167
  if labels is not None:
 
169
  loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
170
 
171
  # Calculate the segmentation
172
+ if self.prefix is not None and (labels is None or labels_type_str == 'prefix'):
173
  loss, prefix_logits = self.prefix(hidden_states, prefix_class_id_options, labels)
174
  logits = prefix_logits
175
 
176
  # Calculate the lexeme
177
+ if self.lex is not None and (labels is None or labels_type_str == 'lex'):
178
  lex_logits = self.lex(hidden_states)
179
  logits = lex_logits
180
  if labels is not None:
181
  loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
182
  loss = loss_fct(lex_logits.view(-1, self.config.vocab_size), labels.view(-1))
183
 
184
+ if self.morph is not None and (labels is None or labels_type_str == 'morph'):
185
  loss, morph_logits = self.morph(hidden_states, labels)
186
  logits = morph_logits
187
 
 
226
  final_output = [dict(text=sentence, tokens=combine_token_wordpieces(ids, offsets, tokenizer)) for sentence, ids, offsets in zip(sentences, input_ids, offset_mapping)]
227
  # Syntax logits: each sentence gets a dict(tree: List[dict(word,dep_head,dep_head_idx,dep_func)], root_idx: int)
228
  if output.syntax_logits is not None:
229
+ for sent_idx,parsed in enumerate(syntax_parse_logits(input_ids, sentences, tokenizer, output.syntax_logits, self.syntax.func_label_idx)):
230
  merge_token_list(final_output[sent_idx]['tokens'], parsed['tree'], 'syntax')
231
  final_output[sent_idx]['root_idx'] = parsed['root_idx']
232
 
 
415
  for pre in get_prefixes_from_str(word['seg'][0], model_cfg.prefix_cfg, greedy=True):
416
  # pos - just take the first valid pos that appears in the predicted prefixes list.
417
  pos = next((pos for pos in ud_prefixes_to_pos[pre] if pos in word['morph']['prefixes']), ud_prefixes_to_pos[pre][0])
418
+ dep, func = ud_get_prefix_dep(pre, word, word_idx, sentence['tokens'])
419
  intermediate_output.append(dict(word=pre, lex=pre, pos=pos, dep=dep, func=func, feats='_'))
420
 
421
  # if there was an implicit heh, add it in dependent on the method
 
475
  # if the function is obj, then add a את pointing to the next word
476
  elif func == 'obj' and s_lex != 'את':
477
  intermediate_output.append(dict(word='_את_', lex='את', pos='ADP', dep=len(intermediate_output) + 2, func='case', feats='_', absolute_dep=True))
 
478
  # add the main suffix in
479
  intermediate_output.append(dict(word=suf, lex='הוא', pos='PRON', dep=dep, func=func, feats='|'.join(f'{k}={v}' for k,v in word['morph']['suffix_feats'].items())))
480
  if entry_to_assign_suf_dep:
 
522
  return dep
523
 
524
 
525
+ def ud_get_prefix_dep(pre, word, word_idx, all_toks):
526
  does_follow_main = False
527
+ is_head_prev = False
528
+ does_follow_prev = False
529
 
530
+ # Special rabbinic daled case as an adposition, like psukei *de*-zimra
531
+ if pre == "ד" and "ADP" in word['morph']['prefixes']:
532
+ func = "case:gen"
533
+ # Special rabbinic quf case as an aspect-tense marker, like *qa*-amar
534
+ elif pre == "ק":
535
+ func = "aux"
536
  # shin goes to the main word for verbs, otherwise follows the word
537
+ elif pre.endswith('ש') or pre.endswith('ד'):
538
+ # short circuit for fixed subjugators (e.g. לפני ש, אף אל פי ש)
539
+ func = None
540
+ if word_idx > 0 and all_toks[word_idx - 1]['syntax']['dep_func'] == 'mark':
541
+ is_head_prev = True
542
+ func = 'fixed'
543
+ elif word_idx > 1 and all_toks[word_idx - 1]['syntax']['dep_func'] == 'fixed':
544
+ grandparent_index = all_toks[word_idx - 1]['syntax']['dep_head_idx']
545
+ if all_toks[grandparent_index]['syntax']['dep_func'] == 'mark':
546
+ does_follow_prev = True
547
+ func = 'fixed'
548
+ if func is None:
549
+ does_follow_main = word['morph']['pos'] != 'VERB' and word['syntax']['dep_head_idx'] > word_idx
550
+ func = 'mark'
551
  # vuv goes to the main word if the function is in the list, otherwise follows
552
  elif pre == 'ו':
553
  does_follow_main = word['syntax']['dep_func'] not in ["conj", "acl:recl", "parataxis", "root", "acl", "amod", "list", "appos", "dep", "flatccomp"]
 
563
  if pre == 'ה':
564
  func = 'det' if 'DET' in word['morph']['prefixes'] else 'mark'
565
 
566
+ if is_head_prev:
567
+ return word_idx - 1, func
568
+ elif does_follow_prev:
569
+ return all_toks[word_idx - 1]['syntax']['dep_head_idx'], func
570
  return (word['syntax']['dep_head_idx'] if does_follow_main else word_idx), func
BertForMorphTagging.py CHANGED
@@ -16,6 +16,12 @@ ALL_FEATURES = [
16
  ('Person', ['none', '1', '2', '3', '1,2,3']),
17
  ('Tense', ['none', 'Past', 'Fut', 'Pres', 'Imp'])
18
  ]
 
 
 
 
 
 
19
 
20
  @dataclass
21
  class MorphLogitsOutput(ModelOutput):
@@ -55,19 +61,22 @@ class BertMorphTaggingHead(nn.Module):
55
  super().__init__()
56
  self.config = config
57
 
58
- self.num_prefix_classes = len(ALL_PREFIX_POS)
59
- self.num_pos_classes = len(ALL_POS)
60
- self.num_suffix_classes = len(ALL_SUFFIX_POS)
61
- self.num_features_classes = list(map(len, map(itemgetter(1), ALL_FEATURES)))
 
 
 
62
  # we need a classifier for prefix cls and POS cls
63
  # the prefix will use BCEWithLogits for multiple labels cls
64
  self.prefix_cls = nn.Linear(config.hidden_size, self.num_prefix_classes)
65
  # and pos + feats will use good old cross entropy for single label
66
  self.pos_cls = nn.Linear(config.hidden_size, self.num_pos_classes)
67
- self.features_cls = nn.ModuleList([nn.Linear(config.hidden_size, len(features)) for _, features in ALL_FEATURES])
68
  # and suffix + feats will also be cross entropy
69
  self.suffix_cls = nn.Linear(config.hidden_size, self.num_suffix_classes)
70
- self.suffix_features_cls = nn.ModuleList([nn.Linear(config.hidden_size, len(features)) for _, features in ALL_FEATURES])
71
 
72
  def forward(
73
  self,
@@ -84,7 +93,7 @@ class BertMorphTaggingHead(nn.Module):
84
  if labels is not None:
85
  # step 1: prefix labels loss
86
  loss_fct = nn.BCEWithLogitsLoss(weight=(labels.prefix_labels != -100).float())
87
- loss = loss_fct(prefix_logits, labels.prefix_labels)
88
  # step 2: pos labels loss
89
  loss_fct = nn.CrossEntropyLoss()
90
  loss += loss_fct(pos_logits.view(-1, self.num_pos_classes), labels.pos_labels.view(-1))
@@ -178,7 +187,6 @@ def parse_logits(input_ids: List[List[int]], sentences: List[str], tokenizer: Be
178
  special_toks = tokenizer.all_special_tokens
179
  special_toks.remove(tokenizer.unk_token)
180
  special_toks.remove(tokenizer.mask_token)
181
-
182
  ret = []
183
  for sent_idx,sentence in enumerate(sentences):
184
  input_id_strs = tokenizer.convert_ids_to_tokens(input_ids[sent_idx])
 
16
  ('Person', ['none', '1', '2', '3', '1,2,3']),
17
  ('Tense', ['none', 'Past', 'Fut', 'Pres', 'Imp'])
18
  ]
19
+ ALL_FEATURES_MAP = {
20
+ 'Gender': {'Fem, Masc': 'Fem,Masc'},
21
+ 'Number': {},
22
+ 'Person': {},
23
+ 'Tense': { 'Present': 'Pres' }
24
+ }
25
 
26
  @dataclass
27
  class MorphLogitsOutput(ModelOutput):
 
61
  super().__init__()
62
  self.config = config
63
 
64
+ if not hasattr(config, 'classes_config'):
65
+ config.classes_config = dict(ALL_PREFIX_POS=ALL_PREFIX_POS, ALL_POS=ALL_POS, ALL_SUFFIX_POS=ALL_SUFFIX_POS, ALL_FEATURES=list(map(itemgetter(1), ALL_FEATURES)))
66
+
67
+ self.num_prefix_classes = len(config.classes_config['ALL_PREFIX_POS'])
68
+ self.num_pos_classes = len(config.classes_config['ALL_POS'])
69
+ self.num_suffix_classes = len(config.classes_config['ALL_SUFFIX_POS'])
70
+ self.num_features_classes = list(map(len, config.classes_config['ALL_FEATURES']))
71
  # we need a classifier for prefix cls and POS cls
72
  # the prefix will use BCEWithLogits for multiple labels cls
73
  self.prefix_cls = nn.Linear(config.hidden_size, self.num_prefix_classes)
74
  # and pos + feats will use good old cross entropy for single label
75
  self.pos_cls = nn.Linear(config.hidden_size, self.num_pos_classes)
76
+ self.features_cls = nn.ModuleList([nn.Linear(config.hidden_size, len(features)) for features in config.classes_config['ALL_FEATURES']])
77
  # and suffix + feats will also be cross entropy
78
  self.suffix_cls = nn.Linear(config.hidden_size, self.num_suffix_classes)
79
+ self.suffix_features_cls = nn.ModuleList([nn.Linear(config.hidden_size, len(features)) for features in config.classes_config['ALL_FEATURES']])
80
 
81
  def forward(
82
  self,
 
93
  if labels is not None:
94
  # step 1: prefix labels loss
95
  loss_fct = nn.BCEWithLogitsLoss(weight=(labels.prefix_labels != -100).float())
96
+ loss = loss_fct(prefix_logits, labels.prefix_labels) * 25#is the *25 needed? No idea, but worked for Rabbinic
97
  # step 2: pos labels loss
98
  loss_fct = nn.CrossEntropyLoss()
99
  loss += loss_fct(pos_logits.view(-1, self.num_pos_classes), labels.pos_labels.view(-1))
 
187
  special_toks = tokenizer.all_special_tokens
188
  special_toks.remove(tokenizer.unk_token)
189
  special_toks.remove(tokenizer.mask_token)
 
190
  ret = []
191
  for sent_idx,sentence in enumerate(sentences):
192
  input_id_strs = tokenizer.convert_ids_to_tokens(input_ids[sent_idx])
BertForPrefixMarking.py CHANGED
@@ -1,9 +1,15 @@
1
  from transformers.utils import ModelOutput
2
  import torch
3
  from torch import nn
4
- from typing import Dict, List, Tuple, Optional
5
  from dataclasses import dataclass
6
- from transformers import BertPreTrainedModel, BertModel, BertTokenizerFast
 
 
 
 
 
 
7
 
8
  # define the classes, and the possible prefixes for each class
9
  POSSIBLE_PREFIX_CLASSES = [ ['לכש', 'כש', 'מש', 'בש', 'לש'], ['מ'], ['ש'], ['ה'], ['ו'], ['כ'], ['ל'], ['ב'] ]
@@ -104,14 +110,22 @@ class BertPrefixMarkingHead(nn.Module):
104
 
105
  return (loss, logits)
106
 
107
-
108
-
109
- class BertForPrefixMarking(BertPreTrainedModel):
110
-
111
- def __init__(self, config):
 
 
 
 
112
  super().__init__(config)
 
 
 
 
 
113
 
114
- self.bert = BertModel(config, add_pooling_layer=False)
115
  self.dropout = nn.Dropout(config.hidden_dropout_prob)
116
  self.prefix = BertPrefixMarkingHead(config)
117
 
@@ -138,16 +152,17 @@ class BertForPrefixMarking(BertPreTrainedModel):
138
  """
139
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
140
 
 
 
141
  bert_outputs = self.bert(
142
  input_ids,
143
  attention_mask=attention_mask,
144
- token_type_ids=token_type_ids,
145
  position_ids=position_ids,
146
- head_mask=head_mask,
147
  inputs_embeds=inputs_embeds,
148
  output_attentions=output_attentions,
149
  output_hidden_states=output_hidden_states,
150
  return_dict=return_dict,
 
151
  )
152
 
153
  hidden_states = bert_outputs[0]
@@ -174,6 +189,20 @@ class BertForPrefixMarking(BertPreTrainedModel):
174
  logits = self.forward(**inputs, return_dict=True).logits
175
  return parse_logits(inputs['input_ids'].tolist(), sentences, tokenizer, logits, self.config.prefix_cfg)
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  def parse_logits(input_ids: List[List[int]], sentences: List[str], tokenizer: BertTokenizerFast, logits: torch.FloatTensor, config: PrefixConfig):
178
  # extract the predictions by argmaxing the final dimension (batch x sequence x prefixes x prediction)
179
  logit_preds = torch.argmax(logits, axis=3).tolist()
@@ -182,6 +211,7 @@ def parse_logits(input_ids: List[List[int]], sentences: List[str], tokenizer: Be
182
 
183
  for sent_idx,sent_ids in enumerate(input_ids):
184
  tokens = tokenizer.convert_ids_to_tokens(sent_ids)
 
185
  ret.append([])
186
  for tok_idx,token in enumerate(tokens):
187
  # If we've reached the pad token, then we are at the end
@@ -193,6 +223,9 @@ def parse_logits(input_ids: List[List[int]], sentences: List[str], tokenizer: Be
193
  while next_tok_idx < len(tokens) and tokens[next_tok_idx].startswith('##'):
194
  token += tokens[next_tok_idx][2:]
195
  next_tok_idx += 1
 
 
 
196
 
197
  prefix_len = get_predicted_prefix_len_from_logits(token, logit_preds[sent_idx][tok_idx], config)
198
 
 
1
  from transformers.utils import ModelOutput
2
  import torch
3
  from torch import nn
4
+ from typing import Dict, List, Tuple, Optional, Union
5
  from dataclasses import dataclass
6
+ from transformers import BertPreTrainedModel, BertModel, BertTokenizerFast, AutoConfig, AutoModel
7
+ from transformers.models.auto.auto_factory import _BaseAutoModelClass
8
+ try:
9
+ from transformers.modeling_utils import no_init_weights
10
+ except ImportError:
11
+ from transformers.initialization import no_init_weights
12
+ import inspect, os
13
 
14
  # define the classes, and the possible prefixes for each class
15
  POSSIBLE_PREFIX_CLASSES = [ ['לכש', 'כש', 'מש', 'בש', 'לש'], ['מ'], ['ש'], ['ה'], ['ו'], ['כ'], ['ל'], ['ב'] ]
 
110
 
111
  return (loss, logits)
112
 
113
+ def can_func_take_parameter(fn, param_name):
114
+ signature = inspect.signature(fn)
115
+ # Exclude 'self' from parameters
116
+ parameters = [p.name for p in signature.parameters.values() if p.name != 'self']
117
+ return 'kwargs' in parameters or param_name in parameters
118
+
119
+ class BaseForPrefixMarking(BertPreTrainedModel):
120
+ base_model_prefix = ""
121
+ def __init__(self, config, bert_cls=BertModel):
122
  super().__init__(config)
123
+ setattr(config, "hidden_dropout_prob", getattr(config, "hidden_dropout_prob", 0.1))
124
+ setattr(config, "initializer_range", getattr(config, "classifier_init_range", getattr(config, 'decoder_init_range', 0.02)))
125
+
126
+ self.bert = bert_cls(config, **({} if not can_func_take_parameter(bert_cls.__init__, 'add_pooling_layer') else {'add_pooling_layer': False}))
127
+ self.send_token_type_ids = can_func_take_parameter(self.bert.forward, 'token_type_ids')
128
 
 
129
  self.dropout = nn.Dropout(config.hidden_dropout_prob)
130
  self.prefix = BertPrefixMarkingHead(config)
131
 
 
152
  """
153
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
154
 
155
+ kwargs = dict(token_type_ids=token_type_ids, head_mask=head_mask) if self.send_token_type_ids else {}
156
+
157
  bert_outputs = self.bert(
158
  input_ids,
159
  attention_mask=attention_mask,
 
160
  position_ids=position_ids,
 
161
  inputs_embeds=inputs_embeds,
162
  output_attentions=output_attentions,
163
  output_hidden_states=output_hidden_states,
164
  return_dict=return_dict,
165
+ **kwargs
166
  )
167
 
168
  hidden_states = bert_outputs[0]
 
189
  logits = self.forward(**inputs, return_dict=True).logits
190
  return parse_logits(inputs['input_ids'].tolist(), sentences, tokenizer, logits, self.config.prefix_cfg)
191
 
192
+
193
+ class AutoForPrefixMarking(_BaseAutoModelClass):
194
+ @classmethod
195
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *args, **kwargs):
196
+ auto_cfg = AutoConfig.from_pretrained(pretrained_model_name_or_path, trust_remote_code=True)
197
+ base_cls = BaseForPrefixMarking
198
+ with no_init_weights():
199
+ bert_cls = AutoModel.from_config(auto_cfg, *args, **{k: v for k, v in kwargs.items() if k != 'config'}).__class__
200
+ if 'Prefix' in bert_cls.__name__:
201
+ base_cls = bert_cls
202
+
203
+ return base_cls.from_pretrained(pretrained_model_name_or_path, *args, **kwargs, bert_cls=bert_cls, key_mapping={"^model": "bert"})
204
+
205
+
206
  def parse_logits(input_ids: List[List[int]], sentences: List[str], tokenizer: BertTokenizerFast, logits: torch.FloatTensor, config: PrefixConfig):
207
  # extract the predictions by argmaxing the final dimension (batch x sequence x prefixes x prediction)
208
  logit_preds = torch.argmax(logits, axis=3).tolist()
 
211
 
212
  for sent_idx,sent_ids in enumerate(input_ids):
213
  tokens = tokenizer.convert_ids_to_tokens(sent_ids)
214
+
215
  ret.append([])
216
  for tok_idx,token in enumerate(tokens):
217
  # If we've reached the pad token, then we are at the end
 
223
  while next_tok_idx < len(tokens) and tokens[next_tok_idx].startswith('##'):
224
  token += tokens[next_tok_idx][2:]
225
  next_tok_idx += 1
226
+
227
+ if hasattr(tokenizer, 'splinter') and tokenizer.splinter:
228
+ token = tokenizer.splinter.unsplinter_word(token)
229
 
230
  prefix_len = get_predicted_prefix_len_from_logits(token, logit_preds[sent_idx][tok_idx], config)
231
 
BertForSyntaxParsing.py CHANGED
@@ -1,12 +1,19 @@
1
- import math
2
  from transformers.utils import ModelOutput
3
  import torch
4
  from torch import nn
5
  from typing import Dict, List, Tuple, Optional, Union
6
  from dataclasses import dataclass
7
- from transformers import BertPreTrainedModel, BertModel, BertTokenizerFast
 
 
 
 
 
 
8
 
9
  ALL_FUNCTION_LABELS = ["nsubj", "nsubj:cop", "punct", "mark", "mark:q", "case", "case:gen", "case:acc", "fixed", "obl", "det", "amod", "acl:relcl", "nmod", "cc", "conj", "root", "compound:smixut", "cop", "compound:affix", "advmod", "nummod", "appos", "nsubj:pass", "nmod:poss", "xcomp", "obj", "aux", "parataxis", "advcl", "ccomp", "csubj", "acl", "obl:tmod", "csubj:pass", "dep", "dislocated", "nmod:tmod", "nmod:npmod", "flat", "obl:npmod", "goeswith", "reparandum", "orphan", "list", "discourse", "iobj", "vocative", "expl", "flat:name"]
 
10
 
11
  @dataclass
12
  class SyntaxLogitsOutput(ModelOutput):
@@ -20,7 +27,7 @@ class SyntaxLogitsOutput(ModelOutput):
20
  @dataclass
21
  class SyntaxTaggingOutput(ModelOutput):
22
  loss: Optional[torch.FloatTensor] = None
23
- logits: Optional[SyntaxLogitsOutput] = None
24
  hidden_states: Optional[Tuple[torch.FloatTensor]] = None
25
  attentions: Optional[Tuple[torch.FloatTensor]] = None
26
 
@@ -28,13 +35,124 @@ class SyntaxTaggingOutput(ModelOutput):
28
  class SyntaxLabels(ModelOutput):
29
  dependency_labels: Optional[torch.LongTensor] = None
30
  function_labels: Optional[torch.LongTensor] = None
 
31
 
32
  def detach(self):
33
- return SyntaxLabels(self.dependency_labels.detach(), self.function_labels.detach())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- def to(self, device):
36
- return SyntaxLabels(self.dependency_labels.to(device), self.function_labels.to(device))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
 
 
38
  class BertSyntaxParsingHead(nn.Module):
39
  def __init__(self, config):
40
  super().__init__()
@@ -42,11 +160,15 @@ class BertSyntaxParsingHead(nn.Module):
42
 
43
  # the attention query & key values
44
  self.head_size = config.syntax_head_size# int(config.hidden_size / config.num_attention_heads * 2)
45
- self.query = nn.Linear(config.hidden_size, self.head_size)
46
- self.key = nn.Linear(config.hidden_size, self.head_size)
 
47
  # the function classifier gets two encoding values and predicts the labels
 
48
  self.num_function_classes = len(ALL_FUNCTION_LABELS)
49
- self.cls = nn.Linear(config.hidden_size * 2, self.num_function_classes)
 
 
50
 
51
  def forward(
52
  self,
@@ -54,36 +176,44 @@ class BertSyntaxParsingHead(nn.Module):
54
  extended_attention_mask: Optional[torch.Tensor],
55
  labels: Optional[SyntaxLabels] = None,
56
  compute_mst: bool = False) -> Tuple[torch.Tensor, SyntaxLogitsOutput]:
 
 
57
 
58
- # Take the dot product between "query" and "key" to get the raw attention scores.
59
- query_layer = self.query(hidden_states)
60
- key_layer = self.key(hidden_states)
61
- attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / math.sqrt(self.head_size)
62
 
 
 
 
 
 
 
63
  # add in the attention mask
64
  if extended_attention_mask is not None:
65
- if extended_attention_mask.ndim == 4:
66
- extended_attention_mask = extended_attention_mask.squeeze(1)
67
- attention_scores += extended_attention_mask# batch x seq x seq
68
 
69
  # At this point take the hidden_state of the word and of the dependency word, and predict the function
70
  # If labels are provided, use the labels.
71
  if self.training and labels is not None:
72
  # Note that the labels can have -100, so just set those to zero with a max
73
- dep_indices = labels.dependency_labels.clamp_min(0)
74
  # Otherwise - check if he wants the MST or just the argmax
75
  elif compute_mst:
76
- dep_indices = compute_mst_tree(attention_scores, extended_attention_mask)
77
  else:
78
- dep_indices = torch.argmax(attention_scores, dim=-1)
79
-
80
- # After we retrieved the dependency indicies, create a tensor of teh batch indices, and and retrieve the vectors of the heads to calculate the function
81
- batch_indices = torch.arange(dep_indices.size(0)).view(-1, 1).expand(-1, dep_indices.size(1)).to(dep_indices.device)
82
- dep_vectors = hidden_states[batch_indices, dep_indices, :] # batch x seq x dim
83
-
84
- # concatenate that with the last hidden states, and send to the classifier output
85
- cls_inputs = torch.cat((hidden_states, dep_vectors), dim=-1)
86
- function_logits = self.cls(cls_inputs)
 
 
 
 
 
87
 
88
  loss = None
89
  if labels is not None:
@@ -91,19 +221,72 @@ class BertSyntaxParsingHead(nn.Module):
91
  # step 1: dependency scores loss - this is applied to the attention scores
92
  loss = loss_fct(attention_scores.view(-1, hidden_states.size(-2)), labels.dependency_labels.view(-1))
93
  # step 2: function loss
94
- loss += loss_fct(function_logits.view(-1, self.num_function_classes), labels.function_labels.view(-1))
 
95
 
96
  return (loss, SyntaxLogitsOutput(attention_scores, function_logits, dep_indices))
97
 
 
 
 
 
 
98
 
99
- class BertForSyntaxParsing(BertPreTrainedModel):
100
-
101
- def __init__(self, config):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  super().__init__(config)
103
-
104
- self.bert = BertModel(config, add_pooling_layer=False)
105
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
106
- self.syntax = BertSyntaxParsingHead(config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  # Initialize weights and apply final processing
109
  self.post_init()
@@ -114,7 +297,8 @@ class BertForSyntaxParsing(BertPreTrainedModel):
114
  attention_mask: Optional[torch.Tensor] = None,
115
  token_type_ids: Optional[torch.Tensor] = None,
116
  position_ids: Optional[torch.Tensor] = None,
117
- labels: Optional[SyntaxLabels] = None,
 
118
  head_mask: Optional[torch.Tensor] = None,
119
  inputs_embeds: Optional[torch.Tensor] = None,
120
  output_attentions: Optional[bool] = None,
@@ -124,25 +308,49 @@ class BertForSyntaxParsing(BertPreTrainedModel):
124
  ):
125
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
126
 
 
 
 
 
 
 
 
 
 
 
127
  bert_outputs = self.bert(
128
  input_ids,
129
  attention_mask=attention_mask,
130
- token_type_ids=token_type_ids,
131
  position_ids=position_ids,
132
- head_mask=head_mask,
133
  inputs_embeds=inputs_embeds,
134
  output_attentions=output_attentions,
135
  output_hidden_states=output_hidden_states,
136
  return_dict=return_dict,
 
137
  )
138
 
139
  extended_attention_mask = None
140
  if attention_mask is not None:
141
  extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_ids.size())
 
 
 
 
 
 
 
142
  # apply the syntax head
143
- loss, logits = self.syntax(self.dropout(bert_outputs[0]), extended_attention_mask, labels, compute_syntax_mst)
144
 
 
 
 
 
 
 
145
  if not return_dict:
 
 
146
  return (loss,(logits.dependency_logits, logits.function_logits)) + bert_outputs[2:]
147
 
148
  return SyntaxTaggingOutput(
@@ -152,7 +360,15 @@ class BertForSyntaxParsing(BertPreTrainedModel):
152
  attentions=bert_outputs.attentions,
153
  )
154
 
 
 
 
 
 
 
155
  def predict(self, sentences: Union[str, List[str]], tokenizer: BertTokenizerFast, compute_mst=True):
 
 
156
  if isinstance(sentences, str):
157
  sentences = [sentences]
158
 
@@ -160,17 +376,32 @@ class BertForSyntaxParsing(BertPreTrainedModel):
160
  inputs = tokenizer(sentences, padding='longest', truncation=True, return_tensors='pt')
161
  inputs = {k:v.to(self.device) for k,v in inputs.items()}
162
  logits = self.forward(**inputs, return_dict=True, compute_syntax_mst=compute_mst).logits
163
- return parse_logits(inputs['input_ids'].tolist(), sentences, tokenizer, logits)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
- def parse_logits(input_ids: List[List[int]], sentences: List[str], tokenizer: BertTokenizerFast, logits: SyntaxLogitsOutput):
166
  outputs = []
167
 
168
  special_toks = tokenizer.all_special_tokens
169
  special_toks.remove(tokenizer.unk_token)
170
  special_toks.remove(tokenizer.mask_token)
171
-
172
  for i in range(len(sentences)):
173
- deps = logits.dependency_head_indices[i].tolist()
 
174
  funcs = logits.function_logits.argmax(-1)[i].tolist()
175
  toks = [tok for tok in tokenizer.convert_ids_to_tokens(input_ids[i]) if tok not in special_toks]
176
 
@@ -312,4 +543,7 @@ def choose_contracting_arc(indices: torch.LongTensor, sorted_indices: List[List[
312
  if best_base_idx == -1:
313
  raise ValueError('Stuck in endless loop trying to compute syntax mst. Please try again setting compute_syntax_mst=False')
314
 
315
- return best_base_idx, best_head_idx
 
 
 
 
1
+ import math, os, inspect
2
  from transformers.utils import ModelOutput
3
  import torch
4
  from torch import nn
5
  from typing import Dict, List, Tuple, Optional, Union
6
  from dataclasses import dataclass
7
+ from transformers import BertPreTrainedModel, BertModel, BertTokenizerFast, AutoModel, AutoConfig
8
+ from transformers.models.auto.auto_factory import _BaseAutoModelClass
9
+ try:
10
+ from transformers.modeling_utils import no_init_weights
11
+ except ImportError:
12
+ from transformers.initialization import no_init_weights
13
+
14
 
15
  ALL_FUNCTION_LABELS = ["nsubj", "nsubj:cop", "punct", "mark", "mark:q", "case", "case:gen", "case:acc", "fixed", "obl", "det", "amod", "acl:relcl", "nmod", "cc", "conj", "root", "compound:smixut", "cop", "compound:affix", "advmod", "nummod", "appos", "nsubj:pass", "nmod:poss", "xcomp", "obj", "aux", "parataxis", "advcl", "ccomp", "csubj", "acl", "obl:tmod", "csubj:pass", "dep", "dislocated", "nmod:tmod", "nmod:npmod", "flat", "obl:npmod", "goeswith", "reparandum", "orphan", "list", "discourse", "iobj", "vocative", "expl", "flat:name"]
16
+ ALL_POS = ['DET', 'NOUN', 'VERB', 'CCONJ', 'ADP', 'PRON', 'PUNCT', 'ADJ', 'ADV', 'SCONJ', 'NUM', 'PROPN', 'AUX', 'X', 'INTJ', 'SYM']
17
 
18
  @dataclass
19
  class SyntaxLogitsOutput(ModelOutput):
 
27
  @dataclass
28
  class SyntaxTaggingOutput(ModelOutput):
29
  loss: Optional[torch.FloatTensor] = None
30
+ logits: Optional[Union[torch.FloatTensor, SyntaxLogitsOutput]] = None
31
  hidden_states: Optional[Tuple[torch.FloatTensor]] = None
32
  attentions: Optional[Tuple[torch.FloatTensor]] = None
33
 
 
35
  class SyntaxLabels(ModelOutput):
36
  dependency_labels: Optional[torch.LongTensor] = None
37
  function_labels: Optional[torch.LongTensor] = None
38
+ pos_labels: Optional[torch.LongTensor] = None
39
 
40
  def detach(self):
41
+ return SyntaxLabels(self.dependency_labels.detach(), self.function_labels.detach(), self.pos_labels.detach() if self.pos_labels is not None else None)
42
+
43
+ def to(self, device, non_blocking=False):
44
+ return SyntaxLabels(self.dependency_labels.to(device, non_blocking=non_blocking), self.function_labels.to(device, non_blocking=non_blocking), self.pos_labels.to(device, non_blocking=non_blocking) if self.pos_labels is not None else None)
45
+
46
+ class BertSyntaxPartialInfoHead(nn.Module):
47
+ def __init__(self, config):
48
+ super().__init__()
49
+ self.config = config
50
+
51
+ # we want an embedding table of size 64 for each function label & unk + a single parameter embedding for unknown head
52
+ FUNCTION_CLASS_EMBED_SIZE = 64
53
+ TRANSFORM_SIZE = config.hidden_size * 2 + FUNCTION_CLASS_EMBED_SIZE
54
+ self.function_class_embed = nn.Embedding(len(ALL_FUNCTION_LABELS) + 1, FUNCTION_CLASS_EMBED_SIZE)
55
+ self.unk_function_class = len(ALL_FUNCTION_LABELS) # 0-based
56
+ self.head_unk_embed = nn.Embedding(1, config.hidden_size)
57
+
58
+ if False:
59
+ TRANSFORM_SIZE += FUNCTION_CLASS_EMBED_SIZE
60
+ self.pos_class_embed = nn.Embedding(len(ALL_POS) + 1, FUNCTION_CLASS_EMBED_SIZE)
61
+ self.unk_pos_class = len(ALL_POS) # 0-based
62
+
63
+ # Linear layer to transform the hidden states + activation
64
+ self.transform = nn.Linear(TRANSFORM_SIZE, config.hidden_size)
65
+ self.activation = nn.Tanh()
66
+
67
+ # Auxiliary classifier to predict the input function labels from the transformed hidden states
68
+ if False:
69
+ self.aux_function_classifier = nn.Linear(config.hidden_size, len(ALL_FUNCTION_LABELS))
70
+ self.aux_loss_weight = getattr(config, 'partial_info_aux_loss_weight', 0.6)
71
+
72
+ # Storage for auxiliary losses from each layer (will be accumulated during forward passes)
73
+ # Note: This won't work correctly in distributed training - we check and skip if distributed
74
+ self.aux_losses = []
75
+ self._partial_labels = None
76
+ if torch.distributed.is_initialized():
77
+ raise NotImplementedError("Partial info head not supported in distributed training")
78
 
79
+ def clear_aux_losses(self):
80
+ self.aux_losses = []
81
+
82
+ def set_partial_labels(self, partial_labels: SyntaxLabels):
83
+ self._partial_labels = partial_labels
84
+
85
+ def get_total_aux_loss(self):
86
+ if not self.aux_losses:
87
+ return None
88
+ total_loss = sum(self.aux_losses)
89
+ return total_loss * self.aux_loss_weight
90
+
91
+ def forward(
92
+ self,
93
+ hidden_states: torch.Tensor,
94
+ ) -> torch.Tensor:
95
+
96
+ is_tuple, tuple_values = False, (None,)
97
+ if isinstance(hidden_states, tuple):
98
+ is_tuple = True
99
+ hidden_states, tuple_values = hidden_states[0], hidden_states[1:]
100
+
101
+ # lookup the function embeddings - turn the -1s into the unknown function label
102
+ function_embeddings = self.function_class_embed(replace_tensor_value(self._partial_labels.function_labels.clamp_min(-1), -1, self.unk_function_class))
103
+ # lookup the dependency embeddings - first just lookup the labels in the hidden_states - for now -1 gets clamped to 0, we don't care
104
+ # after that, replace the -1s, with the actual value
105
+ dependency_embedding = torch.gather(hidden_states, 1, self._partial_labels.dependency_labels.unsqueeze(-1).expand(-1, -1, self.config.hidden_size).clamp_min(0))
106
+ dependency_embedding = torch.where((self._partial_labels.dependency_labels == -1).unsqueeze(-1), self.head_unk_embed.weight[0], dependency_embedding)
107
+
108
+ # cat them all into a single embedding
109
+ intermediate_states = torch.cat([hidden_states, function_embeddings, dependency_embedding], dim=-1)
110
+
111
+ if False:
112
+ pos_embeddings = self.pos_class_embed(replace_tensor_value(self._partial_labels.pos_labels.clamp_min(-1), -1, self.unk_pos_class))
113
+ intermediate_states = torch.cat([intermediate_states, pos_embeddings], dim=-1)
114
+
115
+ # run through transform and activation
116
+ transformed = self.activation(self.transform(intermediate_states))
117
+
118
+ # Auxiliary classifier: predict the input function labels from the transformed hidden states
119
+ if self.training and self._partial_labels is not None and False:
120
+ aux_logits = self.aux_function_classifier(transformed)
121
+ # Compute auxiliary loss - only on positions where we have valid function labels (not -1)
122
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-1)
123
+ aux_loss = loss_fct(aux_logits.view(-1, len(ALL_FUNCTION_LABELS)), self._partial_labels.function_labels.clamp_min(-1).view(-1))
124
+ self.aux_losses.append(aux_loss)
125
+
126
+ if is_tuple:
127
+ return (transformed, *tuple_values)
128
+ return transformed
129
+
130
+ class BertSyntaxValidClassifierHead(nn.Module):
131
+ def __init__(self, config):
132
+ super().__init__()
133
+ self.config = config
134
+
135
+ self.transform = nn.Linear(config.hidden_size, config.hidden_size)
136
+ self.act = nn.Tanh()
137
+ self.cls = nn.Linear(config.hidden_size, 2) # valid / invalid
138
+
139
+ def forward(
140
+ self,
141
+ hidden_states: torch.Tensor,
142
+ extended_attention_mask: Optional[torch.Tensor] = None,
143
+ labels: Optional[torch.Tensor] = None,
144
+ compute_mst: bool = None) -> Tuple[torch.Tensor, torch.Tensor]:
145
+ # transform the hidden states
146
+ transformed_states = self.act(self.transform(hidden_states[:, 0, :])) # batch x dim
147
+ logits = self.cls(transformed_states) # batch x 2
148
+
149
+ loss = None
150
+ if labels is not None:
151
+ loss_fct = nn.CrossEntropyLoss()
152
+ loss = loss_fct(logits.view(-1, 2), labels.view(-1))
153
 
154
+ return (loss, logits)
155
+
156
  class BertSyntaxParsingHead(nn.Module):
157
  def __init__(self, config):
158
  super().__init__()
 
160
 
161
  # the attention query & key values
162
  self.head_size = config.syntax_head_size# int(config.hidden_size / config.num_attention_heads * 2)
163
+ self.label_count = getattr(config, 'syntax_attn_label_count', 1)
164
+ self.query = nn.Linear(config.hidden_size, self.head_size * self.label_count)
165
+ self.key = nn.Linear(config.hidden_size, self.head_size * self.label_count)
166
  # the function classifier gets two encoding values and predicts the labels
167
+ self.func_label_idx = getattr(config, 'syntax_func_label_idx', 0)
168
  self.num_function_classes = len(ALL_FUNCTION_LABELS)
169
+ if self.func_label_idx > -1:
170
+ self.cls = nn.Linear(config.hidden_size * 2, self.num_function_classes)
171
+ else: self.cls = None
172
 
173
  def forward(
174
  self,
 
176
  extended_attention_mask: Optional[torch.Tensor],
177
  labels: Optional[SyntaxLabels] = None,
178
  compute_mst: bool = False) -> Tuple[torch.Tensor, SyntaxLogitsOutput]:
179
+ if compute_mst:
180
+ assert self.label_count == 1, "Cannot compute MST with multiple attention labels - please set syntax_attn_label_count to 1"
181
 
182
+ device = hidden_states.device
 
 
 
183
 
184
+ # Take the dot product between "query" and "key" to get the raw attention scores.
185
+ hidden_shape = (*hidden_states.shape[:-1], -1, self.head_size) # batch x seq x label_count x head_size
186
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
187
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
188
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) / math.sqrt(self.head_size) # batch x label_count x seq x seq
189
+
190
  # add in the attention mask
191
  if extended_attention_mask is not None:
192
+ attention_scores += extended_attention_mask# batch x label_count x seq x seq
 
 
193
 
194
  # At this point take the hidden_state of the word and of the dependency word, and predict the function
195
  # If labels are provided, use the labels.
196
  if self.training and labels is not None:
197
  # Note that the labels can have -100, so just set those to zero with a max
198
+ dep_indices = labels.dependency_labels.clamp_min(0) # batch x seq x label_count
199
  # Otherwise - check if he wants the MST or just the argmax
200
  elif compute_mst:
201
+ dep_indices = compute_mst_tree(attention_scores[:, self.func_label_idx, :, :], extended_attention_mask[:, self.func_label_idx, :, :]).unsqueeze(-1) # batch x seq x 1
202
  else:
203
+ dep_indices = torch.argmax(attention_scores, dim=-1).transpose(-1, -2) # batch x seq x label_count
204
+
205
+ function_logits = None
206
+ if self.cls:
207
+ # After we retrieved the dependency indicies, create a tensor of teh batch indices, and and retrieve the vectors of the heads to calculate the function
208
+ # Equivalent to:
209
+ # batch_indices = torch.arange(dep_indices.size(0)).view(-1, 1).expand(-1, dep_indices.size(1)).to(dep_indices.device)
210
+ # hidden_states[batch_indices, dep_indices, :] # batch x seq x dim
211
+ dep_vectors = torch.gather(hidden_states, 1,
212
+ dep_indices[:, :, self.func_label_idx].unsqueeze(-1).expand(-1, -1, hidden_states.size(-1)))
213
+
214
+ # concatenate that with the last hidden states, and send to the classifier output
215
+ cls_inputs = torch.cat((hidden_states, dep_vectors), dim=-1)
216
+ function_logits = self.cls(cls_inputs)
217
 
218
  loss = None
219
  if labels is not None:
 
221
  # step 1: dependency scores loss - this is applied to the attention scores
222
  loss = loss_fct(attention_scores.view(-1, hidden_states.size(-2)), labels.dependency_labels.view(-1))
223
  # step 2: function loss
224
+ if self.cls:
225
+ loss += loss_fct(function_logits.view(-1, self.num_function_classes), labels.function_labels.view(-1))
226
 
227
  return (loss, SyntaxLogitsOutput(attention_scores, function_logits, dep_indices))
228
 
229
+ def can_func_take_parameter(fn, param_name):
230
+ signature = inspect.signature(fn)
231
+ # Exclude 'self' from parameters
232
+ parameters = [p.name for p in signature.parameters.values() if p.name != 'self']
233
+ return 'kwargs' in parameters or param_name in parameters
234
 
235
+ class BertLayerWrapper(nn.Module):
236
+ def __init__(self, layer_idx: int, bert_layer: nn.Module, partial_info: nn.Module):
237
+ super().__init__()
238
+ self.layer_idx = layer_idx
239
+ self.bert_layer = bert_layer
240
+ self.partial_info = partial_info
241
+
242
+ def forward(self, **kwargs):
243
+ hidden_states = self.bert_layer(**kwargs)
244
+ hidden_states = self.partial_info(hidden_states)
245
+ return hidden_states
246
+
247
+ def wrap_bert_layer_with_partial_info(layer_idx: int, bert_layer: nn.Module, partial_info: nn.Module):
248
+ if layer_idx != 8: return
249
+ orig_forward = bert_layer.forward
250
+ def new_forward(*args, **kwargs):
251
+ hidden_states = orig_forward(*args, **kwargs)
252
+ # Read partial_labels from the module instead of kwargs
253
+ hidden_states = partial_info(hidden_states)
254
+ return hidden_states
255
+ bert_layer.forward = new_forward
256
+
257
+ class BaseForSyntaxParsing(BertPreTrainedModel):
258
+ base_model_prefix = ""
259
+ def __init__(self, config, syntax_head_size=128, bert_cls=BertModel, is_partial_info_model=False, is_cls_model=False, syntax_attn_label_count=1, syntax_func_label_idx=0):
260
  super().__init__(config)
261
+ # conversions
262
+ setattr(config, "hidden_dropout_prob", getattr(config, "hidden_dropout_prob", 0.1))
263
+ setattr(config, "initializer_range", getattr(config, "classifier_init_range", getattr(config, 'decoder_init_range', 0.02)))
264
+
265
+ if not hasattr(config, 'syntax_head_size'):
266
+ config.syntax_head_size = syntax_head_size
267
+ if not hasattr(config, 'syntax_attn_label_count'):
268
+ config.syntax_attn_label_count = syntax_attn_label_count
269
+ if not hasattr(config, 'syntax_func_label_idx'):
270
+ config.syntax_func_label_idx = syntax_func_label_idx
271
+ if not hasattr(config, 'is_partial_info_model'):
272
+ config.is_partial_info_model = is_partial_info_model
273
+ if not hasattr(config, 'is_cls_model'):
274
+ config.is_cls_model = is_cls_model
275
+ # if is_cls_model:
276
+ # assert config.is_partial_info_model, "CLS model requires partial info model to be set to True"
277
+
278
+ self.bert = bert_cls(config, **({} if not can_func_take_parameter(bert_cls.__init__, 'add_pooling_layer') else {'add_pooling_layer': False}))
279
+ self.send_token_type_ids = can_func_take_parameter(self.bert.forward, 'token_type_ids')
280
+ self.dropout = nn.Dropout(getattr(config, "hidden_dropout_prob", 0.1))
281
+ if config.is_partial_info_model:
282
+ self.partial_info = BertSyntaxPartialInfoHead(config)
283
+ for layer_idx, layer in enumerate(self.bert.encoder.layer):
284
+ wrap_bert_layer_with_partial_info(layer_idx, layer, self.partial_info)
285
+ # self.bert.encoder.layer = nn.ModuleList([BertLayerWrapper(layer_idx, layer, self.partial_info) for layer_idx, layer in enumerate(self.bert.encoder.layer)])
286
+ if config.is_cls_model:
287
+ self.syntax = BertSyntaxValidClassifierHead(config)
288
+ else:
289
+ self.syntax = BertSyntaxParsingHead(config)
290
 
291
  # Initialize weights and apply final processing
292
  self.post_init()
 
297
  attention_mask: Optional[torch.Tensor] = None,
298
  token_type_ids: Optional[torch.Tensor] = None,
299
  position_ids: Optional[torch.Tensor] = None,
300
+ partial_labels: Optional[torch.Tensor] = None,
301
+ labels: Optional[Union[SyntaxLabels, torch.Tensor]] = None,
302
  head_mask: Optional[torch.Tensor] = None,
303
  inputs_embeds: Optional[torch.Tensor] = None,
304
  output_attentions: Optional[bool] = None,
 
308
  ):
309
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
310
 
311
+ if not self.config.is_partial_info_model and partial_labels:
312
+ raise ValueError('Cannot pass partial label when model not initialized with partial info')
313
+
314
+ kwargs = dict(token_type_ids=token_type_ids, head_mask=head_mask) if self.send_token_type_ids else {}
315
+ if self.config.is_partial_info_model:
316
+ # Store partial_labels on the module (avoids passing through kwargs which newer BERT doesn't support)
317
+ self.partial_info.set_partial_labels(partial_labels)
318
+ # Clear auxiliary losses before forward pass
319
+ self.partial_info.clear_aux_losses()
320
+
321
  bert_outputs = self.bert(
322
  input_ids,
323
  attention_mask=attention_mask,
 
324
  position_ids=position_ids,
 
325
  inputs_embeds=inputs_embeds,
326
  output_attentions=output_attentions,
327
  output_hidden_states=output_hidden_states,
328
  return_dict=return_dict,
329
+ **kwargs
330
  )
331
 
332
  extended_attention_mask = None
333
  if attention_mask is not None:
334
  extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_ids.size())
335
+
336
+ hidden_states = self.dropout(bert_outputs[0])
337
+
338
+ # if self.config.is_partial_info_model:
339
+ # partial_labels = partial_labels or SyntaxLabels(dependency_labels=torch.full_like(input_ids, -1), function_labels=torch.full_like(input_ids, -1))
340
+ # hidden_states = self.partial_info(hidden_states, partial_labels)
341
+
342
  # apply the syntax head
343
+ loss, logits = self.syntax(hidden_states, extended_attention_mask, labels, compute_syntax_mst)
344
 
345
+ # Add auxiliary loss from partial info head (weighted lightly)
346
+ if self.config.is_partial_info_model and self.training:
347
+ aux_loss = self.partial_info.get_total_aux_loss()
348
+ if aux_loss is not None and loss is not None:
349
+ loss = loss + aux_loss
350
+
351
  if not return_dict:
352
+ if self.config.is_cls_model:
353
+ return (loss, logits) + bert_outputs[2:]
354
  return (loss,(logits.dependency_logits, logits.function_logits)) + bert_outputs[2:]
355
 
356
  return SyntaxTaggingOutput(
 
360
  attentions=bert_outputs.attentions,
361
  )
362
 
363
+ def get_input_embeddings(self):
364
+ return self.bert.embeddings.word_embeddings
365
+
366
+ def set_input_embeddings(self, value):
367
+ self.bert.embeddings.word_embeddings = value
368
+
369
  def predict(self, sentences: Union[str, List[str]], tokenizer: BertTokenizerFast, compute_mst=True):
370
+ if self.config.is_cls_model:
371
+ raise ValueError('Cannot use predict function with classification model')
372
  if isinstance(sentences, str):
373
  sentences = [sentences]
374
 
 
376
  inputs = tokenizer(sentences, padding='longest', truncation=True, return_tensors='pt')
377
  inputs = {k:v.to(self.device) for k,v in inputs.items()}
378
  logits = self.forward(**inputs, return_dict=True, compute_syntax_mst=compute_mst).logits
379
+ return parse_logits(inputs['input_ids'].tolist(), sentences, tokenizer, logits, self.syntax.func_label_idx)
380
+
381
+ class AutoForSyntaxParsing(_BaseAutoModelClass):
382
+ @classmethod
383
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *args, **kwargs):
384
+ auto_cfg = AutoConfig.from_pretrained(pretrained_model_name_or_path, trust_remote_code=True)
385
+ custom_kwargs = dict(syntax_head_size=128, is_partial_info_model=False, is_cls_model=False, syntax_attn_label_count=1, syntax_func_label_idx=0)
386
+ custom_kwargs = {k:kwargs.pop(k, getattr(auto_cfg, k, v)) for k,v in custom_kwargs.items()}
387
+ base_cls = BaseForSyntaxParsing
388
+ with no_init_weights():
389
+ bert_cls = AutoModel.from_config(auto_cfg, *args, **kwargs).__class__
390
+ if 'Syntax' in bert_cls.__name__:
391
+ base_cls = bert_cls
392
+
393
+ return base_cls.from_pretrained(pretrained_model_name_or_path, *args, **kwargs, **custom_kwargs, bert_cls=bert_cls, key_mapping={"^model": "bert"})
394
+
395
 
396
+ def parse_logits(input_ids: List[List[int]], sentences: List[str], tokenizer: BertTokenizerFast, logits: SyntaxLogitsOutput, func_label_idx: int = 0):
397
  outputs = []
398
 
399
  special_toks = tokenizer.all_special_tokens
400
  special_toks.remove(tokenizer.unk_token)
401
  special_toks.remove(tokenizer.mask_token)
 
402
  for i in range(len(sentences)):
403
+ # dependency_head_indices is seq x label_count - the tree is built from the function label's column
404
+ deps = logits.dependency_head_indices[i][:, func_label_idx].tolist()
405
  funcs = logits.function_logits.argmax(-1)[i].tolist()
406
  toks = [tok for tok in tokenizer.convert_ids_to_tokens(input_ids[i]) if tok not in special_toks]
407
 
 
543
  if best_base_idx == -1:
544
  raise ValueError('Stuck in endless loop trying to compute syntax mst. Please try again setting compute_syntax_mst=False')
545
 
546
+ return best_base_idx, best_head_idx
547
+
548
+ def replace_tensor_value(tensor, orig_value, replacement_value):
549
+ return torch.where(tensor == orig_value, replacement_value, tensor)