PawelNarcos commited on
Commit
616b35e
1 Parent(s): 0c028cc

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 +273 -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,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
19
+ def cls_pooling(last_hidden_state, attention_mask):
20
+ return last_hidden_state[:, 0, :]
21
+
22
+
23
+ def create_head_blocks(
24
+ hidden_size: int,
25
+ n_dense: int,
26
+ use_batch_norm: bool,
27
+ use_layer_norm: bool,
28
+ dropout: float,
29
+ **kwargs,
30
+ ) -> nn.Module:
31
+ blocks = []
32
+ for _ in range(n_dense):
33
+ blocks.append(nn.Linear(hidden_size, hidden_size))
34
+ if use_batch_norm:
35
+ blocks.append(nn.BatchNorm1d(hidden_size))
36
+ elif use_layer_norm:
37
+ blocks.append(nn.LayerNorm(hidden_size))
38
+ blocks.append(nn.ReLU())
39
+ if dropout > 0:
40
+ blocks.append(nn.Dropout(dropout))
41
+ return nn.Sequential(*blocks)
42
+
43
+
44
+ class SentenceEmbeddingHead(nn.Module):
45
+ def __init__(
46
+ self, backbone_hidden_size: int, embedding_head_config: Dict[str, Any]
47
+ ):
48
+ super().__init__()
49
+ self.config = embedding_head_config
50
+
51
+ self.head = nn.Sequential(
52
+ *[
53
+ create_head_blocks(backbone_hidden_size, **embedding_head_config),
54
+ ]
55
+ )
56
+
57
+ def forward(
58
+ self, backbone_output: BaseModelOutput, attention_mask: torch.Tensor, **kwargs
59
+ ) -> BaseModelOutputWithPooling:
60
+ if self.config["pool_type"] == "cls":
61
+ embeddings = cls_pooling(backbone_output.last_hidden_state, attention_mask)
62
+ else:
63
+ raise NotImplementedError(
64
+ f"Pooling type {self.config['pool_type']} not implemented"
65
+ )
66
+ if self.config["normalize_embeddings"]:
67
+ embeddings = nn.functional.normalize(embeddings, p=2, dim=-1)
68
+ return BaseModelOutputWithPooling(
69
+ last_hidden_state=backbone_output.last_hidden_state,
70
+ pooler_output=embeddings, # type: ignore
71
+ )
72
+
73
+
74
+ class MLMHead(nn.Module):
75
+ def __init__(
76
+ self,
77
+ backbone_hidden_size: int,
78
+ vocab_size: int,
79
+ mlm_head_config: Dict[str, Any],
80
+ ):
81
+ super().__init__()
82
+ self.config = mlm_head_config
83
+
84
+ self.head = nn.Sequential(
85
+ *[
86
+ create_head_blocks(backbone_hidden_size, **mlm_head_config),
87
+ nn.Linear(backbone_hidden_size, vocab_size),
88
+ ]
89
+ )
90
+
91
+ def forward(
92
+ self,
93
+ backbone_output: BaseModelOutput,
94
+ attention_mask: torch.Tensor,
95
+ labels: Optional[torch.Tensor] = None,
96
+ **kwargs,
97
+ ) -> MaskedLMOutput:
98
+ prediction_scores = self.head(backbone_output.last_hidden_state)
99
+
100
+ loss = None
101
+ if labels is not None:
102
+ loss_fct = nn.CrossEntropyLoss()
103
+ loss = loss_fct(
104
+ prediction_scores.view(-1, prediction_scores.size(-1)),
105
+ labels.view(-1),
106
+ )
107
+ return MaskedLMOutput(loss=loss)
108
+
109
+
110
+ class CLSHead(nn.Module):
111
+ def __init__(
112
+ self,
113
+ backbone_hidden_size: int,
114
+ n_classes: int,
115
+ cls_head_config: Dict[str, Any],
116
+ ):
117
+ super().__init__()
118
+ self.config = cls_head_config
119
+
120
+ self.head = nn.Sequential(
121
+ *[
122
+ create_head_blocks(backbone_hidden_size, **cls_head_config),
123
+ nn.Linear(backbone_hidden_size, n_classes),
124
+ ]
125
+ )
126
+
127
+ def forward(
128
+ self,
129
+ backbone_output: BaseModelOutput,
130
+ attention_mask: torch.Tensor,
131
+ labels: Optional[torch.Tensor] = None,
132
+ **kwargs,
133
+ ) -> SequenceClassifierOutput:
134
+ if self.config["pool_type"] == "cls":
135
+ embeddings = cls_pooling(backbone_output.last_hidden_state, attention_mask)
136
+ else:
137
+ raise NotImplementedError(
138
+ f"Pooling type {self.config['pool_type']} not implemented"
139
+ )
140
+
141
+ prediction_scores = self.head(embeddings)
142
+
143
+ loss = None
144
+ if labels is not None:
145
+ loss_fct = nn.CrossEntropyLoss()
146
+ loss = loss_fct(
147
+ prediction_scores.view(-1, prediction_scores.size(-1)),
148
+ labels.view(-1),
149
+ )
150
+ return SequenceClassifierOutput(loss=loss)
151
+
152
+
153
+ class ForwardRouting(Enum):
154
+ GET_SENTENCE_EMBEDDING = "get_sentence_embedding"
155
+ GET_MLM_OUTPUT = "get_mlm_output"
156
+ GET_CLS_OUTPUT = "get_cls_output"
157
+
158
+
159
+ class ILKTModel(PreTrainedModel):
160
+ config_class = ILKTConfig
161
+
162
+ def __init__(self, config: ILKTConfig):
163
+ super().__init__(config)
164
+
165
+ backbone_config = AutoConfig.from_pretrained(**config.backbone_config)
166
+ pretrained_model_name_or_path = config.backbone_config[
167
+ "pretrained_model_name_or_path"
168
+ ]
169
+ self.backbone = AutoModel.from_pretrained(
170
+ pretrained_model_name_or_path, config=backbone_config
171
+ )
172
+
173
+ backbone_hidden_size = backbone_config.hidden_size
174
+ self.config.hidden_size = backbone_hidden_size
175
+ backbone_vocab_size = backbone_config.vocab_size
176
+ self.embedding_head = SentenceEmbeddingHead(
177
+ backbone_hidden_size, config.embedding_head_config
178
+ )
179
+ self.mlm_head = MLMHead(
180
+ backbone_hidden_size, backbone_vocab_size, config.mlm_head_config
181
+ )
182
+
183
+ self.cls_heads = nn.ModuleDict(
184
+ dict(
185
+ [
186
+ (
187
+ name,
188
+ CLSHead(
189
+ backbone_hidden_size, n_classes, config.cls_head_config
190
+ ),
191
+ )
192
+ for n_classes, name in config.cls_heads
193
+ ]
194
+ )
195
+ )
196
+
197
+ self.backbone.encoder.layer[-1].register_full_backward_hook(self._backward_hook)
198
+ self.gradients = []
199
+
200
+ def forward(
201
+ self,
202
+ input_ids: torch.Tensor,
203
+ attention_mask: torch.Tensor,
204
+ token_type_ids: Optional[torch.Tensor] = None,
205
+ forward_routing: ForwardRouting = ForwardRouting.GET_SENTENCE_EMBEDDING,
206
+ **kwargs,
207
+ ):
208
+ if forward_routing == ForwardRouting.GET_SENTENCE_EMBEDDING:
209
+ return self.get_sentence_embedding(
210
+ input_ids, attention_mask, token_type_ids=token_type_ids
211
+ )
212
+ elif forward_routing == ForwardRouting.GET_MLM_OUTPUT:
213
+ return self.get_mlm_output(
214
+ input_ids, attention_mask, token_type_ids=token_type_ids, **kwargs
215
+ )
216
+ elif forward_routing == ForwardRouting.GET_CLS_OUTPUT:
217
+ return self.get_cls_output(
218
+ input_ids, attention_mask, token_type_ids=token_type_ids, **kwargs
219
+ )
220
+ else:
221
+ raise ValueError(f"Unknown forward routing {forward_routing}")
222
+
223
+ def get_sentence_embedding(
224
+ self, input_ids: torch.Tensor, attention_mask: torch.Tensor, **kwargs
225
+ ):
226
+ backbone_output: BaseModelOutput = self.backbone(
227
+ input_ids=input_ids, attention_mask=attention_mask, **kwargs
228
+ )
229
+
230
+ embedding_output = self.embedding_head(
231
+ backbone_output, attention_mask, **kwargs
232
+ )
233
+
234
+ return embedding_output
235
+
236
+ def get_mlm_output(
237
+ self,
238
+ input_ids: torch.Tensor,
239
+ attention_mask: torch.Tensor,
240
+ labels: Optional[torch.Tensor] = None,
241
+ **kwargs,
242
+ ):
243
+ backbone_output: BaseModelOutput = self.backbone(
244
+ input_ids=input_ids, attention_mask=attention_mask, **kwargs
245
+ )
246
+
247
+ mlm_output = self.mlm_head(backbone_output, attention_mask, labels, **kwargs)
248
+
249
+ return mlm_output
250
+
251
+ def get_cls_output(
252
+ self,
253
+ input_ids: torch.Tensor,
254
+ attention_mask: torch.Tensor,
255
+ head_name: str,
256
+ labels: Optional[torch.Tensor] = None,
257
+ **kwargs,
258
+ ):
259
+ backbone_output: BaseModelOutput = self.backbone(
260
+ input_ids=input_ids, attention_mask=attention_mask, **kwargs
261
+ )
262
+
263
+ if head_name not in self.cls_heads:
264
+ raise ValueError(f"Head {head_name} not found in model")
265
+
266
+ cls_output = self.cls_heads[head_name](
267
+ backbone_output, attention_mask, labels, **kwargs
268
+ )
269
+
270
+ return cls_output
271
+
272
+ def _backward_hook(self, module, grad_input, grad_output):
273
+ self.gradients.append(grad_input[0])
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d9a88e5948a6574e55646661c506c45394d4436c1f9779f592271cb9dcbdf64
3
+ size 1884975744