Upload model
Browse files- README.md +201 -0
- config.json +65 -0
- configuration_bionextextractor.py +24 -0
- model.safetensors +3 -0
- modeling_bionextextractor.py +212 -0
README.md
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
tags: []
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
200 |
+
|
201 |
+
|
config.json
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "michiyasunaga/BioLinkBERT-large",
|
3 |
+
"arch_type": "mha",
|
4 |
+
"architectures": [
|
5 |
+
"BioNExtExtractorModel"
|
6 |
+
],
|
7 |
+
"attention_probs_dropout_prob": 0.1,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_bionextextractor.BioNExtExtractorConfig",
|
10 |
+
"AutoModel": "modeling_bionextextractor.BioNExtExtractorModel"
|
11 |
+
},
|
12 |
+
"classifier_dropout": null,
|
13 |
+
"gradient_checkpointing": false,
|
14 |
+
"hidden_act": "gelu",
|
15 |
+
"hidden_dropout_prob": 0.1,
|
16 |
+
"hidden_size": 1024,
|
17 |
+
"id2label": {
|
18 |
+
"0": "Association",
|
19 |
+
"1": "Positive_Correlation",
|
20 |
+
"2": "Negative_Correlation",
|
21 |
+
"3": "Cotreatment",
|
22 |
+
"4": "Bind",
|
23 |
+
"5": "Comparison",
|
24 |
+
"6": "Conversion",
|
25 |
+
"7": "Drug_Interaction",
|
26 |
+
"8": "Negative_Class"
|
27 |
+
},
|
28 |
+
"index_type": "both",
|
29 |
+
"initializer_range": 0.02,
|
30 |
+
"intermediate_size": 4096,
|
31 |
+
"label2id": {
|
32 |
+
"Association": 0,
|
33 |
+
"Bind": 4,
|
34 |
+
"Comparison": 5,
|
35 |
+
"Conversion": 6,
|
36 |
+
"Cotreatment": 3,
|
37 |
+
"Drug_Interaction": 7,
|
38 |
+
"Negative_Class": 8,
|
39 |
+
"Negative_Correlation": 2,
|
40 |
+
"Positive_Correlation": 1
|
41 |
+
},
|
42 |
+
"layer_norm_eps": 1e-12,
|
43 |
+
"max_position_embeddings": 512,
|
44 |
+
"model_type": "relation-novelty-extractor",
|
45 |
+
"novel": true,
|
46 |
+
"num_attention_heads": 16,
|
47 |
+
"num_hidden_layers": 24,
|
48 |
+
"num_lstm_layers": 1,
|
49 |
+
"pad_token_id": 0,
|
50 |
+
"position_embedding_type": "absolute",
|
51 |
+
"resize_embeddings": true,
|
52 |
+
"tokenizer_special_tokens": [
|
53 |
+
"[s1]",
|
54 |
+
"[e1]",
|
55 |
+
"[s2]",
|
56 |
+
"[e2]"
|
57 |
+
],
|
58 |
+
"torch_dtype": "float32",
|
59 |
+
"transformers_version": "4.37.2",
|
60 |
+
"type_vocab_size": 2,
|
61 |
+
"update_vocab": 28899,
|
62 |
+
"use_cache": true,
|
63 |
+
"version": "0.1.0",
|
64 |
+
"vocab_size": 28899
|
65 |
+
}
|
configuration_bionextextractor.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from transformers import PretrainedConfig, AutoConfig
|
3 |
+
from typing import List
|
4 |
+
|
5 |
+
|
6 |
+
class BioNExtExtractorConfig(PretrainedConfig):
|
7 |
+
model_type = "relation-novelty-extractor"
|
8 |
+
|
9 |
+
def __init__(
|
10 |
+
self,
|
11 |
+
arch_type = "mha",
|
12 |
+
index_type = "both",
|
13 |
+
novel = True,
|
14 |
+
version="0.1.0",
|
15 |
+
**kwargs,
|
16 |
+
):
|
17 |
+
self.version = version
|
18 |
+
self.arch_type = arch_type
|
19 |
+
self.index_type = index_type
|
20 |
+
self.novel = novel
|
21 |
+
super().__init__(**kwargs)
|
22 |
+
|
23 |
+
|
24 |
+
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5614db1403a5339630fef087a18cc985693d4b7188cf6c81aa9f15eff71fe520
|
3 |
+
size 1350790260
|
modeling_bionextextractor.py
ADDED
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import os
|
3 |
+
from typing import Optional, Union
|
4 |
+
from transformers import BertModel, PreTrainedModel, AutoConfig, BertModel
|
5 |
+
from transformers.modeling_outputs import TokenClassifierOutput
|
6 |
+
from torch import nn
|
7 |
+
from torch.nn import CrossEntropyLoss
|
8 |
+
|
9 |
+
from typing import List, Optional
|
10 |
+
|
11 |
+
import torch
|
12 |
+
from itertools import islice
|
13 |
+
from .configuration_bionextextractor import BioNExtExtractorConfig
|
14 |
+
|
15 |
+
|
16 |
+
import torch
|
17 |
+
|
18 |
+
from transformers import AutoModel, PreTrainedModel, AutoConfig, BertConfig
|
19 |
+
from transformers.modeling_outputs import TokenClassifierOutput, SequenceClassifierOutput
|
20 |
+
|
21 |
+
from torch.nn import CrossEntropyLoss
|
22 |
+
import math
|
23 |
+
|
24 |
+
class RelationLossMixin:
|
25 |
+
|
26 |
+
def model_loss(self, logits, labels, novel=None, reduction=None):
|
27 |
+
if reduction is None:
|
28 |
+
return torch.nn.functional.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
|
29 |
+
else:
|
30 |
+
return torch.nn.functional.cross_entropy(logits.view(-1,self.num_labels), labels.view(-1), reduction=reduction)
|
31 |
+
|
32 |
+
class RelationAndNovelLossMixin(RelationLossMixin):
|
33 |
+
|
34 |
+
def model_loss(self, logits, labels, novel=None):
|
35 |
+
relation_logits, novel_logits = logits
|
36 |
+
relation_loss = super().model_loss(relation_logits, labels, reduction="none")
|
37 |
+
novel_loss = torch.nn.functional.cross_entropy(novel_logits.view(-1, 2), novel.view(-1), reduction="none")
|
38 |
+
per_sample_loss = relation_loss + (labels!=8).type(logits[0].dtype)*novel_loss
|
39 |
+
|
40 |
+
return per_sample_loss.mean()#relation_loss + (labels!=8).type(logits[0].dtype)*novel_loss(novel_logits.view(-1, 2), novel.view(-1))
|
41 |
+
#return relation_loss + novel_loss(novel_logits.view(-1, 2), novel.view(-1))
|
42 |
+
|
43 |
+
class RelationClassifierBase(PreTrainedModel, RelationLossMixin):
|
44 |
+
#_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
45 |
+
config_class=BioNExtExtractorConfig
|
46 |
+
|
47 |
+
def __init__(self, config):
|
48 |
+
super().__init__(config)
|
49 |
+
self.num_labels = config.num_labels
|
50 |
+
|
51 |
+
#print(config)
|
52 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
53 |
+
|
54 |
+
def group_embeddings_by_index(self, embeddings, indexes):
|
55 |
+
assert len(embeddings.shape)==3
|
56 |
+
|
57 |
+
batch_size = indexes.shape[0]
|
58 |
+
max_tokens = embeddings.shape[1]
|
59 |
+
emb_size = embeddings.shape[2]
|
60 |
+
# masking padding
|
61 |
+
mask_index = indexes!=-1
|
62 |
+
|
63 |
+
# convert index to 1d of valid index (ignore paddings)
|
64 |
+
indexes = indexes + mask_index*(torch.arange(batch_size).to(self.device)*max_tokens).view(batch_size,1,1)
|
65 |
+
indexes = indexes.masked_select(mask_index)
|
66 |
+
|
67 |
+
# reshape
|
68 |
+
embeddings = embeddings.view(batch_size*max_tokens, emb_size)
|
69 |
+
|
70 |
+
# get the embeddings by index
|
71 |
+
selected_embeddings_by_index = torch.index_select(embeddings, 0, indexes)
|
72 |
+
|
73 |
+
final_output_shape = (mask_index.shape[0], mask_index.shape[1], emb_size)
|
74 |
+
group_embeddings = torch.zeros(final_output_shape, dtype=embeddings.dtype).to(self.device).masked_scatter(mask_index, selected_embeddings_by_index)
|
75 |
+
|
76 |
+
return group_embeddings, mask_index
|
77 |
+
|
78 |
+
def classifier_representation(self, embeddings, mask = None):
|
79 |
+
raise NotImplementedError("This is base class, pleas extend an implement classifier_representation")
|
80 |
+
|
81 |
+
def classifier(self, class_representation, relation_mask = None):
|
82 |
+
raise NotImplementedError("This is base class, pleas extend an implement classifier")
|
83 |
+
|
84 |
+
def forward(self,
|
85 |
+
input_ids,
|
86 |
+
indexes=None,
|
87 |
+
novel=None,
|
88 |
+
labels=None,
|
89 |
+
mask=None,
|
90 |
+
return_dict=None,
|
91 |
+
**model_kwargs
|
92 |
+
):
|
93 |
+
# Default `model.config.use_return_dict´ is `True´
|
94 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
95 |
+
|
96 |
+
outputs = self.bert(input_ids, return_dict=return_dict, **model_kwargs)
|
97 |
+
|
98 |
+
assert indexes is not None
|
99 |
+
|
100 |
+
embeddings = outputs.last_hidden_state
|
101 |
+
|
102 |
+
selected_embeddings, mask_group = self.group_embeddings_by_index(embeddings, indexes)
|
103 |
+
|
104 |
+
class_representation = self.classifier_representation(selected_embeddings, mask_group)
|
105 |
+
|
106 |
+
logits = self.classifier(class_representation, relation_mask=mask)
|
107 |
+
|
108 |
+
loss = None
|
109 |
+
if labels is not None:
|
110 |
+
loss = self.model_loss(logits, labels, novel)
|
111 |
+
|
112 |
+
|
113 |
+
return SequenceClassifierOutput(
|
114 |
+
loss=loss,
|
115 |
+
logits=logits,
|
116 |
+
hidden_states=outputs.hidden_states,
|
117 |
+
attentions=outputs.attentions,
|
118 |
+
)
|
119 |
+
|
120 |
+
|
121 |
+
class RelationClassifierBiLSTM(RelationClassifierBase):
|
122 |
+
|
123 |
+
def __init__(self, config):
|
124 |
+
super().__init__(config)
|
125 |
+
self.num_lstm_layers = config.num_lstm_layers
|
126 |
+
self.lstm = torch.nn.LSTM(config.hidden_size, (config.hidden_size) // 2, self.num_lstm_layers, batch_first=True, bidirectional=True)
|
127 |
+
self.fc = torch.nn.Linear(config.hidden_size, self.num_labels) # 2 for bidirection
|
128 |
+
|
129 |
+
def classifier_representation(self, embeddings, mask=None):
|
130 |
+
out, _ = self.lstm(embeddings)
|
131 |
+
return out[:, -1, :]
|
132 |
+
|
133 |
+
def classifier(self, class_representation, mask=None):
|
134 |
+
return self.fc(class_representation)
|
135 |
+
|
136 |
+
class RelationAndNovelClassifierBiLSTM(RelationClassifierBiLSTM, RelationAndNovelLossMixin):
|
137 |
+
|
138 |
+
def __init__(self, config):
|
139 |
+
super().__init__(config)
|
140 |
+
self.fc_novel = torch.nn.Linear(config.hidden_size, 2) # 2 for bidirection
|
141 |
+
|
142 |
+
def classifier(self, class_representation):
|
143 |
+
return super().classifier(class_representation), self.fc_novel(class_representation)
|
144 |
+
|
145 |
+
class RelationClassifierMHAttention(RelationClassifierBase):
|
146 |
+
|
147 |
+
def __init__(self, config):
|
148 |
+
super().__init__(config)
|
149 |
+
|
150 |
+
self.weight = torch.nn.Parameter(torch.Tensor(1,1,config.hidden_size))
|
151 |
+
torch.nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
152 |
+
|
153 |
+
self.MHattention_layer = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True) # 2 for bidirection
|
154 |
+
self.fc1 = torch.nn.Linear(config.hidden_size, config.hidden_size//2) # 2 for bidirection
|
155 |
+
self.fc1_activation = torch.nn.GELU(approximate='none')
|
156 |
+
self.fc2 = torch.nn.Linear(config.hidden_size//2, self.num_labels) # 2 for bidirection
|
157 |
+
|
158 |
+
def classifier_representation(self, embeddings, mask=None):
|
159 |
+
batch_size = embeddings.shape[0]
|
160 |
+
weight = self.weight.repeat(batch_size, 1, 1)
|
161 |
+
|
162 |
+
if mask is not None:
|
163 |
+
# flip
|
164 |
+
mask = mask.squeeze(-1)==False
|
165 |
+
|
166 |
+
out_tensors, _ = self.MHattention_layer(weight, embeddings, embeddings, key_padding_mask=mask)
|
167 |
+
|
168 |
+
return out_tensors
|
169 |
+
|
170 |
+
def classifier(self, class_representation, relation_mask = None):
|
171 |
+
|
172 |
+
x = self.fc1(class_representation)
|
173 |
+
x = self.fc1_activation(x)
|
174 |
+
logits = self.fc2(x)
|
175 |
+
if relation_mask is not None:
|
176 |
+
#print(logits.shape, relation_mask.shape)
|
177 |
+
logits = logits + relation_mask.view(-1,1,self.num_labels)
|
178 |
+
return logits
|
179 |
+
|
180 |
+
class RelationAndNovelClassifierMHAttention(RelationClassifierMHAttention, RelationAndNovelLossMixin):
|
181 |
+
def __init__(self, config):
|
182 |
+
super().__init__(config)
|
183 |
+
|
184 |
+
self.fc1_novel = torch.nn.Linear(config.hidden_size, config.hidden_size//2) # 2 for bidirection
|
185 |
+
self.fc1_novel_activation = torch.nn.GELU(approximate='none')
|
186 |
+
self.fc2_novel = torch.nn.Linear(config.hidden_size//2, 2) # 2 for bidirection
|
187 |
+
|
188 |
+
def classifier(self, class_representation, relation_mask=None):
|
189 |
+
x = self.fc1_novel(class_representation)
|
190 |
+
x = self.fc1_novel_activation(x)
|
191 |
+
|
192 |
+
return super().classifier(class_representation, relation_mask=relation_mask), self.fc2_novel(x)
|
193 |
+
|
194 |
+
ARCH_MAPPING = {"mhawNovelty": RelationAndNovelClassifierMHAttention,
|
195 |
+
"mha": RelationClassifierMHAttention,
|
196 |
+
"bilstmwNovelty" : RelationAndNovelClassifierBiLSTM,
|
197 |
+
"bilstm": RelationClassifierBiLSTM}
|
198 |
+
|
199 |
+
class BioNExtExtractorModel(PreTrainedModel):
|
200 |
+
config_class=BioNExtExtractorConfig
|
201 |
+
|
202 |
+
def __init__(self, config):
|
203 |
+
super().__init__(config)
|
204 |
+
|
205 |
+
if config.novel:
|
206 |
+
self.model = ARCH_MAPPING[f"{config.arch_type}wNovelty"](config)
|
207 |
+
else:
|
208 |
+
self.model = ARCH_MAPPING[config.arch_type](config)
|
209 |
+
|
210 |
+
def forward(self, *args, **kwargs):
|
211 |
+
return self.model(*args, **kwargs)
|
212 |
+
|