jijivski commited on
Commit
d60b1f5
1 Parent(s): 9bd79c8

testonline

Browse files
README.md CHANGED
@@ -1,13 +1,12 @@
1
  ---
2
- title: Fresh Bench
3
- emoji: 🏢
4
- colorFrom: purple
5
- colorTo: blue
6
  sdk: gradio
7
  sdk_version: 4.21.0
8
  app_file: app.py
9
  pinned: false
10
- license: apache-2.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: FreshBench
3
+ emoji: 🌖
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 4.21.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
__init__.py ADDED
File without changes
app.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from transformers import AutoTokenizer
4
+ from get_loss.get_loss_hf import run_get_loss
5
+ import pdb
6
+ from types import SimpleNamespace
7
+ # os.system('git clone https://github.com/EleutherAI/lm-evaluation-harness')
8
+ # os.system('cd lm-evaluation-harness')
9
+ # os.system('pip install -e .')
10
+ # -i https://pypi.tuna.tsinghua.edu.cn/simple
11
+ # 第一个功能:基于输入文本和对应的损失值对文本进行着色展示
12
+
13
+ def color_text(text_list=["hi", "FreshEval","!"], loss_list=[0.1,0.7]):
14
+ """
15
+ 根据损失值为文本着色。
16
+ """
17
+ highlighted_text = []
18
+ loss_list=[0]+loss_list
19
+ for text, loss in zip(text_list, loss_list):
20
+ # color = "#FF0000" if float(loss) > 0.5 else "#00FF00"
21
+ color=loss/25
22
+ # highlighted_text.append({"text": text, "bg_color": color})
23
+ highlighted_text.append((text, color))
24
+
25
+ print('highlighted_text',highlighted_text)
26
+ return highlighted_text
27
+
28
+ # 第二个功能:根据 ID 列表和 tokenizer 将 ID 转换为文本,并展示
29
+ def get_text(ids_list=[0.1,0.7], tokenizer=None):
30
+ """
31
+ 给定一个 ID 列表和 tokenizer 名称,将这些 ID 转换成文本。
32
+ """
33
+ # return ['Hi', 'Adam']
34
+ # tokenizer = AutoTokenizer.from_pretrained(tokenizer)
35
+ print('ids_list',ids_list)
36
+ # pdb.set_trace()
37
+ text=[]
38
+ for id in ids_list:
39
+ text.append( tokenizer.decode(id, skip_special_tokens=True))
40
+ # 这里只是简单地返回文本,但是可以根据实际需求添加颜色或其他样式
41
+ print(f'L41:{text}')
42
+ return text
43
+
44
+
45
+ # def get_ids_loss(text, tokenizer, model):
46
+ # """
47
+ # 给定一个文本,model and its tokenizer,返回其对应的 IDs 和损失值。
48
+ # """
49
+ # # tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
50
+ # # model = AutoModelForCausalLM.from_pretrained(model_name)
51
+ # # 这里只是简单地返回 IDs 和损失值,但是可以根据实际需求添加颜色或其他样式
52
+ # return [1, 2], [0.1, 0.7]
53
+
54
+
55
+ def color_pipeline(texts=["Hi","FreshEval","!"], model=None):
56
+ """
57
+ 给定一个文本,返回其对应的着色文本。
58
+ """
59
+ print('text,model',texts,model)
60
+ args=SimpleNamespace(texts=texts,model=model)
61
+ print(f'L60,text:{texts}')
62
+ rtn_dic=run_get_loss(args)
63
+ # print(rtn_dic)
64
+ # pdb.set_trace()
65
+ # {'logit':logit,'input_ids':input_chunk,'tokenizer':tokenizer,'neg_log_prob_temp':neg_log_prob_temp}
66
+ ids, loss =rtn_dic['input_ids'],rtn_dic['loss']#= get_ids_loss(text, tokenizer, model)
67
+ tokenizer=rtn_dic['tokenizer'] # get tokenizer
68
+ text = get_text(ids, tokenizer)
69
+ # print('ids, loss ,text',ids, loss ,text)
70
+ return color_text(text, loss)
71
+
72
+
73
+ # TODO can this be global ? maybe need session to store info of the user
74
+
75
+ # 创建 Gradio 界面
76
+ with gr.Blocks() as demo:
77
+ with gr.Tab("color your text"):
78
+ with gr.Row():
79
+ text_input = gr.Textbox(label="input text", placeholder="input your text here...")
80
+ # TODO craw and drop the file
81
+
82
+ # loss_input = gr.Number(label="loss")
83
+ model_input = gr.Textbox(label="model name", placeholder="input your model name here... now I am trying phi-2...")
84
+ output_box=gr.HighlightedText(label="colored text")
85
+ # gr.Examples(
86
+ # [
87
+ # # ["Hi FreshEval !", "microsoft/phi-2"],
88
+ # ["Hello FreshBench !", "/home/sribd/chenghao/models/phi-2"],
89
+ # ],
90
+ # [text_input, model_input],
91
+ # cache_examples=True,
92
+ # # cache_examples=False,
93
+ # fn=color_pipeline,
94
+ # outputs=output_box
95
+ # )
96
+ # TODO select models that can be used online
97
+ # TODO maybe add our own models
98
+
99
+
100
+ color_text_output = gr.HTML(label="colored text")
101
+
102
+ color_text_button = gr.Button("color the text").click(color_pipeline, inputs=[text_input, model_input], outputs=output_box)
103
+
104
+
105
+ date_time_input = gr.Textbox(label="the date when the text is generated")#TODO add date time input
106
+ description_input = gr.Textbox(label="description of the text")
107
+ submit_button = gr.Button("submit a post or record").click()
108
+ #TODO add model and its score
109
+
110
+ with gr.Tab('test your qeustion'):
111
+ '''
112
+ use extract, or use ppl
113
+ '''
114
+ question=gr.Textbox(placeholder='input your question here...')
115
+ answer=gr.Textbox(placeholder='input your answer here...')
116
+ other_choices=gr.Textbox(placeholder='input your other choices here...')
117
+
118
+ test_button=gr.Button('test').click()
119
+ #TODO add the model and its score
120
+
121
+ def test_question(question, answer, other_choices):
122
+ '''
123
+ use extract, or use ppl
124
+ '''
125
+ answer_ppl, other_choices_ppl = get_ppl(question, answer, other_choices)
126
+ return answer_ppl, other_choices_ppl
127
+
128
+
129
+
130
+ with gr.Tab("model text ppl with time"):
131
+ '''
132
+ see the matplotlib example, to see ppl with time, select the models
133
+ '''
134
+ # load the json file with time,
135
+
136
+
137
+ with gr.Tab("model quesion acc with time"):
138
+ '''
139
+ see the matplotlib example, to see ppl with time, select the models
140
+ '''
141
+ #
142
+
143
+
144
+ with gr.Tab("hot questions"):
145
+ '''
146
+ see the questions and answers
147
+ '''
148
+ with gr.Tab("ppl"):
149
+ '''
150
+ see the questions
151
+ '''
152
+
153
+
154
+ demo.launch(debug=True)
155
+
156
+
157
+
158
+
159
+
160
+ # import gradio as gr
161
+ # import os
162
+ # os.system('python -m spacy download en_core_web_sm')
163
+ # import spacy
164
+ # from spacy import displacy
165
+
166
+ # nlp = spacy.load("en_core_web_sm")
167
+
168
+ # def text_analysis(text):
169
+ # doc = nlp(text)
170
+ # html = displacy.render(doc, style="dep", page=True)
171
+ # html = (
172
+ # "<div style='max-width:100%; max-height:360px; overflow:auto'>"
173
+ # + html
174
+ # + "</div>"
175
+ # )
176
+ # pos_count = {
177
+ # "char_count": len(text),
178
+ # "token_count": 0,
179
+ # }
180
+ # pos_tokens = []
181
+
182
+ # for token in doc:
183
+ # pos_tokens.extend([(token.text, token.pos_), (" ", None)])
184
+
185
+ # return pos_tokens, pos_count, html
186
+
187
+ # demo = gr.Interface(
188
+ # text_analysis,
189
+ # gr.Textbox(placeholder="Enter sentence here..."),
190
+ # ["highlight", "json", "html"],
191
+ # examples=[
192
+ # ["What a beautiful morning for a walk!"],
193
+ # ["It was the best of times, it was the worst of times."],
194
+ # ],
195
+ # )
196
+
197
+ # demo.launch()
198
+
199
+
200
+
201
+ # # lm-eval
202
+ # # lm-evaluation-harness
diff_color.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from difflib import Differ
3
+
4
+ import gradio as gr
5
+
6
+
7
+ def diff_texts(text1, text2):
8
+ d = Differ()
9
+ rtn =[
10
+ (token[2:], token[0] if token[0] != " " else None)
11
+ for token in d.compare(text1, text2)
12
+ ]
13
+ print(rtn)
14
+ return rtn
15
+
16
+
17
+ demo = gr.Interface(
18
+ diff_texts,
19
+ [
20
+ gr.Textbox(
21
+ label="Text 1",
22
+ info="Initial text",
23
+ lines=3,
24
+ value="The quick brown fox jumped over the lazy dogs.",
25
+ ),
26
+ gr.Textbox(
27
+ label="Text 2",
28
+ info="Text to compare",
29
+ lines=3,
30
+ value="The fast brown fox jumps over lazy dogs.",
31
+ ),
32
+ ],
33
+ gr.HighlightedText(
34
+ label="Diff",
35
+ combine_adjacent=True,
36
+ show_legend=True,
37
+ color_map={"+": "red", "-": "green"}),
38
+ theme=gr.themes.Base()# the return is here
39
+ )
40
+ if __name__ == "__main__":
41
+ demo.launch()
42
+
flagged/log.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Text 1,Text 2,Diff,flag,username,timestamp
2
+ The quick brown fox jumped over the lazy dogs.,The fast brown fox jumps over lazy dogs.,,,,2024-03-13 16:50:01.853095
get_loss/__pycache__/get_loss_hf.cpython-310.pyc ADDED
Binary file (3.76 kB). View file
 
