commit files to HF hub
Browse files- README.md +199 -0
- config.json +29 -0
- config.yaml +60 -0
- configuration_energy.py +58 -0
- mlm.py +410 -0
- model.safetensors +3 -0
- special_tokens_map.json +37 -0
- tokenizer.json +0 -0
- tokenizer/special_tokens_map.json +37 -0
- tokenizer/tokenizer.json +0 -0
- tokenizer/tokenizer_config.json +53 -0
- tokenizer_config.json +54 -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,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "NRJ-350",
|
| 3 |
+
"activation": "softmax",
|
| 4 |
+
"alpha": 0.1,
|
| 5 |
+
"architectures": [
|
| 6 |
+
"BertEnergyModelForMaskedLM"
|
| 7 |
+
],
|
| 8 |
+
"auto_map": {
|
| 9 |
+
"AutoModel": "mlm.BertEnergyModelForMaskedLM"
|
| 10 |
+
},
|
| 11 |
+
"beta": 0.125,
|
| 12 |
+
"bias": true,
|
| 13 |
+
"block_size": 512,
|
| 14 |
+
"compile": false,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"embedding_dim": 768,
|
| 17 |
+
"forward_memories": 3072,
|
| 18 |
+
"layer_norm": 1e-12,
|
| 19 |
+
"model_type": "bert_energy",
|
| 20 |
+
"num_heads": 12,
|
| 21 |
+
"num_layers": 12,
|
| 22 |
+
"pad_idx": null,
|
| 23 |
+
"positional": true,
|
| 24 |
+
"share_layers": false,
|
| 25 |
+
"tie_weights": false,
|
| 26 |
+
"torch_dtype": "float32",
|
| 27 |
+
"transformers_version": "4.47.0",
|
| 28 |
+
"vocabulary_size": 30000
|
| 29 |
+
}
|
config.yaml
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
activation: softmax
|
| 2 |
+
adam_beta1: 0.9
|
| 3 |
+
adam_beta2: 0.99
|
| 4 |
+
adam_epsilon: 1.0e-06
|
| 5 |
+
alpha: 0.1
|
| 6 |
+
attn_implementation: null
|
| 7 |
+
beta: 0.125
|
| 8 |
+
bf16: true
|
| 9 |
+
block_size: 512
|
| 10 |
+
checkpoint_dir: mlruns/896390784617014591/892b97fa0aa6499288906c463545ae00/checkpoints
|
| 11 |
+
compile: false
|
| 12 |
+
config_path: configs/JZ/NRJ_base-wiki-original.yaml
|
| 13 |
+
dataloader_num_workers: 8
|
| 14 |
+
dataset_path: /lustre/fswork/projects/rech/oou/uqh26ve/data/pre_training/en/en_wiki/wiki_20220301-cleaned-valid001/data-bin/wiki_20220301-cleaned-valid001-BPE30K/
|
| 15 |
+
ddp_find_unused_parameters: false
|
| 16 |
+
disable_tqdm: true
|
| 17 |
+
do_eval: true
|
| 18 |
+
dropout: 0.1
|
| 19 |
+
embedding_dim: 768
|
| 20 |
+
eval_steps: 25000
|
| 21 |
+
evaluation_strategy: steps
|
| 22 |
+
forward_memories: 3072
|
| 23 |
+
fp16: false
|
| 24 |
+
gradient_accumulation_steps: 1
|
| 25 |
+
ignore_lines: false
|
| 26 |
+
layer_norm: 1.0e-12
|
| 27 |
+
learning_rate: 0.0007
|
| 28 |
+
log_on_each_node: false
|
| 29 |
+
logging_steps: 1000
|
| 30 |
+
logging_strategy: steps
|
| 31 |
+
lr_scheduler_kwargs: {}
|
| 32 |
+
lr_scheduler_type: cosine
|
| 33 |
+
max_steps: 500000
|
| 34 |
+
model_name: NRJ-V_30000K_bpe-NL12-NH12-EMB768-FFN3072
|
| 35 |
+
model_type: energyBERT
|
| 36 |
+
n_run: 51
|
| 37 |
+
num_heads: 12
|
| 38 |
+
num_layers: 12
|
| 39 |
+
num_params: 50638896
|
| 40 |
+
optimizer: adamw_torch
|
| 41 |
+
output_dir: null
|
| 42 |
+
per_device_eval_batch_size: 8
|
| 43 |
+
per_device_train_batch_size: 64
|
| 44 |
+
remove_unused_columns: false
|
| 45 |
+
report_to: mlflow
|
| 46 |
+
save_steps: 25000
|
| 47 |
+
save_strategy: steps
|
| 48 |
+
seed: 42
|
| 49 |
+
share_layers: false
|
| 50 |
+
test_file: /lustre/fswork/projects/rech/oou/uqh26ve/data/pre_training/en/en_wiki/wiki_20220301-cleaned-valid001/wikipedia.test.txt
|
| 51 |
+
tie_weights: false
|
| 52 |
+
tokenizer_path: /lustre/fswork/projects/rech/oou/uqh26ve/data/pre_training/en/en_wiki/wiki_20220301-cleaned-valid001/data-bin/wiki_20220301-cleaned-valid001-BPE30K/tokenizer
|
| 53 |
+
tokenizer_type: bpe
|
| 54 |
+
total_batch_size: 4096
|
| 55 |
+
training_file: /lustre/fswork/projects/rech/oou/uqh26ve/data/pre_training/en/en_wiki/wiki_20220301-cleaned-valid001/wikipedia.train.txt
|
| 56 |
+
valid_file: /lustre/fswork/projects/rech/oou/uqh26ve/data/pre_training/en/en_wiki/wiki_20220301-cleaned-valid001/wikipedia.valid.txt
|
| 57 |
+
vocabulary_size: 30000
|
| 58 |
+
warmup_ratio: 0.0
|
| 59 |
+
warmup_steps: 24000
|
| 60 |
+
weight_decay: 0.01
|
configuration_energy.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import sqrt,log
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
#sys.path.append("../energy") # Messy
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from torch.nn.functional import softmax,relu,linear
|
| 9 |
+
from common import PositionalEncoding
|
| 10 |
+
from hopfield import HopfieldLayer, HopfieldMHA, HopfieldReLU, HopfieldSoftmax
|
| 11 |
+
|
| 12 |
+
from torch.cuda.amp import autocast
|
| 13 |
+
import yaml
|
| 14 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
| 15 |
+
from transformers.modeling_outputs import MaskedLMOutput, BaseModelOutput
|
| 16 |
+
|
| 17 |
+
class BertEnergyConfig(PretrainedConfig):
|
| 18 |
+
|
| 19 |
+
model_type = "bert_energy"
|
| 20 |
+
|
| 21 |
+
def __init__(self, config=None, path=None, vocabulary_size=50, num_layers=12, num_heads=12, forward_memories=2048, embedding_dim=768, activation="relu",positional=True, bias=True, tie_weights=True, alpha=1.0,
|
| 22 |
+
beta=1., layer_norm=1e-05, dropout=0.0, block_size=512, share_layers=False, compile=False, pad_idx=None, **kwargs):
|
| 23 |
+
|
| 24 |
+
self.vocabulary_size = vocabulary_size
|
| 25 |
+
self.num_layers = num_layers
|
| 26 |
+
self.num_heads = num_heads
|
| 27 |
+
self.activation = activation
|
| 28 |
+
self.positional = positional
|
| 29 |
+
self.tie_weights = tie_weights
|
| 30 |
+
self.bias = bias
|
| 31 |
+
self.forward_memories = forward_memories
|
| 32 |
+
self.embedding_dim = embedding_dim
|
| 33 |
+
self.share_layers = share_layers
|
| 34 |
+
self.alpha = alpha
|
| 35 |
+
self.beta = beta
|
| 36 |
+
self.layer_norm = float(layer_norm)
|
| 37 |
+
self.dropout = dropout
|
| 38 |
+
self.block_size = block_size
|
| 39 |
+
self.compile = compile
|
| 40 |
+
self.pad_idx = pad_idx
|
| 41 |
+
|
| 42 |
+
if config is not None:
|
| 43 |
+
for key,value in config.to_dict():
|
| 44 |
+
if key.lower() in self.__dict__.keys():
|
| 45 |
+
print(key, file=sys.stderr)
|
| 46 |
+
setattr(self,key.lower(),value)
|
| 47 |
+
|
| 48 |
+
elif path is not None:
|
| 49 |
+
if path.endswith(".yaml"):
|
| 50 |
+
with open(path) as istream:
|
| 51 |
+
config = yaml.safe_load(istream)
|
| 52 |
+
for key,value in config.items():
|
| 53 |
+
print(key)
|
| 54 |
+
if key.lower() in self.__dict__.keys():
|
| 55 |
+
setattr(self,key.lower(),value)
|
| 56 |
+
else:
|
| 57 |
+
raise NotImplementedError
|
| 58 |
+
super().__init__(**kwargs)
|
mlm.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import sqrt,log
|
| 2 |
+
import sys
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch.nn.functional import softmax,relu,linear, gelu
|
| 6 |
+
from common import PositionalEncoding
|
| 7 |
+
from hopfield import HopfieldLayer, HopfieldMHA, HopfieldReLU, HopfieldSoftmax
|
| 8 |
+
from configuration_energy import BertEnergyConfig
|
| 9 |
+
from torch.cuda.amp import autocast
|
| 10 |
+
import yaml
|
| 11 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 12 |
+
|
| 13 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 14 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
| 15 |
+
from transformers.modeling_outputs import MaskedLMOutput, BaseModelOutput
|
| 16 |
+
|
| 17 |
+
ACT2FN={'relu': relu, 'gelu': gelu, 'softmax': softmax}
|
| 18 |
+
|
| 19 |
+
class BertModel(PreTrainedModel):
|
| 20 |
+
""" Backbone of standard BERT model
|
| 21 |
+
outputs : last hidden state, history"""
|
| 22 |
+
|
| 23 |
+
config_class = BertEnergyConfig
|
| 24 |
+
|
| 25 |
+
def __init__(self, config, add_pooling_layer=True, pad_idx=None, **kwargs):
|
| 26 |
+
super().__init__(config)
|
| 27 |
+
|
| 28 |
+
self.Emb_in = nn.Embedding(config.vocabulary_size, config.embedding_dim, padding_idx=pad_idx)
|
| 29 |
+
self.posn = PositionalEncoding(config.embedding_dim, max_len=config.block_size,dropout=config.dropout) if config.positional else None
|
| 30 |
+
|
| 31 |
+
if config.share_layers: # ALBERT config
|
| 32 |
+
self.embedding_hidden_in = nn.Linear(config.embedding_dim, config.forward_memories) if config.share_layers else None # Albert uses two matrices instead of one for embeddings see 3.1 in Albert paper
|
| 33 |
+
# Albert normalise and penalise embeddings
|
| 34 |
+
self.embed_norm = nn.LayerNorm(config.embedding_dim, eps=config.layer_norm)
|
| 35 |
+
self.embed_dropout = nn.Dropout(config.dropout)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
self.num_layers = config.num_layers
|
| 39 |
+
self.share_layers = config.share_layers
|
| 40 |
+
|
| 41 |
+
if config.share_layers:
|
| 42 |
+
layer = nn.TransformerEncoderLayer(config.forward_memories,
|
| 43 |
+
config.num_heads,
|
| 44 |
+
activation=config.activation,
|
| 45 |
+
dim_feedforward=config.forward_memories*4,
|
| 46 |
+
dropout=config.dropout,
|
| 47 |
+
layer_norm_eps=config.layer_norm,
|
| 48 |
+
batch_first=True,
|
| 49 |
+
norm_first=True,
|
| 50 |
+
)
|
| 51 |
+
self.layers = nn.ModuleList([layer])
|
| 52 |
+
|
| 53 |
+
else:
|
| 54 |
+
self.layers = nn.ModuleList([nn.TransformerEncoderLayer(config.embedding_dim,
|
| 55 |
+
config.num_heads,
|
| 56 |
+
dim_feedforward=config.forward_memories*4,
|
| 57 |
+
dropout=config.dropout,
|
| 58 |
+
layer_norm_eps=config.layer_norm,
|
| 59 |
+
batch_first=True,
|
| 60 |
+
norm_first=True,
|
| 61 |
+
) for _ in range(config.num_layers)])
|
| 62 |
+
|
| 63 |
+
def forward(self,input_ids, attention_mask=None, **kwargs):
|
| 64 |
+
""" Warning : expect attention mask with 0 pad tokens -> mismatch Pytorch/HF tokenizer"""
|
| 65 |
+
|
| 66 |
+
xbatch = self.Emb_in(input_ids)
|
| 67 |
+
|
| 68 |
+
if self.posn:
|
| 69 |
+
X = xbatch + self.posn(xbatch)
|
| 70 |
+
else:
|
| 71 |
+
X = xbatch
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if self.share_layers:
|
| 75 |
+
X = self.embed_norm(X)
|
| 76 |
+
X = self.embed_dropout(X)
|
| 77 |
+
X = self.embedding_hidden_in(X)
|
| 78 |
+
|
| 79 |
+
history = None if self.training else [X]
|
| 80 |
+
|
| 81 |
+
# WARNING
|
| 82 |
+
attention_mask = ~attention_mask.bool() # Mismatch between HF tokenizer and Torch attention mask https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html#torch.nn.Transformer
|
| 83 |
+
for i in range(self.num_layers):
|
| 84 |
+
if self.share_layers:
|
| 85 |
+
layer = self.layers[0]
|
| 86 |
+
else:
|
| 87 |
+
layer = self.layers[i]
|
| 88 |
+
X = layer(X, src_key_padding_mask=attention_mask)
|
| 89 |
+
|
| 90 |
+
if not self.training:
|
| 91 |
+
history.append(X)
|
| 92 |
+
|
| 93 |
+
# TODO add return attention
|
| 94 |
+
return BaseModelOutput(last_hidden_state=X,
|
| 95 |
+
hidden_states=history,
|
| 96 |
+
attentions=None)
|
| 97 |
+
|
| 98 |
+
class BertModelForMaskedLM(PreTrainedModel):
|
| 99 |
+
""" Bert model to be trained on the MLM task.
|
| 100 |
+
Based on the backbone Bert model + projection on the vocabulary with tied weight and norm
|
| 101 |
+
outputs: cross entropy loss / logits / hidden states
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
config_class = BertEnergyConfig
|
| 105 |
+
ignore_index = -100
|
| 106 |
+
|
| 107 |
+
_tied_weights_keys = ["Emb_out.weight", "Emb_out.bias"]
|
| 108 |
+
|
| 109 |
+
def __init__(self, config, add_pooling_layer=True, pad_idx=None):
|
| 110 |
+
super().__init__(config)
|
| 111 |
+
self.config = config
|
| 112 |
+
|
| 113 |
+
self.model = BertModel(config, pad_idx=pad_idx)
|
| 114 |
+
|
| 115 |
+
self.norm = nn.LayerNorm(config.embedding_dim, eps=config.layer_norm)
|
| 116 |
+
self.dense = nn.Linear(config.forward_memories, config.embedding_dim)
|
| 117 |
+
self.activation = ACT2FN[config.activation]
|
| 118 |
+
"""
|
| 119 |
+
if config.tie_weights:
|
| 120 |
+
self.Emb_out = nn.Linear(config.embedding_dim, config.vocabulary_size, bias=False)
|
| 121 |
+
self.tie_weights()
|
| 122 |
+
else:
|
| 123 |
+
self.Emb_out = nn.Linear(config.embedding_dim, config.vocabulary_size)
|
| 124 |
+
self.bias = nn.Parameter(torch.zeros(config.vocabulary_size))
|
| 125 |
+
self.Emb_out.bias = self.bias
|
| 126 |
+
"""
|
| 127 |
+
self.Emb_out = nn.Linear(config.forward_memories, config.vocabulary_size)
|
| 128 |
+
self.bias = nn.Parameter(torch.zeros(config.vocabulary_size))
|
| 129 |
+
self.Emb_out.bias = self.bias
|
| 130 |
+
|
| 131 |
+
def get_input_embeddings(self):
|
| 132 |
+
return self.model.Emb_in
|
| 133 |
+
|
| 134 |
+
def set_output_embeddings(self, new_embeddings):
|
| 135 |
+
self.Emb_out = new_embeddings
|
| 136 |
+
|
| 137 |
+
def forward(self,input_ids, attention_mask=None, labels=None, **kwargs):
|
| 138 |
+
|
| 139 |
+
outputs = self.model(input_ids, attention_mask, **kwargs)
|
| 140 |
+
last_hidden_state = outputs.last_hidden_state
|
| 141 |
+
hidden_states = outputs.hidden_states
|
| 142 |
+
attentions = outputs.attentions
|
| 143 |
+
|
| 144 |
+
last_hidden_state = self.dense(last_hidden_state)
|
| 145 |
+
last_hidden_state = self.activation(last_hidden_state)
|
| 146 |
+
last_hidden_state = self.norm(last_hidden_state)
|
| 147 |
+
|
| 148 |
+
"""
|
| 149 |
+
if self.config.tie_weights:
|
| 150 |
+
logits = last_hidden_state @ self.Emb_out.weight.transpose(-1,-2)
|
| 151 |
+
else:
|
| 152 |
+
logits = self.Emb_out(last_hidden_state)
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
logits = self.Emb_out(last_hidden_state)
|
| 156 |
+
|
| 157 |
+
loss = None
|
| 158 |
+
|
| 159 |
+
if labels is not None:
|
| 160 |
+
loss_fct = CrossEntropyLoss()
|
| 161 |
+
loss = loss_fct(logits.view(-1, self.config.vocabulary_size), labels.view(-1))
|
| 162 |
+
|
| 163 |
+
return MaskedLMOutput(loss=loss,
|
| 164 |
+
logits=logits,
|
| 165 |
+
hidden_states=hidden_states,
|
| 166 |
+
attentions=attentions)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class BertModelForSequenceClassification(PreTrainedModel):
|
| 170 |
+
""" Bert model to be trained on Sequence classification tasks.
|
| 171 |
+
Based on the backbone Bert model + projection on the vocabulary with tied weight and norm
|
| 172 |
+
outputs: cross entropy loss / logits / hidden states
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
config_class = BertEnergyConfig
|
| 176 |
+
ignore_index = -100
|
| 177 |
+
|
| 178 |
+
def __init__(self, config, add_pooling_layer=True, pad_idx=None,
|
| 179 |
+
num_labels=2, classifier_dropout=None, return_dict=True):
|
| 180 |
+
super().__init__(config)
|
| 181 |
+
self.config = config
|
| 182 |
+
self.num_labels = num_labels
|
| 183 |
+
self.classifier_dropout = classifier_dropout
|
| 184 |
+
self.return_dict = return_dict
|
| 185 |
+
|
| 186 |
+
self.model = BertModel(config, pad_idx=pad_idx)
|
| 187 |
+
self.dense = nn.Linear(config.forward_memories, config.forward_memories)
|
| 188 |
+
classifier_dropout = (
|
| 189 |
+
classifier_dropout if classifier_dropout is not None else config.dropout
|
| 190 |
+
)
|
| 191 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 192 |
+
self.classifier = nn.Linear(config.forward_memories,num_labels)
|
| 193 |
+
self.norm = nn.LayerNorm(config.embedding_dim)
|
| 194 |
+
|
| 195 |
+
#self.Emb_out = nn.Linear(config.embedding_dim, config.vocabulary_size, bias=False)
|
| 196 |
+
#self.Emb_out.weight = self.model.Emb_in.weight # weight tying
|
| 197 |
+
|
| 198 |
+
def forward(self,input_ids, labels=None, return_dict=False, **kwargs):
|
| 199 |
+
|
| 200 |
+
outputs = self.model(input_ids, **kwargs)
|
| 201 |
+
last_hidden_state = self.norm(outputs.last_hidden_state)
|
| 202 |
+
# Code from roberta : https://github.com/huggingface/transformers/blob/v4.39.3/src/transformers/models/roberta/modeling_roberta.py#L1426
|
| 203 |
+
x = last_hidden_state[:, 0, :] # take <s> token (equiv. to [CLS])
|
| 204 |
+
x = self.dropout(x)
|
| 205 |
+
x = self.dense(x)
|
| 206 |
+
x = torch.tanh(x)
|
| 207 |
+
x = self.dropout(x)
|
| 208 |
+
|
| 209 |
+
logits = self.classifier(x)
|
| 210 |
+
hidden_states = outputs.hidden_states
|
| 211 |
+
attentions = outputs.attentions
|
| 212 |
+
|
| 213 |
+
loss = None
|
| 214 |
+
|
| 215 |
+
if labels is not None:
|
| 216 |
+
# move labels to correct device to enable model parallelism
|
| 217 |
+
labels = labels.to(logits.device)
|
| 218 |
+
if self.config.problem_type is None:
|
| 219 |
+
if self.num_labels == 1:
|
| 220 |
+
self.config.problem_type = "regression"
|
| 221 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 222 |
+
self.config.problem_type = "single_label_classification"
|
| 223 |
+
else:
|
| 224 |
+
self.config.problem_type = "multi_label_classification"
|
| 225 |
+
|
| 226 |
+
if self.config.problem_type == "regression":
|
| 227 |
+
loss_fct = MSELoss()
|
| 228 |
+
if self.num_labels == 1:
|
| 229 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 230 |
+
else:
|
| 231 |
+
loss = loss_fct(logits, labels)
|
| 232 |
+
elif self.config.problem_type == "single_label_classification":
|
| 233 |
+
loss_fct = CrossEntropyLoss()
|
| 234 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 235 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 236 |
+
loss_fct = BCEWithLogitsLoss()
|
| 237 |
+
loss = loss_fct(logits, labels)
|
| 238 |
+
|
| 239 |
+
if not return_dict:
|
| 240 |
+
output = (logits,) + outputs[2:]
|
| 241 |
+
return ((loss,) + output) if loss is not None else output
|
| 242 |
+
|
| 243 |
+
return SequenceClassifierOutput(
|
| 244 |
+
loss=loss,
|
| 245 |
+
logits=logits,
|
| 246 |
+
hidden_states=outputs.hidden_states,
|
| 247 |
+
attentions=outputs.attentions,
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
def compute_loss(self, logits, labels):
|
| 251 |
+
# code from https://github.com/huggingface/transformers/blob/main/src/transformers/trainer_pt_utils.py#L494
|
| 252 |
+
log_probs = -nn.functional.log_softmax(logits, dim=-1)
|
| 253 |
+
if labels.dim() == log_probs.dim() - 1:
|
| 254 |
+
labels = labels.unsqueeze(-1)
|
| 255 |
+
|
| 256 |
+
padding_mask = labels.eq(self.ignore_index)
|
| 257 |
+
# In case the ignore_index is -100, the gather will fail, so we replace labels by 0. The padding_mask
|
| 258 |
+
# will ignore them in any case.
|
| 259 |
+
labels = torch.clamp(labels, min=0)
|
| 260 |
+
nll_loss = log_probs.gather(dim=-1, index=labels)
|
| 261 |
+
nll_loss.masked_fill_(padding_mask, 0.0)
|
| 262 |
+
num_active_elements = padding_mask.numel() - padding_mask.long().sum()
|
| 263 |
+
nll_loss = nll_loss.sum() / num_active_elements
|
| 264 |
+
return nll_loss
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class BertEnergyModel(PreTrainedModel):
|
| 268 |
+
|
| 269 |
+
config_class = BertEnergyConfig
|
| 270 |
+
|
| 271 |
+
def __init__(self, config, add_pooling_layer=True, pad_idx=None, **kwargs):
|
| 272 |
+
super().__init__(config)
|
| 273 |
+
|
| 274 |
+
self.Emb_in = nn.Embedding(config.vocabulary_size, config.embedding_dim, padding_idx=pad_idx)
|
| 275 |
+
self.posn = PositionalEncoding(config.embedding_dim,max_len=config.block_size,dropout=config.dropout) if config.positional else None
|
| 276 |
+
|
| 277 |
+
self.num_layers = config.num_layers
|
| 278 |
+
self.layer = HopfieldLayer(config.embedding_dim,config.num_heads,forward_memories=config.forward_memories,forward_activation=config.activation,bias=config.bias,beta=config.beta,dropout=config.dropout)
|
| 279 |
+
|
| 280 |
+
self.alpha = config.alpha
|
| 281 |
+
|
| 282 |
+
def forward(self,input_ids, attention_mask=None, **kwargs):
|
| 283 |
+
|
| 284 |
+
xbatch = self.Emb_in(input_ids)
|
| 285 |
+
|
| 286 |
+
if self.posn:
|
| 287 |
+
X = xbatch + self.posn(xbatch)
|
| 288 |
+
else:
|
| 289 |
+
X = xbatch
|
| 290 |
+
|
| 291 |
+
history = None if self.training else [X]
|
| 292 |
+
|
| 293 |
+
for _ in range(self.num_layers):
|
| 294 |
+
#TODO add src_key pad attention mask
|
| 295 |
+
X = X - self.alpha * self.layer(X, src_key_padding_mask=attention_mask, is_causal=False)
|
| 296 |
+
if not self.training:
|
| 297 |
+
history.append(X)
|
| 298 |
+
|
| 299 |
+
return BaseModelOutput(last_hidden_state=X,
|
| 300 |
+
hidden_states=history,
|
| 301 |
+
attentions=None)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class BertEnergyModelForMaskedLM(PreTrainedModel):
|
| 305 |
+
|
| 306 |
+
config_class = BertEnergyConfig
|
| 307 |
+
ignore_index = -100
|
| 308 |
+
|
| 309 |
+
_tied_weights_keys = ["Emb_out.weight", "Emb_out.bias"]
|
| 310 |
+
|
| 311 |
+
def __init__(self, config, add_pooling_layer=True, pad_idx=None):
|
| 312 |
+
super().__init__(config)
|
| 313 |
+
self.config = config
|
| 314 |
+
|
| 315 |
+
self.model = BertEnergyModel(config, pad_idx=pad_idx)
|
| 316 |
+
|
| 317 |
+
self.norm = nn.LayerNorm(config.embedding_dim, eps=config.layer_norm)
|
| 318 |
+
self.dense = nn.Linear(config.embedding_dim, config.embedding_dim)
|
| 319 |
+
self.activation = ACT2FN[config.activation]
|
| 320 |
+
|
| 321 |
+
self.Emb_out = nn.Linear(config.embedding_dim, config.vocabulary_size)
|
| 322 |
+
self.bias = nn.Parameter(torch.zeros(config.vocabulary_size))
|
| 323 |
+
self.Emb_out.bias = self.bias
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def get_input_embeddings(self):
|
| 327 |
+
return self.model.Emb_in
|
| 328 |
+
|
| 329 |
+
def set_output_embeddings(self, new_embeddings):
|
| 330 |
+
self.Emb_out = new_embeddings
|
| 331 |
+
|
| 332 |
+
def forward(self,input_ids, attention_mask=None, labels=None, **kwargs ):
|
| 333 |
+
|
| 334 |
+
outputs = self.model(input_ids , attention_mask=attention_mask)
|
| 335 |
+
last_hidden_state = outputs.last_hidden_state
|
| 336 |
+
hidden_states = outputs.hidden_states
|
| 337 |
+
attentions = outputs.attentions
|
| 338 |
+
|
| 339 |
+
last_hidden_state = self.dense(last_hidden_state)
|
| 340 |
+
last_hidden_state = gelu(last_hidden_state) #XXX
|
| 341 |
+
last_hidden_state = self.norm(last_hidden_state)
|
| 342 |
+
|
| 343 |
+
#logits = self.norm(last_hidden_state) @ self.Emb_out.weight.transpose(-1,-2)
|
| 344 |
+
if self.config.tie_weights:
|
| 345 |
+
logits = last_hidden_state @ self.Emb_out.weight.transpose(-1,-2)
|
| 346 |
+
else:
|
| 347 |
+
logits = self.Emb_out(last_hidden_state)
|
| 348 |
+
|
| 349 |
+
loss = None
|
| 350 |
+
hidden_states = hidden_states
|
| 351 |
+
attentions = None
|
| 352 |
+
|
| 353 |
+
#if labels is not None:
|
| 354 |
+
# loss = self.compute_loss(logits, labels)
|
| 355 |
+
if labels is not None:
|
| 356 |
+
loss_fct = CrossEntropyLoss()
|
| 357 |
+
loss = loss_fct(logits.view(-1, self.config.vocabulary_size), labels.view(-1))
|
| 358 |
+
|
| 359 |
+
return MaskedLMOutput(loss=loss,
|
| 360 |
+
logits=logits,
|
| 361 |
+
hidden_states=hidden_states,
|
| 362 |
+
attentions=attentions)
|
| 363 |
+
|
| 364 |
+
if __name__ == '__main__':
|
| 365 |
+
|
| 366 |
+
def grads(f, x):
|
| 367 |
+
""" Autograd used for the energy """
|
| 368 |
+
return torch.func.jacrev(f)(x)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
#from test import *
|
| 372 |
+
x = torch.randn(1,10)
|
| 373 |
+
input_ids = torch.tensor([[3,12,44, 2]])
|
| 374 |
+
|
| 375 |
+
#test relu
|
| 376 |
+
#print('relu')
|
| 377 |
+
#hrelu = HopfieldReLU(10,4,bias=False)
|
| 378 |
+
#print(hrelu(x),hrelu.energy(x))
|
| 379 |
+
#print(grads(hrelu.energy,x))
|
| 380 |
+
|
| 381 |
+
#test softmax
|
| 382 |
+
#print('softmax')
|
| 383 |
+
#hsoftmax = HopfieldSoftmax(10,4,bias=None)
|
| 384 |
+
#print(hsoftmax(x),hsoftmax.energy(x))
|
| 385 |
+
#print(grads(hsoftmax.energy,x))
|
| 386 |
+
|
| 387 |
+
#test MHA
|
| 388 |
+
#print('mha')
|
| 389 |
+
#mha = HopfieldMHA(15,3)
|
| 390 |
+
#X = torch.randn(2,4,15)
|
| 391 |
+
#causal = True
|
| 392 |
+
#print(mha(X,is_causal=causal),mha.energy(X,is_causal=causal))
|
| 393 |
+
#print()
|
| 394 |
+
#print('=== Ref=== ')
|
| 395 |
+
#for x in X: #autograd breaks with higher order tensors
|
| 396 |
+
# print(grads(lambda y: mha.energy(y,is_causal=causal) ,x))
|
| 397 |
+
config = HopfieldConfig(path="../lmconfig.yaml")
|
| 398 |
+
print(config)
|
| 399 |
+
#exit()
|
| 400 |
+
mdl = HFHopfieldModel(config)
|
| 401 |
+
mdl.eval()
|
| 402 |
+
#print(mdl)
|
| 403 |
+
out = mdl(input_ids)
|
| 404 |
+
print(out[0].mean())
|
| 405 |
+
mdl.save_pretrained("test_checkpoint")
|
| 406 |
+
reloaded = HFHopfieldModel.from_pretrained("test_checkpoint")
|
| 407 |
+
out_reloaded = reloaded(input_ids)
|
| 408 |
+
print(out_reloaded[0].mean())
|
| 409 |
+
reloaded.to("cuda:0")
|
| 410 |
+
print(reloaded(input_ids.to("cuda:0"))[0])
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:84b9d586b1e5d0e9662d1ca8cacd558a323da7d6c30ac29efd6b2678ae51c923
|
| 3 |
+
size 202676920
|
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 |
+
"eos_token": {
|
| 10 |
+
"content": "[SEP]",
|
| 11 |
+
"lstrip": false,
|
| 12 |
+
"normalized": false,
|
| 13 |
+
"rstrip": false,
|
| 14 |
+
"single_word": false
|
| 15 |
+
},
|
| 16 |
+
"mask_token": {
|
| 17 |
+
"content": "[MASK]",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": false,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
},
|
| 23 |
+
"pad_token": {
|
| 24 |
+
"content": "[PAD]",
|
| 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/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 |
+
"eos_token": {
|
| 10 |
+
"content": "[SEP]",
|
| 11 |
+
"lstrip": false,
|
| 12 |
+
"normalized": false,
|
| 13 |
+
"rstrip": false,
|
| 14 |
+
"single_word": false
|
| 15 |
+
},
|
| 16 |
+
"mask_token": {
|
| 17 |
+
"content": "[MASK]",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": false,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
},
|
| 23 |
+
"pad_token": {
|
| 24 |
+
"content": "[PAD]",
|
| 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/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer/tokenizer_config.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "[UNK]",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"1": {
|
| 12 |
+
"content": "[CLS]",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": false,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
},
|
| 19 |
+
"2": {
|
| 20 |
+
"content": "[SEP]",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": false,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false,
|
| 25 |
+
"special": true
|
| 26 |
+
},
|
| 27 |
+
"3": {
|
| 28 |
+
"content": "[PAD]",
|
| 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": false,
|
| 45 |
+
"cls_token": "[CLS]",
|
| 46 |
+
"eos_token": "[SEP]",
|
| 47 |
+
"mask_token": "[MASK]",
|
| 48 |
+
"max_length": 512,
|
| 49 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 50 |
+
"pad_token": "[PAD]",
|
| 51 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 52 |
+
"unk_token": "[UNK]"
|
| 53 |
+
}
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "[UNK]",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"1": {
|
| 12 |
+
"content": "[CLS]",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": false,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
},
|
| 19 |
+
"2": {
|
| 20 |
+
"content": "[SEP]",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": false,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false,
|
| 25 |
+
"special": true
|
| 26 |
+
},
|
| 27 |
+
"3": {
|
| 28 |
+
"content": "[PAD]",
|
| 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": false,
|
| 45 |
+
"cls_token": "[CLS]",
|
| 46 |
+
"eos_token": "[SEP]",
|
| 47 |
+
"extra_special_tokens": {},
|
| 48 |
+
"mask_token": "[MASK]",
|
| 49 |
+
"max_length": 512,
|
| 50 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 51 |
+
"pad_token": "[PAD]",
|
| 52 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 53 |
+
"unk_token": "[UNK]"
|
| 54 |
+
}
|