prince-canuma commited on
Commit
544626b
1 Parent(s): 0b6bf9a

Upload folder using huggingface_hub (#1)

Browse files

- b64bb4e49fcc1f300c7b28f52808af88cd8b8371d799f6297c5d2bd5f43ecd35 (5f8030bec8f73a801dca5b5034ed95426a4cdfa2)
- 73c1bc83a12f0b13b615eab75a12b4cc4c61cc6d08d03438c4e9fd5e38e0a6ac (c8ada85568990cdc8590f3465de6290775baa458)
- 7523aa286cd41a7c6be7a19d25a1bae5742cdd38b71c0b50ec4564bb7a0dad7e (fab178fc722dbeeff1bfb58904a14cc63e8f6063)

README.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - code
4
+ license: other
5
+ tags:
6
+ - code
7
+ - mlx
8
+ inference: false
9
+ license_name: mnpl
10
+ license_link: https://mistral.ai/licences/MNPL-0.1.md
11
+ ---
12
+
13
+ # mlx-community/Codestral-22B-v0.1-4bit
14
+
15
+ The Model [mlx-community/Codestral-22B-v0.1-4bit](https://huggingface.co/mlx-community/Codestral-22B-v0.1-4bit) was converted to MLX format from [bullerwins/Codestral-22B-v0.1-hf](https://huggingface.co/bullerwins/Codestral-22B-v0.1-hf) using mlx-lm version **0.14.0**.
16
+
17
+ ## Use with mlx
18
+
19
+ ```bash
20
+ pip install mlx-lm
21
+ ```
22
+
23
+ ```python
24
+ from mlx_lm import load, generate
25
+
26
+ model, tokenizer = load("mlx-community/Codestral-22B-v0.1-4bit")
27
+ response = generate(model, tokenizer, prompt="hello", verbose=True)
28
+ ```
config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MistralForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 1,
7
+ "eos_token_id": 2,
8
+ "hidden_act": "silu",
9
+ "hidden_size": 6144,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 16384,
12
+ "max_position_embeddings": 32768,
13
+ "model_type": "mistral",
14
+ "num_attention_heads": 48,
15
+ "num_hidden_layers": 56,
16
+ "num_key_value_heads": 8,
17
+ "quantization": {
18
+ "group_size": 64,
19
+ "bits": 4
20
+ },
21
+ "rms_norm_eps": 1e-05,
22
+ "rope_theta": 1000000.0,
23
+ "sliding_window": null,
24
+ "tie_word_embeddings": false,
25
+ "torch_dtype": "bfloat16",
26
+ "transformers_version": "4.40.2",
27
+ "use_cache": true,
28
+ "vocab_size": 32768
29
+ }
convert_mistral_weights_to_hf-22B.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Mistral 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
+ MistralConfig,
27
+ MistralForCausalLM,
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/mistral/convert_mistral_weights_to_hf.py \
47
+ --input_dir /path/to/downloaded/mistral/weights --model_size 22B --output_dir /output/path
48
+ ```
49
+
50
+ Thereafter, models can be loaded via:
51
+
52
+ ```py
53
+ from transformers import MistralForCausalLM, LlamaTokenizer
54
+
55
+ model = MistralForCausalLM.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 = {"22B": 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 = MistralConfig(
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 Mistral model.")
238
+ model = MistralForCausalLM.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 Mistral weights, which contains tokenizer.model and model folders",
260
+ )
261
+ parser.add_argument(
262
+ "--model_size",
263
+ choices=["22B", "tokenizer_only"],
264
+ help="'f' models correspond to the finetuned versions, and are specific to the Mistral2 official release. For more details on Mistral2, checkout the original repo: https://huggingface.co/meta-mistral",
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()
model-00001-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b45248ac11869deeec18d7f83faf35bba906668c0cb794d960547f36d9c76bba
3
+ size 5323199454
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9169555f884802cbb69397267925b640c6dd76835e600e41eb45f0a9da675efb
3
+ size 5351562197
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0bd4ce6459a47076f5f05f2400112aa99a47dd71b9fb0c81b2b7e5cf50ac73f2
3
+ size 1840479994
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37f00374dea48658ee8f5d0f21895b9bc55cb0103939607c8185bfd1c6ca1f89
3
+ size 587404
tokenizer_config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ }
30
+ },
31
+ "bos_token": "<s>",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "</s>",
34
+ "legacy": true,
35
+ "model_max_length": 1000000000000000019884624838656,
36
+ "pad_token": null,
37
+ "sp_model_kwargs": {},
38
+ "spaces_between_special_tokens": false,
39
+ "tokenizer_class": "LlamaTokenizer",
40
+ "unk_token": "<unk>",
41
+ "use_default_system_prompt": false
42
+ }