zxw commited on
Commit
aa03335
1 Parent(s): b0a1475

update apply delta

Browse files
Files changed (1) hide show
  1. apply_delta.py +164 -0
apply_delta.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Apply the delta weights on top of a base model.
3
+
4
+ Usage:
5
+ python3 apply_delta.py --base ~/model_weights/llama-7b --target ~/model_weights/ChatYuan-7b --delta ~/model_weights/ChatYuan-7b-delta
6
+ """
7
+ import argparse
8
+ import gc
9
+ import glob
10
+ import json
11
+ import os
12
+ import shutil
13
+ import tempfile
14
+
15
+ import torch
16
+ from torch import nn
17
+ from tqdm import tqdm
18
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
19
+
20
+
21
+ GB = 1 << 30
22
+
23
+
24
+ def split_files(model_path, tmp_path, split_size):
25
+ if not os.path.exists(tmp_path):
26
+ os.makedirs(tmp_path)
27
+
28
+ file_pattern = os.path.join(model_path, "pytorch_model-*.bin")
29
+ files = glob.glob(file_pattern)
30
+
31
+ part = 0
32
+ try:
33
+ for file_path in tqdm(files):
34
+ state_dict = torch.load(file_path)
35
+ new_state_dict = {}
36
+
37
+ current_size = 0
38
+ for name, param in state_dict.items():
39
+ param_size = param.numel() * param.element_size()
40
+
41
+ if current_size + param_size > split_size:
42
+ new_file_name = f"pytorch_model-{part}.bin"
43
+ new_file_path = os.path.join(tmp_path, new_file_name)
44
+ torch.save(new_state_dict, new_file_path)
45
+ current_size = 0
46
+ new_state_dict = None
47
+ gc.collect()
48
+ new_state_dict = {}
49
+ part += 1
50
+
51
+ new_state_dict[name] = param
52
+ current_size += param_size
53
+
54
+ new_file_name = f"pytorch_model-{part}.bin"
55
+ new_file_path = os.path.join(tmp_path, new_file_name)
56
+ torch.save(new_state_dict, new_file_path)
57
+ new_state_dict = None
58
+ gc.collect()
59
+ new_state_dict = {}
60
+ part += 1
61
+ except Exception as e:
62
+ print(f"An error occurred during split_files: {e}")
63
+ shutil.rmtree(tmp_path)
64
+ raise
65
+
66
+
67
+ def apply_delta_low_cpu_mem(base_model_path, target_model_path, delta_path):
68
+ delta_tokenizer = AutoTokenizer.from_pretrained(delta_path, use_fast=False)
69
+ delta_config = AutoConfig.from_pretrained(delta_path)
70
+
71
+ if os.path.exists(target_model_path):
72
+ shutil.rmtree(target_model_path)
73
+ os.makedirs(target_model_path)
74
+
75
+ split_size = 4 * GB
76
+
77
+ with tempfile.TemporaryDirectory() as tmp_base_path, tempfile.TemporaryDirectory() as tmp_delta_path:
78
+ print(f"Split files for the base model to {tmp_base_path}")
79
+ split_files(base_model_path, tmp_base_path, split_size)
80
+ print(f"Split files for the delta weights to {tmp_delta_path}")
81
+ split_files(delta_path, tmp_delta_path, split_size)
82
+
83
+ base_pattern = os.path.join(tmp_base_path, "pytorch_model-*.bin")
84
+ base_files = glob.glob(base_pattern)
85
+ delta_pattern = os.path.join(tmp_delta_path, "pytorch_model-*.bin")
86
+ delta_files = glob.glob(delta_pattern)
87
+ delta_state_dict = torch.load(delta_files[0])
88
+
89
+ print("Applying the delta")
90
+ weight_map = {}
91
+ total_size = 0
92
+
93
+ for i, base_file in tqdm(enumerate(base_files)):
94
+ state_dict = torch.load(base_file)
95
+ file_name = f"pytorch_model-{i}.bin"
96
+ for name, param in state_dict.items():
97
+ if name not in delta_state_dict:
98
+ for delta_file in delta_files:
99
+ delta_state_dict = torch.load(delta_file)
100
+ gc.collect()
101
+ if name in delta_state_dict:
102
+ break
103
+
104
+ state_dict[name] += delta_state_dict[name]
105
+ weight_map[name] = file_name
106
+ total_size += param.numel() * param.element_size()
107
+ gc.collect()
108
+ torch.save(state_dict, os.path.join(target_model_path, file_name))
109
+
110
+ with open(
111
+ os.path.join(target_model_path, "pytorch_model.bin.index.json"), "w"
112
+ ) as f:
113
+ json.dump(
114
+ {"weight_map": weight_map, "metadata": {"total_size": total_size}}, f
115
+ )
116
+
117
+ print(f"Saving the target model to {target_model_path}")
118
+ delta_tokenizer.save_pretrained(target_model_path)
119
+ delta_config.save_pretrained(target_model_path)
120
+
121
+
122
+ def apply_delta(base_model_path, target_model_path, delta_path):
123
+ print(f"Loading the delta weights from {delta_path}")
124
+ delta_tokenizer = AutoTokenizer.from_pretrained(delta_path, use_fast=False)
125
+ delta = AutoModelForCausalLM.from_pretrained(
126
+ delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True
127
+ )
128
+
129
+ print(f"Loading the base model from {base_model_path}")
130
+ base = AutoModelForCausalLM.from_pretrained(
131
+ base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True
132
+ )
133
+
134
+ print("Applying the delta")
135
+ for name, param in tqdm(base.state_dict().items(), desc="Applying delta"):
136
+ assert name in delta.state_dict()
137
+ param.data += delta.state_dict()[name]
138
+
139
+ print(f"Saving the target model to {target_model_path}")
140
+ base.save_pretrained(target_model_path)
141
+ delta_tokenizer.save_pretrained(target_model_path)
142
+
143
+
144
+ if __name__ == "__main__":
145
+ parser = argparse.ArgumentParser()
146
+ parser.add_argument("--base-model-path", type=str, required=True)
147
+ parser.add_argument("--target-model-path", type=str, required=True)
148
+ parser.add_argument("--delta-path", type=str, required=True)
149
+ parser.add_argument(
150
+ "--low-cpu-mem",
151
+ action="store_true",
152
+ help="Lower the cpu memory usage. This will split large files and use "
153
+ "disk as swap to reduce the memory usage below 10GB.",
154
+ )
155
+ args = parser.parse_args()
156
+
157
+ print(args.base_model_path, args.target_model_path, args.delta_path)
158
+
159
+ if args.low_cpu_mem:
160
+ apply_delta_low_cpu_mem(
161
+ args.base_model_path, args.target_model_path, args.delta_path
162
+ )
163
+ else:
164
+ apply_delta(args.base_model_path, args.target_model_path, args.delta_path)