TCMVince commited on
Commit
8dac5d2
·
verified ·
1 Parent(s): 56764f4

Upload model

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +35 -0
  3. hf_configuration.py +93 -0
  4. mlm.py +486 -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,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "FOR_JOSEPH/NRJ-BASE-125K",
3
+ "activation": "relu",
4
+ "alpha": 1.0,
5
+ "architectures": [
6
+ "BertEnergyModelForMaskedLM"
7
+ ],
8
+ "attention_probs_dropout_prob": 0.0,
9
+ "auto_map": {
10
+ "AutoConfig": "hf_configuration.BertEnergyConfig",
11
+ "AutoModelForMaskedLM": "mlm.BertEnergyModelForMaskedLM"
12
+ },
13
+ "beta": null,
14
+ "bias": true,
15
+ "compile": true,
16
+ "embedding_dim": 768,
17
+ "hidden_dropout_prob": 0.1,
18
+ "hidden_size": 3072,
19
+ "initializer_hopfield_range": 0.002,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 12288,
22
+ "layer_norm_eps": 1e-12,
23
+ "max_position_embeddings": 512,
24
+ "model_type": "bert_energy",
25
+ "num_attention_heads": 12,
26
+ "num_hidden_layers": 12,
27
+ "pad_token_id": 3,
28
+ "path": null,
29
+ "positional": true,
30
+ "share_layers": true,
31
+ "tie_word_embeddings": false,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.49.0",
34
+ "vocab_size": 30000
35
+ }
hf_configuration.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class BertEnergyConfig(PretrainedConfig):
5
+ model_type = "bert_energy"
6
+
7
+ def __init__(
8
+ self,
9
+ path: str | None = None,
10
+ alpha: float = 1.0,
11
+ beta: float | None = None,
12
+ vocab_size: int = 30000,
13
+ hidden_size: int = 768,
14
+ embedding_dim: int | None = None,
15
+ num_hidden_layers: int = 12,
16
+ num_attention_heads: int = 12,
17
+ intermediate_size: int | None = None,
18
+ activation: str = "relu",
19
+ positional: bool = True,
20
+ share_layers: bool = False,
21
+ layer_norm_eps: float = 1e-12,
22
+ initializer_range: float = 0.02,
23
+ initializer_hopfield_range: float = 0.002,
24
+ hidden_dropout_prob: float = 0.1,
25
+ attention_probs_dropout_prob: float = 0.1,
26
+ max_position_embeddings: int = 512,
27
+ tie_word_embeddings: bool = True,
28
+ bias: bool = True,
29
+ compile: bool = False,
30
+ pad_token_id: int | None = None,
31
+ problem_type: str | None = None,
32
+ **kwargs,
33
+ ):
34
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
35
+
36
+ self.path = path
37
+
38
+ # Energy-specific parameters
39
+ self.alpha = alpha
40
+ self.beta = beta
41
+
42
+ # Vocabulary / dimensions
43
+ self.vocab_size = vocab_size
44
+ self.hidden_size = hidden_size
45
+ self.embedding_dim = embedding_dim if embedding_dim is not None else hidden_size
46
+
47
+ # Transformer architecture
48
+ self.num_hidden_layers = num_hidden_layers
49
+ self.num_attention_heads = num_attention_heads
50
+ self.intermediate_size = (
51
+ intermediate_size if intermediate_size is not None else hidden_size * 4
52
+ )
53
+ self.activation = activation
54
+ self.positional = positional
55
+ self.share_layers = share_layers
56
+ self.tie_word_embeddings = tie_word_embeddings
57
+ self.bias = bias
58
+
59
+ # Regularization / initialization
60
+ self.layer_norm_eps = layer_norm_eps
61
+ self.initializer_range = initializer_range
62
+ self.initializer_hopfield_range = initializer_hopfield_range
63
+ self.hidden_dropout_prob = hidden_dropout_prob
64
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
65
+
66
+ # Sequence length
67
+ self.max_position_embeddings = max_position_embeddings
68
+
69
+ # Misc
70
+ self.compile = compile
71
+ self.problem_type = problem_type
72
+
73
+ # ---- Validation ----
74
+ if self.embedding_dim % self.num_attention_heads != 0:
75
+ raise ValueError("embedding_dim must be divisible by num_attention_heads")
76
+
77
+ if self.hidden_size <= 0:
78
+ raise ValueError("hidden_size must be > 0")
79
+
80
+ if self.embedding_dim <= 0:
81
+ raise ValueError("embedding_dim must be > 0")
82
+
83
+ if self.num_hidden_layers <= 0:
84
+ raise ValueError("num_hidden_layers must be > 0")
85
+
86
+ if self.num_attention_heads <= 0:
87
+ raise ValueError("num_attention_heads must be > 0")
88
+
89
+ if self.max_position_embeddings <= 0:
90
+ raise ValueError("max_position_embeddings must be > 0")
91
+
92
+ if self.activation not in ["relu", "gelu", "softmax"]:
93
+ raise ValueError("activation must be one of: relu, gelu, softmax")
mlm.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn.functional import gelu
4
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
5
+
6
+ from transformers import PreTrainedModel
7
+ from transformers.modeling_outputs import (
8
+ BaseModelOutput,
9
+ MaskedLMOutput,
10
+ SequenceClassifierOutput,
11
+ )
12
+
13
+ from hopfield import HopfieldLayer
14
+ from hf_configuration import BertEnergyConfig
15
+ from positional import PositionalEncoding
16
+
17
+
18
+ class EnergyLMHead(nn.Module):
19
+ """
20
+ MLM head for the energy backbone.
21
+
22
+ Architecture:
23
+ hidden -> dense -> gelu -> layer_norm -> decoder(vocab)
24
+ """
25
+
26
+ def __init__(self, config):
27
+ super().__init__()
28
+ self.dense = nn.Linear(config.embedding_dim, config.embedding_dim)
29
+ self.layer_norm = nn.LayerNorm(
30
+ config.embedding_dim,
31
+ eps=config.layer_norm_eps,
32
+ )
33
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
34
+
35
+ self.decoder = nn.Linear(config.embedding_dim, config.vocab_size, bias=True)
36
+
37
+ @property
38
+ def bias(self):
39
+ return self.decoder.bias
40
+
41
+ def forward(self, hidden_states):
42
+ x = self.dense(hidden_states)
43
+ x = gelu(x)
44
+ x = self.layer_norm(x)
45
+ x = self.dropout(x)
46
+ x = self.decoder(x)
47
+ return x
48
+
49
+ def _tie_weights(self):
50
+ pass
51
+
52
+ class AlbertMLMHead(nn.Module):
53
+ """
54
+ ALBERT-style MLM head:
55
+ hidden (H) -> embedding (E) -> LN -> vocab (V)
56
+ """
57
+
58
+ def __init__(self, config):
59
+ super().__init__()
60
+ self.dense = nn.Linear(config.hidden_size, config.embedding_dim)
61
+ self.layer_norm = nn.LayerNorm(config.embedding_dim, eps=config.layer_norm_eps)
62
+ self.decoder = nn.Linear(config.embedding_dim, config.vocab_size, bias=True)
63
+
64
+ def forward(self, hidden_states):
65
+ x = self.dense(hidden_states)
66
+ x = gelu(x)
67
+ x = self.layer_norm(x)
68
+ return self.decoder(x)
69
+
70
+
71
+ class MLMHead(nn.Module):
72
+ """
73
+ Standard BERT/RoBERTa-style MLM head.
74
+ """
75
+
76
+ def __init__(self, input_dim, hidden_dim, config):
77
+ super().__init__()
78
+ self.dense = nn.Linear(input_dim, hidden_dim)
79
+ self.layer_norm = nn.LayerNorm(hidden_dim, eps=config.layer_norm_eps)
80
+ self.decoder = nn.Linear(hidden_dim, config.vocab_size, bias=True)
81
+
82
+ @property
83
+ def bias(self):
84
+ return self.decoder.bias
85
+
86
+ def forward(self, features, **kwargs):
87
+ x = self.dense(features)
88
+ x = gelu(x)
89
+ x = self.layer_norm(x)
90
+ x = self.decoder(x)
91
+ return x
92
+
93
+ def _tie_weights(self):
94
+ pass
95
+
96
+
97
+ class BertPreTrainedModel(PreTrainedModel):
98
+ """
99
+ Common pretrained model base.
100
+ """
101
+ config_class = BertEnergyConfig
102
+
103
+ def _init_weights(self, module):
104
+ if isinstance(module, nn.Linear):
105
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
106
+ if module.bias is not None:
107
+ module.bias.data.zero_()
108
+
109
+ elif isinstance(module, nn.Embedding):
110
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
111
+ if module.padding_idx is not None:
112
+ module.weight.data[module.padding_idx].zero_()
113
+
114
+ elif isinstance(module, nn.LayerNorm):
115
+ module.bias.data.zero_()
116
+ module.weight.data.fill_(1.0)
117
+
118
+
119
+ class BertModel(BertPreTrainedModel):
120
+ """
121
+ Standard transformer backbone.
122
+ Outputs: last hidden state, optional hidden state history.
123
+ """
124
+
125
+ config_class = BertEnergyConfig
126
+
127
+ def __init__(self, config, add_pooling_layer=True, pad_idx=None, **kwargs):
128
+ super().__init__(config)
129
+
130
+ self.Emb_in = nn.Embedding(config.vocab_size, config.embedding_dim, padding_idx=pad_idx)
131
+ self.posn = (
132
+ PositionalEncoding(
133
+ config.embedding_dim,
134
+ max_len=config.max_position_embeddings,
135
+ )
136
+ if config.positional
137
+ else None
138
+ )
139
+ self.embed_norm = nn.LayerNorm(config.embedding_dim, eps=config.layer_norm_eps)
140
+ self.embed_dropout = nn.Dropout(config.hidden_dropout_prob)
141
+
142
+ self.num_layers = config.num_hidden_layers
143
+ self.share_layers = config.share_layers
144
+
145
+ if self.share_layers:
146
+ self.embedding_hidden_in = nn.Linear(config.embedding_dim, config.hidden_size)
147
+
148
+ layer = nn.TransformerEncoderLayer(
149
+ d_model=config.hidden_size,
150
+ nhead=config.num_attention_heads,
151
+ activation=config.activation,
152
+ dim_feedforward=config.hidden_size,
153
+ dropout=config.hidden_dropout_prob,
154
+ layer_norm_eps=config.layer_norm_eps,
155
+ batch_first=True,
156
+ norm_first=True,
157
+ )
158
+ self.layers = nn.ModuleList([layer])
159
+ self.output_dim = config.hidden_size
160
+ else:
161
+ self.embedding_hidden_in = None
162
+ self.layers = nn.ModuleList(
163
+ [
164
+ nn.TransformerEncoderLayer(
165
+ d_model=config.embedding_dim,
166
+ nhead=config.num_attention_heads,
167
+ dim_feedforward=config.intermediate_size,
168
+ dropout=config.hidden_dropout_prob,
169
+ layer_norm_eps=config.layer_norm_eps,
170
+ batch_first=True,
171
+ norm_first=True,
172
+ )
173
+ for _ in range(config.num_hidden_layers)
174
+ ]
175
+ )
176
+ self.output_dim = config.embedding_dim
177
+
178
+ self.post_init()
179
+
180
+ def get_input_embeddings(self):
181
+ return self.Emb_in
182
+
183
+ def set_input_embeddings(self, new_embeddings):
184
+ self.Emb_in = new_embeddings
185
+
186
+ def forward(self, input_ids, attention_mask=None, **kwargs):
187
+ x = self.Emb_in(input_ids)
188
+
189
+ if self.posn is not None:
190
+ x = x + self.posn(x)
191
+
192
+ x = self.embed_norm(x)
193
+ x = self.embed_dropout(x)
194
+
195
+ if self.share_layers:
196
+ x = self.embedding_hidden_in(x)
197
+
198
+ history = None if self.training else [x]
199
+
200
+ pad_mask = None
201
+ if attention_mask is not None:
202
+ pad_mask = ~attention_mask.to(torch.bool)
203
+
204
+ for i in range(self.num_layers):
205
+ layer = self.layers[0] if self.share_layers else self.layers[i]
206
+ x = layer(x, src_key_padding_mask=pad_mask)
207
+
208
+ if not self.training:
209
+ history.append(x)
210
+
211
+ return BaseModelOutput(
212
+ last_hidden_state=x,
213
+ hidden_states=history,
214
+ attentions=None,
215
+ )
216
+
217
+
218
+ class BertModelForMaskedLM(BertPreTrainedModel):
219
+ """
220
+ Standard transformer model for MLM.
221
+ """
222
+
223
+ config_class = BertEnergyConfig
224
+ ignore_index = -100
225
+ _tied_weights_keys = ["lm_head.decoder.weight"]
226
+
227
+ def __init__(self, config, add_pooling_layer=True, pad_idx=None):
228
+ super().__init__(config)
229
+ self.config = config
230
+
231
+ self.model = BertModel(config, pad_idx=pad_idx)
232
+
233
+ if config.share_layers:
234
+ self.lm_head = AlbertMLMHead(config)
235
+ else:
236
+ self.lm_head = MLMHead(config.embedding_dim, config.embedding_dim, config)
237
+
238
+ self.post_init()
239
+
240
+ if self.config.tie_word_embeddings:
241
+ self.tie_weights()
242
+
243
+ def get_input_embeddings(self):
244
+ return self.model.Emb_in
245
+
246
+ def set_input_embeddings(self, new_embeddings):
247
+ self.model.set_input_embeddings(new_embeddings)
248
+
249
+ def get_output_embeddings(self):
250
+ return self.lm_head.decoder
251
+
252
+ def set_output_embeddings(self, new_embeddings):
253
+ self.lm_head.decoder = new_embeddings
254
+
255
+ def forward(self, input_ids, attention_mask=None, labels=None, **kwargs):
256
+ outputs = self.model(input_ids, attention_mask=attention_mask, **kwargs)
257
+ logits = self.lm_head(outputs.last_hidden_state)
258
+
259
+ loss = None
260
+ if labels is not None:
261
+ if attention_mask is not None:
262
+ labels = labels.masked_fill(attention_mask == 0, self.ignore_index)
263
+
264
+ loss_fct = CrossEntropyLoss()
265
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
266
+
267
+ return MaskedLMOutput(
268
+ loss=loss,
269
+ logits=logits,
270
+ hidden_states=outputs.hidden_states,
271
+ attentions=outputs.attentions,
272
+ )
273
+
274
+
275
+ class BertModelForSequenceClassification(BertPreTrainedModel):
276
+ """
277
+ Standard transformer model for sequence classification.
278
+ """
279
+
280
+ config_class = BertEnergyConfig
281
+
282
+ def __init__(
283
+ self,
284
+ config,
285
+ add_pooling_layer=True,
286
+ pad_idx=None,
287
+ num_labels=2,
288
+ classifier_dropout=None,
289
+ return_dict=True,
290
+ ):
291
+ super().__init__(config)
292
+ self.config = config
293
+ self.num_labels = num_labels
294
+ self.return_dict = return_dict
295
+
296
+ self.model = BertModel(config, pad_idx=pad_idx)
297
+
298
+ output_dim = self.model.output_dim
299
+ dropout = classifier_dropout if classifier_dropout is not None else config.hidden_dropout_prob
300
+
301
+ self.dropout = nn.Dropout(dropout)
302
+ self.norm = nn.LayerNorm(output_dim, eps=config.layer_norm_eps)
303
+ self.classifier = nn.Linear(output_dim, num_labels)
304
+
305
+ self.post_init()
306
+
307
+ def forward(self, input_ids, labels=None, return_dict=None, **kwargs):
308
+ if return_dict is None:
309
+ return_dict = self.return_dict
310
+
311
+ outputs = self.model(input_ids, **kwargs)
312
+ last_hidden_state = self.norm(outputs.last_hidden_state)
313
+
314
+ x = last_hidden_state[:, 0, :]
315
+ x = self.dropout(x)
316
+ logits = self.classifier(x)
317
+
318
+ loss = None
319
+ if labels is not None:
320
+ labels = labels.to(logits.device)
321
+
322
+ if self.config.problem_type is None:
323
+ if self.num_labels == 1:
324
+ self.config.problem_type = "regression"
325
+ elif self.num_labels > 1 and labels.dtype in (torch.long, torch.int):
326
+ self.config.problem_type = "single_label_classification"
327
+ else:
328
+ self.config.problem_type = "multi_label_classification"
329
+
330
+ if self.config.problem_type == "regression":
331
+ loss_fct = MSELoss()
332
+ loss = loss_fct(logits.squeeze(), labels.squeeze()) if self.num_labels == 1 else loss_fct(logits, labels)
333
+ elif self.config.problem_type == "single_label_classification":
334
+ loss_fct = CrossEntropyLoss()
335
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
336
+ else:
337
+ loss_fct = BCEWithLogitsLoss()
338
+ loss = loss_fct(logits, labels)
339
+
340
+ if not return_dict:
341
+ output = (logits, outputs.hidden_states, outputs.attentions)
342
+ return ((loss,) + output) if loss is not None else output
343
+
344
+ return SequenceClassifierOutput(
345
+ loss=loss,
346
+ logits=logits,
347
+ hidden_states=outputs.hidden_states,
348
+ attentions=outputs.attentions,
349
+ )
350
+
351
+
352
+ class BertEnergyModel(BertPreTrainedModel):
353
+ """
354
+ Energy-based backbone.
355
+
356
+ Update rule:
357
+ g = LayerNorm(X)
358
+ X <- X - alpha * layer(g)
359
+ """
360
+
361
+ config_class = BertEnergyConfig
362
+
363
+ def __init__(self, config, add_pooling_layer=True, pad_idx=None, **kwargs):
364
+ super().__init__(config)
365
+
366
+ self.config = config
367
+ self.num_layers = config.num_hidden_layers
368
+ self.alpha = config.alpha
369
+
370
+ self.Emb_in = nn.Embedding(
371
+ config.vocab_size,
372
+ config.embedding_dim,
373
+ padding_idx=pad_idx,
374
+ )
375
+
376
+ self.posn = (
377
+ PositionalEncoding(
378
+ config.embedding_dim,
379
+ max_len=config.max_position_embeddings,
380
+ )
381
+ if config.positional
382
+ else None
383
+ )
384
+
385
+ self.embed_dropout = nn.Dropout(config.hidden_dropout_prob)
386
+
387
+ # External normalization, as in the original ET implementation
388
+ self.norm = nn.LayerNorm(config.embedding_dim, eps=config.layer_norm_eps)
389
+
390
+ self.layer = HopfieldLayer(
391
+ embedding_dim=config.embedding_dim,
392
+ nheads=config.num_attention_heads,
393
+ forward_memories=config.hidden_size,
394
+ forward_activation=config.activation,
395
+ bias=config.bias,
396
+ beta=config.beta,
397
+ device=None,
398
+ dropout=0.0,
399
+ initializer_range=config.initializer_hopfield_range,
400
+ )
401
+
402
+ self.post_init()
403
+
404
+ def set_input_embeddings(self, new_embeddings):
405
+ self.Emb_in = new_embeddings
406
+
407
+ def forward(self, input_ids, attention_mask=None, **kwargs):
408
+ x = self.Emb_in(input_ids)
409
+
410
+ if self.posn is not None:
411
+ x = x + self.posn(x)
412
+
413
+ x = self.embed_dropout(x)
414
+
415
+ keep_mask = attention_mask.to(torch.bool) if attention_mask is not None else None
416
+ history = None if self.training else [x]
417
+
418
+ for _ in range(self.num_layers):
419
+ g = self.norm(x)
420
+ update = self.layer(
421
+ g,
422
+ attention_mask=keep_mask,
423
+ )
424
+ x = x - self.alpha * update
425
+
426
+ if not self.training:
427
+ history.append(x)
428
+
429
+ return BaseModelOutput(
430
+ last_hidden_state=x,
431
+ hidden_states=history,
432
+ attentions=None,
433
+ )
434
+
435
+
436
+ class BertEnergyModelForMaskedLM(BertPreTrainedModel):
437
+ """
438
+ Energy-based model for MLM.
439
+ """
440
+
441
+ config_class = BertEnergyConfig
442
+ ignore_index = -100
443
+ _tied_weights_keys = ["lm_head.decoder.weight"]
444
+
445
+ def __init__(self, config, add_pooling_layer=True, pad_idx=None):
446
+ super().__init__(config)
447
+ self.config = config
448
+
449
+ self.model = BertEnergyModel(config, pad_idx=pad_idx)
450
+ self.lm_head = EnergyLMHead(config)
451
+
452
+ self.post_init()
453
+
454
+ if self.config.tie_word_embeddings:
455
+ self.tie_weights()
456
+
457
+ def get_input_embeddings(self):
458
+ return self.model.Emb_in
459
+
460
+ def set_input_embeddings(self, new_embeddings):
461
+ self.model.set_input_embeddings(new_embeddings)
462
+
463
+ def get_output_embeddings(self):
464
+ return self.lm_head.decoder
465
+
466
+ def set_output_embeddings(self, new_embeddings):
467
+ self.lm_head.decoder = new_embeddings
468
+
469
+ def forward(self, input_ids, attention_mask=None, labels=None, **kwargs):
470
+ outputs = self.model(input_ids, attention_mask=attention_mask, **kwargs)
471
+ logits = self.lm_head(outputs.last_hidden_state)
472
+
473
+ loss = None
474
+ if labels is not None:
475
+ if attention_mask is not None:
476
+ labels = labels.masked_fill(attention_mask == 0, self.ignore_index)
477
+
478
+ loss_fct = CrossEntropyLoss()
479
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
480
+
481
+ return MaskedLMOutput(
482
+ loss=loss,
483
+ logits=logits,
484
+ hidden_states=outputs.hidden_states,
485
+ attentions=outputs.attentions,
486
+ )
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03d5ca8d5fb8ad089ef941dce630aceb768e8c556cce1279165640d0ce2b3278
3
+ size 200983936