Spaces:
Build error
Build error
lab_PC
commited on
Commit
•
52d0c82
1
Parent(s):
5e1514b
add logit calc
Browse files- get_loss/get_loss.py +294 -0
- get_loss/my_geyt.py +334 -0
get_loss/get_loss.py
ADDED
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# import packages
|
2 |
+
import os
|
3 |
+
from tqdm import tqdm
|
4 |
+
import warnings
|
5 |
+
import json
|
6 |
+
import torch.nn.functional as F
|
7 |
+
import torch
|
8 |
+
import gc
|
9 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
10 |
+
from datetime import datetime
|
11 |
+
import argparse
|
12 |
+
|
13 |
+
|
14 |
+
RWKV4_TOKENIZER_FILE = "./support/20B_tokenizer.json"
|
15 |
+
|
16 |
+
|
17 |
+
def load_list_from_json(file_path):
|
18 |
+
"""
|
19 |
+
Loads a list of strings from a JSON file.
|
20 |
+
|
21 |
+
:param file_path: Path of the JSON file to be loaded.
|
22 |
+
:return: List of strings loaded from the JSON file.
|
23 |
+
"""
|
24 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
25 |
+
return json.load(file)
|
26 |
+
|
27 |
+
|
28 |
+
def calculate_log_sum(logits, target_token_ids):
|
29 |
+
shifted_logits = logits[:-1, :]
|
30 |
+
shifted_targets = target_token_ids[1:]
|
31 |
+
|
32 |
+
log_probs = F.log_softmax(shifted_logits, dim=-1)
|
33 |
+
|
34 |
+
target_log_probs = -log_probs.gather(1, shifted_targets.unsqueeze(1)).squeeze()
|
35 |
+
# print(target_log_probs)
|
36 |
+
|
37 |
+
log_sum = torch.sum(target_log_probs, dim=-1)
|
38 |
+
# print(perplexity_sum)
|
39 |
+
|
40 |
+
return log_sum.item()
|
41 |
+
|
42 |
+
|
43 |
+
def print_model_parameters_in_billions(model):
|
44 |
+
total_params = sum(p.numel() for p in model.parameters())
|
45 |
+
|
46 |
+
total_params_billion = total_params / 1e9
|
47 |
+
|
48 |
+
print(f"Model parameters: {total_params_billion:.3f} billion")
|
49 |
+
|
50 |
+
|
51 |
+
def make_log(data_dict, folder_path):
|
52 |
+
if not os.path.exists(folder_path):
|
53 |
+
try:
|
54 |
+
os.makedirs(folder_path)
|
55 |
+
print(f"Directory created at {folder_path}")
|
56 |
+
except Exception as e:
|
57 |
+
print(f"Error creating directory: {e}")
|
58 |
+
return
|
59 |
+
|
60 |
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
61 |
+
file_name = f"{timestamp}.json"
|
62 |
+
file_path = os.path.join(folder_path, file_name)
|
63 |
+
|
64 |
+
try:
|
65 |
+
with open(file_path, 'w') as file:
|
66 |
+
json.dump(data_dict, file, indent=4)
|
67 |
+
print(f"Dictionary saved successfully to {file_path}")
|
68 |
+
except Exception as e:
|
69 |
+
print(f"Error saving dictionary: {e}")
|
70 |
+
|
71 |
+
|
72 |
+
def load_rwkv(path):
|
73 |
+
os.environ['RWKV_JIT_ON'] = '1'
|
74 |
+
os.environ["RWKV_CUDA_ON"] = '1'
|
75 |
+
|
76 |
+
from rwkv.model import RWKV
|
77 |
+
from rwkv.utils import PIPELINE
|
78 |
+
|
79 |
+
rwkv_model = RWKV(model=path, strategy='cuda fp16')
|
80 |
+
rwkv_pipeline = PIPELINE(rwkv_model, r"rwkv_vocab_v20230424")
|
81 |
+
rwkv_tokenizer = rwkv_pipeline.tokenizer
|
82 |
+
|
83 |
+
return rwkv_model, rwkv_tokenizer
|
84 |
+
|
85 |
+
|
86 |
+
def load_rwkv4pile(path):
|
87 |
+
os.environ['RWKV_JIT_ON'] = '1'
|
88 |
+
os.environ["RWKV_CUDA_ON"] = '1'
|
89 |
+
|
90 |
+
from rwkv.model import RWKV
|
91 |
+
from rwkv.utils import PIPELINE
|
92 |
+
|
93 |
+
rwkv_model = RWKV(model=path, strategy='cuda fp16')
|
94 |
+
rwkv_pipeline = PIPELINE(rwkv_model, RWKV4_TOKENIZER_FILE)
|
95 |
+
rwkv_tokenizer = rwkv_pipeline.tokenizer
|
96 |
+
|
97 |
+
return rwkv_model, rwkv_tokenizer
|
98 |
+
|
99 |
+
|
100 |
+
def load_hf_model(path, cache_path):
|
101 |
+
hf_tokenizer = AutoTokenizer.from_pretrained(path)
|
102 |
+
if cache_path is not None:
|
103 |
+
hf_model = AutoModelForCausalLM.from_pretrained(path,
|
104 |
+
device_map="cuda",
|
105 |
+
trust_remote_code=True,
|
106 |
+
cache_dir=cache_path).eval()
|
107 |
+
else:
|
108 |
+
hf_model = AutoModelForCausalLM.from_pretrained(path,
|
109 |
+
device_map="cuda",
|
110 |
+
trust_remote_code=True).eval()
|
111 |
+
|
112 |
+
print_model_parameters_in_billions(hf_model)
|
113 |
+
|
114 |
+
return hf_model, hf_tokenizer
|
115 |
+
|
116 |
+
|
117 |
+
def load_mamba(path):
|
118 |
+
from mamba_ssm.models.mixer_seq_simple import MambaLMHeadModel
|
119 |
+
|
120 |
+
mamba_tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
|
121 |
+
mamba_model = MambaLMHeadModel.from_pretrained(path, device="cuda", dtype=torch.float16)
|
122 |
+
mamba_model.device = torch.device('cuda')
|
123 |
+
|
124 |
+
print_model_parameters_in_billions(mamba_model)
|
125 |
+
|
126 |
+
return mamba_model, mamba_tokenizer
|
127 |
+
|
128 |
+
|
129 |
+
def eval_rwkv(model, tokenizer, texts, chunk_size, v4pile=False):
|
130 |
+
rwkv_test_data = []
|
131 |
+
rwkv_token_length_list = []
|
132 |
+
|
133 |
+
for idx, sample in tqdm(enumerate(texts), total=len(texts)):
|
134 |
+
|
135 |
+
with torch.no_grad():
|
136 |
+
|
137 |
+
if v4pile:
|
138 |
+
input_seq = tokenizer.encode(sample).ids # v4
|
139 |
+
else:
|
140 |
+
input_seq = tokenizer.encode(sample)
|
141 |
+
|
142 |
+
input_length = len(input_seq)
|
143 |
+
|
144 |
+
neg_log_prob_temp = 0
|
145 |
+
for begin in range(0, input_length, chunk_size):
|
146 |
+
input_chunk = input_seq[begin: begin + chunk_size]
|
147 |
+
|
148 |
+
logit = model.forward(input_chunk, None, full_output=True)[0]
|
149 |
+
|
150 |
+
if len(input_chunk) == 1:
|
151 |
+
logit = logit.unsqueeze(0)
|
152 |
+
|
153 |
+
# log_sum = calculate_log_sum(logit, torch.tensor(input_chunk).cuda())
|
154 |
+
|
155 |
+
# neg_log_prob_temp += log_sum
|
156 |
+
|
157 |
+
# rwkv_token_length_list.append(input_length)
|
158 |
+
# rwkv_test_data.append(neg_log_prob_temp)
|
159 |
+
|
160 |
+
# data_dict = {
|
161 |
+
# 'neg_log_prob_sum': sum(rwkv_test_data) / len(rwkv_test_data),
|
162 |
+
# 'avg tokens': sum(rwkv_token_length_list) / len(rwkv_token_length_list),
|
163 |
+
# }
|
164 |
+
|
165 |
+
# print(f'log probability sum: {sum(rwkv_test_data) / len(rwkv_test_data):.2f}')
|
166 |
+
# print(f'avg tokens: {sum(rwkv_token_length_list) / len(rwkv_token_length_list):.0f}')
|
167 |
+
|
168 |
+
return logit
|
169 |
+
|
170 |
+
|
171 |
+
def eval_hf_model(model, tokenizer, texts, chunk_size):
|
172 |
+
data = []
|
173 |
+
token_length_list = []
|
174 |
+
|
175 |
+
for idx, sample in tqdm(enumerate(texts), total=len(texts)):
|
176 |
+
|
177 |
+
with torch.no_grad():
|
178 |
+
|
179 |
+
inputs = tokenizer(sample, return_tensors='pt')
|
180 |
+
inputs = inputs.to(model.device)
|
181 |
+
|
182 |
+
seq_length = inputs['input_ids'].shape[-1]
|
183 |
+
|
184 |
+
neg_log_prob_temp = 0
|
185 |
+
# for begin in range(0, seq_length, chunk_size):
|
186 |
+
input_chunk = inputs['input_ids'][:, begin: begin + chunk_size]
|
187 |
+
|
188 |
+
logit = model.forward(input_ids=input_chunk).logits[0, :, :]
|
189 |
+
|
190 |
+
# log_sum = calculate_log_sum(logit, input_chunk.squeeze(0))
|
191 |
+
# neg_log_prob_temp += log_sum
|
192 |
+
|
193 |
+
# token_length_list.append(seq_length)
|
194 |
+
# data.append(neg_log_prob_temp)
|
195 |
+
|
196 |
+
# data_dict = {
|
197 |
+
# 'neg_log_prob_sum': sum(data) / len(data),
|
198 |
+
# 'avg tokens': sum(token_length_list) / len(token_length_list),
|
199 |
+
# }
|
200 |
+
|
201 |
+
# print(f'log probability sum: {sum(data) / len(data):.2f}')
|
202 |
+
# print(f'avg tokens: {sum(token_length_list) / len(token_length_list):.0f}')
|
203 |
+
|
204 |
+
return logit
|
205 |
+
|
206 |
+
|
207 |
+
# if __name__ == '__main__':
|
208 |
+
# parser = argparse.ArgumentParser()
|
209 |
+
|
210 |
+
# parser.add_argument('--model', type=str, required=True, help='model name or path')
|
211 |
+
# parser.add_argument('--model_type', choices=['hf', 'rwkv', 'mamba', 'rwkv4pile'], required=True, help='model type')
|
212 |
+
# parser.add_argument('--data', type=str, required=True, help='data path (json file)')
|
213 |
+
# parser.add_argument('--log_path', type=str, default='./logs/', help='log file path')
|
214 |
+
# parser.add_argument('--model_cache', type=str, help='hugging face model cache')
|
215 |
+
# parser.add_argument('--chunk_size', type=int, default=1024, help='chunk size')
|
216 |
+
|
217 |
+
|
218 |
+
def run_get_loss(args):
|
219 |
+
# args = parser.parse_args()
|
220 |
+
|
221 |
+
# load data
|
222 |
+
texts = load_list_from_json(args.data)
|
223 |
+
print(f'data size: {len(texts)}')
|
224 |
+
|
225 |
+
# load model
|
226 |
+
if args.model_type == 'hf':
|
227 |
+
model, tokenizer = load_hf_model(args.model, args.model_cache)# tokenzier path, model path
|
228 |
+
elif args.model_type == 'rwkv':
|
229 |
+
model, tokenizer = load_rwkv(args.model)
|
230 |
+
elif args.model_type == 'mamba':
|
231 |
+
model, tokenizer = load_mamba(args.model)
|
232 |
+
elif args.model_type == 'rwkv4pile':
|
233 |
+
model, tokenizer = load_rwkv4pile(args.model)
|
234 |
+
else:
|
235 |
+
raise NotImplementedError
|
236 |
+
|
237 |
+
# eval
|
238 |
+
if args.model_type in ['hf', 'mamba']:
|
239 |
+
results = eval_hf_model(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
|
240 |
+
elif args.model_type == 'rwkv':
|
241 |
+
results = eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
|
242 |
+
elif args.model_type == 'rwkv4pile':
|
243 |
+
results = eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size, v4pile=True)
|
244 |
+
else:
|
245 |
+
raise NotImplementedError
|
246 |
+
|
247 |
+
# results['model_name_or_path'] = args.model
|
248 |
+
# results['data_path'] = args.data
|
249 |
+
# results['chunk_size'] = args.chunk_size
|
250 |
+
|
251 |
+
# make_log(results, args.log_path)
|
252 |
+
|
253 |
+
# print(json.dumps(results, indent=4, ensure_ascii=False))
|
254 |
+
|
255 |
+
|
256 |
+
|
257 |
+
if __name__ == '__main__':
|
258 |
+
|
259 |
+
|
260 |
+
|
261 |
+
def run_get_loss(input_string, model_type):
|
262 |
+
# load data
|
263 |
+
texts = [input_string]
|
264 |
+
print(f'data size: {len(texts)}')
|
265 |
+
|
266 |
+
# load model
|
267 |
+
if model_type == 'hf':
|
268 |
+
model, tokenizer = load_hf_model(args.model, args.model_cache)# tokenzier path, model path
|
269 |
+
elif model_type == 'rwkv':
|
270 |
+
model, tokenizer = load_rwkv(args.model)
|
271 |
+
elif model_type == 'mamba':
|
272 |
+
model, tokenizer = load_mamba(args.model)
|
273 |
+
elif model_type == 'rwkv4pile':
|
274 |
+
model, tokenizer = load_rwkv4pile(args.model)
|
275 |
+
else:
|
276 |
+
raise NotImplementedError
|
277 |
+
|
278 |
+
# eval
|
279 |
+
if model_type in ['hf', 'mamba']:
|
280 |
+
results = eval_hf_model(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
|
281 |
+
elif model_type == 'rwkv':
|
282 |
+
results = eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
|
283 |
+
elif model_type == 'rwkv4pile':
|
284 |
+
results = eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size, v4pile=True)
|
285 |
+
else:
|
286 |
+
raise NotImplementedError
|
287 |
+
|
288 |
+
results['model_name_or_path'] = args.model
|
289 |
+
results['data_path'] = args.data
|
290 |
+
results['chunk_size'] = args.chunk_size
|
291 |
+
|
292 |
+
make_log(results, args.log_path)
|
293 |
+
|
294 |
+
print(json.dumps(results, indent=4, ensure_ascii=False))
|
get_loss/my_geyt.py
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import logging
|
3 |
+
import warnings
|
4 |
+
import os
|
5 |
+
from tqdm import tqdm
|
6 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
|
7 |
+
import transformers
|
8 |
+
import torch
|
9 |
+
import gc
|
10 |
+
from torch.utils.data import DataLoader, TensorDataset
|
11 |
+
from torch.nn.utils.rnn import pack_padded_sequence
|
12 |
+
|
13 |
+
|
14 |
+
from calc_metrics import calculate_log_sum,calculate_log_last
|
15 |
+
import torch.nn.functional as F
|
16 |
+
import logging
|
17 |
+
import time
|
18 |
+
import traceback
|
19 |
+
|
20 |
+
import datetime
|
21 |
+
doday=datetime.datetime.now().strftime("%Y-%m-%d")
|
22 |
+
# 配置日志
|
23 |
+
extra_info='fill'
|
24 |
+
|
25 |
+
# logging.basicConfig(level=logging.INFO,filename='/wangbenyou/chenghao/fersh_bench/log/app.log', filemode='a', format='%(name)s - %(levelname)s - %(message)s')
|
26 |
+
# logging.basicConfig(level=logging.INFO,filename=f'../log/app_jieduan_{extra_info}{doday}_year.log', filemode='a', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
27 |
+
|
28 |
+
import torch
|
29 |
+
import pdb
|
30 |
+
import json
|
31 |
+
|
32 |
+
|
33 |
+
paths=[
|
34 |
+
'/mntcephfs/data/med/fanyaxin/Qwen-7B-Chat',
|
35 |
+
|
36 |
+
]
|
37 |
+
|
38 |
+
|
39 |
+
|
40 |
+
# file_in_data_folder='2024-01-04_18'
|
41 |
+
# file_in_data_folder='2023-12-31'
|
42 |
+
file_in_data_folder='2023-12-27'
|
43 |
+
# file_in_data_folder='2020_100'
|
44 |
+
# file_in_data_folder='2020'
|
45 |
+
# file_in_data_folder='2014'
|
46 |
+
# file_in_data_folder='2017'
|
47 |
+
# file_in_data_folder='2019'
|
48 |
+
# file_in_data_folder='2019'
|
49 |
+
# file_in_data_folder='rephrase_MMLU'
|
50 |
+
# file_in_data_folder='mock_MMLU'
|
51 |
+
|
52 |
+
# mmlu_mock_concat
|
53 |
+
|
54 |
+
# not arxiv not year, but rep MMLU
|
55 |
+
# 你的语料列表
|
56 |
+
import get_text
|
57 |
+
# file_dic_list_strings=get_text.file_dic_list_strings
|
58 |
+
limit_lines_per_file=10
|
59 |
+
file_dic_list_strings=get_text.get_text_from(file_in_data_folder,limit=limit_lines_per_file)
|
60 |
+
# file_dic_list_strings=get_text.get_mmlu_rephrase_text(directory='/mntnfs/med_data5/chenghao/fresh_eval/data/mmlu_rephrase_concat/gpt-4-1106-preview/')
|
61 |
+
# file_dic_list_strings=get_text.get_mmlu_rephrase_text(directory='/mntnfs/med_data5/chenghao/fresh_eval/data/mmlu_mock_concat/gpt-4-1106-preview/')
|
62 |
+
|
63 |
+
|
64 |
+
|
65 |
+
# file_in_data_folder='2024-01-03'
|
66 |
+
|
67 |
+
def get_rwkv_model_tokenizer(model_name):
|
68 |
+
os.environ['RWKV_JIT_ON'] = '1'
|
69 |
+
os.environ["RWKV_CUDA_ON"] = '1'
|
70 |
+
from rwkv.model import RWKV
|
71 |
+
from rwkv.utils import PIPELINE
|
72 |
+
model=RWKV(model=model_name, strategy='cuda fp16')
|
73 |
+
pipeline = PIPELINE(model, r"rwkv_vocab_v20230424")
|
74 |
+
tokenizer = pipeline.tokenizer
|
75 |
+
return model,tokenizer
|
76 |
+
|
77 |
+
def get_mamba_model_tokenizer(model_name):
|
78 |
+
from mamba_ssm.models.mixer_seq_simple import MambaLMHeadModel
|
79 |
+
device = "cuda"
|
80 |
+
tokenizer = AutoTokenizer.from_pretrained("/mntcephfs/data/med/chenghao/models/gpt-neox-20b_tokenizer")
|
81 |
+
model = MambaLMHeadModel.from_pretrained(model_name, device=device, dtype=torch.float16)
|
82 |
+
return model,tokenizer
|
83 |
+
|
84 |
+
|
85 |
+
def get_HF_model_tokenizer(model_name):
|
86 |
+
if 'llama_hf_13b' in model_name:
|
87 |
+
tokenizer = transformers.LlamaTokenizer.from_pretrained(model_name, unk_token="<unk>")
|
88 |
+
else:
|
89 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
90 |
+
|
91 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
92 |
+
|
93 |
+
if 'zephyr' in model_name.lower():
|
94 |
+
model = AutoModelForCausalLM.from_pretrained(model_name,device_map="auto").eval()
|
95 |
+
|
96 |
+
else:
|
97 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", trust_remote_code=True).eval()
|
98 |
+
return model,tokenizer
|
99 |
+
|
100 |
+
limit_lines_per_file=10
|
101 |
+
|
102 |
+
def run_model_on_dic(config):
|
103 |
+
config['clear_log_first']=True
|
104 |
+
logging.info("start up")
|
105 |
+
paths=config['model_path']
|
106 |
+
file_dic_list_strings=config['file_dic_list_strings']
|
107 |
+
detail_log_base=config['detail_log_path']
|
108 |
+
extract_log_base=config['extract_log_path']
|
109 |
+
max_sequence_length,max_str_len,limit_lines_per_file=config['max_sequence_length'],config['max_str_len'],config['limit_lines_per_file']
|
110 |
+
|
111 |
+
for model_name in tqdm(paths):
|
112 |
+
model_name=model_name.strip()
|
113 |
+
tmp_path=model_name[:-1] if model_name[-1]=='/' else model_name
|
114 |
+
short_model_name=tmp_path.split('/')[-1]
|
115 |
+
config['detail_log_path']=detail_log_base.replace('TOFILL',f'{short_model_name}')
|
116 |
+
config['extract_log_path']=extract_log_base.replace('TOFILL',f'{short_model_name}')
|
117 |
+
if 'clear_log_first' in config.keys() and config['clear_log_first'] is True:
|
118 |
+
with open( config['extract_log_path'],'w')as f:
|
119 |
+
f.write('')
|
120 |
+
with open( config['detail_log_path'],'w')as f:
|
121 |
+
f.write('')
|
122 |
+
print(f'\n log cleared! ')
|
123 |
+
|
124 |
+
logging.basicConfig(level=logging.INFO,filename=config['detail_log_path'], filemode='a', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',force=True)
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
print()
|
129 |
+
print('model_path',model_name)
|
130 |
+
print(f'extract_log_path:{config["extract_log_path"]}\ndetail_log_path:{config["detail_log_path"]}')
|
131 |
+
print()
|
132 |
+
|
133 |
+
try:
|
134 |
+
if config['model_type']=='RWKV':#'HF' not in model_name and (('RWKV' in model_name) or ('rwkv' in model_name )):
|
135 |
+
model,tokenizer=get_rwkv_model_tokenizer(model_name)
|
136 |
+
|
137 |
+
|
138 |
+
elif config['model_type']=='MAMBA':#('mamba' in model_name) or ('MAMBA'in model_name ):
|
139 |
+
model,tokenizer=get_mamba_model_tokenizer(model_name)
|
140 |
+
|
141 |
+
|
142 |
+
elif config['model_type']=='HF':#'HF' in model_name:
|
143 |
+
|
144 |
+
model,tokenizer=get_HF_model_tokenizer(model_name)
|
145 |
+
print(f'model device:{model.device}')
|
146 |
+
print('[tokenizer.cls_token]',[tokenizer.cls_token])
|
147 |
+
print('[tokenizer.sep_token]',[tokenizer.sep_token])
|
148 |
+
else:
|
149 |
+
raise Exception('model type not found')
|
150 |
+
|
151 |
+
# === get model and tokenizer
|
152 |
+
|
153 |
+
for file_name,corpus in file_dic_list_strings.items():
|
154 |
+
|
155 |
+
tokenized_corpus=[]
|
156 |
+
for text in corpus:
|
157 |
+
text=text[:max_str_len]
|
158 |
+
if config['model_type']=='RWKV':
|
159 |
+
#'HF' not in model_name and (('RWKV' in model_name) or ('rwkv' in model_name )):
|
160 |
+
tokenized_corpus.append(tokenizer.encode(text))
|
161 |
+
|
162 |
+
elif 'HF' in model_name and ('RWKV' in model_name):
|
163 |
+
tokenized_corpus.append(tokenizer(text, return_tensors="pt")['input_ids'])
|
164 |
+
|
165 |
+
elif ('mamba' in model_name) or ('MAMBA'in model_name ):
|
166 |
+
device=torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
167 |
+
tokenized_corpus.append(tokenizer(text, return_tensors="pt").input_ids.to(device=device))
|
168 |
+
|
169 |
+
else:
|
170 |
+
tokens = tokenizer.tokenize(text)
|
171 |
+
if tokenizer.cls_token:# attention here is not [None]
|
172 |
+
tokens = [tokenizer.cls_token] + tokens
|
173 |
+
if tokenizer.sep_token:
|
174 |
+
tokens = tokens +[tokenizer.sep_token]
|
175 |
+
input_ids = tokenizer.convert_tokens_to_ids(tokens)
|
176 |
+
tokenized_corpus.append(input_ids)
|
177 |
+
# tokenized_corpus.append(tokenizer(text, return_tensors="pt")['input_ids'])
|
178 |
+
|
179 |
+
|
180 |
+
|
181 |
+
processed_sequences = []
|
182 |
+
|
183 |
+
# 遍历 tokenized_corpus,截断或补全序列
|
184 |
+
for sequence in tokenized_corpus:
|
185 |
+
# print('len(sequence)',len(sequence))
|
186 |
+
if len(sequence) < max_sequence_length:
|
187 |
+
pass
|
188 |
+
# 补全序列
|
189 |
+
# sequence = sequence + [tokenizer.pad_token_id] * (max_sequence_length - len(sequence))
|
190 |
+
# print(f'longer {max_sequence_length - len(sequence)}')
|
191 |
+
elif len(sequence) > max_sequence_length:
|
192 |
+
# 截断序列
|
193 |
+
sequence = sequence[:max_sequence_length]
|
194 |
+
|
195 |
+
# 将处理后的序列添加到列表中
|
196 |
+
processed_sequences.append(sequence)
|
197 |
+
|
198 |
+
|
199 |
+
total_loss = 0.0
|
200 |
+
total_tokens = 0
|
201 |
+
# pdb.set_trace()
|
202 |
+
|
203 |
+
for enu,batch_input_ids in tqdm(enumerate(processed_sequences)):
|
204 |
+
# if 'test_fun_dev' in config['detail_log_path'] and enu>50:
|
205 |
+
# print(f'enu:{enu} batch_input_ids: break')
|
206 |
+
# break
|
207 |
+
|
208 |
+
batch_input_ids=torch.tensor(batch_input_ids).unsqueeze(0)
|
209 |
+
|
210 |
+
with torch.no_grad():
|
211 |
+
# 获取模型的输出
|
212 |
+
# pdb.set_trace()
|
213 |
+
if config['model_type']=='RWKV':
|
214 |
+
# if 'HF' not in model_name and (('RWKV' in model_name) or ('rwkv' in model_name )):
|
215 |
+
# print('rwkv1')
|
216 |
+
# pdb.set_trace()
|
217 |
+
# logits = model.forward(batch_input_ids.squeeze().to(torch.float32), None, full_output=True)[0]
|
218 |
+
logits = model.forward(batch_input_ids.squeeze().long(), None, full_output=True)[0]
|
219 |
+
# logits = model.forward(batch_input_ids.squeeze(), None, full_output=True)[0]
|
220 |
+
# print(logits.shape)
|
221 |
+
'''
|
222 |
+
tmp=torch.tensor(batch_input_ids).unsqueeze(0)
|
223 |
+
logits = model.forward(batch_input_ids.squeeze().long(), None)
|
224 |
+
logits = model.forward(batch_input_ids.long(), None,)[0]
|
225 |
+
for output in outputs:print(tokenizer.decode(output.tolist(), skip_special_tokens=True))
|
226 |
+
|
227 |
+
'''
|
228 |
+
# loss = torch.nn.functional.cross_entropy(logits[ :-1, :].view(-1, logits.shape[-1]).to(torch.float32), batch_input_ids[0,1:].to(logits.device).view(-1).to(torch.float32), reduction='none')
|
229 |
+
loss = torch.nn.functional.cross_entropy(logits[ :-1, :].view(-1, logits.shape[-1]).to(torch.float32), batch_input_ids[0,1:].to(logits.device).view(-1), reduction='none')
|
230 |
+
|
231 |
+
elif config['model_type']=='MAMBA':
|
232 |
+
# pdb.set_trace()
|
233 |
+
mamba_output = model.forward(batch_input_ids[0])#the shape should be like (1,length)
|
234 |
+
logits = mamba_output.logits
|
235 |
+
loss = torch.nn.functional.cross_entropy(logits[:, :-1, :].view(-1, logits.shape[-1]), batch_input_ids[0][:,1:].view(-1), reduction='none')
|
236 |
+
# pdb.set_trace()
|
237 |
+
|
238 |
+
|
239 |
+
|
240 |
+
elif config['model_type']=='HF':
|
241 |
+
if 'HF' in model_name and 'RWKV' in model_name:
|
242 |
+
# pdb.set_trace()
|
243 |
+
batch_input_ids=batch_input_ids.to(model.device)
|
244 |
+
logits = model.forward(batch_input_ids[0]).logits#the shape should be like (1,length)
|
245 |
+
loss = torch.nn.functional.cross_entropy(logits[:, :-1, :].view(-1, logits.shape[-1]), batch_input_ids[0][:,1:].view(-1), reduction='none')
|
246 |
+
'''
|
247 |
+
batch_input_ids=batch_input_ids.to(model.device)
|
248 |
+
|
249 |
+
HuggingFace-Download-Accelerator/
|
250 |
+
(Pdb) c
|
251 |
+
/mntnfs/med_data5/chenghao/fresh_eval/src/fun_base_fill_LLM.py:324: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
|
252 |
+
'''
|
253 |
+
else:
|
254 |
+
outputs = model(batch_input_ids)
|
255 |
+
|
256 |
+
# 取出模型的logits
|
257 |
+
if 'chatglm3-6b' in model_name:
|
258 |
+
logits = outputs.logits.float()
|
259 |
+
else:
|
260 |
+
logits = outputs.logits
|
261 |
+
|
262 |
+
loss = torch.nn.functional.cross_entropy(logits[:, :-1, :].view(-1, logits.shape[-1]), batch_input_ids[:,1:].view(-1), reduction='none')
|
263 |
+
|
264 |
+
|
265 |
+
loss_sum = loss.sum()
|
266 |
+
loss_mean = loss.mean()
|
267 |
+
losses_list = loss.tolist()
|
268 |
+
|
269 |
+
# 准备要写入日志的数据
|
270 |
+
tmp_dic = {
|
271 |
+
'model_name': model_name,
|
272 |
+
'file_name': file_name,
|
273 |
+
'lengths': len(batch_input_ids[0]),
|
274 |
+
'length_str':len(corpus[enu][:max_str_len]),
|
275 |
+
'loss_sum': loss_sum.item(), # 转换为Python标准数据类型
|
276 |
+
'loss_mean': loss_mean.item(),
|
277 |
+
'losses_list': losses_list
|
278 |
+
}
|
279 |
+
import json
|
280 |
+
with open(config['detail_log_path'], 'a') as f:
|
281 |
+
|
282 |
+
json.dump(tmp_dic, f)
|
283 |
+
f.write("\n")
|
284 |
+
|
285 |
+
total_loss += loss.sum().item()
|
286 |
+
total_tokens += batch_input_ids.numel()
|
287 |
+
|
288 |
+
# 计算每个类别的平均损失
|
289 |
+
# pdb.set_trace()
|
290 |
+
average_loss = total_loss / total_tokens
|
291 |
+
avg_str_loss = total_loss/len(tokenized_corpus)
|
292 |
+
|
293 |
+
|
294 |
+
print(f"{file_name} total loss:", average_loss)
|
295 |
+
import json
|
296 |
+
|
297 |
+
logs = {
|
298 |
+
"model_name": model_name,
|
299 |
+
"file_name": file_name,
|
300 |
+
"processed_sequences": len(processed_sequences),
|
301 |
+
"average_loss": average_loss,
|
302 |
+
"avg_str_loss": avg_str_loss
|
303 |
+
}
|
304 |
+
|
305 |
+
# with open(f'/mntnfs/med_data5/chenghao/fresh_eval/log/year_arxiv/j_y_ans_{file_in_data_folder}.json', 'a') as f:
|
306 |
+
with open(config['extract_log_path'], 'a') as f:
|
307 |
+
|
308 |
+
json.dump(logs, f)
|
309 |
+
f.write("\n")
|
310 |
+
|
311 |
+
logging.info(logs)
|
312 |
+
|
313 |
+
except Exception as e:
|
314 |
+
logging.error(f"{model_name}, error:{e} ,detail:{traceback.format_exc()}")
|
315 |
+
with open(config['extract_log_path'], 'a') as f:
|
316 |
+
# json.dump(logs, f)
|
317 |
+
f.write(f"{model_name} failed \n")
|
318 |
+
print(f"{model_name} failed for {e} detail:{traceback.format_exc()}\n")
|
319 |
+
|
320 |
+
if __name__=='__main__':
|
321 |
+
config={}
|
322 |
+
print(file_in_data_folder)
|
323 |
+
file_dic_list_strings=get_text.get_text_from(file_in_data_folder,limit=limit_lines_per_file)
|
324 |
+
config['max_sequence_length'],config['max_str_len'],config['limit_lines_per_file']=2048,5000,10
|
325 |
+
config['extract_log_path']=f'/mntnfs/med_data5/chenghao/fresh_eval/log/test_fun_dev/extract.log'
|
326 |
+
config['detail_log_path']=f'/mntnfs/med_data5/chenghao/fresh_eval/log/test_fun_dev/detail.log'
|
327 |
+
|
328 |
+
config['model_path']='/mntnfs/med_data5/liangjuhao/models/TinyLlama-1.1B-Chat-v0.6'#paths[:1]
|
329 |
+
config['batch']=16
|
330 |
+
config['model_type']='HF'
|
331 |
+
|
332 |
+
print('start',config['model_path'])
|
333 |
+
config['file_dic_list_strings']=file_dic_list_strings
|
334 |
+
run_model_on_dic(config)
|