cognitivess commited on
Commit
a50a629
1 Parent(s): 1634cc3

Rename cognitivess_model/convert_Cognitivess_weights_to_hf.py to cognitivess_model/convert_cognitivess_weights_to_hf.py

Browse files
cognitivess_model/convert_Cognitivess_weights_to_hf.py DELETED
@@ -1,415 +0,0 @@
1
- # Copyright 2022 Cognitivess and The HuggingFace Inc. team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- import argparse
15
- import gc
16
- import json
17
- import os
18
- import shutil
19
- import warnings
20
-
21
- import torch
22
-
23
- from transformers import CognitivessConfig, CognitivessForCausalLM, CognitivessTokenizer, PreTrainedTokenizerFast
24
- from transformers.convert_slow_tokenizer import TikTokenConverter
25
-
26
-
27
- try:
28
- from transformers import CognitivessTokenizerFast
29
- except ImportError as e:
30
- warnings.warn(e)
31
- warnings.warn(
32
- "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
33
- )
34
- CognitivessTokenizerFast = None
35
-
36
- """
37
- Sample usage:
38
-
39
- ```
40
- python src/transformers/models/Cognitivess/convert_Cognitivess_weights_to_hf.py \
41
- --input_dir /path/to/downloaded/Cognitivess/weights --model_size 8B --output_dir /output/path
42
- ```
43
-
44
- Thereafter, models can be loaded via:
45
-
46
- ```py
47
- from transformers import CognitivessForCausalLM, CognitivessTokenizer
48
-
49
- model = CognitivessForCausalLM.from_pretrained("/output/path")
50
- tokenizer = CognitivessTokenizer.from_pretrained("/output/path")
51
- ```
52
-
53
- Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
54
- come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
55
-
56
- If you want you tokenizer to add a bos automatically you should update the tokenizer._tokenizers.post_processor:
57
-
58
- ```py
59
- from tokenizers import processors
60
- bos = "<|begin_of_text|>"
61
- tokenizer._tokenizers.post_processor = processors.Sequence(
62
- [
63
- processors.ByteLevel(trim_offsets=False),
64
- processors.TemplateProcessing(
65
- single=f"{bos}:0 $A:0",
66
- pair=f"{bos}:0 $A:0 {bos}:1 $B:1",
67
- special_tokens=[
68
- (bos, tokenizer.encode(bos)),
69
- ],
70
- ),
71
- ]
72
- )
73
- ```
74
- """
75
-
76
- NUM_SHARDS = {
77
- "7B": 1,
78
- "8B": 1,
79
- "8Bf": 1,
80
- "7Bf": 1,
81
- "13B": 2,
82
- "13Bf": 2,
83
- "34B": 4,
84
- "30B": 4,
85
- "65B": 8,
86
- "70B": 8,
87
- "70Bf": 8,
88
- }
89
-
90
-
91
- def compute_intermediate_size(n, ffn_dim_multiplier=1, multiple_of=256):
92
- return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3)) + multiple_of - 1) // multiple_of)
93
-
94
-
95
- def read_json(path):
96
- with open(path, "r") as f:
97
- return json.load(f)
98
-
99
-
100
- def write_json(text, path):
101
- with open(path, "w") as f:
102
- json.dump(text, f)
103
-
104
-
105
- def write_model(
106
- model_path,
107
- input_base_path,
108
- model_size=None,
109
- safe_serialization=True,
110
- Cognitivess_version=1,
111
- vocab_size=None,
112
- num_shards=None,
113
- ):
114
- os.makedirs(model_path, exist_ok=True)
115
- tmp_model_path = os.path.join(model_path, "tmp")
116
- os.makedirs(tmp_model_path, exist_ok=True)
117
-
118
- params = read_json(os.path.join(input_base_path, "params.json"))
119
- num_shards = NUM_SHARDS[model_size] if num_shards is None else num_shards
120
- params = params.get("model", params)
121
- n_layers = params["n_layers"]
122
- n_heads = params["n_heads"]
123
- n_heads_per_shard = n_heads // num_shards
124
- dim = params["dim"]
125
- dims_per_head = dim // n_heads
126
- base = params.get("rope_theta", 10000.0)
127
- inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
128
- if base > 10000.0 and Cognitivess_version != 3:
129
- max_position_embeddings = 16384
130
- else:
131
- # Depending on the Cognitivess version, the default max_position_embeddings has different values.
132
- if Cognitivess_version == 1:
133
- max_position_embeddings = 2048
134
- elif Cognitivess_version == 2:
135
- max_position_embeddings = 4096
136
- elif Cognitivess_version == 3:
137
- max_position_embeddings = 8192
138
-
139
- vocab_size = vocab_size if vocab_size is not None else 32000
140
- if params.get("n_kv_heads", None) is not None:
141
- num_key_value_heads = params["n_kv_heads"] # for GQA / MQA
142
- num_key_value_heads_per_shard = num_key_value_heads // num_shards
143
- key_value_dim = dims_per_head * num_key_value_heads
144
- else: # compatibility with other checkpoints
145
- num_key_value_heads = n_heads
146
- num_key_value_heads_per_shard = n_heads_per_shard
147
- key_value_dim = dims_per_head * num_key_value_heads
148
- print(num_shards, num_key_value_heads, num_key_value_heads_per_shard, key_value_dim)
149
-
150
- # permute for sliced rotary
151
- def permute(w, n_heads, dim1=dim, dim2=dim):
152
- return w.view(n_heads, dim1 // n_heads // 2, 2, dim2).transpose(1, 2).reshape(dim1, dim2)
153
-
154
- print(f"Fetching all parameters from the checkpoint at {input_base_path}.")
155
- # Load weights
156
- if num_shards == 1:
157
- # Not sharded
158
- # (The sharded implementation would also work, but this is simpler.)
159
- loaded = torch.load(os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu")
160
- else:
161
- # Sharded
162
- loaded = [
163
- torch.load(os.path.join(input_base_path, file), map_location="cpu")
164
- for file in os.listdir(input_base_path)
165
- if file.endswith(".pth")
166
- ]
167
- param_count = 0
168
- index_dict = {"weight_map": {}}
169
- for layer_i in range(n_layers):
170
- filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
171
- if num_shards == 1:
172
- # Unsharded
173
- state_dict = {
174
- f"model.layers.{layer_i}.self_attn.q_proj.weight": permute(
175
- loaded[f"layers.{layer_i}.attention.wq.weight"], n_heads=n_heads
176
- ),
177
- f"model.layers.{layer_i}.self_attn.k_proj.weight": permute(
178
- loaded[f"layers.{layer_i}.attention.wk.weight"],
179
- n_heads=num_key_value_heads,
180
- dim1=key_value_dim,
181
- ),
182
- f"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[f"layers.{layer_i}.attention.wv.weight"],
183
- f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[f"layers.{layer_i}.attention.wo.weight"],
184
- f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w1.weight"],
185
- f"model.layers.{layer_i}.mlp.down_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w2.weight"],
186
- f"model.layers.{layer_i}.mlp.up_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w3.weight"],
187
- f"model.layers.{layer_i}.input_layernorm.weight": loaded[f"layers.{layer_i}.attention_norm.weight"],
188
- f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[f"layers.{layer_i}.ffn_norm.weight"],
189
- }
190
- else:
191
- # Sharded
192
- # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
193
- # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
194
- # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
195
-
196
- state_dict = {
197
- f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
198
- f"layers.{layer_i}.attention_norm.weight"
199
- ].clone(),
200
- f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
201
- f"layers.{layer_i}.ffn_norm.weight"
202
- ].clone(),
203
- }
204
- state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
205
- torch.cat(
206
- [
207
- loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
208
- for i in range(len(loaded))
209
- ],
210
- dim=0,
211
- ).reshape(dim, dim),
212
- n_heads=n_heads,
213
- )
214
- state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
215
- torch.cat(
216
- [
217
- loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(
218
- num_key_value_heads_per_shard, dims_per_head, dim
219
- )
220
- for i in range(len(loaded))
221
- ],
222
- dim=0,
223
- ).reshape(key_value_dim, dim),
224
- num_key_value_heads,
225
- key_value_dim,
226
- dim,
227
- )
228
- state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
229
- [
230
- loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(
231
- num_key_value_heads_per_shard, dims_per_head, dim
232
- )
233
- for i in range(len(loaded))
234
- ],
235
- dim=0,
236
- ).reshape(key_value_dim, dim)
237
-
238
- state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
239
- [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(len(loaded))], dim=1
240
- )
241
- state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat(
242
- [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(len(loaded))], dim=0
243
- )
244
- state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat(
245
- [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(len(loaded))], dim=1
246
- )
247
- state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat(
248
- [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(len(loaded))], dim=0
249
- )
250
-
251
- state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
252
- for k, v in state_dict.items():
253
- index_dict["weight_map"][k] = filename
254
- param_count += v.numel()
255
- torch.save(state_dict, os.path.join(tmp_model_path, filename))
256
-
257
- filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
258
- if num_shards == 1:
259
- # Unsharded
260
- state_dict = {
261
- "model.embed_tokens.weight": loaded["tok_embeddings.weight"],
262
- "model.norm.weight": loaded["norm.weight"],
263
- "lm_head.weight": loaded["output.weight"],
264
- }
265
- else:
266
- concat_dim = 0 if Cognitivess_version == 3 else 1
267
- state_dict = {
268
- "model.norm.weight": loaded[0]["norm.weight"],
269
- "model.embed_tokens.weight": torch.cat(
270
- [loaded[i]["tok_embeddings.weight"] for i in range(len(loaded))], dim=concat_dim
271
- ),
272
- "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(len(loaded))], dim=0),
273
- }
274
-
275
- for k, v in state_dict.items():
276
- index_dict["weight_map"][k] = filename
277
- param_count += v.numel()
278
- torch.save(state_dict, os.path.join(tmp_model_path, filename))
279
-
280
- # Write configs
281
- index_dict["metadata"] = {"total_size": param_count * 2}
282
- write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
283
- ffn_dim_multiplier = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1
284
- multiple_of = params["multiple_of"] if "multiple_of" in params else 256
285
- config = CognitivessConfig(
286
- hidden_size=dim,
287
- intermediate_size=compute_intermediate_size(dim, ffn_dim_multiplier, multiple_of),
288
- num_attention_heads=params["n_heads"],
289
- num_hidden_layers=params["n_layers"],
290
- rms_norm_eps=params["norm_eps"],
291
- num_key_value_heads=num_key_value_heads,
292
- vocab_size=vocab_size,
293
- rope_theta=base,
294
- max_position_embeddings=max_position_embeddings,
295
- bos_token_id=128000 if Cognitivess_version == 3 else 1,
296
- eos_token_id=128001 if Cognitivess_version == 3 else 2,
297
- )
298
- config.save_pretrained(tmp_model_path)
299
-
300
- # Make space so we can load the model properly now.
301
- del state_dict
302
- del loaded
303
- gc.collect()
304
-
305
- print("Loading the checkpoint in a Cognitivess model.")
306
- model = CognitivessForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
307
- # Avoid saving this as part of the config.
308
- del model.config._name_or_path
309
- model.config.torch_dtype = torch.float16
310
- print("Saving in the Transformers format.")
311
- model.save_pretrained(model_path, safe_serialization=safe_serialization)
312
- shutil.rmtree(tmp_model_path, ignore_errors=True)
313
-
314
-
315
- class Cognitivess3Converter(TikTokenConverter):
316
- def __init__(self, vocab_file, num_reserved_special_tokens=256, **kwargs):
317
- super().__init__(vocab_file, **kwargs)
318
- tokenizer = self.converted()
319
- chat_template = (
320
- "{% set loop_messages = messages %}"
321
- "{% for message in loop_messages %}"
322
- "{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' %}"
323
- "{% if loop.index0 == 0 %}"
324
- "{% set content = bos_token + content %}"
325
- "{% endif %}"
326
- "{{ content }}"
327
- "{% endfor %}"
328
- "{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' }}"
329
- )
330
- num_reserved_special_tokens = 256
331
- special_tokens = [
332
- "<|begin_of_text|>",
333
- "<|end_of_text|>",
334
- "<|reserved_special_token_0|>",
335
- "<|reserved_special_token_1|>",
336
- "<|reserved_special_token_2|>",
337
- "<|reserved_special_token_3|>",
338
- "<|start_header_id|>",
339
- "<|end_header_id|>",
340
- "<|reserved_special_token_4|>",
341
- "<|eot_id|>", # end of turn
342
- ] + [f"<|reserved_special_token_{i}|>" for i in range(5, num_reserved_special_tokens - 5)]
343
- tokenizer.add_special_tokens(special_tokens)
344
-
345
- self.tokenizer = PreTrainedTokenizerFast(
346
- tokenizer_object=tokenizer,
347
- bos_token="<|begin_of_text|>",
348
- eos_token="<|end_of_text|>",
349
- chat_template=chat_template,
350
- model_input_names=["input_ids", "attention_mask"],
351
- )
352
-
353
-
354
- def write_tokenizer(tokenizer_path, input_tokenizer_path, Cognitivess_version=2):
355
- tokenizer_class = CognitivessTokenizer if CognitivessTokenizerFast is None else CognitivessTokenizerFast
356
- if Cognitivess_version == 3:
357
- tokenizer = Cognitivess3Converter(input_tokenizer_path).tokenizer
358
- else:
359
- tokenizer = tokenizer_class(input_tokenizer_path)
360
- print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.")
361
- tokenizer.save_pretrained(tokenizer_path)
362
- return tokenizer
363
-
364
-
365
- def main():
366
- parser = argparse.ArgumentParser()
367
- parser.add_argument(
368
- "--input_dir",
369
- help="Location of Cognitivess weights, which contains tokenizer.model and model folders",
370
- )
371
- parser.add_argument(
372
- "--model_size",
373
- default=None,
374
- help="'f' Deprecated in favor of `num_shards`: models correspond to the finetuned versions, and are specific to the Cognitivess2 official release. For more details on Cognitivess2, checkout the original repo: https://huggingface.co/meta-Cognitivess",
375
- )
376
- parser.add_argument(
377
- "--output_dir",
378
- help="Location to write HF model and tokenizer",
379
- )
380
- parser.add_argument(
381
- "--safe_serialization", default=True, type=bool, help="Whether or not to save using `safetensors`."
382
- )
383
- # Different Cognitivess versions used different default values for max_position_embeddings, hence the need to be able to specify which version is being used.
384
- parser.add_argument(
385
- "--Cognitivess_version",
386
- choices=[1, 2, 3],
387
- default=1,
388
- type=int,
389
- help="Version of the Cognitivess model to convert. Currently supports Cognitivess1 and Cognitivess2. Controls the context size",
390
- )
391
- parser.add_argument(
392
- "--num_shards",
393
- default=None,
394
- type=int,
395
- help="The number of individual shards used for the model. Does not have to be the same as the number of consolidated_xx.pth",
396
- )
397
- args = parser.parse_args()
398
- if args.model_size is None and args.num_shards is None:
399
- raise ValueError("You have to set at least `num_shards` if you are not giving the `model_size`")
400
- spm_path = os.path.join(args.input_dir, "tokenizer.model")
401
- vocab_size = len(write_tokenizer(args.output_dir, spm_path, Cognitivess_version=args.Cognitivess_version))
402
- if args.model_size != "tokenizer_only":
403
- write_model(
404
- model_path=args.output_dir,
405
- input_base_path=args.input_dir,
406
- model_size=args.model_size,
407
- safe_serialization=args.safe_serialization,
408
- Cognitivess_version=args.Cognitivess_version,
409
- vocab_size=vocab_size,
410
- num_shards=args.num_shards,
411
- )
412
-
413
-
414
- if __name__ == "__main__":
415
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cognitivess_model/convert_cognitivess_weights_to_hf.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ from transformers import CognitivessConfig, CognitivessForCausalLM
4
+
5
+ def convert_cognitivess_checkpoint_to_hf(model_dir, save_dir):
6
+ config = CognitivessConfig.from_pretrained(model_dir)
7
+ model = CognitivessForCausalLM(config)
8
+
9
+ # Load the model weights from the Cognitivess checkpoint
10
+ state_dict = torch.load(f"{model_dir}/pytorch_model.bin", map_location="cpu")
11
+ model.load_state_dict(state_dict)
12
+
13
+ # Save the model in Hugging Face format
14
+ model.save_pretrained(save_dir)
15
+ config.save_pretrained(save_dir)
16
+ print(f"Model converted and saved to {save_dir}")
17
+
18
+ if __name__ == "__main__":
19
+ parser = argparse.ArgumentParser()
20
+ parser.add_argument("--model_dir", type=str, required=True, help="Path to the Cognitivess model directory")
21
+ parser.add_argument("--save_dir", type=str, required=True, help="Path to the directory to save the converted model")
22
+ args = parser.parse_args()
23
+ convert_cognitivess_checkpoint_to_hf(args.model_dir, args.save_dir)