PawelNarcos commited on
Commit
a984e75
1 Parent(s): dc8224a

Upload model

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +39 -0
  3. config.py +29 -0
  4. model.py +306 -0
  5. model.safetensors +3 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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]
config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ILKTModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "config.ILKTConfig",
7
+ "AutoModel": "model.ILKTModel"
8
+ },
9
+ "backbone_config": {
10
+ "pretrained_model_name_or_path": "microsoft/mdeberta-v3-base",
11
+ "trust_remote_code": true
12
+ },
13
+ "cls_head_config": {
14
+ "dropout": 0.0,
15
+ "n_dense": 0,
16
+ "pool_type": "cls",
17
+ "use_batch_norm": true,
18
+ "use_layer_norm": false
19
+ },
20
+ "cls_heads": [],
21
+ "embedding_head_config": {
22
+ "dropout": 0.0,
23
+ "n_dense": 0,
24
+ "normalize_embeddings": false,
25
+ "pool_type": "cls",
26
+ "use_batch_norm": false,
27
+ "use_layer_norm": false
28
+ },
29
+ "hidden_size": 768,
30
+ "mlm_head_config": {
31
+ "dropout": 0.0,
32
+ "n_dense": 0,
33
+ "use_batch_norm": true,
34
+ "use_layer_norm": false
35
+ },
36
+ "model_type": "ILKT",
37
+ "torch_dtype": "float32",
38
+ "transformers_version": "4.41.2"
39
+ }
config.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Tuple
2
+
3
+ from transformers import PretrainedConfig
4
+
5
+
6
+ class ILKTConfig(PretrainedConfig):
7
+
8
+ model_type = "ILKT"
9
+
10
+ def __init__(
11
+ self,
12
+ backbone_config: Dict[str, Any] = {},
13
+ embedding_head_config: Dict[str, Any] = {},
14
+ mlm_head_config: Dict[str, Any] = {},
15
+ cls_head_config: Dict[str, Any] = {},
16
+ cls_heads: List[Tuple[int, str]] = [],
17
+ **kwargs
18
+ ):
19
+ self.backbone_config = backbone_config
20
+ self.embedding_head_config = embedding_head_config
21
+ self.mlm_head_config = mlm_head_config
22
+ self.cls_head_config = cls_head_config
23
+ self.cls_heads = cls_heads
24
+ self.output_hidden_states = False
25
+
26
+ # TODO:
27
+ # make config a proper HF config, save max length ets, don't know how it works exactly in hf ecosystem
28
+
29
+ super().__init__(**kwargs)
model.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers import AutoConfig, AutoModel, PreTrainedModel
6
+ from transformers.modeling_outputs import (
7
+ BaseModelOutputWithPooling,
8
+ MaskedLMOutput,
9
+ BaseModelOutput,
10
+ SequenceClassifierOutput,
11
+ )
12
+ from enum import Enum
13
+ import sys
14
+ import os
15
+
16
+ from .config import ILKTConfig
17
+
18
+ import os, sys
19
+ parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
20
+ sys.path.append(parent_dir)
21
+ from eval_utils.metrics import stiffness
22
+ sys.path.pop(-1)
23
+
24
+
25
+ def cls_pooling(last_hidden_state, attention_mask):
26
+ return last_hidden_state[:, 0, :]
27
+
28
+
29
+ def create_head_blocks(
30
+ hidden_size: int,
31
+ n_dense: int,
32
+ use_batch_norm: bool,
33
+ use_layer_norm: bool,
34
+ dropout: float,
35
+ **kwargs,
36
+ ) -> nn.Module:
37
+ blocks = []
38
+ for _ in range(n_dense):
39
+ blocks.append(nn.Linear(hidden_size, hidden_size))
40
+ if use_batch_norm:
41
+ blocks.append(nn.BatchNorm1d(hidden_size))
42
+ elif use_layer_norm:
43
+ blocks.append(nn.LayerNorm(hidden_size))
44
+ blocks.append(nn.ReLU())
45
+ if dropout > 0:
46
+ blocks.append(nn.Dropout(dropout))
47
+ return nn.Sequential(*blocks)
48
+
49
+
50
+ class SentenceEmbeddingHead(nn.Module):
51
+ def __init__(
52
+ self, backbone_hidden_size: int, embedding_head_config: Dict[str, Any]
53
+ ):
54
+ super().__init__()
55
+ self.config = embedding_head_config
56
+
57
+ self.head = nn.Sequential(
58
+ *[
59
+ create_head_blocks(backbone_hidden_size, **embedding_head_config),
60
+ ]
61
+ )
62
+
63
+ def forward(
64
+ self, backbone_output: BaseModelOutput, attention_mask: torch.Tensor, **kwargs
65
+ ) -> BaseModelOutputWithPooling:
66
+ if self.config["pool_type"] == "cls":
67
+ embeddings = cls_pooling(backbone_output.last_hidden_state, attention_mask)
68
+ else:
69
+ raise NotImplementedError(
70
+ f"Pooling type {self.config['pool_type']} not implemented"
71
+ )
72
+ if self.config["normalize_embeddings"]:
73
+ embeddings = nn.functional.normalize(embeddings, p=2, dim=-1)
74
+ return BaseModelOutputWithPooling(
75
+ last_hidden_state=backbone_output.last_hidden_state,
76
+ pooler_output=embeddings, # type: ignore
77
+ )
78
+
79
+
80
+ class MLMHead(nn.Module):
81
+ def __init__(
82
+ self,
83
+ backbone_hidden_size: int,
84
+ vocab_size: int,
85
+ mlm_head_config: Dict[str, Any],
86
+ ):
87
+ super().__init__()
88
+ self.config = mlm_head_config
89
+
90
+ self.head = nn.Sequential(
91
+ *[
92
+ create_head_blocks(backbone_hidden_size, **mlm_head_config),
93
+ nn.Linear(backbone_hidden_size, vocab_size),
94
+ ]
95
+ )
96
+
97
+ def forward(
98
+ self,
99
+ backbone_output: BaseModelOutput,
100
+ attention_mask: torch.Tensor,
101
+ labels: Optional[torch.Tensor] = None,
102
+ **kwargs,
103
+ ) -> MaskedLMOutput:
104
+ prediction_scores = self.head(backbone_output.last_hidden_state)
105
+
106
+ loss = None
107
+ if labels is not None:
108
+ loss_fct = nn.CrossEntropyLoss()
109
+ loss = loss_fct(
110
+ prediction_scores.view(-1, prediction_scores.size(-1)),
111
+ labels.view(-1),
112
+ )
113
+ return MaskedLMOutput(loss=loss)
114
+
115
+
116
+ class CLSHead(nn.Module):
117
+ def __init__(
118
+ self,
119
+ backbone_hidden_size: int,
120
+ n_classes: int,
121
+ cls_head_config: Dict[str, Any],
122
+ ):
123
+ super().__init__()
124
+ self.config = cls_head_config
125
+
126
+ self.head = nn.Sequential(
127
+ *[
128
+ create_head_blocks(backbone_hidden_size, **cls_head_config),
129
+ nn.Linear(backbone_hidden_size, n_classes),
130
+ ]
131
+ )
132
+
133
+ def forward(
134
+ self,
135
+ backbone_output: BaseModelOutput,
136
+ attention_mask: torch.Tensor,
137
+ labels: Optional[torch.Tensor] = None,
138
+ **kwargs,
139
+ ) -> SequenceClassifierOutput:
140
+ if self.config["pool_type"] == "cls":
141
+ embeddings = cls_pooling(backbone_output.last_hidden_state, attention_mask)
142
+ else:
143
+ raise NotImplementedError(
144
+ f"Pooling type {self.config['pool_type']} not implemented"
145
+ )
146
+
147
+ prediction_scores = self.head(embeddings)
148
+
149
+ loss = None
150
+ if labels is not None:
151
+ loss_fct = nn.CrossEntropyLoss()
152
+ loss = loss_fct(
153
+ prediction_scores.view(-1, prediction_scores.size(-1)),
154
+ labels.view(-1),
155
+ )
156
+ return SequenceClassifierOutput(loss=loss)
157
+
158
+
159
+ class ForwardRouting(Enum):
160
+ GET_SENTENCE_EMBEDDING = "get_sentence_embedding"
161
+ GET_MLM_OUTPUT = "get_mlm_output"
162
+ GET_CLS_OUTPUT = "get_cls_output"
163
+
164
+
165
+ class ILKTModel(PreTrainedModel):
166
+ config_class = ILKTConfig
167
+
168
+ def __init__(self, config: ILKTConfig):
169
+ super().__init__(config)
170
+
171
+ backbone_config = AutoConfig.from_pretrained(**config.backbone_config)
172
+ pretrained_model_name_or_path = config.backbone_config[
173
+ "pretrained_model_name_or_path"
174
+ ]
175
+ self.backbone = AutoModel.from_pretrained(
176
+ pretrained_model_name_or_path, config=backbone_config
177
+ )
178
+
179
+ backbone_hidden_size = backbone_config.hidden_size
180
+ self.config.hidden_size = backbone_hidden_size
181
+ backbone_vocab_size = backbone_config.vocab_size
182
+ self.embedding_head = SentenceEmbeddingHead(
183
+ backbone_hidden_size, config.embedding_head_config
184
+ )
185
+ self.mlm_head = MLMHead(
186
+ backbone_hidden_size, backbone_vocab_size, config.mlm_head_config
187
+ )
188
+
189
+ self.cls_heads = nn.ModuleDict(
190
+ dict(
191
+ [
192
+ (
193
+ name,
194
+ CLSHead(
195
+ backbone_hidden_size, n_classes, config.cls_head_config
196
+ ),
197
+ )
198
+ for n_classes, name in config.cls_heads
199
+ ]
200
+ )
201
+ )
202
+
203
+ self.initiate_stiffness()
204
+
205
+ def forward(
206
+ self,
207
+ input_ids: torch.Tensor,
208
+ attention_mask: torch.Tensor,
209
+ token_type_ids: Optional[torch.Tensor] = None,
210
+ forward_routing: ForwardRouting = ForwardRouting.GET_SENTENCE_EMBEDDING,
211
+ **kwargs,
212
+ ):
213
+ self.set_current_task(forward_routing)
214
+ if forward_routing == ForwardRouting.GET_SENTENCE_EMBEDDING:
215
+ return self.get_sentence_embedding(
216
+ input_ids, attention_mask, token_type_ids=token_type_ids
217
+ )
218
+ elif forward_routing == ForwardRouting.GET_MLM_OUTPUT:
219
+ return self.get_mlm_output(
220
+ input_ids, attention_mask, token_type_ids=token_type_ids, **kwargs
221
+ )
222
+ elif forward_routing == ForwardRouting.GET_CLS_OUTPUT:
223
+ return self.get_cls_output(
224
+ input_ids, attention_mask, token_type_ids=token_type_ids, **kwargs
225
+ )
226
+ else:
227
+ raise ValueError(f"Unknown forward routing {forward_routing}")
228
+
229
+ def get_sentence_embedding(
230
+ self, input_ids: torch.Tensor, attention_mask: torch.Tensor, **kwargs
231
+ ):
232
+ backbone_output: BaseModelOutput = self.backbone(
233
+ input_ids=input_ids, attention_mask=attention_mask, **kwargs
234
+ )
235
+
236
+ embedding_output = self.embedding_head(
237
+ backbone_output, attention_mask, **kwargs
238
+ )
239
+
240
+ return embedding_output
241
+
242
+ def get_mlm_output(
243
+ self,
244
+ input_ids: torch.Tensor,
245
+ attention_mask: torch.Tensor,
246
+ labels: Optional[torch.Tensor] = None,
247
+ **kwargs,
248
+ ):
249
+ backbone_output: BaseModelOutput = self.backbone(
250
+ input_ids=input_ids, attention_mask=attention_mask, **kwargs
251
+ )
252
+
253
+ mlm_output = self.mlm_head(backbone_output, attention_mask, labels, **kwargs)
254
+
255
+ return mlm_output
256
+
257
+ def get_cls_output(
258
+ self,
259
+ input_ids: torch.Tensor,
260
+ attention_mask: torch.Tensor,
261
+ head_name: str,
262
+ labels: Optional[torch.Tensor] = None,
263
+ **kwargs,
264
+ ):
265
+ backbone_output: BaseModelOutput = self.backbone(
266
+ input_ids=input_ids, attention_mask=attention_mask, **kwargs
267
+ )
268
+
269
+ if head_name not in self.cls_heads:
270
+ raise ValueError(f"Head {head_name} not found in model")
271
+
272
+ cls_output = self.cls_heads[head_name](
273
+ backbone_output, attention_mask, labels, **kwargs
274
+ )
275
+
276
+ return cls_output
277
+
278
+ def set_current_task(self, task):
279
+ self.current_task = task
280
+
281
+ def initiate_stiffness(self):
282
+ self.log_gradients = False
283
+ self.backbone.encoder.layer[-1].register_full_backward_hook(self._backward_hook)
284
+ self.gradients = {}
285
+ self.current_task = None
286
+
287
+ def _backward_hook(self, module, grad_input, grad_output):
288
+ if self.log_gradients and self.current_task in self.gradients:
289
+ self.gradients[self.current_task].append(grad_input[0])
290
+ elif self.log_gradients:
291
+ self.gradients[self.current_task] = [grad_input[0]]
292
+
293
+ def get_stiffness(self):
294
+ # REMARK: make sure that you train on CLS and MLM tasks
295
+ values = {}
296
+
297
+ for task1 in self.gradients:
298
+ for task2 in self.gradients:
299
+ if str(task1) > str(task2) and len(self.gradients[task1]) > 0 and len(self.gradients[task2]) > 0:
300
+ values[f'{task1}x{task2}_cosine'] = stiffness(torch.cat(self.gradients[task1], dim=-2), torch.cat(self.gradients[task2], dim=-2), "cosine")
301
+ values[f'{task1}x{task2}_sign'] = stiffness(torch.cat(self.gradients[task1], dim=-2), torch.cat(self.gradients[task2], dim=-2), "sign")
302
+
303
+ for task in self.gradients:
304
+ del self.gradients[task][:]
305
+
306
+ return values
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54b77df10db83839dcc1b979f552726ea8cf10ed69146afaf64a6cb79996370a
3
+ size 1884975744