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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.
|
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 |
+
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:
|
44 |
+
|
45 |
+
```
|
46 |
+
python src/transformers/models/Cognitivess/convert_Cognitivess_weights_to_hf.py \
|
47 |
+
--input_dir /path/to/downloaded/Cognitivess/weights --model_size 8B --output_dir /output/path
|
48 |
+
```
|
49 |
+
|
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):
|
67 |
+
return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3)) + multiple_of - 1) // multiple_of)
|
68 |
+
|
69 |
+
|
70 |
+
def read_json(path):
|
71 |
+
with open(path, "r") as f:
|
72 |
+
return json.load(f)
|
73 |
+
|
74 |
+
|
75 |
+
def write_json(text, path):
|
76 |
+
with open(path, "w") as f:
|
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
|
101 |
+
dim = params["dim"]
|
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():
|
199 |
+
index_dict["weight_map"][k] = filename
|
200 |
+
param_count += v.numel()
|
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
|
212 |
+
param_count += v.numel()
|
213 |
+
torch.save(state_dict, os.path.join(tmp_model_path, filename))
|
214 |
+
|
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"],
|
224 |
+
num_key_value_heads=num_key_value_heads,
|
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 |
+
|
232 |
+
# Make space so we can load the model properly now.
|
233 |
+
del state_dict
|
234 |
+
del loaded
|
235 |
+
gc.collect()
|
236 |
+
|
237 |
+
print("Loading the checkpoint in a Cognitivess model.")
|
238 |
+
model = CognitivessForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
|
239 |
+
# Avoid saving this as part of the config.
|
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():
|
256 |
+
parser = argparse.ArgumentParser()
|
257 |
+
parser.add_argument(
|
258 |
+
"--input_dir",
|
259 |
+
help="Location of Cognitivess weights, which contains tokenizer.model and model folders",
|
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__":
|
290 |
+
main()
|