cognitivess commited on
Commit
d7df90a
1 Parent(s): a7eb06e

Update cognitivess_model/convert_Cognitivess_weights_to_hf.py

Browse files
cognitivess_model/convert_Cognitivess_weights_to_hf.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright 2023 Cognitivess AI 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.
@@ -19,25 +19,19 @@ import shutil
19
  import warnings
20
 
21
  import torch
22
- from safetensors.torch import load_file as safe_load_file
23
 
24
- from transformers import (
25
- LlamaTokenizer,
26
- CognitivessConfig,
27
- CognitivessForCausalLM,
28
- )
29
 
30
 
31
  try:
32
- from transformers import LlamaTokenizerFast
33
-
34
- tokenizer_class = LlamaTokenizerFast
35
  except ImportError as e:
36
  warnings.warn(e)
37
  warnings.warn(
38
  "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
39
  )
40
- tokenizer_class = LlamaTokenizer
41
 
42
  """
43
  Sample usage:
@@ -50,17 +44,48 @@ python src/transformers/models/Cognitivess/convert_Cognitivess_weights_to_hf.py
50
  Thereafter, models can be loaded via:
51
 
52
  ```py
53
- from transformers import CognitivessForCausalLM, LlamaTokenizer
54
 
55
  model = CognitivessForCausalLM.from_pretrained("/output/path")
56
- tokenizer = LlamaTokenizer.from_pretrained("/output/path")
57
  ```
58
 
59
  Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
60
  come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  """
62
 
63
- NUM_SHARDS = {"7B": 1}
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
 
66
  def compute_intermediate_size(n, ffn_dim_multiplier=1, multiple_of=256):
@@ -77,24 +102,22 @@ def write_json(text, path):
77
  json.dump(text, f)
78
 
79
 
80
- def write_model(model_path, input_base_path, model_size, tokenizer_path=None, safe_serialization=True, is_v3=False):
81
- # for backward compatibility, before you needed the repo to be called `my_repo/model_size`
82
- if not os.path.isfile(os.path.join(input_base_path, "params.json")):
83
- input_base_path = os.path.join(input_base_path, model_size)
84
-
 
 
 
 
85
  os.makedirs(model_path, exist_ok=True)
86
  tmp_model_path = os.path.join(model_path, "tmp")
87
  os.makedirs(tmp_model_path, exist_ok=True)
88
 
89
  params = read_json(os.path.join(input_base_path, "params.json"))
90
- num_shards = NUM_SHARDS[model_size]
91
-
92
- sliding_window = params.get("sliding_window", None)
93
-
94
- # For some reason this is a string in the params.json
95
- if sliding_window is not None:
96
- sliding_window = int(sliding_window)
97
-
98
  n_layers = params["n_layers"]
99
  n_heads = params["n_heads"]
100
  n_heads_per_shard = n_heads // num_shards
@@ -102,97 +125,128 @@ def write_model(model_path, input_base_path, model_size, tokenizer_path=None, sa
102
  dims_per_head = dim // n_heads
103
  base = params.get("rope_theta", 10000.0)
104
  inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
105
- max_position_embeddings = 4096 * 8
106
-
107
- if tokenizer_path is not None:
108
- tokenizer = tokenizer_class(tokenizer_path + ".v3" if is_v3 else "")
109
- tokenizer.save_pretrained(model_path)
110
- vocab_size = tokenizer.vocab_size if tokenizer_path is not None else 32000
111
-
112
- if "n_kv_heads" in params:
 
 
 
 
 
113
  num_key_value_heads = params["n_kv_heads"] # for GQA / MQA
114
- num_local_key_value_heads = num_key_value_heads // num_shards
115
- key_value_dim = dims_per_head * num_local_key_value_heads
116
  else: # compatibility with other checkpoints
117
  num_key_value_heads = n_heads
118
- num_local_key_value_heads = n_heads_per_shard
119
- key_value_dim = dim
 
120
 
121
  # permute for sliced rotary
122
- def permute(w, n_heads=n_heads, dim1=dim, dim2=dim):
123
  return w.view(n_heads, dim1 // n_heads // 2, 2, dim2).transpose(1, 2).reshape(dim1, dim2)
124
 
125
  print(f"Fetching all parameters from the checkpoint at {input_base_path}.")
126
-
127
- # Load weights - for v3 models the consolidated weights are in a single file format in safetensors
128
- if is_v3:
129
- loaded = [safe_load_file(os.path.join(input_base_path, "consolidated.safetensors"))]
 
130
  else:
 
131
  loaded = [
132
- torch.load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"), map_location="cpu")
133
- for i in range(num_shards)
 
134
  ]
135
  param_count = 0
136
  index_dict = {"weight_map": {}}
137
  for layer_i in range(n_layers):
138
  filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
139
-
140
- # Sharded
141
- # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
142
- # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
143
- # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
144
-
145
- state_dict = {
146
- f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
147
- f"layers.{layer_i}.attention_norm.weight"
148
- ].clone(),
149
- f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
150
- f"layers.{layer_i}.ffn_norm.weight"
151
- ].clone(),
152
- }
153
- state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
154
- torch.cat(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  [
156
- loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
157
- for i in range(num_shards)
158
- ],
159
- dim=0,
160
- ).reshape(dim, dim)
161
- )
162
- state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
163
- torch.cat(
164
- [
165
- loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(
166
- num_local_key_value_heads, dims_per_head, dim
167
  )
168
- for i in range(num_shards)
169
  ],
170
  dim=0,
171
- ).reshape(key_value_dim, dim),
172
- num_key_value_heads,
173
- key_value_dim,
174
- dim,
175
- )
176
- state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
177
- [
178
- loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(num_local_key_value_heads, dims_per_head, dim)
179
- for i in range(num_shards)
180
- ],
181
- dim=0,
182
- ).reshape(key_value_dim, dim)
183
-
184
- state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
185
- [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(num_shards)], dim=1
186
- )
187
- state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat(
188
- [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(num_shards)], dim=0
189
- )
190
- state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat(
191
- [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(num_shards)], dim=1
192
- )
193
- state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat(
194
- [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(num_shards)], dim=0
195
- )
196
 
