emanuelaboros commited on
Commit
8d73145
1 Parent(s): 5d1e7ad

Initial commit of the trained NER model with code

Browse files
Files changed (7) hide show
  1. config.json +25 -0
  2. model.safetensors +3 -0
  3. models.py +128 -0
  4. special_tokens_map.json +37 -0
  5. tokenizer.json +0 -0
  6. tokenizer_config.json +58 -0
  7. vocab.txt +0 -0
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "../experiments_final/model_dbmdz_bert_medium_historic_multilingual_cased_max_sequence_length_512_epochs_5_run_extended_suffix_baseline/checkpoint-450",
3
+ "architectures": [
4
+ "ExtendedMultitaskModelForTokenClassification"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "classifier_dropout": null,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.1,
10
+ "hidden_size": 512,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 2048,
13
+ "layer_norm_eps": 1e-12,
14
+ "max_position_embeddings": 512,
15
+ "model_type": "bert",
16
+ "num_attention_heads": 8,
17
+ "num_hidden_layers": 8,
18
+ "pad_token_id": 0,
19
+ "position_embedding_type": "absolute",
20
+ "torch_dtype": "float32",
21
+ "transformers_version": "4.40.0.dev0",
22
+ "type_vocab_size": 2,
23
+ "use_cache": true,
24
+ "vocab_size": 32000
25
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03a807b124debff782406c816eacb7ced1f2e25b9a5198b27e1616a41faa0662
3
+ size 193971960
models.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.modeling_outputs import TokenClassifierOutput
2
+ import torch
3
+ import torch.nn as nn
4
+ from transformers import PreTrainedModel, AutoModel, AutoConfig
5
+ from torch.nn import CrossEntropyLoss
6
+ from typing import Optional, Tuple, Union
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class ExtendedMultitaskModelForTokenClassification(PreTrainedModel):
13
+
14
+ config_class = AutoConfig
15
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
16
+
17
+ def __init__(self, config, num_token_labels_dict):
18
+ super().__init__(config)
19
+ self.num_token_labels_dict = num_token_labels_dict
20
+ self.config = config
21
+
22
+ # self.bert = AutoModel.from_config(config)
23
+ self.bert = AutoModel.from_pretrained(config.name_or_path, config=config)
24
+ if "classifier_dropout" not in config.__dict__:
25
+ classifier_dropout = 0.1
26
+ else:
27
+ classifier_dropout = (
28
+ config.classifier_dropout
29
+ if config.classifier_dropout is not None
30
+ else config.hidden_dropout_prob
31
+ )
32
+ self.dropout = nn.Dropout(classifier_dropout)
33
+
34
+ # Additional transformer layers
35
+ self.transformer_encoder = nn.TransformerEncoder(
36
+ nn.TransformerEncoderLayer(
37
+ d_model=config.hidden_size, nhead=config.num_attention_heads
38
+ ),
39
+ num_layers=2,
40
+ )
41
+
42
+ # For token classification, create a classifier for each task
43
+ self.token_classifiers = nn.ModuleDict(
44
+ {
45
+ task: nn.Linear(config.hidden_size, num_labels)
46
+ for task, num_labels in num_token_labels_dict.items()
47
+ }
48
+ )
49
+
50
+ # Initialize weights and apply final processing
51
+ self.post_init()
52
+
53
+ def forward(
54
+ self,
55
+ input_ids: Optional[torch.Tensor] = None,
56
+ attention_mask: Optional[torch.Tensor] = None,
57
+ token_type_ids: Optional[torch.Tensor] = None,
58
+ position_ids: Optional[torch.Tensor] = None,
59
+ head_mask: Optional[torch.Tensor] = None,
60
+ inputs_embeds: Optional[torch.Tensor] = None,
61
+ labels: Optional[torch.Tensor] = None,
62
+ token_labels: Optional[dict] = None,
63
+ output_attentions: Optional[bool] = None,
64
+ output_hidden_states: Optional[bool] = None,
65
+ return_dict: Optional[bool] = None,
66
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
67
+ r"""
68
+ token_labels (`dict` of `torch.LongTensor` of shape `(batch_size, seq_length)`, *optional*):
69
+ Labels for computing the token classification loss. Keys should match the tasks.
70
+ """
71
+ return_dict = (
72
+ return_dict if return_dict is not None else self.config.use_return_dict
73
+ )
74
+
75
+ bert_kwargs = {
76
+ "input_ids": input_ids,
77
+ "attention_mask": attention_mask,
78
+ "token_type_ids": token_type_ids,
79
+ "position_ids": position_ids,
80
+ "head_mask": head_mask,
81
+ "inputs_embeds": inputs_embeds,
82
+ "output_attentions": output_attentions,
83
+ "output_hidden_states": output_hidden_states,
84
+ "return_dict": return_dict,
85
+ }
86
+
87
+ if any(
88
+ keyword in self.config.name_or_path.lower()
89
+ for keyword in ["llama", "deberta"]
90
+ ):
91
+ bert_kwargs.pop("token_type_ids")
92
+ bert_kwargs.pop("head_mask")
93
+
94
+ outputs = self.bert(**bert_kwargs)
95
+
96
+ # For token classification
97
+ token_output = outputs[0]
98
+ token_output = self.dropout(token_output)
99
+
100
+ # Pass through additional transformer layers
101
+ token_output = self.transformer_encoder(token_output.transpose(0, 1)).transpose(
102
+ 0, 1
103
+ )
104
+
105
+ # Collect the logits and compute the loss for each task
106
+ task_logits = {}
107
+ total_loss = 0
108
+ for task, classifier in self.token_classifiers.items():
109
+ logits = classifier(token_output)
110
+ task_logits[task] = logits
111
+ if token_labels and task in token_labels:
112
+ loss_fct = CrossEntropyLoss()
113
+ loss = loss_fct(
114
+ logits.view(-1, self.num_token_labels_dict[task]),
115
+ token_labels[task].view(-1),
116
+ )
117
+ total_loss += loss
118
+
119
+ if not return_dict:
120
+ output = (task_logits,) + outputs[2:]
121
+ return ((total_loss,) + output) if total_loss != 0 else output
122
+
123
+ return TokenClassifierOutput(
124
+ loss=total_loss,
125
+ logits=task_logits,
126
+ hidden_states=outputs.hidden_states,
127
+ attentions=outputs.attentions,
128
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_basic_tokenize": true,
47
+ "do_lower_case": false,
48
+ "mask_token": "[MASK]",
49
+ "max_len": 512,
50
+ "model_max_length": 512,
51
+ "never_split": null,
52
+ "pad_token": "[PAD]",
53
+ "sep_token": "[SEP]",
54
+ "strip_accents": false,
55
+ "tokenize_chinese_chars": true,
56
+ "tokenizer_class": "BertTokenizer",
57
+ "unk_token": "[UNK]"
58
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff