maxoul commited on
Commit
cf4c20c
·
verified ·
1 Parent(s): 9d2fb6e

Upload COCOM

Browse files
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]
adapters.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c3a419bb9f29ee5817df83071ee39d3c0d32f67731cefe6e752c42d4fd14567
3
+ size 80867374
compressor/compressor.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6ab50bf4e150201943126729ce70dbac3f8d93771ada01c2005eef6885c19db
3
+ size 2471719312
compressor/mlp.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9805098fc58e5adc06ff9a0eb6743d9b191ce76fac70eeca33d3901b9a85ac25
3
+ size 91218544
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_attn_implementation_autoset": true,
3
+ "attn_implementation": null,
4
+ "auto_map": {
5
+ "AutoConfig": "modelling_pisco.COCOMConfig",
6
+ "AutoModel": "modelling_pisco.COCOM"
7
+ },
8
+ "compr_base_model_name": null,
9
+ "compr_bidirectional": false,
10
+ "compr_every_n_layer": null,
11
+ "compr_mlp_hidden_dim": 8096,
12
+ "compr_model_name": "meta-llama/Llama-3.2-1B-Instruct",
13
+ "compr_n_layers": null,
14
+ "compr_rate": 16,
15
+ "compr_rms_norm": false,
16
+ "compr_use_mlp": true,
17
+ "decoder_model_name": "Qwen/Qwen2-7B-Instruct",
18
+ "device_map": "auto",
19
+ "different_mem_tokens": true,
20
+ "doc_max_length": 128,
21
+ "generation_top_k": 1,
22
+ "kbtc_training": false,
23
+ "load_adapters": true,
24
+ "lora": true,
25
+ "lora_compressor": false,
26
+ "lora_r": 16,
27
+ "lora_r_compressor": 16,
28
+ "model_type": "COCOM",
29
+ "optimize_mem_tokens": true,
30
+ "quantization": "no",
31
+ "sep": true,
32
+ "training_form": "both_separately",
33
+ "transformers_version": "4.48.0"
34
+ }
decoder_first_last_layers.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:819493121aa58c390992e975881ddfe776f77b282ab48f2296c06493cf3d9217
3
+ size 2174156420
modelling_pisco.py ADDED
@@ -0,0 +1,1110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ import os
3
+ import torch
4
+ import gc
5
+
6
+ from torch import nn
7
+ from jinja2.exceptions import TemplateError
8
+ from peft import LoraConfig
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, PreTrainedModel, PretrainedConfig, AutoModel, AutoConfig
10
+ from huggingface_hub import hf_hub_download, HfApi, hf_hub_url
11
+
12
+
13
+ def get_local_file_path(pretrained_model_name_or_path, filename) -> str:
14
+ """
15
+ loads from the hub if necessary, and returns path of downloaded file
16
+ if local checkpoint, also returns path to local file :)
17
+ """
18
+ try:
19
+ # If loading from Hugging Face Hub
20
+ local_path = hf_hub_download(repo_id=pretrained_model_name_or_path, filename=filename)
21
+ except Exception as e:
22
+ # If loading from a local directory
23
+ local_path = os.path.join(pretrained_model_name_or_path, filename)
24
+
25
+ return local_path
26
+
27
+
28
+ def get_first_layers_model(base_model_name: str, n_layers: int, attn_implementation: str = 'flash_attention_2'):
29
+ """
30
+ Builds a model comprising only the n_layers first layer of the base_model_name
31
+ (it keeps the embedding and head layers)
32
+ """
33
+ full_model = AutoModelForCausalLM.from_pretrained(base_model_name)
34
+
35
+ # Create a new config for a model with fewer layers (e.g., 3 layers)
36
+ custom_config = AutoConfig.from_pretrained(base_model_name)
37
+ custom_config.num_hidden_layers = n_layers
38
+ first_layers_model = AutoModelForCausalLM.from_config(config=custom_config, attn_implementation=attn_implementation, torch_dtype=torch.bfloat16)
39
+
40
+ # Load the state dict of the full model
41
+ full_state_dict = full_model.state_dict()
42
+ custom_state_dict = first_layers_model.state_dict()
43
+ kept_state_dict = {k:v for k,v in full_state_dict.items() if k in custom_state_dict}
44
+
45
+ first_layers_model.load_state_dict(kept_state_dict, strict=True)
46
+
47
+ del full_model
48
+ torch.cuda.empty_cache()
49
+ gc.collect()
50
+
51
+ return first_layers_model
52
+
53
+
54
+ def get_every_n_layer_model(base_model_name: str, every_n_layer: int, attn_implementation: str = 'flash_attention_2'):
55
+ """
56
+ Builds a model comprising 1 every every_n_layer layer of the base_model_name
57
+ (it keeps the embedding and head layers)
58
+ """
59
+ full_model = AutoModelForCausalLM.from_pretrained(base_model_name)
60
+ n_kept_layers = full_model.config.num_hidden_layers // every_n_layer
61
+
62
+ print(f'New model with 1/{every_n_layer} from {base_model_name} will have {n_kept_layers} layers')
63
+
64
+ custom_config = AutoConfig.from_pretrained(base_model_name)
65
+ custom_config.num_hidden_layers = n_kept_layers
66
+ custom_model = AutoModelForCausalLM.from_config(config=custom_config,
67
+ attn_implementation=attn_implementation,
68
+ torch_dtype=torch.bfloat16)
69
+ full_state_dict = full_model.state_dict()
70
+ custom_state_dict = custom_model.state_dict()
71
+
72
+ # Filter out every Nth layer and rename to form a new state dict
73
+ kept_state_dict = {}
74
+ for key, value in full_state_dict.items():
75
+ if ".layers." in key:
76
+ # Extract layer index
77
+ layer_idx = int(key.split(".layers.")[1].split(".")[0])
78
+ # Check if it's an Nth layer
79
+ if layer_idx % every_n_layer == 0:
80
+ # Adjust layer index for the smaller model
81
+ new_layer_idx = layer_idx // every_n_layer
82
+ # print('replacing', f".layers.{layer_idx}.", f".layers.{new_layer_idx}.")
83
+ new_key = key.replace(f".layers.{layer_idx}.", f".layers.{new_layer_idx}.")
84
+ if new_key in custom_state_dict:
85
+ kept_state_dict[new_key] = value
86
+ else:
87
+ # Keep non-layer-specific parameters
88
+ if key in custom_state_dict:
89
+ kept_state_dict[key] = value
90
+
91
+ # Load the filtered state dict into the custom model
92
+ custom_model.load_state_dict(kept_state_dict, strict=True)
93
+
94
+ del full_model
95
+ torch.cuda.empty_cache()
96
+ gc.collect()
97
+
98
+ return custom_model
99
+
100
+
101
+ class MistralTrimmed(torch.nn.Module):
102
+ """
103
+ Trimmed version of base models for faster compression
104
+ NB: the name 'MistralTrimmed' suggests it just works with mistral but NO in fact most LLMs are supported !
105
+ """
106
+ def __init__(self,
107
+ n_layers: int = 15,
108
+ every_n_layer: int = None,
109
+ rms_norm: bool = False,
110
+ base_model_name: str = 'mistralai/Mistral-7B-Instruct-v0.2',
111
+ attn_implementation: str = 'flash_attention_2'):
112
+ """
113
+ you can either specify
114
+ - n_layers to some number: we take the n_layers first layers of the base model.
115
+ - every_n_layer to some number: in that case we take 1/N layer of the base model
116
+ The base_model_name is the name of the model from which this model is built.
117
+ """
118
+ assert (n_layers is None) ^ (every_n_layer is None), 'Cannot specify both n_layers and every_n_layer for MistralTrimmed'
119
+ super().__init__()
120
+
121
+ self.n_layers = n_layers
122
+ self.every_n_layer = every_n_layer
123
+ self.base_model_name = base_model_name
124
+
125
+ if n_layers is not None:
126
+ self.custom_model = get_first_layers_model(self.base_model_name,
127
+ n_layers,
128
+ attn_implementation=attn_implementation)
129
+
130
+ else:
131
+ self.custom_model = get_every_n_layer_model(self.base_model_name,
132
+ every_n_layer,
133
+ attn_implementation=attn_implementation)
134
+
135
+ self.custom_model = self.custom_model.bfloat16()
136
+ self.custom_model.cuda()
137
+
138
+ if rms_norm:
139
+ print('Compressor keeps its original rms norm')
140
+ else:
141
+ print('De-activating RMS norm in compressor')
142
+ # We deactivate the norm: we don't need it here since we want to manipulate stuff within embed space
143
+ # see https://github.com/huggingface/transformers/blob/v4.45.0/src/transformers/models/mistral/modeling_mistral.py#L699
144
+ self.custom_model.model.norm = nn.Identity()
145
+
146
+ # Piping useful methods:
147
+ self.add_adapter = self.custom_model.add_adapter
148
+ self.set_adapter = self.custom_model.set_adapter
149
+ self.load_adapter = self.custom_model.load_adapter
150
+ self.num_parameters = self.custom_model.num_parameters
151
+ self.resize_token_embeddings = self.custom_model.resize_token_embeddings
152
+ self.get_input_embeddings = self.custom_model.get_input_embeddings
153
+ self.get_adapter_state_dict = self.custom_model.get_adapter_state_dict
154
+
155
+ # self.custom_model.gradient_checkpointing_enable()
156
+
157
+ # del self.custom_model.lm_head # THIS FAILS since some models have tie_embeddings=True !
158
+ # gc.collect()
159
+ # torch.cuda.empty_cache()
160
+
161
+ def forward(self, input_ids, attention_mask=None):
162
+ return self.custom_model.model(input_ids, attention_mask, output_hidden_states=True) # we call the .model attribute of the causal LM to avoid the cost of the LM head ! nice huh ?
163
+
164
+ def __call__(self, input_ids, attention_mask=None, output_hidden_states=True):
165
+ return self.forward(input_ids, attention_mask)
166
+
167
+
168
+ class AbstractCompressor(nn.Module):
169
+ def __init__(self, compr_model_name: str, compr_rate: int, decoder_hidden_size: int):
170
+ super().__init__()
171
+ self.compr_model_name = compr_model_name
172
+ self.compr_rate = compr_rate
173
+ self.decoder_hidden_size = decoder_hidden_size
174
+
175
+ def forward(self, input_ids, attention_mask, generation_top_k):
176
+ """
177
+ input_ids of shape (batch_size, top_k, seq_length)
178
+ attention_mask of shape (batch_size, top_k, seq_length)
179
+ generation_top_k: the number of docs
180
+ """
181
+ raise NotImplementedError
182
+
183
+ def save_pretrained(self, save_directory):
184
+ raise NotImplementedError
185
+
186
+ def load_pretrained(self, load_directory):
187
+ raise NotImplementedError
188
+
189
+
190
+ class BertCompressor(AbstractCompressor):
191
+ def __init__(self,
192
+ compr_model_name: str,
193
+ compr_rate: int,
194
+ decoder_hidden_size: int,
195
+ mlp_hidden_dim: int = 8192,
196
+ use_mlp: bool = True,
197
+ doc_max_length : int = 128,
198
+ **kwargs):
199
+ # TODO use the device_map
200
+ super().__init__(compr_model_name=compr_model_name, compr_rate=compr_rate, decoder_hidden_size=decoder_hidden_size)
201
+ if compr_model_name == 'mistral_trimmed':
202
+ assert 'compr_n_layers' in kwargs
203
+ self.model = MistralTrimmed(n_layers=kwargs['compr_n_layers'],
204
+ every_n_layer=kwargs['compr_every_n_layer'],
205
+ rms_norm=kwargs['compr_rms_norm'],
206
+ base_model_name=kwargs['compr_base_model_name'],
207
+ attn_implementation=kwargs['attn_implementation'])
208
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model.base_model_name)
209
+ self.hidden_size = self.model.custom_model.config.hidden_size
210
+ else:
211
+ self.model = AutoModel.from_pretrained(compr_model_name, torch_dtype=torch.bfloat16, device_map='auto')
212
+ self.tokenizer = AutoTokenizer.from_pretrained(compr_model_name, use_fast=True)
213
+ self.tokenizer.padding_side = "left"
214
+ self.hidden_size = self.model.config.hidden_size
215
+
216
+ print('Base compressor nb parameters', self.model.num_parameters())
217
+
218
+ self.mlp_hidden_dim = mlp_hidden_dim
219
+ self.use_mlp = use_mlp
220
+ self.doc_max_length = doc_max_length
221
+
222
+ if self.use_mlp:
223
+ self.mlp = nn.Sequential(
224
+ nn.Linear(self.hidden_size, self.mlp_hidden_dim),
225
+ nn.ReLU(),
226
+ nn.Linear(self.mlp_hidden_dim, decoder_hidden_size)
227
+ ).bfloat16()
228
+ self.mlp.cuda()
229
+
230
+ self.n_emb = self.doc_max_length // self.compr_rate
231
+
232
+ mem_tokens = ['<MEM' + str(i) + '>' for i in range(self.n_emb)]
233
+ self.tokenizer.add_special_tokens({'additional_special_tokens': mem_tokens})
234
+ self.tokenizer.mem_tokens = mem_tokens
235
+ self.tokenizer.mem_token_ids = [self.tokenizer.convert_tokens_to_ids(elt) for elt in self.tokenizer.mem_tokens]
236
+ self.tokenizer.mem_token_ids_pt = torch.LongTensor(self.tokenizer.mem_token_ids)
237
+ self.model.resize_token_embeddings(len(self.tokenizer))
238
+
239
+ if self.tokenizer.pad_token_id is None:
240
+ self.tokenizer.pad_token_id = self.tokenizer.bos_token_id
241
+
242
+ if not use_mlp:
243
+ assert decoder_hidden_size == self.hidden_size, f'Mlp mandatory is hidden sizes not equal: {decoder_hidden_size} vs {self.hidden_size}'
244
+
245
+ self.lora = False
246
+ self.lora_name = 'compr_adapter'
247
+
248
+ def prepare_mem_tokens_optimization(self):
249
+ assert self.lora, 'should only be called with lora.'
250
+ self.model.get_input_embeddings().weight.requires_grad = True
251
+ # Applying a hook zero-ing the gradients except for the mem token:
252
+ def hook(grad):
253
+ mask = torch.zeros_like(grad)
254
+ mask[self.tokenizer.mem_token_ids] = 1.0
255
+ return grad * mask
256
+ self.model.get_input_embeddings().weight.register_hook(hook)
257
+
258
+ def set_lora(self, peft_config):
259
+ self.model.add_adapter(peft_config, self.lora_name)
260
+ self.model.set_adapter(self.lora_name)
261
+ self.lora = True
262
+ self.prepare_mem_tokens_optimization()
263
+
264
+ def forward(self, input_ids, attention_mask):
265
+ assert input_ids.size() == attention_mask.size()
266
+ assert len(input_ids.size()) == 2
267
+
268
+ batch_size_times_top_k = input_ids.size(0)
269
+
270
+ last_hidden_states = self.model(input_ids=input_ids,
271
+ attention_mask=attention_mask,
272
+ output_hidden_states=True).hidden_states[-1]
273
+
274
+ # Getting the hidden states at the mem token positions, as for regular cocom:
275
+ mask = torch.isin(input_ids, self.tokenizer.mem_token_ids_pt.to(input_ids.device))
276
+ selected_n_tokens = last_hidden_states[mask].reshape(last_hidden_states.size(0), -1, last_hidden_states.size(-1))
277
+
278
+ assert selected_n_tokens.size() == (batch_size_times_top_k, self.n_emb, self.hidden_size), f"{selected_n_tokens.size()} vs {(batch_size_times_top_k, self.n_emb, self.hidden_size)}"
279
+
280
+ if self.use_mlp:
281
+ selected_n_tokens = self.mlp(selected_n_tokens) # now of shape (batch_size, top_k, decoder_hidden_size)
282
+
283
+ assert selected_n_tokens.size() == (batch_size_times_top_k, self.n_emb, self.decoder_hidden_size), f"{selected_n_tokens.size()} vs {(batch_size_times_top_k, self.n_emb, self.decoder_hidden_size)}"
284
+
285
+ return selected_n_tokens
286
+
287
+ def get_lora_path_from_directory(self, directory):
288
+ return os.path.join(directory, 'compressor_adapters.pth')
289
+
290
+ def get_compressor_path_from_directory(self, directory):
291
+ return os.path.join(directory, 'compressor.pth')
292
+
293
+ def get_mlp_path_from_directory(self, directory):
294
+ return os.path.join(directory, 'mlp.pth')
295
+
296
+ def get_first_layer_path_from_directory(self, directory):
297
+ return os.path.join(directory, 'first_layer.pth')
298
+
299
+ def get_first_layer_state_dict(self) -> dict:
300
+ out = {}
301
+ for k, v in self.model.named_parameters():
302
+ if 'embed_tokens.weight' in k:
303
+ out[k] = v.cpu()
304
+
305
+ assert len(out) == 1, len(out) # We should get exactly one layer here
306
+ return out
307
+
308
+ def save_pretrained(self, save_directory):
309
+ """
310
+ Here we just save mlp state_dict and model state_dict
311
+ Config is handled in cocom model.
312
+ """
313
+ if not os.path.exists(save_directory):
314
+ os.makedirs(save_directory)
315
+
316
+ # Save MLP weights
317
+ if self.use_mlp:
318
+ mlp_path = self.get_mlp_path_from_directory(directory=save_directory)
319
+ torch.save(self.mlp.state_dict(), mlp_path)
320
+
321
+ # Saving the model
322
+ if not self.lora: # full training: save the full dict:
323
+ model_path = self.get_compressor_path_from_directory(directory=save_directory)
324
+ torch.save(self.model.state_dict(), model_path)
325
+ else: # lora training of the compressor
326
+ # We save the first layer:
327
+ first_layer_state_dict = self.get_first_layer_state_dict()
328
+ torch.save(first_layer_state_dict, self.get_first_layer_path_from_directory(directory=save_directory))
329
+
330
+ # We save the adapters:
331
+ adapter_state_dict = {k: v.cpu() for k, v in self.model.get_adapter_state_dict(self.lora_name).items()}
332
+ torch.save(adapter_state_dict, self.get_lora_path_from_directory(directory=save_directory))
333
+
334
+ def load_adapter(self, load_directory, peft_config):
335
+ assert peft_config is not None
336
+ map_location = torch.device("cpu") if not torch.cuda.is_available else None
337
+ adapter_state_dict = torch.load(self.get_lora_path_from_directory(directory=load_directory), map_location=map_location, weights_only=True)
338
+ print('loading compr adapter onto compressor model from', self.get_lora_path_from_directory(directory=load_directory))
339
+ self.model.load_adapter(peft_config=peft_config, adapter_name=self.lora_name, adapter_state_dict=adapter_state_dict)
340
+ self.lora = True
341
+ self.prepare_mem_tokens_optimization()
342
+
343
+ def load_first_layer(self, load_directory):
344
+ map_location = torch.device("cpu") if not torch.cuda.is_available else None
345
+ first_layer_state_dict = torch.load(self.get_first_layer_path_from_directory(load_directory), map_location=map_location, weights_only=True)
346
+ assert len(first_layer_state_dict.keys()) == 1
347
+ self.model.load_state_dict(first_layer_state_dict, strict=False)
348
+
349
+ def load_pretrained(self, load_directory, lora: bool = False, peft_config=None):
350
+ """
351
+ Loading the state dicts.
352
+ :lora: if True then the compressor was trained using lora: we just need to load the adapters
353
+ if False, the compressor was fully trained: we load it fully.
354
+ """
355
+ if self.use_mlp:
356
+ mlp_path = self.get_mlp_path_from_directory(directory=load_directory)
357
+ self.mlp.load_state_dict(torch.load(mlp_path, weights_only=True))
358
+
359
+ if lora:
360
+ self.load_first_layer(load_directory)
361
+ self.load_adapter(load_directory, peft_config)
362
+
363
+ else:
364
+ model_path = self.get_compressor_path_from_directory(directory=load_directory)
365
+ self.model.load_state_dict(torch.load(model_path, weights_only=True))
366
+
367
+ def prepare_inputs(self, texts, max_length, q_texts=None):
368
+ if q_texts is not None: # Query-dependent here:
369
+ assert len(texts) == len(q_texts), f"{len(texts)} == {len(q_texts)}"
370
+ if self.compr_model_name == 'mistral_trimmed':
371
+ # No special token, just formulating:
372
+ texts_to_encode = [ '\nQuery:\n' + query + 'Document:\n' + text for text, query in zip(texts, q_texts)]
373
+ inp_enc = self.tokenizer(texts_to_encode,
374
+ return_tensors='pt',
375
+ padding='max_length',
376
+ max_length=max_length + 8, # some margin for query/doc stuff + bos / eos
377
+ truncation=True,
378
+ add_special_tokens=True)
379
+ else:
380
+ inp_enc = self.tokenizer(q_texts, # we put the query in first position
381
+ texts,
382
+ return_tensors='pt',
383
+ padding='max_length',
384
+ max_length=max_length + 3,
385
+ truncation='only_second',
386
+ add_special_tokens=True)
387
+ else:
388
+ inp_enc = self.tokenizer(texts, return_tensors='pt', padding='max_length', max_length=max_length + 2, truncation=True, add_special_tokens=True)
389
+
390
+ inp_enc['input_ids'], inp_enc['attention_mask'] = add_memory_tokens_to_inputs(inp_enc['input_ids'],
391
+ inp_enc['attention_mask'],
392
+ self.n_emb,
393
+ tokenizer=self.tokenizer)
394
+
395
+ return inp_enc
396
+
397
+
398
+ def add_memory_tokens_to_inputs(input_ids: torch.Tensor, attention_mask: torch.Tensor, n_mem_tokens: int, tokenizer):
399
+ """
400
+ Concatenate the input ids with n_mem_tokens mem_tokens and update the corresponding attention mask
401
+ """
402
+ assert len(tokenizer.mem_tokens) == n_mem_tokens, f"{len(tokenizer.mem_tokens)} VS {n_mem_tokens}"
403
+ mem_tokens = torch.stack([tokenizer.mem_token_ids_pt] * input_ids.size(0), 0)
404
+ assert len(mem_tokens.size()) == 2
405
+ assert len(mem_tokens) == input_ids.size(0)
406
+ assert len(mem_tokens[0]) == n_mem_tokens
407
+ #mem_tokens = torch.full((input_ids.size(0), n_mem_tokens), tokenizer.mem_token_id, dtype=torch.long)
408
+ input_ids = torch.cat([input_ids, mem_tokens], dim=1)
409
+ attention_mask = torch.cat([attention_mask, torch.ones(input_ids.size(0), n_mem_tokens)], dim=1)
410
+ return input_ids, attention_mask
411
+
412
+
413
+ class COCOMConfig(PretrainedConfig):
414
+
415
+ model_type = "COCOM"
416
+ def __init__(self,
417
+ decoder_model_name: str = "meta-llama/Llama-2-7b-chat-hf",
418
+ doc_max_length: int = 128,
419
+ quantization: str = 'no',
420
+ sep: bool = False,
421
+ compr_model_name: str = "google-bert/bert-base-uncased",
422
+ compr_rate: int = 64,
423
+ compr_n_layers: int = None, # only for surgical mistral compressor
424
+ compr_every_n_layer: int = None,
425
+ compr_base_model_name: str = 'mistralai/Mistral-7B-Instruct-v0.2',
426
+ compr_rms_norm: bool = False, # only for surgical mistral compressor: if true, rms norm applied on h-s
427
+ compr_mlp_hidden_dim: int = 8096,
428
+ compr_use_mlp: bool = True,
429
+ lora: bool = False, # lora on decoder (and decoder as compr)
430
+ lora_compressor: bool = False, # lora only on the compressor if it exists
431
+ training_form: str = "both",
432
+ lora_r: int = 16,
433
+ lora_r_compressor: int = None,
434
+ load_adapters: bool = True,
435
+ kbtc_training: bool = False,
436
+ optimize_mem_tokens: bool = False,
437
+ different_mem_tokens: bool = False,
438
+ attn_implementation: str = 'flash_attention_2',
439
+ device_map = None,
440
+ **kwargs):
441
+ super().__init__(**kwargs)
442
+
443
+ self.decoder_model_name = decoder_model_name # model name of decoder
444
+ self.doc_max_length = doc_max_length # the maximum length of document that can be used by this model (it is used to compute number of mem tokens !)
445
+ self.quantization = quantization # quantization, could be no, int4, int8
446
+ self.sep = sep # boolean type, whether to use sep token
447
+
448
+ self.compr_model_name = compr_model_name # model name of compressor
449
+ self.compr_rate = compr_rate # compression rate
450
+ self.compr_use_mlp = compr_use_mlp
451
+ self.compr_mlp_hidden_dim = compr_mlp_hidden_dim
452
+ self.compr_n_layers = compr_n_layers
453
+ self.compr_every_n_layer = compr_every_n_layer
454
+ self.compr_base_model_name = compr_base_model_name
455
+ self.compr_rms_norm = compr_rms_norm
456
+
457
+ self.lora = lora # boolean type, whether to use lora trsining
458
+ self.lora_compressor = lora_compressor
459
+ self.training_form = training_form # training form, could be compressor: training only comprssor; both: training both
460
+ # Or both_separately: training both with separate adapters
461
+ self.lora_r = lora_r # lora_r for lora training, we use 16 throughout the experiment.
462
+ self.lora_r_compressor = lora_r_compressor or lora_r # defaulting to same lora as decoder.
463
+ self.load_adapters = load_adapters # used to load pretrained model: we first load without adapters, and then load them from file.
464
+ self.optimize_mem_tokens = optimize_mem_tokens
465
+ self.different_mem_tokens = different_mem_tokens
466
+
467
+ self.kbtc_training = kbtc_training
468
+
469
+ self.device_map = device_map
470
+
471
+ self.attn_implementation = attn_implementation
472
+
473
+ if training_form == 'compressor':
474
+ assert compr_model_name is not None and not self.lora
475
+
476
+
477
+ class COCOM(PreTrainedModel):
478
+ config_class = COCOMConfig
479
+ def __init__(self, cfg):
480
+ super().__init__(cfg)
481
+ self.decoder_model_name = cfg.decoder_model_name
482
+ self.decoder = self.create_decoder(cfg)
483
+
484
+ self.doc_max_length = cfg.doc_max_length
485
+
486
+ print('Base decoder nb parameters', self.decoder.num_parameters())
487
+
488
+ self.compr_model_name = cfg.compr_model_name
489
+ self.training_form = cfg.training_form
490
+ self.lora = cfg.lora
491
+ self.adapter_keys = []
492
+
493
+ self.compr = None
494
+ # when compr_model_name is not set, then means using a decoder-based compressor, otherwise a bert based compressor
495
+ if cfg.compr_model_name is not None:
496
+ # case bert based compressor
497
+ print('Instantiating compressor ', cfg.compr_model_name)
498
+ self.compr = BertCompressor(cfg.compr_model_name,
499
+ cfg.compr_rate,
500
+ doc_max_length=self.doc_max_length,
501
+ decoder_hidden_size=self.decoder.config.hidden_size,
502
+ mlp_hidden_dim=cfg.compr_mlp_hidden_dim,
503
+ compr_n_layers=cfg.compr_n_layers,
504
+ compr_every_n_layer=cfg.compr_every_n_layer,
505
+ compr_base_model_name=cfg.compr_base_model_name,
506
+ compr_rms_norm=cfg.compr_rms_norm,
507
+ use_mlp=cfg.compr_use_mlp,
508
+ attn_implementation=cfg.attn_implementation)
509
+
510
+ # set lora adaptors on decoder model
511
+ if cfg.lora:
512
+ peft_config = self.get_peft_config(lora_r=cfg.lora_r)
513
+
514
+ if cfg.load_adapters:
515
+ self.decoder.add_adapter(peft_config, 'decoder_adapter')
516
+ self.decoder.set_adapter('decoder_adapter') # active adapter by default
517
+ self.adapter_keys.append('decoder_adapter')
518
+
519
+ # Create separate adapters (if not BERT compressor and training_form == 'both_separately')
520
+ if self.training_form == 'both_separately' and self.compr is None:
521
+ if cfg.load_adapters:
522
+ self.decoder.add_adapter(peft_config, 'encoder_adapter')
523
+ self.adapter_keys.append('encoder_adapter')
524
+
525
+ # set lora adapters on compressor model:
526
+ if cfg.lora_compressor and self.compr is not None and cfg.load_adapters:
527
+ peft_config = self.get_peft_config(lora_r=cfg.lora_r_compressor)
528
+ self.compr.set_lora(peft_config)
529
+
530
+ self.decoder_tokenizer = COCOM.create_decoder_tokenizer(cfg)
531
+
532
+ # resize the tokenizer embedding
533
+ self.decoder.resize_token_embeddings(len(self.decoder_tokenizer))
534
+ self.decoder.generation_config.top_p = None
535
+ self.decoder.generation_config.temperature = None
536
+ self.decoder.generation_config.pad_token_id = self.decoder_tokenizer.pad_token_id
537
+
538
+ # self.decoder.gradient_checkpointing_enable()
539
+ # if self.compr is not None:
540
+ # self.compr.gradient_checkpointing_enable()
541
+
542
+ # other settings
543
+ self.generation_top_k = 1
544
+ self.sep = cfg.sep
545
+ self.compr_rate = cfg.compr_rate
546
+ self.local_rank = os.getenv('LOCAL_RANK', '0')
547
+
548
+ self.n_mem_tokens = self.doc_max_length // self.compr_rate # crucial!
549
+
550
+
551
+ if self.lora:
552
+ for adapter_key in self.adapter_keys:
553
+ self.decoder.set_adapter(adapter_key)
554
+ print(f'Adapter {adapter_key} trainable parameters: {self.num_parameters(only_trainable=True)}')
555
+
556
+ # We need to activate all adapters so that they are both trained...
557
+ self.set_all_adapters()
558
+ else:
559
+ print(f'Total trainable parameters: {self.num_parameters(only_trainable=True)}')
560
+
561
+ if self.compr is not None:
562
+ print(f'Compressor number of parameters: {self.compr.model.num_parameters(only_trainable=True)}')
563
+
564
+ self.prepare_mem_tokens_optimization()
565
+
566
+ def prepare_mem_tokens_optimization(self):
567
+ if self.config.optimize_mem_tokens:
568
+ if self.compr is None:
569
+ # Enforcing gradients for input embeddings (even if lora)
570
+ self.decoder.get_input_embeddings().weight.requires_grad = True
571
+ # Applying a hook zero-ing the gradients except for the mem token:
572
+ def hook(grad):
573
+ mask = torch.zeros_like(grad)
574
+ mask[self.decoder_tokenizer.mem_token_ids] = 1.0
575
+ return grad * mask
576
+ self.decoder.get_input_embeddings().weight.register_hook(hook)
577
+
578
+ def set_all_adapters(self):
579
+ if len(self.adapter_keys) > 0:
580
+ self.decoder.set_adapter(self.adapter_keys)
581
+
582
+ @staticmethod
583
+ def create_decoder_tokenizer(cfg: COCOMConfig):
584
+ decoder_tokenizer = AutoTokenizer.from_pretrained(cfg.decoder_model_name, use_fast=True, padding_side='left')
585
+
586
+ # define special tokens
587
+ n_mem_tokens = cfg.doc_max_length // cfg.compr_rate
588
+ if cfg.different_mem_tokens:
589
+ # estimation fo the number of memory tokens needed:
590
+ mem_tokens = ['<MEM' + str(i) + '>' for i in range(n_mem_tokens)]
591
+ decoder_tokenizer.add_special_tokens({'additional_special_tokens': mem_tokens + ['<AE>', '<ENC>', '<SEP>']})
592
+ decoder_tokenizer.mem_tokens = mem_tokens
593
+ else:
594
+ decoder_tokenizer.add_special_tokens({'additional_special_tokens': ['<MEM>', '<AE>', '<ENC>', '<SEP>']})
595
+ decoder_tokenizer.mem_tokens = ['<MEM>'] * n_mem_tokens
596
+
597
+ decoder_tokenizer.mem_token_ids = [decoder_tokenizer.convert_tokens_to_ids(elt) for elt in decoder_tokenizer.mem_tokens]
598
+ decoder_tokenizer.mem_token_ids_pt = torch.LongTensor(decoder_tokenizer.mem_token_ids) # required later on for operations on tensors
599
+
600
+ decoder_tokenizer.ae_token = '<AE>' # token for autoencoding on decoder side
601
+ decoder_tokenizer.ae_token_id = decoder_tokenizer.convert_tokens_to_ids('<AE>')
602
+ decoder_tokenizer.enc_token = '<ENC>' # token for autoencoding on compressor side
603
+ decoder_tokenizer.sep_token = '<SEP>' # sep token between document
604
+ decoder_tokenizer.sep_token_id = decoder_tokenizer.convert_tokens_to_ids('<SEP>')
605
+
606
+ # If kbtc training, we add another one yet
607
+ if cfg.kbtc_training:
608
+ decoder_tokenizer.add_special_tokens({'additional_special_tokens': ['<KBTC>']})
609
+ decoder_tokenizer.kbtc_token = '<KBTC>'
610
+ decoder_tokenizer.kbtc_token_id = decoder_tokenizer.convert_tokens_to_ids('<KBTC>')
611
+
612
+ # if pad token exists then use pad token, othrwise bos token
613
+ if decoder_tokenizer.pad_token_id is None:
614
+ decoder_tokenizer.pad_token_id = decoder_tokenizer.bos_token_id
615
+
616
+ return decoder_tokenizer
617
+
618
+ def get_peft_config(self, lora_r: int) -> LoraConfig:
619
+ """
620
+ Builds the peft config
621
+ """
622
+ return LoraConfig(task_type="CAUSAL_LM", r=lora_r, lora_alpha=2*lora_r, target_modules='all-linear', lora_dropout=0.1)
623
+
624
+ def create_decoder(self, cfg):
625
+ """
626
+ Loads the base decoder.
627
+ """
628
+ if torch.cuda.is_available():
629
+ if cfg.quantization == "no":
630
+ return AutoModelForCausalLM.from_pretrained(
631
+ cfg.decoder_model_name,
632
+ torch_dtype=torch.bfloat16,
633
+ attn_implementation=self.config.attn_implementation,
634
+ # low_cpu_mem_usage = True,
635
+ device_map=cfg.device_map
636
+ )
637
+ elif cfg.quantization == "int4":
638
+ quant_config = BitsAndBytesConfig(
639
+ load_in_4bit=True,
640
+ bnb_4bit_quant_type='nf4',
641
+ bnb_4bit_compute_dtype='bfloat16',
642
+ # low_cpu_mem_usage = True,
643
+ )
644
+ return AutoModelForCausalLM.from_pretrained(
645
+ cfg.decoder_model_name,
646
+ quantization_config=quant_config,
647
+ attn_implementation=self.config.attn_implementation,
648
+ torch_dtype=torch.bfloat16,
649
+ resume_download=True,
650
+ # low_cpu_mem_usage = True,
651
+ trust_remote_code=True,
652
+ device_map=cfg.device_map
653
+ )
654
+ elif cfg.quantization == "int8":
655
+ quant_config = BitsAndBytesConfig(
656
+ load_in_8bit=True,
657
+ llm_int8_enable_fp32_cpu_offload=True,
658
+ bnb_4bit_compute_dtype='bfloat16',
659
+ # low_cpu_mem_usage = True,
660
+ )
661
+ return AutoModelForCausalLM.from_pretrained(
662
+ cfg.decoder_model_name,
663
+ quantization_config=quant_config,
664
+ attn_implementation=self.config.attn_implementation,
665
+ torch_dtype=torch.bfloat16,
666
+ resume_download=True,
667
+ # low_cpu_mem_usage = True,
668
+ trust_remote_code=True,
669
+ device_map=cfg.device_map
670
+ )
671
+ else:
672
+ raise NotImplementedError()
673
+ else:
674
+ return AutoModelForCausalLM.from_pretrained(
675
+ cfg.decoder_model_name,
676
+ torch_dtype=torch.bfloat16,
677
+ resume_download=True,
678
+ # low_cpu_mem_usage = True,
679
+ trust_remote_code=True,
680
+ device_map=cfg.device_map
681
+ )
682
+
683
+ def compress(self, enc_input_ids, enc_attention_mask):
684
+ if self.compr:
685
+ return self.compr(enc_input_ids, enc_attention_mask)
686
+ else:
687
+ return self.compr_decoder(enc_input_ids, enc_attention_mask)
688
+
689
+ def replace_emb(self, compressed_embs, dec_input_ids):
690
+ """
691
+ Compression logic (either with decoder or with dedicated compressor)
692
+ """
693
+ indices = range(0, compressed_embs.size(0) + 1, self.generation_top_k)
694
+ input_embeds = self.replace_embeddings(compressed_embs, dec_input_ids, indices)
695
+ return input_embeds
696
+
697
+ def compr_decoder(self, input_ids, attention_mask):
698
+ """
699
+ Compression using the decoder
700
+ """
701
+ assert input_ids.size() == attention_mask.size(), f"{input_ids.size()} vs {attention_mask.size()}"
702
+
703
+ # Switch adapter if we are training two different ones:
704
+ if 'encoder_adapter' in self.adapter_keys:
705
+ self.decoder.set_adapter('encoder_adapter')
706
+
707
+ emb = self.decoder(input_ids=input_ids,
708
+ attention_mask=attention_mask,
709
+ output_hidden_states=True).hidden_states[-1]
710
+ mask = torch.isin(input_ids, self.decoder_tokenizer.mem_token_ids_pt.to(input_ids.device))
711
+ return emb[mask].reshape(emb.size(0), -1, emb.size(-1))
712
+
713
+ def prepare_encoder_inputs_to_decoder(self, texts, max_length, q_texts=None):
714
+ if q_texts is not None:
715
+ texts_to_encode = [self.decoder_tokenizer.enc_token + self.decoder_tokenizer.bos_token + '\nQuery:\n' + query + 'Document:\n' + text + self.decoder_tokenizer.eos_token
716
+ for text, query in zip(texts, q_texts)]
717
+ inp_enc = self.decoder_tokenizer(texts_to_encode, return_tensors='pt', padding='max_length', max_length=max_length + 8, truncation=True, add_special_tokens=False)
718
+ else:
719
+ inp_enc = [self.decoder_tokenizer.enc_token + self.decoder_tokenizer.bos_token + text + self.decoder_tokenizer.eos_token for text in texts]
720
+ inp_enc = self.decoder_tokenizer(inp_enc, return_tensors='pt', padding="max_length", max_length=max_length+3, truncation=True, add_special_tokens=False)
721
+
722
+ num_mem_tokens = self.doc_max_length // self.compr_rate
723
+ assert num_mem_tokens == len(self.decoder_tokenizer.mem_tokens)
724
+ inp_enc['input_ids'], inp_enc['attention_mask'] = add_memory_tokens_to_inputs(inp_enc['input_ids'],
725
+ inp_enc['attention_mask'],
726
+ num_mem_tokens,
727
+ tokenizer=self.decoder_tokenizer)
728
+
729
+ return inp_enc
730
+
731
+ def prepare_encoder_inputs(self, texts: list[str], max_length: int, q_texts: list[str] = None):
732
+ """
733
+ Create the inputs to the encoder, for compression.
734
+ """
735
+ if q_texts is not None:
736
+ assert len(texts) == len(q_texts), f"{len(texts)} == {len(q_texts)}"
737
+
738
+ # Case where the encoder is the decoder with adapter:
739
+ if self.compr is None:
740
+ return self.prepare_encoder_inputs_to_decoder(texts, max_length, q_texts)
741
+
742
+ # Case where the encoder is a separate network:
743
+ else:
744
+ return self.compr.prepare_inputs(texts, max_length, q_texts)
745
+
746
+ def replace_embeddings(self, compressed_embs, dec_input_ids, indices):
747
+ """
748
+ Replace memory tokens in the decoder input to with the compressed embeddings
749
+ """
750
+ inputs_embeds = self.decoder.get_input_embeddings()(dec_input_ids)
751
+ num_embs = compressed_embs.size(1)
752
+ if self.sep:
753
+ slot_len = num_embs + 1
754
+ else:
755
+ slot_len = num_embs
756
+ # get first mem_token indices
757
+ first_mem_token_indices = torch.argmax((dec_input_ids == self.decoder_tokenizer.mem_token_ids[0]).int(), dim=1)
758
+ batch_size = inputs_embeds.size(0)
759
+ # for each example in batch, replace them with compressed embeddings
760
+ for i in range(batch_size):
761
+ for j in range(indices[i], indices[i + 1]):
762
+ start_idx = first_mem_token_indices[i].item() + (j-indices[i]) * slot_len
763
+ assert inputs_embeds[i, start_idx:start_idx + num_embs, :].size() == compressed_embs[j].size(), \
764
+ f"{inputs_embeds[i, start_idx:start_idx + num_embs, :].size()} VS {compressed_embs[j].size()}"
765
+ inputs_embeds[i, start_idx:start_idx + num_embs, :] = compressed_embs[j]
766
+ return inputs_embeds
767
+
768
+ def forward(self,
769
+ enc_input_ids: torch.LongTensor = None,
770
+ enc_attention_mask: torch.LongTensor = None,
771
+ dec_input_ids: torch.LongTensor = None,
772
+ dec_attention_mask: torch.LongTensor = None,
773
+ labels: torch.LongTensor = None):
774
+ """
775
+ enc_input_ids: stores the contexts, should be flattened from all queries before input, can be of shape:
776
+ - (batch_size*generation_top_k, enc_token_length)
777
+ - (batch_size, generation_top_k, enc_token_length)
778
+ enc_attention_mask: attention mask of enc_input_ids, same shape as enc_input_ids
779
+ dec_input_ids: stores the prompts (including mem tokens), dimention (batch_size, dec_token_length)
780
+ dec_attention_mask: attention mask of dec_input_ids
781
+ """
782
+ assert enc_input_ids.size() == enc_attention_mask.size(), f"{enc_input_ids.size()} vs {enc_attention_mask.size()}"
783
+
784
+ if len(enc_input_ids.size()) == 3: # likely from bergen: we just flatten all of this to perform encoding in one batch
785
+ batch_size, top_k, seq_length = enc_input_ids.size()
786
+ enc_input_ids = enc_input_ids.view(batch_size * top_k, seq_length)
787
+ enc_attention_mask = enc_attention_mask.view(batch_size * top_k, seq_length)
788
+
789
+ # Here, we should have top_k times more elements in enc_input_ids than in dec_input_ids
790
+ assert enc_input_ids.size(0) == dec_input_ids.size(0) * self.generation_top_k, \
791
+ f"{enc_input_ids.size(0)} VS {dec_input_ids.size(0)} with generation_top_k={self.generation_top_k}"
792
+
793
+ # Perform compression with gradient tracking
794
+ compressed_embs = self.compress(enc_input_ids, enc_attention_mask)
795
+ inputs_embeds = self.replace_emb(compressed_embs, dec_input_ids)
796
+
797
+ # if training_form is compressor, then detach the inputs_embeds, to make gradient not count in decoder
798
+ if (self.training_form == "compressor") and (self.compr is None):
799
+ inputs_embeds = inputs_embeds.detach()
800
+
801
+ # decoding
802
+ if 'decoder_adapter' in self.adapter_keys:
803
+ self.decoder.set_adapter('decoder_adapter')
804
+
805
+ decoder_outputs = self.decoder(inputs_embeds=inputs_embeds, attention_mask=dec_attention_mask, labels=labels)
806
+
807
+ # At end of forward, we need to activate all adapters so that they are both trained...
808
+ self.set_all_adapters()
809
+
810
+ return {"loss": decoder_outputs.loss, "logits": decoder_outputs.logits}
811
+
812
+ def generate(self, model_input, max_new_tokens=128, return_doc_embeddings: bool = False):
813
+
814
+ 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']
815
+
816
+ assert enc_input_ids.size() == enc_attention_mask.size()
817
+
818
+ if len(enc_input_ids.size()) == 3: # likely from bergen: we just flatten all of this to perform encoding in one batch
819
+ batch_size, top_k, seq_length = enc_input_ids.size()
820
+ enc_input_ids = enc_input_ids.view(batch_size * top_k, seq_length)
821
+ enc_attention_mask = enc_attention_mask.view(batch_size * top_k, seq_length)
822
+
823
+ # Here, we should have top_k times more elements in enc_input_ids than in dec_input_ids
824
+ assert enc_input_ids.size(0) == dec_input_ids.size(0) * self.generation_top_k, \
825
+ f"{enc_input_ids.size(0)} VS {dec_input_ids.size(0)} with generation_top_k={self.generation_top_k}"
826
+
827
+ compressed_embs = self.compress(enc_input_ids.to('cuda'), enc_attention_mask.to('cuda'))
828
+ inputs_embeds = self.replace_emb(compressed_embs, dec_input_ids.to('cuda'))
829
+
830
+ # Switch adapter if we are training two different ones:
831
+ if 'decoder_adapter' in self.adapter_keys:
832
+ self.decoder.set_adapter('decoder_adapter')
833
+
834
+ output_ids = self.decoder.generate(
835
+ inputs_embeds=inputs_embeds.to("cuda"),
836
+ attention_mask=dec_attention_mask.to("cuda"),
837
+ do_sample=False,
838
+ top_p=None,
839
+ max_new_tokens=max_new_tokens
840
+ )
841
+
842
+ decoded = self.decoder_tokenizer.batch_decode(output_ids, skip_special_tokens=True)
843
+
844
+ if return_doc_embeddings:
845
+ # Compressed_embds is of shape (batch_size*top_k, n_mem_tokens, hidden_dim)
846
+ # We reshape to batch_size, top_k, n_mem_tokens, hidden_dim
847
+ assert batch_size is not None
848
+ assert top_k is not None
849
+ compressed_embs = compressed_embs.view(batch_size, top_k, compressed_embs.size(1), compressed_embs.size(2))
850
+ return decoded, compressed_embs
851
+ else:
852
+ return decoded
853
+
854
+ def get_all_adapters_state_dict(self):
855
+ """
856
+ Return the state dicts of the adapters
857
+ Used for saving so we go to cpu automatically
858
+ """
859
+ return {key: {k:v.cpu() for k, v in self.decoder.get_adapter_state_dict(key).items()} for key in self.adapter_keys}
860
+
861
+ def load_adapter_from_state_dict(self, peft_config: LoraConfig, adapter_name: str, adapter_state_dict: dict) -> None:
862
+ """
863
+ Creates an adapter from the state dict (used to load from pretrained)
864
+ """
865
+ # assert adapter_name not in self.adapter_keys, f'Adapter {adapter_name} already exists'
866
+ print(f'loading adapter {adapter_name}')
867
+ self.decoder.load_adapter(peft_config=peft_config, adapter_name=adapter_name, adapter_state_dict=adapter_state_dict)
868
+ self.adapter_keys.append(adapter_name)
869
+
870
+ def get_decoder_first_and_last_layer_state_dict(self) -> dict:
871
+ """
872
+ Just getting the first and last layers: the only ones which change when adding tokens
873
+ Used to save the model so we automatically move to cpu.
874
+ """
875
+ out = {}
876
+ for k, v in self.decoder.named_parameters():
877
+ if 'lm_head.weight' in k or 'embed_tokens.weight' in k:
878
+ out[k] = v.cpu()
879
+
880
+ # assert len(out) == 2, len(out) # We should get both the embedding layer and the head layer.
881
+ return out
882
+
883
+ def save_pretrained(self, save_directory: str, **kwargs):
884
+ """
885
+ Save only the LoRA adapters and their configurations.
886
+ """
887
+ if self.lora:
888
+ if not os.path.exists(save_directory):
889
+ os.makedirs(save_directory)
890
+
891
+ # Save the LoRA adapter weights
892
+ torch.save(self.get_all_adapters_state_dict(), os.path.join(save_directory, "adapters.pth"))
893
+
894
+ # Save the first and last layers of decoder (because of diffs with tokens !)
895
+ torch.save(self.get_decoder_first_and_last_layer_state_dict(), os.path.join(save_directory, "decoder_first_last_layers.pth"))
896
+
897
+ # Save the bert compressor if it exists
898
+ if self.compr_model_name is not None:
899
+ self.compr.save_pretrained(os.path.join(save_directory, 'compressor'))
900
+
901
+ # Save the configuration
902
+ self.config.save_pretrained(save_directory)
903
+ else:
904
+ super().save_pretrained(save_directory, **kwargs)
905
+
906
+ @classmethod
907
+ def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
908
+ """
909
+ Loading: to take care of checkpoints containing only lora and not base model.
910
+ """
911
+ # Load the configuration
912
+ config = COCOMConfig.from_pretrained(pretrained_model_name_or_path)
913
+
914
+ config.attn_implementation = kwargs.get('attn_implementation', config.attn_implementation)
915
+
916
+ map_location = torch.device("cpu") if not torch.cuda.is_available() else None
917
+
918
+ if config.lora:
919
+ # We need to delay the construction of the adapters (otherwise peft complains)
920
+ config.load_adapters = False
921
+
922
+ if 'device_map' in kwargs:
923
+ config.device_map = kwargs['device_map']
924
+
925
+ # Initialize the model
926
+ model = cls(config)
927
+
928
+ # Loading first and last layers (they might have changed due to extra tokens)
929
+ first_and_last_layers_path = get_local_file_path(pretrained_model_name_or_path, "decoder_first_last_layers.pth")
930
+
931
+ if os.path.exists(first_and_last_layers_path):
932
+ first_and_last_decoder_state_dict = torch.load(first_and_last_layers_path, map_location=map_location, weights_only=True)
933
+ for key in first_and_last_decoder_state_dict:
934
+ assert key in model.decoder.state_dict()
935
+ model.decoder.load_state_dict(first_and_last_decoder_state_dict, strict=False)
936
+
937
+ else:
938
+ print('FIRST AND LAST LAYER NOT FOUND (ok for some old models):', first_and_last_layers_path)
939
+
940
+ peft_config = model.get_peft_config(lora_r=config.lora_r)
941
+
942
+ adapters_path = get_local_file_path(pretrained_model_name_or_path, "adapters.pth")
943
+
944
+ if os.path.exists(adapters_path):
945
+ adapters_state_dict = torch.load(adapters_path, map_location=map_location, weights_only=True)
946
+
947
+ for key, val in adapters_state_dict.items():
948
+ model.load_adapter_from_state_dict(peft_config=peft_config, adapter_name=key, adapter_state_dict=val)
949
+
950
+ else:
951
+ warnings.warn(f'I see lora on that PISCO model, but {adapters_path} does not exist, it may be normal \
952
+ for recent versions of transformers, be aware.')
953
+
954
+ # If there is a compressor, it's been built: we just need to load the state dict or the adapters:
955
+ if config.compr_model_name is not None:
956
+ compressor_mlp_path = get_local_file_path(pretrained_model_name_or_path, "compressor/mlp.pth")
957
+ compressor_compressor_path = get_local_file_path(pretrained_model_name_or_path, "compressor/compressor.pth")
958
+ model.compr.load_pretrained(os.path.dirname(compressor_mlp_path),
959
+ lora=config.lora_compressor,
960
+ peft_config=model.get_peft_config(lora_r=config.lora_r_compressor))
961
+
962
+ model.set_all_adapters()
963
+ model.config.load_adapters = True
964
+ return model
965
+
966
+ else:
967
+ return super().from_pretrained(pretrained_model_name_or_path, **kwargs)
968
+
969
+ def generate_from_text(self, questions: list[str], documents: list[list[str]], max_new_tokens: int = 128, query_dependent: bool = False) -> list[str]:
970
+ """
971
+ Generates answers from documents (via compression then decoding)
972
+ questions: list of string
973
+ documents: list of list of strings (they should all be of equal length: the nb of doc for each question)
974
+ query_dependent: if true then the compression is done query-dependently
975
+ """
976
+ self.generation_top_k = len(documents[0])
977
+ assert len(documents) == len(questions)
978
+ assert all([len(context) == len(documents[0]) for context in documents])
979
+ flat_documents = sum(documents, [])
980
+
981
+ model_input = {}
982
+
983
+ # Creating encoder inputs:
984
+ if query_dependent:
985
+ # We provide the question for compression:
986
+ input_encoder = self.prepare_encoder_inputs(flat_documents, max_length=128, q_texts=questions)
987
+ else:
988
+ input_encoder = self.prepare_encoder_inputs(flat_documents, max_length=128)
989
+
990
+ device = self.decoder.device
991
+ model_input['enc_input_ids'], model_input['enc_attention_mask'] = input_encoder['input_ids'].to(device), input_encoder['attention_mask'].to(device)
992
+
993
+ # Creating decoder inputs
994
+ instr = [self.blend_prompt_and_memory_tokens(query=q) for q in questions]
995
+ inp_dec = self.decoder_tokenizer(instr, return_tensors='pt', padding="longest", add_special_tokens=False, truncation=True, max_length=2048)
996
+ model_input['dec_input_ids'], model_input['dec_attention_mask'] = inp_dec['input_ids'].to(device), inp_dec['attention_mask'].to(device)
997
+
998
+ # Generation
999
+ return self.generate(model_input, max_new_tokens=max_new_tokens)
1000
+
1001
+ def generate_from_compressed_documents_and_questions(self, questions: list[str], compressed_documents: torch.Tensor, max_new_tokens: int = 128) -> list[str]:
1002
+ """
1003
+ Generates answers from compressed documents
1004
+ questions: list of string
1005
+ compressed_documents: torch tensor, its first dimension should be a multiple of len(questions)
1006
+ """
1007
+ self.generation_top_k = compressed_documents.size(0) // len(questions)
1008
+ assert compressed_documents.size(0) % self.generation_top_k == 0, f"{compressed_documents.size(0)} {self.generation_top_k}"
1009
+
1010
+ # Creating decoder inputs
1011
+ instr = [self.blend_prompt_and_memory_tokens(query=q) for q in questions]
1012
+ inp_dec = self.decoder_tokenizer(instr, return_tensors='pt', padding="longest", add_special_tokens=False, truncation=True, max_length=2048)
1013
+ device = self.decoder.device
1014
+ dec_input_ids, dec_attention_mask = inp_dec['input_ids'].to(device), inp_dec['attention_mask'].to(device)
1015
+
1016
+ # Creating input decoder embeddings from prompt + compressed documents
1017
+ inputs_embeds = self.replace_emb(compressed_documents, dec_input_ids)
1018
+
1019
+ # Activating decoder generator:
1020
+ if 'decoder_adapter' in self.adapter_keys:
1021
+ self.decoder.set_adapter('decoder_adapter')
1022
+
1023
+ output_ids = self.decoder.generate(
1024
+ inputs_embeds=inputs_embeds,
1025
+ attention_mask=dec_attention_mask,
1026
+ generation_config=self.generation_config,
1027
+ max_new_tokens=max_new_tokens
1028
+ )
1029
+
1030
+ # de-tokenizing
1031
+ return self.decoder_tokenizer.batch_decode(output_ids, skip_special_tokens=True)
1032
+
1033
+ def compress_documents(self, documents: list[str], questions: list[str] = None) -> torch.Tensor:
1034
+ """
1035
+ Compress a list of documents
1036
+ if questions is not None, assumes compression is done query-dependently !
1037
+ """
1038
+ if questions is None:
1039
+ input_encoder = self.prepare_encoder_inputs(documents, max_length=128)
1040
+ else:
1041
+ input_encoder = self.prepare_encoder_inputs(documents, max_length=128, q_texts=questions)
1042
+ enc_input_ids = input_encoder['input_ids'].to(self.decoder.device)
1043
+ attention_mask = input_encoder['attention_mask'].to(self.decoder.device)
1044
+ return self.compress(enc_input_ids=enc_input_ids, enc_attention_mask=attention_mask)
1045
+
1046
+ def blend_prompt_and_memory_tokens(self, query: str):
1047
+ """
1048
+ Takes care of blending the prompt with the memory tokens:
1049
+ Also returns, if a label is provided, the position of the first token index of the label (for loss comp later on)
1050
+ (Used for the HUB version)
1051
+ """
1052
+ mem_tokens_str = ''.join(self.decoder_tokenizer.mem_tokens) + self.decoder_tokenizer.sep_token
1053
+
1054
+ # proper names for "eval" call, don't remove these lines
1055
+ docs = mem_tokens_str * self.generation_top_k
1056
+ question = query
1057
+
1058
+ 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.'
1059
+ prompt_user = f"Background:\n{docs}\n\nQuestion:{question}"
1060
+
1061
+ # Prepare the messages with system and user roles
1062
+ messages = [
1063
+ {"role": "system", "content": prompt_system},
1064
+ {"role": "user", "content": prompt_user.replace(':\ ', ': ')}
1065
+ ]
1066
+
1067
+ # Attempt to apply the system role and catch if it's not supported
1068
+ try:
1069
+ prompt = self.decoder_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
1070
+
1071
+ except TemplateError as e:
1072
+ # Catch the error related to system role and handle it (e.g. gemma)
1073
+ if "System role not supported" in str(e):
1074
+ # Remove system role and proceed with only the user role
1075
+ messages = [{"role": "user", "content": messages[0]['content'] + '\n' + messages[1]['content']}]
1076
+ # Apply template again without system role
1077
+ prompt = self.decoder_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
1078
+ else:
1079
+ # Re-raise the exception if it's unrelated to system role
1080
+ raise e
1081
+
1082
+ return prompt
1083
+
1084
+
1085
+ if __name__ == '__main__':
1086
+ cfg = COCOMConfig(decoder_model_name='mistralai/Mistral-7B-Instruct-v0.2',
1087
+ compr_model_name = "mistral_trimmed",
1088
+ compr_rate = 64,
1089
+ compr_n_layers = 5,
1090
+ compr_mlp_hidden_dim = 8096,
1091
+ compr_use_mlp = False,
1092
+ lora = True, # lora on decoder (and decoder as compr)
1093
+ lora_compressor = True, # lora only on the compressor if it exists
1094
+ training_form = "both",
1095
+ load_adapters = True,
1096
+ kbtc_training = False,
1097
+ optimize_mem_tokens = True,
1098
+ different_mem_tokens = True,
1099
+ attn_implementation = 'flash_attention_2')
1100
+
1101
+ cocom = COCOM(cfg)
1102
+
1103
+ cocom.save_pretrained('test_ckpt')
1104
+
1105
+ del cocom
1106
+ torch.cuda.empty_cache()
1107
+ import gc
1108
+ gc.collect()
1109
+
1110
+ cocom = COCOM.from_pretrained('test_ckpt')