197
  state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
198
  for k, v in state_dict.items():
@@ -201,11 +255,22 @@ def write_model(model_path, input_base_path, model_size, tokenizer_path=None, sa
201
  torch.save(state_dict, os.path.join(tmp_model_path, filename))
202
 
203
  filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
204
- state_dict = {
205
- "model.norm.weight": loaded[0]["norm.weight"],
206
- "model.embed_tokens.weight": torch.cat([loaded[i]["tok_embeddings.weight"] for i in range(num_shards)], dim=1),
207
- "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(num_shards)], dim=0),
208
- }
 
 
 
 
 
 
 
 
 
 
 
209
 
210
  for k, v in state_dict.items():
211
  index_dict["weight_map"][k] = filename
@@ -215,9 +280,11 @@ def write_model(model_path, input_base_path, model_size, tokenizer_path=None, sa
215
  # Write configs
216
  index_dict["metadata"] = {"total_size": param_count * 2}
217
  write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
 
 
218
  config = CognitivessConfig(
219
  hidden_size=dim,
220
- intermediate_size=params["hidden_dim"],
221
  num_attention_heads=params["n_heads"],
222
  num_hidden_layers=params["n_layers"],
223
  rms_norm_eps=params["norm_eps"],
@@ -225,7 +292,8 @@ def write_model(model_path, input_base_path, model_size, tokenizer_path=None, sa
225
  vocab_size=vocab_size,
226
  rope_theta=base,
227
  max_position_embeddings=max_position_embeddings,
228
- sliding_window=sliding_window,
 
229
  )
230
  config.save_pretrained(tmp_model_path)
231
 
@@ -240,16 +308,58 @@ def write_model(model_path, input_base_path, model_size, tokenizer_path=None, sa
240
  del model.config._name_or_path
241
  model.config.torch_dtype = torch.float16
242
  print("Saving in the Transformers format.")
243
-
244
  model.save_pretrained(model_path, safe_serialization=safe_serialization)
245
- shutil.rmtree(tmp_model_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
 
247
 
248
- def write_tokenizer(tokenizer_path, input_tokenizer_path):
249
- # Initialize the tokenizer based on the `spm` model
 
 
 
 
250
  print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.")
251
- tokenizer = tokenizer_class(input_tokenizer_path)
252
  tokenizer.save_pretrained(tokenizer_path)
 
253
 
254
 
255
  def main():
@@ -260,30 +370,45 @@ def main():
260
  )
261
  parser.add_argument(
262
  "--model_size",
263
- choices=["8B", "tokenizer_only"],
264
- help="'f' 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",
265
  )
266
  parser.add_argument(
267
  "--output_dir",
268
  help="Location to write HF model and tokenizer",
269
  )
270
- parser.add_argument("--safe_serialization", type=bool, help="Whether or not to save using `safetensors`.")
271
  parser.add_argument(
272
- "--is_v3", action="store_true", help="Whether the checkpoints correspond to the 3rd version or not."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  )
274
  args = parser.parse_args()
 
 
275
  spm_path = os.path.join(args.input_dir, "tokenizer.model")
 
276
  if args.model_size != "tokenizer_only":
277
  write_model(
278
  model_path=args.output_dir,
279
  input_base_path=args.input_dir,
280
  model_size=args.model_size,
281
  safe_serialization=args.safe_serialization,
282
- tokenizer_path=spm_path,
283
- is_v3=args.is_v3,
 
284
  )
285
- else:
286
- write_tokenizer(args.output_dir, spm_path)
287
 
288
 
289
  if __name__ == "__main__":
 
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.
 
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:
 
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):
 
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
 
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():
 
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
 
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"],
 
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
 
 
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():
 
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__":