yuanzu commited on
Commit
2a3701d
·
verified ·
1 Parent(s): aae2227

Delete bf16_cast_block_int8.py

Browse files
Files changed (1) hide show
  1. bf16_cast_block_int8.py +0 -63
bf16_cast_block_int8.py DELETED
@@ -1,63 +0,0 @@
1
- import os
2
- import json
3
- from argparse import ArgumentParser
4
- from glob import glob
5
- from tqdm import tqdm
6
-
7
- import torch
8
- from safetensors.torch import load_file, save_file
9
- from huggingface_hub import snapshot_download
10
-
11
- from kernel import weight_quant
12
-
13
- def main(bf16_path, int8_path, model_name="deepseek-ai/DeepSeek-R1"):
14
- torch.set_default_dtype(torch.bfloat16)
15
- os.makedirs(int8_path, exist_ok=True)
16
- model_index_file = os.path.join(int8_path, "model.safetensors.index.json")
17
-
18
- if not os.path.exists(model_index_file):
19
- snapshot_download(
20
- repo_id=model_name,
21
- allow_patterns=["model.safetensors.index.json"],
22
- local_dir=int8_path,
23
- local_dir_use_symlinks=False
24
- )
25
- print(f"model index file downloaded to {model_index_file}")
26
-
27
- with open(model_index_file, "r") as f:
28
- model_index = json.load(f)
29
- weight_map = model_index["weight_map"]
30
- scale_count = len([key for key in weight_map.keys() if key.endswith("_scale_inv")])
31
-
32
- safetensor_files = list(glob(os.path.join(bf16_path, "*.safetensors")))
33
- safetensor_files.sort()
34
- quant_count = 0
35
- for safetensor_file in tqdm(safetensor_files):
36
- file_name = os.path.basename(safetensor_file)
37
- state_dict = load_file(safetensor_file, device="cuda")
38
- new_state_dict = {}
39
- for weight_name, weight in state_dict.items():
40
- scale_inv_name = f"{weight_name}_scale_inv"
41
- if scale_inv_name in weight_map:
42
- assert weight.element_size() == 2
43
- quant_count += 1
44
- int8_weight, scale_inv = weight_quant(weight)
45
- new_state_dict[weight_name] = int8_weight
46
- new_state_dict[scale_inv_name] = scale_inv
47
- else:
48
- new_state_dict[weight_name] = weight
49
- new_safetensor_file = os.path.join(int8_path, file_name)
50
- save_file(new_state_dict, new_safetensor_file)
51
- assert quant_count == scale_count
52
- print(f"{quant_count} weights are quantized.")
53
-
54
-
55
- if __name__ == "__main__":
56
- parser = ArgumentParser()
57
- parser.add_argument("--input-bf16-hf-path", type=str, required=True)
58
- parser.add_argument("--output-int8-hf-path", type=str, required=True)
59
- parser.add_argument("--model-name", type=str, default="deepseek-ai/DeepSeek-R1")
60
- args = parser.parse_args()
61
- main(args.input_bf16_hf_path, args.output_int8_hf_path, args.model_name)
62
- print("done")
63
-