get_loss/get_loss.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import mamba_ssm
13
+ import rwkv
14
+
15
+
16
+ RWKV4_TOKENIZER_FILE = "./support/20B_tokenizer.json"
17
+
18
+
19
+ def load_list_from_json(file_path):
20
+ """
21
+ Loads a list of strings from a JSON file.
22
+
23
+ :param file_path: Path of the JSON file to be loaded.
24
+ :return: List of strings loaded from the JSON file.
25
+ """
26
+ with open(file_path, 'r', encoding='utf-8') as file:
27
+ return json.load(file)
28
+
29
+
30
+ def calculate_log_sum(logits, target_token_ids):
31
+ shifted_logits = logits[:-1, :]
32
+ shifted_targets = target_token_ids[1:]
33
+
34
+ log_probs = F.log_softmax(shifted_logits, dim=-1)
35
+
36
+ target_log_probs = -log_probs.gather(1, shifted_targets.unsqueeze(1)).squeeze()
37
+ # print(target_log_probs)
38
+
39
+ log_sum = torch.sum(target_log_probs, dim=-1)
40
+ # print(perplexity_sum)
41
+
42
+ return log_sum.item()
43
+
44
+
45
+ def print_model_parameters_in_billions(model):
46
+ total_params = sum(p.numel() for p in model.parameters())
47
+
48
+ total_params_billion = total_params / 1e9
49
+
50
+ print(f"Model parameters: {total_params_billion:.3f} billion")
51
+
52
+
53
+ def make_log(data_dict, folder_path):
54
+ if not os.path.exists(folder_path):
55
+ try:
56
+ os.makedirs(folder_path)
57
+ print(f"Directory created at {folder_path}")
58
+ except Exception as e:
59
+ print(f"Error creating directory: {e}")
60
+ return
61
+
62
+ timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
63
+ file_name = f"{timestamp}.json"
64
+ file_path = os.path.join(folder_path, file_name)
65
+
66
+ try:
67
+ with open(file_path, 'w') as file:
68
+ json.dump(data_dict, file, indent=4)
69
+ print(f"Dictionary saved successfully to {file_path}")
70
+ except Exception as e:
71
+ print(f"Error saving dictionary: {e}")
72
+
73
+
74
+ def load_rwkv(path):
75
+ os.environ['RWKV_JIT_ON'] = '1'
76
+ os.environ["RWKV_CUDA_ON"] = '1'
77
+
78
+ from rwkv.model import RWKV
79
+ from rwkv.utils import PIPELINE
80
+
81
+ rwkv_model = RWKV(model=path, strategy='cuda fp16')
82
+ rwkv_pipeline = PIPELINE(rwkv_model, r"rwkv_vocab_v20230424")
83
+ rwkv_tokenizer = rwkv_pipeline.tokenizer
84
+
85
+ return rwkv_model, rwkv_tokenizer
86
+
87
+
88
+ def load_rwkv4pile(path):
89
+ os.environ['RWKV_JIT_ON'] = '1'
90
+ os.environ["RWKV_CUDA_ON"] = '1'
91
+
92
+ from rwkv.model import RWKV
93
+ from rwkv.utils import PIPELINE
94
+
95
+ rwkv_model = RWKV(model=path, strategy='cuda fp16')
96
+ rwkv_pipeline = PIPELINE(rwkv_model, RWKV4_TOKENIZER_FILE)
97
+ rwkv_tokenizer = rwkv_pipeline.tokenizer
98
+
99
+ return rwkv_model, rwkv_tokenizer
100
+
101
+
102
+ def load_hf_model(path, cache_path):
103
+ hf_tokenizer = AutoTokenizer.from_pretrained(path)
104
+ if cache_path is not None:
105
+ hf_model = AutoModelForCausalLM.from_pretrained(path,
106
+ device_map="cuda",
107
+ trust_remote_code=True,
108
+ cache_dir=cache_path).eval()
109
+ else:
110
+ hf_model = AutoModelForCausalLM.from_pretrained(path,
111
+ device_map="cuda",
112
+ trust_remote_code=True).eval()
113
+
114
+ print_model_parameters_in_billions(hf_model)
115
+
116
+ return hf_model, hf_tokenizer
117
+
118
+
119
+ def load_mamba(path):
120
+ from mamba_ssm.models.mixer_seq_simple import MambaLMHeadModel
121
+
122
+ mamba_tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
123
+ mamba_model = MambaLMHeadModel.from_pretrained(path, device="cuda", dtype=torch.float16)
124
+ mamba_model.device = torch.device('cuda')
125
+
126
+ print_model_parameters_in_billions(mamba_model)
127
+
128
+ return mamba_model, mamba_tokenizer
129
+
130
+
131
+ def eval_rwkv(model, tokenizer, texts, chunk_size, v4pile=False):
132
+ rwkv_test_data = []
133
+ rwkv_token_length_list = []
134
+
135
+ for idx, sample in tqdm(enumerate(texts), total=len(texts)):
136
+
137
+ with torch.no_grad():
138
+
139
+ if v4pile:
140
+ input_seq = tokenizer.encode(sample).ids # v4
141
+ else:
142
+ input_seq = tokenizer.encode(sample)
143
+
144
+ input_length = len(input_seq)
145
+
146
+ neg_log_prob_temp = 0
147
+ # for begin in range(0, input_length, chunk_size):
148
+ input_chunk = input_seq[:chunk_size]
149
+
150
+ logit = model.forward(input_chunk, None, full_output=True)[0]
151
+
152
+ if len(input_chunk) == 1:
153
+ logit = logit.unsqueeze(0)
154
+
155
+ # log_sum = calculate_log_sum(logit, torch.tensor(input_chunk).cuda())
156
+
157
+ # neg_log_prob_temp += log_sum
158
+
159
+ # rwkv_token_length_list.append(input_length)
160
+ # rwkv_test_data.append(neg_log_prob_temp)
161
+
162
+ # data_dict = {
163
+ # 'neg_log_prob_sum': sum(rwkv_test_data) / len(rwkv_test_data),
164
+ # 'avg tokens': sum(rwkv_token_length_list) / len(rwkv_token_length_list),
165
+ # }
166
+
167
+ # print(f'log probability sum: {sum(rwkv_test_data) / len(rwkv_test_data):.2f}')
168
+ # print(f'avg tokens: {sum(rwkv_token_length_list) / len(rwkv_token_length_list):.0f}')
169
+
170
+ return logit,logit,input_chunk,tokenizer
171
+
172
+
173
+ def eval_hf_model(model, tokenizer, texts, chunk_size):
174
+ data = []
175
+ token_length_list = []
176
+
177
+ for idx, sample in tqdm(enumerate(texts), total=len(texts)):
178
+
179
+ with torch.no_grad():
180
+
181
+ inputs = tokenizer(sample, return_tensors='pt')
182
+ inputs = inputs.to(model.device)
183
+
184
+ seq_length = inputs['input_ids'].shape[-1]
185
+
186
+ neg_log_prob_temp = 0
187
+ # for begin in range(0, seq_length, chunk_size):
188
+ input_chunk = inputs['input_ids'][:, :chunk_size]
189
+
190
+ logit = model.forward(input_ids=input_chunk).logits[0, :, :]
191
+
192
+ # log_sum = calculate_log_sum(logit, input_chunk.squeeze(0))
193
+ # neg_log_prob_temp += log_sum
194
+
195
+ # token_length_list.append(seq_length)
196
+ # data.append(neg_log_prob_temp)
197
+
198
+ # data_dict = {
199
+ # 'neg_log_prob_sum': sum(data) / len(data),
200
+ # 'avg tokens': sum(token_length_list) / len(token_length_list),
201
+ # }
202
+
203
+ # print(f'log probability sum: {sum(data) / len(data):.2f}')
204
+ # print(f'avg tokens: {sum(token_length_list) / len(token_length_list):.0f}')
205
+
206
+ return logit,input_chunk,tokenizer
207
+
208
+
209
+ # if __name__ == '__main__':
210
+ # parser = argparse.ArgumentParser()
211
+
212
+ # parser.add_argument('--model', type=str, required=True, help='model name or path')
213
+ # parser.add_argument('--model_type', choices=['hf', 'rwkv', 'mamba', 'rwkv4pile'], required=True, help='model type')
214
+ # parser.add_argument('--data', type=str, required=True, help='data path (json file)')
215
+ # parser.add_argument('--log_path', type=str, default='./logs/', help='log file path')
216
+ # parser.add_argument('--model_cache', type=str, help='hugging face model cache')
217
+ # parser.add_argument('--chunk_size', type=int, default=1024, help='chunk size')
218
+
219
+
220
+ def run_get_loss(args):
221
+ # args = parser.parse_args()
222
+
223
+ # load data
224
+ texts = load_list_from_json(args.data)
225
+ print(f'data size: {len(texts)}')
226
+
227
+ # load model
228
+ if args.model_type == 'hf':
229
+ model, tokenizer = load_hf_model(args.model, args.model_cache)# tokenzier path, model path
230
+ elif args.model_type == 'rwkv':
231
+ model, tokenizer = load_rwkv(args.model)
232
+ elif args.model_type == 'mamba':
233
+ model, tokenizer = load_mamba(args.model)
234
+ elif args.model_type == 'rwkv4pile':
235
+ model, tokenizer = load_rwkv4pile(args.model)
236
+ else:
237
+ raise NotImplementedError
238
+
239
+ # eval
240
+ if args.model_type in ['hf', 'mamba']:
241
+ return eval_hf_model(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
242
+ elif args.model_type == 'rwkv':
243
+ return eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
244
+ elif args.model_type == 'rwkv4pile':
245
+ return eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size, v4pile=True)
246
+ else:
247
+ raise NotImplementedError
248
+
249
+ # results['model_name_or_path'] = args.model
250
+ # results['data_path'] = args.data
251
+ # results['chunk_size'] = args.chunk_size
252
+
253
+ # make_log(results, args.log_path)
254
+
255
+ # print(json.dumps(results, indent=4, ensure_ascii=False))
256
+
257
+ from types import SimpleNamespace
258
+
259
+ if __name__ == '__main__':
260
+ args=SimpleNamespace(model='microsoft/phi-2',texts=['Hello FreshBench !'],model_type='hf',data='data.json',model_cache=None,chunk_size=1024)
261
+
262
+
263
+
264
+ # def run_get_loss(input_string, model_type):
265
+ # # load data
266
+ # texts = [input_string]
267
+ # print(f'data size: {len(texts)}')
268
+
269
+ # # load model
270
+ # if model_type == 'hf':
271
+ # model, tokenizer = load_hf_model(args.model, args.model_cache)# tokenzier path, model path
272
+ # elif model_type == 'rwkv':
273
+ # model, tokenizer = load_rwkv(args.model)
274
+ # elif model_type == 'mamba':
275
+ # model, tokenizer = load_mamba(args.model)
276
+ # elif model_type == 'rwkv4pile':
277
+ # model, tokenizer = load_rwkv4pile(args.model)
278
+ # else:
279
+ # raise NotImplementedError
280
+
281
+ # # eval
282
+ # if model_type in ['hf', 'mamba']:
283
+ # results = eval_hf_model(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
284
+ # elif model_type == 'rwkv':
285
+ # results = eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
286
+ # elif model_type == 'rwkv4pile':
287
+ # results = eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size, v4pile=True)
288
+ # else:
289
+ # raise NotImplementedError
290
+
291
+ # results['model_name_or_path'] = args.model
292
+ # results['data_path'] = args.data
293
+ # results['chunk_size'] = args.chunk_size
294
+
295
+ # make_log(results, args.log_path)
296
+
297
+ # print(json.dumps(results, indent=4, ensure_ascii=False))
get_loss/get_loss_hf.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from types import SimpleNamespace
13
+ import pdb
14
+ # import mamba_ssm
15
+ # import rwkv
16
+
17
+
18
+ # RWKV4_TOKENIZER_FILE = "./support/20B_tokenizer.json"
19
+ # device = 'cuda' if torch.cuda.is_available() else 'cpu'
20
+ device = 'cpu'
21
+
22
+
23
+ def load_list_from_json(file_path):
24
+ """
25
+ Loads a list of strings from a JSON file.
26
+
27
+ :param file_path: Path of the JSON file to be loaded.
28
+ :return: List of strings loaded from the JSON file.
29
+ """
30
+ with open(file_path, 'r', encoding='utf-8') as file:
31
+ return json.load(file)
32
+
33
+
34
+ def calculate_loss(logits, target_token_ids):
35
+ # shifted_logits = logits[:-1, :]
36
+ # shifted_targets = target_token_ids[1:]
37
+
38
+ # log_probs = F.log_softmax(shifted_logits, dim=-1)
39
+ loss = torch.nn.functional.cross_entropy(logits[:-1, :].view(-1, logits.shape[-1]),
40
+ target_token_ids[1:].view(-1), reduction='none')
41
+ # pdb.set_trace()
42
+
43
+
44
+ # target_log_probs = -log_probs.gather(1, shifted_targets.unsqueeze(1)).squeeze()
45
+ # # print(target_log_probs)
46
+
47
+ # log_sum = torch.sum(target_log_probs, dim=-1)
48
+ # print(perplexity_sum)
49
+
50
+ return loss.cpu().numpy()
51
+
52
+
53
+ def calculate_log_sum(logits, target_token_ids):
54
+ shifted_logits = logits[:-1, :]
55
+ shifted_targets = target_token_ids[1:]
56
+
57
+ log_probs = F.log_softmax(shifted_logits, dim=-1)
58
+
59
+ target_log_probs = -log_probs.gather(1, shifted_targets.unsqueeze(1)).squeeze()
60
+ # print(target_log_probs)
61
+
62
+ log_sum = torch.sum(target_log_probs, dim=-1)
63
+ # print(perplexity_sum)
64
+
65
+ return log_sum.item()
66
+
67
+
68
+ def print_model_parameters_in_billions(model):
69
+ total_params = sum(p.numel() for p in model.parameters())
70
+
71
+ total_params_billion = total_params / 1e9
72
+
73
+ print(f"Model parameters: {total_params_billion:.3f} billion")
74
+
75
+
76
+ # def make_log(data_dict, folder_path):
77
+ # if not os.path.exists(folder_path):
78
+ # try:
79
+ # os.makedirs(folder_path)
80
+ # print(f"Directory created at {folder_path}")
81
+ # except Exception as e:
82
+ # print(f"Error creating directory: {e}")
83
+ # return
84
+
85
+ # timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
86
+ # file_name = f"{timestamp}.json"
87
+ # file_path = os.path.join(folder_path, file_name)
88
+
89
+ # try:
90
+ # with open(file_path, 'w') as file:
91
+ # json.dump(data_dict, file, indent=4)
92
+ # print(f"Dictionary saved successfully to {file_path}")
93
+ # except Exception as e:
94
+ # print(f"Error saving dictionary: {e}")
95
+
96
+
97
+ # def load_rwkv(path):
98
+ # os.environ['RWKV_JIT_ON'] = '1'
99
+ # os.environ["RWKV_CUDA_ON"] = '1'
100
+
101
+ # from rwkv.model import RWKV
102
+ # from rwkv.utils import PIPELINE
103
+
104
+ # rwkv_model = RWKV(model=path, strategy='cuda fp16')
105
+ # rwkv_pipeline = PIPELINE(rwkv_model, r"rwkv_vocab_v20230424")
106
+ # rwkv_tokenizer = rwkv_pipeline.tokenizer
107
+
108
+ # return rwkv_model, rwkv_tokenizer
109
+
110
+
111
+ # def load_rwkv4pile(path):
112
+ # os.environ['RWKV_JIT_ON'] = '1'
113
+ # os.environ["RWKV_CUDA_ON"] = '1'
114
+
115
+ # from rwkv.model import RWKV
116
+ # from rwkv.utils import PIPELINE
117
+
118
+ # rwkv_model = RWKV(model=path, strategy='cuda fp16')
119
+ # rwkv_pipeline = PIPELINE(rwkv_model, RWKV4_TOKENIZER_FILE)
120
+ # rwkv_tokenizer = rwkv_pipeline.tokenizer
121
+
122
+ # return rwkv_model, rwkv_tokenizer
123
+
124
+
125
+ def load_hf_model(path, cache_path):
126
+ hf_tokenizer = AutoTokenizer.from_pretrained(path)
127
+ if cache_path is not None:
128
+ # pdb.set_trace()
129
+ hf_model = AutoModelForCausalLM.from_pretrained(path,
130
+ device_map=device,
131
+ trust_remote_code=True,
132
+ cache_dir=cache_path).eval()
133
+ else:
134
+ hf_model = AutoModelForCausalLM.from_pretrained(path,
135
+ device_map=device,
136
+ trust_remote_code=True).eval()
137
+
138
+ print_model_parameters_in_billions(hf_model)
139
+
140
+ return hf_model, hf_tokenizer
141
+
142
+
143
+ # def load_mamba(path):
144
+ # from mamba_ssm.models.mixer_seq_simple import MambaLMHeadModel
145
+
146
+ # mamba_tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
147
+ # mamba_model = MambaLMHeadModel.from_pretrained(path, device="cuda", dtype=torch.float16)
148
+ # mamba_model.device = torch.device('cuda')
149
+
150
+ # print_model_parameters_in_billions(mamba_model)
151
+
152
+ # return mamba_model, mamba_tokenizer
153
+
154
+
155
+ # def eval_rwkv(model, tokenizer, texts, chunk_size, v4pile=False):
156
+ # rwkv_test_data = []
157
+ # rwkv_token_length_list = []
158
+
159
+ # for idx, sample in tqdm(enumerate(texts), total=len(texts)):
160
+
161
+ # with torch.no_grad():
162
+
163
+ # if v4pile:
164
+ # input_seq = tokenizer.encode(sample).ids # v4
165
+ # else:
166
+ # input_seq = tokenizer.encode(sample)
167
+
168
+ # input_length = len(input_seq)
169
+
170
+ # neg_log_prob_temp = 0
171
+ # # for begin in range(0, input_length, chunk_size):
172
+ # input_chunk = input_seq[:chunk_size]
173
+
174
+ # logit = model.forward(input_chunk, None, full_output=True)[0]
175
+
176
+ # if len(input_chunk) == 1:
177
+ # logit = logit.unsqueeze(0)
178
+
179
+ # log_sum = calculate_log_sum(logit, torch.tensor(input_chunk).cuda())
180
+
181
+ # neg_log_prob_temp += log_sum
182
+
183
+ # rwkv_token_length_list.append(input_length)
184
+ # rwkv_test_data.append(neg_log_prob_temp)
185
+
186
+ # data_dict = {
187
+ # 'neg_log_prob_sum': sum(rwkv_test_data) / len(rwkv_test_data),
188
+ # 'avg tokens': sum(rwkv_token_length_list) / len(rwkv_token_length_list),
189
+ # }
190
+
191
+ # print(f'log probability sum: {sum(rwkv_test_data) / len(rwkv_test_data):.2f}')
192
+ # print(f'avg tokens: {sum(rwkv_token_length_list) / len(rwkv_token_length_list):.0f}')
193
+
194
+ return logit,logit,input_chunk,tokenizer
195
+
196
+
197
+ def eval_hf_model(model, tokenizer, texts, chunk_size):
198
+ data = []
199
+ token_length_list = []
200
+
201
+ # for idx, sample in tqdm(enumerate(texts), total=len(texts)):#TODO deleta the forloop
202
+ with torch.no_grad():
203
+
204
+ inputs = tokenizer(texts, return_tensors='pt')
205
+ inputs = inputs.to(model.device)
206
+
207
+ seq_length = inputs['input_ids'].shape[-1]
208
+
209
+ neg_log_prob_temp = 0
210
+ # for begin in range(0, seq_length, chunk_size):
211
+ input_chunk = inputs['input_ids'][:, :chunk_size]
212
+
213
+ logit = model.forward(input_ids=input_chunk).logits[0, :, :]
214
+
215
+ log_sum = calculate_log_sum(logit, input_chunk.squeeze(0))# suppose shape of logit is (seq_length, vocab_size),shape of input_chunk is (,seq_length)
216
+ neg_log_prob_temp += log_sum
217
+
218
+ loss = calculate_loss(logit, input_chunk.squeeze(0))
219
+
220
+ # token_length_list.append(seq_length)
221
+ # data.append(neg_log_prob_temp)
222
+
223
+ # data_dict = {
224
+ # 'neg_log_prob_sum': sum(data) / len(data),
225
+ # 'avg tokens': sum(token_length_list) / len(token_length_list),
226
+ # }
227
+
228
+ # print(f'log probability sum: {sum(data) / len(data):.2f}')
229
+ # print(f'avg tokens: {sum(token_length_list) / len(token_length_list):.0f}')
230
+ rtn_dic={'logit':logit.cpu().numpy(),'input_ids':input_chunk.cpu().numpy()[0],'loss':loss,'tokenizer':tokenizer,'neg_log_prob_temp':neg_log_prob_temp}
231
+ return rtn_dic
232
+
233
+
234
+ # if __name__ == '__main__':
235
+ # parser = argparse.ArgumentParser()
236
+
237
+ # parser.add_argument('--model', type=str, required=True, help='model name or path')
238
+ # parser.add_argument('--model_type', choices=['hf', 'rwkv', 'mamba', 'rwkv4pile'], required=True, help='model type')
239
+ # parser.add_argument('--data', type=str, required=True, help='data path (json file)')
240
+ # parser.add_argument('--log_path', type=str, default='./logs/', help='log file path')
241
+ # parser.add_argument('--model_cache', type=str, help='hugging face model cache')
242
+ # parser.add_argument('--chunk_size', type=int, default=1024, help='chunk size')
243
+
244
+
245
+ def run_get_loss(args=None):
246
+ if args is None:
247
+ # args=SimpleNamespace(model='microsoft/phi-2',texts='Hello FreshBench !',model_type='hf',model_cache=None,chunk_size=1024)
248
+ args=SimpleNamespace(model='/home/sribd/chenghao/models/phi-2',texts='Hello FreshBench !',model_type='hf',model_cache=None,chunk_size=1024)
249
+
250
+
251
+ if 'chunk_size' not in args.__dict__:
252
+ args.chunk_size=1024
253
+ if 'model_type' not in args.__dict__:
254
+ args.model_type='hf'
255
+ if 'model' not in args.__dict__ or len(args.model)<2:
256
+ # args.model='/home/sribd/chenghao/models/phi-2'
257
+ args.model='microsoft/phi-2'
258
+
259
+ if 'model_cache' not in args.__dict__:
260
+ args.model_cache=args.model
261
+
262
+ # args = parser.parse_args()
263
+
264
+ # load data
265
+ # texts = load_list_from_json(args.data)
266
+ print('args',args)
267
+ texts=args.texts
268
+ print(f'data size: {len(texts)}')
269
+
270
+ # load model
271
+ if args.model_type == 'hf':
272
+ model, tokenizer = load_hf_model(args.model, args.model_cache)# tokenzier path, model path
273
+ # elif args.model_type == 'rwkv':
274
+ # model, tokenizer = load_rwkv(args.model)
275
+ # elif args.model_type == 'mamba':
276
+ # model, tokenizer = load_mamba(args.model)
277
+ # elif args.model_type == 'rwkv4pile':
278
+ # model, tokenizer = load_rwkv4pile(args.model)
279
+ else:
280
+ raise NotImplementedError
281
+
282
+ # eval
283
+ if args.model_type in ['hf', 'mamba']:
284
+ print(f'eval hf')
285
+ return eval_hf_model(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
286
+ # elif args.model_type == 'rwkv':
287
+ # return eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size)
288
+ # elif args.model_type == 'rwkv4pile':
289
+ # return eval_rwkv(model=model, tokenizer=tokenizer, texts=texts, chunk_size=args.chunk_size, v4pile=True)
290
+ else:
291
+ raise NotImplementedError
292
+
293
+ # results['model_name_or_path'] = args.model
294
+ # results['data_path'] = args.data
295
+ # results['chunk_size'] = args.chunk_size
296
+
297
+ # make_log(results, args.log_path)
298
+
299
+ # print(json.dumps(results, indent=4, ensure_ascii=False))
300
+
301
+
302
+ if __name__ == '__main__':
303
+ args=SimpleNamespace(model='microsoft/phi-2',texts='Hello FreshBench !',model_type='hf',model_cache=None,chunk_size=1024)
304
+ run_get_loss(args)
305
+
306
+ # run_get_loss(args)
get_loss/my_get_logit.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)
gradio_cached_examples/186/log.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ colored text,flag,username,timestamp
2
+ "[{""token"":""Hi"",""class_or_confidence"":13.59826946258545},{""token"":""Adam"",""class_or_confidence"":14.804081916809082}]",,,2024-03-14 14:05:40.149274
3
+ "[{""token"":""Hi"",""class_or_confidence"":13.59826946258545},{""token"":""Adam"",""class_or_confidence"":14.804081916809082}]",,,2024-03-14 14:05:42.364248
gradio_cached_examples/212/log.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ colored text,flag,username,timestamp
2
+ "[{""token"":""Hi"",""class_or_confidence"":13.59826946258545},{""token"":""Adam"",""class_or_confidence"":14.804081916809082}]",,,2024-03-14 14:05:44.632048
3
+ "[{""token"":""Hi"",""class_or_confidence"":13.59826946258545},{""token"":""Adam"",""class_or_confidence"":14.804081916809082}]",,,2024-03-14 14:05:46.813954
hello_test.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ def greet(name, intensity):
4
+ return "Hello, " + name + ",,!" * int(intensity)
5
+ # return "Hello, " + name + ",,!" * int(0/int(intensity))# you can see the bug in command line
6
+
7
+ demo = gr.Interface(
8
+ fn=greet,
9
+ inputs=["text", "slider"],
10
+ outputs=["text"],
11
+ )
12
+
13
+ demo.launch(debug=True)
hf_space_test.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # this need hugginface connection
2
+ import gradio as gr
3
+ from transformers import pipeline
4
+
5
+
6
+ pipeline = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog")
7
+
8
+ def predict(input_img):
9
+ predictions = pipeline(input_img)
10
+ return input_img, {p["label"]: p["score"] for p in predictions}
11
+
12
+ gradio_app = gr.Interface(
13
+ predict,
14
+ inputs=gr.Image(label="Select hot dog candidate", sources=['upload', 'webcam'], type="pil"),
15
+ outputs=[gr.Image(label="Processed Image"), gr.Label(label="Result", num_top_classes=2)],
16
+ title="Hot Dog? Or Not?",
17
+ )
18
+
19
+ if __name__ == "__main__":
20
+ gradio_app.launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ transformers
2
+ torch