Upload PISCO
Browse files- README.md +199 -0
- config.json +18 -0
- generation_config.json +4 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modelling_pisco.py +335 -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,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "/scratch/1/user/mlouis/calmar/pisco_hub_models/pisco-llama",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"PISCO"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "modelling_pisco.PISCOConfig",
|
| 8 |
+
"AutoModel": "modelling_pisco.PISCO"
|
| 9 |
+
},
|
| 10 |
+
"compr_rate": 16,
|
| 11 |
+
"decoder_model_name": "meta-llama/Meta-Llama-3.1-8B-Instruct",
|
| 12 |
+
"device_map": "auto",
|
| 13 |
+
"lora_r": 16,
|
| 14 |
+
"model_type": "PISCO",
|
| 15 |
+
"sep": true,
|
| 16 |
+
"torch_dtype": "bfloat16",
|
| 17 |
+
"transformers_version": "4.44.2"
|
| 18 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"top_p": null,
|
| 3 |
+
"transformers_version": "4.44.2"
|
| 4 |
+
}
|
model-00001-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:643f7e54e17605653a257eaca8eb81b1ed7cfa27c391cc91b7dd27ebbf9c1145
|
| 3 |
+
size 4905375000
|
model-00002-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:296c63e0cb34e90e6925e4afde518d84aca239f8a5dc8e944c47c24f0c5c8655
|
| 3 |
+
size 4974831072
|
model-00003-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4215c093d0dc5129818da31ca2c716f4d9b6663b7e9f8c1d7a0740df3128bc27
|
| 3 |
+
size 4941786528
|
model-00004-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e3d048390103c4935793134af823deb779b39c273d12752a67ad0340acaaf782
|
| 3 |
+
size 1406650936
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modelling_pisco.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
import os
|
| 3 |
+
import torch
|
| 4 |
+
from peft import LoraConfig
|
| 5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedModel, PretrainedConfig, AutoConfig, GenerationConfig
|
| 6 |
+
from jinja2.exceptions import TemplateError
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def add_memory_tokens_to_inputs(input_ids: torch.Tensor, attention_mask: torch.Tensor, n_mem_tokens: int, tokenizer):
|
| 10 |
+
"""
|
| 11 |
+
Concatenate the input ids with n_mem_tokens mem_tokens and update the corresponding attention mask
|
| 12 |
+
"""
|
| 13 |
+
assert len(tokenizer.mem_tokens) == n_mem_tokens, f"{len(tokenizer.mem_tokens)} VS {n_mem_tokens}"
|
| 14 |
+
mem_tokens = torch.stack([tokenizer.mem_token_ids_pt] * input_ids.size(0), 0)
|
| 15 |
+
assert len(mem_tokens.size()) == 2
|
| 16 |
+
assert len(mem_tokens) == input_ids.size(0)
|
| 17 |
+
assert len(mem_tokens[0]) == n_mem_tokens
|
| 18 |
+
#mem_tokens = torch.full((input_ids.size(0), n_mem_tokens), tokenizer.mem_token_id, dtype=torch.long)
|
| 19 |
+
input_ids = torch.cat([input_ids, mem_tokens], dim=1)
|
| 20 |
+
attention_mask = torch.cat([attention_mask, torch.ones(input_ids.size(0), n_mem_tokens)], dim=1)
|
| 21 |
+
return input_ids, attention_mask
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class PISCOConfig(PretrainedConfig):
|
| 25 |
+
|
| 26 |
+
model_type = "PISCO"
|
| 27 |
+
def __init__(self,
|
| 28 |
+
decoder_model_name: str = "meta-llama/Llama-2-7b-chat-hf",
|
| 29 |
+
compr_rate: int = 16,
|
| 30 |
+
**kwargs):
|
| 31 |
+
super().__init__(**kwargs)
|
| 32 |
+
|
| 33 |
+
self.decoder_model_name = decoder_model_name # model name of decoder
|
| 34 |
+
self.compr_rate = compr_rate # compression rate
|
| 35 |
+
self.lora_r = 16
|
| 36 |
+
self.sep = True
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class PISCO(PreTrainedModel):
|
| 40 |
+
config_class = PISCOConfig
|
| 41 |
+
def __init__(self, cfg):
|
| 42 |
+
super().__init__(cfg)
|
| 43 |
+
self.decoder_model_name = cfg.decoder_model_name
|
| 44 |
+
self.sep = cfg.sep
|
| 45 |
+
self.compr_rate = cfg.compr_rate
|
| 46 |
+
|
| 47 |
+
self.create_tokenizer(cfg)
|
| 48 |
+
|
| 49 |
+
# Base model config but we modify vocab size since we added tokens (mainly the mem tokens)
|
| 50 |
+
decoder_config = AutoConfig.from_pretrained(cfg.decoder_model_name)
|
| 51 |
+
decoder_config.vocab_size = len(self.tokenizer)
|
| 52 |
+
|
| 53 |
+
# Initializing placeholder model:
|
| 54 |
+
self.decoder = AutoModelForCausalLM.from_config(decoder_config,
|
| 55 |
+
attn_implementation='flash_attention_2',
|
| 56 |
+
torch_dtype=torch.bfloat16)
|
| 57 |
+
|
| 58 |
+
peft_config = self.get_peft_config(cfg)
|
| 59 |
+
|
| 60 |
+
self.adapter_keys = []
|
| 61 |
+
self.decoder.add_adapter(peft_config, 'decoder_adapter')
|
| 62 |
+
self.decoder.set_adapter('decoder_adapter')
|
| 63 |
+
self.adapter_keys.append('decoder_adapter')
|
| 64 |
+
self.decoder.add_adapter(peft_config, 'encoder_adapter')
|
| 65 |
+
self.adapter_keys.append('encoder_adapter')
|
| 66 |
+
|
| 67 |
+
self.generation_config = GenerationConfig(do_sample=False, top_p=None)
|
| 68 |
+
|
| 69 |
+
def create_tokenizer(self, cfg):
|
| 70 |
+
self.tokenizer = AutoTokenizer.from_pretrained(cfg.decoder_model_name, use_fast=True, padding_side='left')
|
| 71 |
+
|
| 72 |
+
n_mem_tokens = 128 // cfg.compr_rate
|
| 73 |
+
mem_tokens = ['<MEM' + str(i) + '>' for i in range(n_mem_tokens)]
|
| 74 |
+
self.tokenizer.add_special_tokens({'additional_special_tokens': mem_tokens + ['<AE>', '<ENC>', '<SEP>']})
|
| 75 |
+
self.tokenizer.mem_tokens = mem_tokens
|
| 76 |
+
|
| 77 |
+
self.tokenizer.mem_token_ids = [self.tokenizer.convert_tokens_to_ids(elt) for elt in self.tokenizer.mem_tokens]
|
| 78 |
+
self.tokenizer.mem_token_ids_pt = torch.LongTensor(self.tokenizer.mem_token_ids) # required later on for operations on tensors
|
| 79 |
+
|
| 80 |
+
self.tokenizer.ae_token = '<AE>' # token for autoencoding on decoder side
|
| 81 |
+
self.tokenizer.ae_token_id = self.tokenizer.convert_tokens_to_ids('<AE>')
|
| 82 |
+
self.tokenizer.enc_token = '<ENC>' # token for autoencoding on compressor side
|
| 83 |
+
self.tokenizer.sep_token = '<SEP>' # sep token between document
|
| 84 |
+
self.tokenizer.sep_token_id = self.tokenizer.convert_tokens_to_ids('<SEP>')
|
| 85 |
+
|
| 86 |
+
# if pad token exists then use pad token, othrwise bos token
|
| 87 |
+
if self.tokenizer.pad_token_id is None:
|
| 88 |
+
self.tokenizer.pad_token_id = self.tokenizer.bos_token_id
|
| 89 |
+
|
| 90 |
+
def set_all_adapters(self):
|
| 91 |
+
if len(self.adapter_keys) > 0:
|
| 92 |
+
self.decoder.set_adapter(self.adapter_keys)
|
| 93 |
+
|
| 94 |
+
def get_peft_config(self, cfg: PISCOConfig) -> LoraConfig:
|
| 95 |
+
"""
|
| 96 |
+
Builds the peft config
|
| 97 |
+
"""
|
| 98 |
+
return LoraConfig(task_type="CAUSAL_LM", r=cfg.lora_r, lora_alpha=2* cfg.lora_r, target_modules='all-linear', lora_dropout=0.1)
|
| 99 |
+
|
| 100 |
+
def compress(self, enc_input_ids, enc_attention_mask):
|
| 101 |
+
return self.compr_decoder(enc_input_ids, enc_attention_mask)
|
| 102 |
+
|
| 103 |
+
def replace_emb(self, compressed_embs, dec_input_ids):
|
| 104 |
+
"""
|
| 105 |
+
Create an input embedding vector combining the compressed_embs and the dec_input_ids
|
| 106 |
+
"""
|
| 107 |
+
indices = range(0, compressed_embs.size(0) + 1, self.generation_top_k)
|
| 108 |
+
|
| 109 |
+
input_embeds = self.decoder.get_input_embeddings()(dec_input_ids)
|
| 110 |
+
num_embs = compressed_embs.size(1)
|
| 111 |
+
if self.sep:
|
| 112 |
+
slot_len = num_embs + 1
|
| 113 |
+
else:
|
| 114 |
+
slot_len = num_embs
|
| 115 |
+
# get first mem_token indices
|
| 116 |
+
first_mem_token_indices = torch.argmax((dec_input_ids == self.tokenizer.mem_token_ids[0]).int(), dim=1)
|
| 117 |
+
batch_size = input_embeds.size(0)
|
| 118 |
+
# for each example in batch, replace them with compressed embeddings
|
| 119 |
+
for i in range(batch_size):
|
| 120 |
+
for j in range(indices[i], indices[i + 1]):
|
| 121 |
+
start_idx = first_mem_token_indices[i].item() + (j-indices[i]) * slot_len
|
| 122 |
+
assert input_embeds[i, start_idx:start_idx + num_embs, :].size() == compressed_embs[j].size(), \
|
| 123 |
+
f"{input_embeds[i, start_idx:start_idx + num_embs, :].size()} VS {compressed_embs[j].size()}"
|
| 124 |
+
input_embeds[i, start_idx:start_idx + num_embs, :] = compressed_embs[j]
|
| 125 |
+
|
| 126 |
+
return input_embeds
|
| 127 |
+
|
| 128 |
+
def compr_decoder(self, input_ids, attention_mask):
|
| 129 |
+
"""
|
| 130 |
+
Compression using the decoder
|
| 131 |
+
"""
|
| 132 |
+
assert input_ids.size() == attention_mask.size(), f"{input_ids.size()} vs {attention_mask.size()}"
|
| 133 |
+
|
| 134 |
+
# Switch adapter if we are training two different ones:
|
| 135 |
+
if 'encoder_adapter' in self.adapter_keys:
|
| 136 |
+
self.decoder.set_adapter('encoder_adapter')
|
| 137 |
+
|
| 138 |
+
emb = self.decoder(input_ids=input_ids,
|
| 139 |
+
attention_mask=attention_mask,
|
| 140 |
+
output_hidden_states=True).hidden_states[-1]
|
| 141 |
+
mask = torch.isin(input_ids, self.tokenizer.mem_token_ids_pt.to(input_ids.device))
|
| 142 |
+
return emb[mask].reshape(emb.size(0), -1, emb.size(-1))
|
| 143 |
+
|
| 144 |
+
def prepare_encoder_inputs_to_decoder(self, texts, max_length):
|
| 145 |
+
inp_enc = [self.tokenizer.enc_token + self.tokenizer.bos_token + text + self.tokenizer.eos_token for text in texts]
|
| 146 |
+
inp_enc = self.tokenizer(inp_enc, return_tensors='pt', padding="longest", max_length=max_length+3, truncation=True, add_special_tokens=False)
|
| 147 |
+
num_mem_tokens = 128 // self.compr_rate # hardcode size
|
| 148 |
+
assert num_mem_tokens == len(self.tokenizer.mem_tokens)
|
| 149 |
+
inp_enc['input_ids'], inp_enc['attention_mask'] = add_memory_tokens_to_inputs(inp_enc['input_ids'],
|
| 150 |
+
inp_enc['attention_mask'],
|
| 151 |
+
num_mem_tokens,
|
| 152 |
+
tokenizer=self.tokenizer)
|
| 153 |
+
|
| 154 |
+
return inp_enc
|
| 155 |
+
|
| 156 |
+
def prepare_encoder_inputs(self, texts, max_length):
|
| 157 |
+
return self.prepare_encoder_inputs_to_decoder(texts, max_length)
|
| 158 |
+
|
| 159 |
+
def forward(self,
|
| 160 |
+
enc_input_ids: torch.LongTensor = None,
|
| 161 |
+
enc_attention_mask: torch.LongTensor = None,
|
| 162 |
+
dec_input_ids: torch.LongTensor = None,
|
| 163 |
+
dec_attention_mask: torch.LongTensor = None,
|
| 164 |
+
labels: torch.LongTensor = None):
|
| 165 |
+
"""
|
| 166 |
+
enc_input_ids: stores the contexts, should be flattened from all queries before input, can be of shape:
|
| 167 |
+
- (batch_size*generation_top_k, enc_token_length)
|
| 168 |
+
- (batch_size, generation_top_k, enc_token_length)
|
| 169 |
+
enc_attention_mask: attention mask of enc_input_ids, same shape as enc_input_ids
|
| 170 |
+
dec_input_ids: stores the prompts (including mem tokens), dimention (batch_size, dec_token_length)
|
| 171 |
+
dec_attention_mask: attention mask of dec_input_ids
|
| 172 |
+
"""
|
| 173 |
+
assert enc_input_ids.size() == enc_attention_mask.size(), f"{enc_input_ids.size()} vs {enc_attention_mask.size()}"
|
| 174 |
+
|
| 175 |
+
if len(enc_input_ids.size()) == 3: # likely from bergen: we just flatten all of this to perform encoding in one batch
|
| 176 |
+
batch_size, top_k, seq_length = enc_input_ids.size()
|
| 177 |
+
enc_input_ids = enc_input_ids.view(batch_size * top_k, seq_length)
|
| 178 |
+
enc_attention_mask = enc_attention_mask.view(batch_size * top_k, seq_length)
|
| 179 |
+
|
| 180 |
+
# Here, we should have top_k times more elements in enc_input_ids than in dec_input_ids
|
| 181 |
+
assert enc_input_ids.size(0) == dec_input_ids.size(0) * self.generation_top_k, \
|
| 182 |
+
f"{enc_input_ids.size(0)} VS {dec_input_ids.size(0)} with generation_top_k={self.generation_top_k}"
|
| 183 |
+
|
| 184 |
+
# Perform compression with gradient tracking
|
| 185 |
+
compressed_embs = self.compress(enc_input_ids, enc_attention_mask)
|
| 186 |
+
inputs_embeds = self.replace_emb(compressed_embs, dec_input_ids)
|
| 187 |
+
|
| 188 |
+
# decoding
|
| 189 |
+
if 'decoder_adapter' in self.adapter_keys:
|
| 190 |
+
self.decoder.set_adapter('decoder_adapter')
|
| 191 |
+
|
| 192 |
+
decoder_outputs = self.decoder(inputs_embeds=inputs_embeds, attention_mask=dec_attention_mask, labels=labels)
|
| 193 |
+
|
| 194 |
+
# At end of forward, we need to activate all adapters so that they are both trained...
|
| 195 |
+
self.set_all_adapters()
|
| 196 |
+
|
| 197 |
+
return {"loss": decoder_outputs.loss, "logits": decoder_outputs.logits}
|
| 198 |
+
|
| 199 |
+
def generate_from_text(self, questions: list[str], documents: list[list[str]], max_new_tokens: int = 128) -> list[str]:
|
| 200 |
+
"""
|
| 201 |
+
Generates answers from documents (via compression then decoding)
|
| 202 |
+
questions: list of string
|
| 203 |
+
documents: list of list of strings (they should all be of equal length: the nb of doc for each question)
|
| 204 |
+
"""
|
| 205 |
+
self.generation_top_k = len(documents[0])
|
| 206 |
+
assert len(documents) == len(questions)
|
| 207 |
+
assert all([len(context) == len(documents[0]) for context in documents])
|
| 208 |
+
flat_documents = sum(documents, [])
|
| 209 |
+
|
| 210 |
+
model_input = {}
|
| 211 |
+
|
| 212 |
+
# Creating encoder inputs:
|
| 213 |
+
input_encoder = self.prepare_encoder_inputs(flat_documents, max_length=128)
|
| 214 |
+
device = self.decoder.device
|
| 215 |
+
model_input['enc_input_ids'], model_input['enc_attention_mask'] = input_encoder['input_ids'].to(device), input_encoder['attention_mask'].to(device)
|
| 216 |
+
|
| 217 |
+
# Creating decoder inputs
|
| 218 |
+
instr = [self.blend_prompt_and_memory_tokens(query=q) for q in questions]
|
| 219 |
+
inp_dec = self.tokenizer(instr, return_tensors='pt', padding="longest", add_special_tokens=False, truncation=True, max_length=2048)
|
| 220 |
+
model_input['dec_input_ids'], model_input['dec_attention_mask'] = inp_dec['input_ids'].to(device), inp_dec['attention_mask'].to(device)
|
| 221 |
+
|
| 222 |
+
# Generation
|
| 223 |
+
return self.generate(model_input, max_new_tokens=max_new_tokens)
|
| 224 |
+
|
| 225 |
+
def generate_from_compressed_documents_and_questions(self, questions: list[str], compressed_documents: torch.Tensor, max_new_tokens: int = 128) -> list[str]:
|
| 226 |
+
"""
|
| 227 |
+
Generates answers from compressed documents
|
| 228 |
+
questions: list of string
|
| 229 |
+
compressed_documents: torch tensor, its first dimension should be a multiple of len(questions)
|
| 230 |
+
"""
|
| 231 |
+
print(compressed_documents.size(), len(questions))
|
| 232 |
+
self.generation_top_k = compressed_documents.size(0) // len(questions)
|
| 233 |
+
assert compressed_documents.size(0) % self.generation_top_k == 0, f"{compressed_documents.size(0)} {self.generation_top_k}"
|
| 234 |
+
|
| 235 |
+
# Creating decoder inputs
|
| 236 |
+
instr = [self.blend_prompt_and_memory_tokens(query=q) for q in questions]
|
| 237 |
+
inp_dec = self.tokenizer(instr, return_tensors='pt', padding="longest", add_special_tokens=False, truncation=True, max_length=2048)
|
| 238 |
+
device = self.decoder.device
|
| 239 |
+
dec_input_ids, dec_attention_mask = inp_dec['input_ids'].to(device), inp_dec['attention_mask'].to(device)
|
| 240 |
+
|
| 241 |
+
# Creating input decoder embeddings from prompt + compressed documents
|
| 242 |
+
inputs_embeds = self.replace_emb(compressed_documents, dec_input_ids)
|
| 243 |
+
|
| 244 |
+
# Activating decoder generator:
|
| 245 |
+
if 'decoder_adapter' in self.adapter_keys:
|
| 246 |
+
self.decoder.set_adapter('decoder_adapter')
|
| 247 |
+
|
| 248 |
+
output_ids = self.decoder.generate(
|
| 249 |
+
inputs_embeds=inputs_embeds,
|
| 250 |
+
attention_mask=dec_attention_mask,
|
| 251 |
+
generation_config=self.generation_config,
|
| 252 |
+
max_new_tokens=max_new_tokens
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# de-tokenizing
|
| 256 |
+
return self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 257 |
+
|
| 258 |
+
def compress_documents(self, documents: list[str]) -> torch.Tensor:
|
| 259 |
+
"""
|
| 260 |
+
Compress a list of documents
|
| 261 |
+
"""
|
| 262 |
+
input_encoder = self.prepare_encoder_inputs(documents, max_length=128)
|
| 263 |
+
enc_input_ids = input_encoder['input_ids'].to(self.decoder.device)
|
| 264 |
+
attention_mask = input_encoder['attention_mask'].to(self.decoder.device)
|
| 265 |
+
return self.compress(enc_input_ids=enc_input_ids, enc_attention_mask=attention_mask)
|
| 266 |
+
|
| 267 |
+
def generate(self, model_input, max_new_tokens=128):
|
| 268 |
+
"""
|
| 269 |
+
Generation pipeline including compression + decoding from compressed
|
| 270 |
+
"""
|
| 271 |
+
|
| 272 |
+
enc_input_ids, enc_attention_mask, dec_input_ids, dec_attention_mask = model_input['enc_input_ids'], model_input['enc_attention_mask'], model_input['dec_input_ids'], model_input['dec_attention_mask']
|
| 273 |
+
|
| 274 |
+
assert enc_input_ids.size() == enc_attention_mask.size()
|
| 275 |
+
|
| 276 |
+
if len(enc_input_ids.size()) == 3: # likely from bergen: we just flatten all of this to perform encoding in one batch
|
| 277 |
+
batch_size, top_k, seq_length = enc_input_ids.size()
|
| 278 |
+
enc_input_ids = enc_input_ids.view(batch_size * top_k, seq_length)
|
| 279 |
+
enc_attention_mask = enc_attention_mask.view(batch_size * top_k, seq_length)
|
| 280 |
+
|
| 281 |
+
# Here, we should have top_k times more elements in enc_input_ids than in dec_input_ids
|
| 282 |
+
assert enc_input_ids.size(0) == dec_input_ids.size(0) * self.generation_top_k, \
|
| 283 |
+
f"{enc_input_ids.size(0)} VS {dec_input_ids.size(0)} with generation_top_k={self.generation_top_k}"
|
| 284 |
+
|
| 285 |
+
compressed_embs = self.compress(enc_input_ids, enc_attention_mask)
|
| 286 |
+
inputs_embeds = self.replace_emb(compressed_embs, dec_input_ids)
|
| 287 |
+
|
| 288 |
+
if 'decoder_adapter' in self.adapter_keys:
|
| 289 |
+
self.decoder.set_adapter('decoder_adapter')
|
| 290 |
+
|
| 291 |
+
output_ids = self.decoder.generate(
|
| 292 |
+
inputs_embeds=inputs_embeds,
|
| 293 |
+
attention_mask=dec_attention_mask,
|
| 294 |
+
generation_config=self.generation_config,
|
| 295 |
+
max_new_tokens=max_new_tokens
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
return self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 299 |
+
|
| 300 |
+
def blend_prompt_and_memory_tokens(self, query: str):
|
| 301 |
+
"""
|
| 302 |
+
Takes care of blending the prompt with the memory tokens:
|
| 303 |
+
Also returns, if a label is provided, the position of the first token index of the label (for loss comp later on)
|
| 304 |
+
"""
|
| 305 |
+
mem_tokens_str = ''.join(self.tokenizer.mem_tokens) + self.tokenizer.sep_token
|
| 306 |
+
|
| 307 |
+
# proper names for "eval" call, don't remove these lines
|
| 308 |
+
docs = mem_tokens_str * self.generation_top_k
|
| 309 |
+
question = query
|
| 310 |
+
|
| 311 |
+
prompt_system = 'You are a helpful assistant. Your task is to extract relevant information from provided documents and to answer to questions as briefly as possible.'
|
| 312 |
+
prompt_user = f"Background:\n{docs}\n\nQuestion:{question}"
|
| 313 |
+
|
| 314 |
+
# Prepare the messages with system and user roles
|
| 315 |
+
messages = [
|
| 316 |
+
{"role": "system", "content": prompt_system},
|
| 317 |
+
{"role": "user", "content": prompt_user.replace(':\ ', ': ')}
|
| 318 |
+
]
|
| 319 |
+
|
| 320 |
+
# Attempt to apply the system role and catch if it's not supported
|
| 321 |
+
try:
|
| 322 |
+
prompt = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 323 |
+
|
| 324 |
+
except TemplateError as e:
|
| 325 |
+
# Catch the error related to system role and handle it (e.g. gemma)
|
| 326 |
+
if "System role not supported" in str(e):
|
| 327 |
+
# Remove system role and proceed with only the user role
|
| 328 |
+
messages = [{"role": "user", "content": messages[0]['content'] + '\n' + messages[1]['content']}]
|
| 329 |
+
# Apply template again without system role
|
| 330 |
+
prompt = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 331 |
+
else:
|
| 332 |
+
# Re-raise the exception if it's unrelated to system role
|
| 333 |
+
raise e
|
| 334 |
+
|
| 335 |
+
return prompt
|