waleyWang commited on
Commit
ad23950
·
verified ·
1 Parent(s): 334c2fd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +243 -0
app.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import math
4
+ import torch
5
+ import argparse
6
+ import textwrap
7
+ import transformers
8
+ from peft import PeftModel
9
+ from transformers import GenerationConfig, TextStreamer
10
+ #from llama_attn_replace import replace_llama_attn
11
+ from transformers import RobertaTokenizerFast, RobertaForSequenceClassification
12
+ import re
13
+ import gradio as gr
14
+
15
+ PROMPT_DICT = {
16
+ "prompt_no_input": (
17
+ "Below is an instruction that describes a task. "
18
+ "Write a response that appropriately completes the request.\n\n"
19
+ "### Instruction:\n{instruction}\n\n### Response:"
20
+ ),
21
+ "prompt_no_input_llama2": (
22
+ "<s>[INST] <<SYS>>\n"
23
+ "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\n"
24
+ "If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\n"
25
+ "<</SYS>> \n\n {instruction} [/INST]"
26
+ ),
27
+ "prompt_input_llama2": (
28
+ "<s>[INST] <<SYS>>\n"
29
+ "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, #while being safe. Your answers should not include any harmful, unethical, racist, sexist, #toxic, dangerous, or illegal content. Please ensure that your responses are socially #unbiased and positive in nature.\n\n"
30
+ "If a question does not make any sense, or is not factually coherent, explain why instead of #answering something not correct. If you don't know the answer to a question, please don't #share false information.\n"
31
+ "<</SYS>> \n\n {instruction} [/INST]"
32
+ )
33
+ }
34
+
35
+ class Args:
36
+ def __init__(self):
37
+ self.bert_rounter = "waleyWang/CO2RRChat/bert_router_model"
38
+ self.bert_model = "waleyWang/CO2RRChat/product_predict"
39
+ self.com_plan_model = "waleyWang/CO2RRChat/computational_plan"
40
+ self.code_model = "waleyWang/CO2RRChat/code_generate"
41
+ self.context_size = 32768
42
+ self.max_gen_len = 30000
43
+ self.cache_dir = "./cache"
44
+ self.temperature = 0.6
45
+ self.top_p = 0.9
46
+
47
+ def get_label_map():
48
+ return {
49
+ 0: "The main product is CH3CH2OH",
50
+ 1: "The main product is C2H4",
51
+ 2: "The main product is HCOOH/HCOO-",
52
+ 3: "The main product is C2+",
53
+ 4: "The main product is CH3OH",
54
+ 5: "The main product is CH4",
55
+ 6: "The main product is CO"}
56
+
57
+ def load_BERT_Rounter(model_path, query):
58
+ tokenizer = transformers.BertTokenizer.from_pretrained(model_path)
59
+ model = transformers.BertForSequenceClassification.from_pretrained(model_path, num_labels=3)
60
+ model.eval()
61
+ label_list = [f'Label_{i}' for i in range(model.config.num_labels)]
62
+ inputs = tokenizer(query, return_tensors="pt",
63
+ padding=True,
64
+ truncation=True,
65
+ max_length=512)
66
+ with torch.no_grad():
67
+ outputs = model(**inputs)
68
+
69
+ probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
70
+
71
+ predicted_label_id = torch.argmax(probabilities, dim=-1).item()
72
+ predicted_label = label_list[predicted_label_id]
73
+ confidence = probabilities[0][predicted_label_id].item()
74
+ return predicted_label
75
+
76
+ def load_bert(model_name):
77
+ tokenizer = RobertaTokenizerFast.from_pretrained(model_name)
78
+ model = RobertaForSequenceClassification.from_pretrained(model_name)
79
+ return model, tokenizer
80
+
81
+ def run_bert(text, model, tokenizer):
82
+ label_map = get_label_map()
83
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
84
+ outputs = model(**inputs)
85
+ logits = outputs.logits
86
+ predictions = torch.argmax(logits, dim=-1)
87
+ product_label = label_map[predictions.item()]
88
+ return product_label
89
+
90
+ def build_generator(model, tokenizer, temperature=0.6, top_p=0.9, max_gen_len=4096, use_cache=True):
91
+ def response(prompt):
92
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
93
+ output = model.generate(
94
+ **inputs,
95
+ max_new_tokens=max_gen_len,
96
+ temperature=temperature,
97
+ top_p=top_p,
98
+ use_cache=use_cache
99
+ )
100
+ out = tokenizer.decode(output[0], skip_special_tokens=True)
101
+
102
+ if "[/INST]" in out:
103
+ out = out.split("[/INST]")[1].strip()
104
+ return out
105
+ return response
106
+
107
+ def load_llama_model(model_path, device, context_size, cache_dir):
108
+ config = transformers.AutoConfig.from_pretrained(
109
+ model_path,
110
+ cache_dir=cache_dir,
111
+ )
112
+
113
+ orig_ctx_len = getattr(config, "max_position_embeddings", None)
114
+ if orig_ctx_len and context_size > orig_ctx_len:
115
+ scaling_factor = float(math.ceil(context_size / orig_ctx_len))
116
+ config.rope_scaling = {"type": "linear", "factor": scaling_factor}
117
+
118
+ model = transformers.AutoModelForCausalLM.from_pretrained(
119
+ model_path,
120
+ config=config,
121
+ cache_dir=cache_dir,
122
+ torch_dtype=torch.float16,
123
+ device_map="auto",
124
+ )
125
+ model.to(device)
126
+ model.resize_token_embeddings(32001)
127
+
128
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
129
+ model_path,
130
+ cache_dir=cache_dir, # 使用传入的 cache_dir
131
+ model_max_length=context_size if context_size > orig_ctx_len else orig_ctx_len,
132
+ padding_side="right",
133
+ use_fast=False,
134
+ )
135
+
136
+ model.eval()
137
+ if torch.__version__ >= "2" and sys.platform != "win32":
138
+ model = torch.compile(model)
139
+ model.eval()
140
+
141
+ return model, tokenizer
142
+
143
+ def generate_llama_output(model, tokenizer, temperature=0.6, top_p=0.9, max_gen_len=4096, use_cache=True):
144
+ def response(prompt):
145
+ print("Original prompt:", prompt)
146
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
147
+ print("Tokenized prompt:", inputs)
148
+ streamer = TextStreamer(tokenizer)
149
+ print("Generation parameters:")
150
+ print("Max new tokens:", max_gen_len)
151
+ print("Temperature:", temperature)
152
+ print("Top p:", top_p)
153
+
154
+ output = model.generate(
155
+ **inputs,
156
+ max_new_tokens=max_gen_len,
157
+ temperature=temperature,
158
+ top_p=top_p,
159
+ use_cache=use_cache,
160
+ streamer=streamer,
161
+ )
162
+ print("Raw model output:", output)
163
+ out = tokenizer.decode(output[0], skip_special_tokens= False)
164
+ print("Decoded output:", out)
165
+ #out = out.split(prompt.lstrip("<s>"))[1].strip()
166
+ return out
167
+
168
+ return response
169
+
170
+ def main(args):
171
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
172
+ predicted_label = load_BERT_Rounter(args.bert_rounter, args.question)
173
+
174
+ try:
175
+ if predicted_label == 'Label_0':
176
+ bert_model, bert_tokenizer = load_bert(args.bert_model)
177
+ product_label = run_bert(args.question, bert_model, bert_tokenizer)
178
+ response = f"Product Prediction Result:\n{product_label}"
179
+ print("Generating response:", response) # 添加调试信息
180
+ return response
181
+
182
+ elif predicted_label == 'Label_1':
183
+ plan_model, plan_tokenizer = load_llama_model(args.com_plan_model, device, args.context_size, args.cache_dir)
184
+ plan_response = build_generator(plan_model, plan_tokenizer, temperature=args.temperature, top_p=args.top_p, max_gen_len=args.max_gen_len, use_cache=True)
185
+ prompt_no_input = PROMPT_DICT["prompt_no_input_llama2"]
186
+ prompt = prompt_no_input.format_map({"instruction": args.question})
187
+ output = plan_response(prompt=prompt)
188
+ response = f"Computational Planning Result:\n{output}"
189
+ print("Generating response:", response) # 添加调试信息
190
+ return response
191
+
192
+ else:
193
+ code_model, code_tokenizer = load_llama_model(args.code_model, device, args.context_size, args.cache_dir)
194
+ code_response = build_generator(code_model, code_tokenizer, temperature=args.temperature, top_p=args.top_p, max_gen_len=args.max_gen_len, use_cache=True)
195
+ prompt_no_input = PROMPT_DICT["prompt_no_input_llama2"]
196
+ prompt = prompt_no_input.format_map({"instruction": args.question})
197
+ output = code_response(prompt=prompt)
198
+ response = f"Code Generation Result:\n{output}"
199
+ print("Generating response:", response) # 添加调试信息
200
+ return response
201
+
202
+ except Exception as e:
203
+ error_msg = f"Error occurred: {str(e)}"
204
+ print("Error:", error_msg) # 添加错误日志
205
+ return error_msg
206
+
207
+ def process_question(question):
208
+ args = Args()
209
+ args.question = question
210
+ try:
211
+ result = main(args)
212
+ return result
213
+ except Exception as e:
214
+ return f"Error occurred: {str(e)}"
215
+
216
+ def create_demo():
217
+ iface = gr.Interface(
218
+ fn=process_question,
219
+ inputs=gr.Textbox(
220
+ lines=3,
221
+ placeholder="Enter your CO2RR related question here...",
222
+ label="Question"
223
+ ),
224
+ outputs=gr.Textbox(
225
+ lines=10,
226
+ label="Response"
227
+ ),
228
+ title="CO2RR Assistant",
229
+ description="Ask questions about CO2 reduction reaction (CO2RR), including product prediction, computational planning, and code generation.",
230
+ examples=[
231
+ ["What is the main product of CO2RR on Cu(100) surface at -0.9V vs. RHE?"],
232
+ ["Simulate the CO2 reduction reaction (CO2RR) to produce CH4 (methane) on a Cs-Lu alloy (111) surface."],
233
+ ["Generate VASP input files for CO2RR simulation on Cu(111) surface"]
234
+ ]
235
+ )
236
+ return iface
237
+
238
+ if __name__ == "__main__":
239
+ demo = create_demo()
240
+ demo.launch(
241
+ share=True,
242
+ server_name="0.0.0.0"
243
+ )