CMLL commited on
Commit
af7806f
1 Parent(s): a777a95

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -22
app.py CHANGED
@@ -2,23 +2,41 @@ import spaces
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
  import gradio as gr
 
 
 
 
 
 
5
 
6
  # 初始化
7
  peft_model_id = "CMLM/ZhongJing-2-1_8b"
8
  base_model_id = "Qwen/Qwen1.5-1.8B-Chat"
9
-
10
- device = torch.device("cuda")
11
-
12
- model = AutoModelForCausalLM.from_pretrained(base_model_id, device_map={"": device}).to(device)
13
  model.load_adapter(peft_model_id)
14
  tokenizer = AutoTokenizer.from_pretrained(
15
  "CMLM/ZhongJing-2-1_8b",
16
- padding_side="right",
17
  trust_remote_code=True,
18
  pad_token=''
19
  )
20
 
21
- #多轮对话
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  @spaces.GPU
23
  def multi_turn_chat(question, chat_history=None):
24
  if not isinstance(question, str):
@@ -29,14 +47,14 @@ def multi_turn_chat(question, chat_history=None):
29
 
30
  chat_history.append({"role": "user", "content": question})
31
 
32
- # Apply the chat template and prepare the input
33
  inputs = tokenizer.apply_chat_template(chat_history, tokenize=False, add_generation_prompt=True)
34
  model_inputs = tokenizer([inputs], return_tensors="pt").to(device)
35
-
36
  try:
37
  # Generate the response from the model
38
  outputs = model.generate(model_inputs.input_ids, max_new_tokens=512)
39
- generated_ids = outputs[:, model_inputs.input_ids.shape[-1]:].to(device)
40
  response = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
41
  except Exception as e:
42
  raise RuntimeError("Error in model generation: " + str(e))
@@ -45,32 +63,51 @@ def multi_turn_chat(question, chat_history=None):
45
  chat_history.append({"role": "assistant", "content": response})
46
 
47
  # Format the chat history for output
48
- formatted_history = []
49
  tempuser = ""
 
50
  for entry in chat_history:
51
  if entry['role'] == 'user':
52
- tempuser = entry['content']
53
  elif entry['role'] == 'assistant':
54
- formatted_history.append((tempuser, entry['content']))
 
 
55
 
56
  return formatted_history, chat_history
57
 
 
58
  def clear_history():
59
  return [], []
60
 
61
- # 多轮界面
 
 
 
 
 
 
 
 
 
62
  with gr.Blocks() as multi_turn_interface:
63
  chatbot = gr.Chatbot(label="仲景GPT-V2-1.8B 多轮对话")
64
- state = gr.State([])
65
  with gr.Row():
66
  with gr.Column(scale=6):
67
- user_input = gr.Textbox(label="输入", placeholder="输入你的问题")
68
- with gr.Column(scale=6):
69
- submit_button = gr.Button("发送")
70
-
71
- submit_button.click(multi_turn_chat, [user_input, state], [chatbot, state])
 
72
  user_input.submit(multi_turn_chat, [user_input, state], [chatbot, state])
73
- clear_button = gr.Button("清除对话历史")
74
- clear_button.click(clear_history, [], [chatbot, state])
75
 
76
- multi_turn_interface.launch()
 
 
 
 
 
 
 
 
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
  import gradio as gr
5
+ import os
6
+
7
+ os.environ['CUDA_VISIBLE_DEVICES'] = "0,1"
8
+ USE_CUDA = torch.cuda.is_available()
9
+ device_ids_parallel = [0]
10
+ device = torch.device("cuda:{}".format(device_ids_parallel[0]) if USE_CUDA else "cpu")
11
 
12
  # 初始化
13
  peft_model_id = "CMLM/ZhongJing-2-1_8b"
14
  base_model_id = "Qwen/Qwen1.5-1.8B-Chat"
15
+ model = AutoModelForCausalLM.from_pretrained(base_model_id, device_map="auto")
 
 
 
16
  model.load_adapter(peft_model_id)
17
  tokenizer = AutoTokenizer.from_pretrained(
18
  "CMLM/ZhongJing-2-1_8b",
19
+ padding_side="right",
20
  trust_remote_code=True,
21
  pad_token=''
22
  )
23
 
24
+ #单轮
25
+ @spaces.GPU
26
+ def single_turn_chat(question):
27
+ prompt = f"Question: {question}"
28
+ messages = [
29
+ {"role": "system", "content": "You are a helpful TCM medical assistant named 仲景中医大语言模型, created by 医哲未来 of Fudan University."},
30
+ {"role": "user", "content": prompt}
31
+ ]
32
+ input = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
33
+ model_inputs = tokenizer([input], return_tensors="pt").to(device)
34
+ generated_ids = model.generate( model_inputs.input_ids,max_new_tokens=512)
35
+ generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
36
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
37
+ return response
38
+
39
+ #多轮
40
  @spaces.GPU
41
  def multi_turn_chat(question, chat_history=None):
42
  if not isinstance(question, str):
 
47
 
48
  chat_history.append({"role": "user", "content": question})
49
 
50
+ # Apply the chat template and prepare the input
51
  inputs = tokenizer.apply_chat_template(chat_history, tokenize=False, add_generation_prompt=True)
52
  model_inputs = tokenizer([inputs], return_tensors="pt").to(device)
53
+
54
  try:
55
  # Generate the response from the model
56
  outputs = model.generate(model_inputs.input_ids, max_new_tokens=512)
57
+ generated_ids = outputs[:, model_inputs.input_ids.shape[-1]:]
58
  response = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
59
  except Exception as e:
60
  raise RuntimeError("Error in model generation: " + str(e))
 
63
  chat_history.append({"role": "assistant", "content": response})
64
 
65
  # Format the chat history for output
66
+ tempass = ""
67
  tempuser = ""
68
+ formatted_history = []
69
  for entry in chat_history:
70
  if entry['role'] == 'user':
71
+ tempuser = entry['content']
72
  elif entry['role'] == 'assistant':
73
+ tempass = entry['content']
74
+ temp = tempuser,tempass
75
+ formatted_history.append(temp)
76
 
77
  return formatted_history, chat_history
78
 
79
+
80
  def clear_history():
81
  return [], []
82
 
83
+ # 单轮界面
84
+ single_turn_interface = gr.Interface(
85
+ fn=single_turn_chat,
86
+ inputs=["text"],
87
+ outputs="text",
88
+ title="仲景GPT-V2-1.8B 单轮对话",
89
+ description="博极医源,精勤不倦。Unlocking the Wisdom of Traditional Chinese Medicine with AI."
90
+ )
91
+
92
+ # 多轮界面
93
  with gr.Blocks() as multi_turn_interface:
94
  chatbot = gr.Chatbot(label="仲景GPT-V2-1.8B 多轮对话")
95
+ state = gr.State([])
96
  with gr.Row():
97
  with gr.Column(scale=6):
98
+ user_input = gr.Textbox(label="输入",placeholder="输入你的问题")
99
+ with gr.Column(scale=1):
100
+ submit_btn = gr.Button("提交")
101
+ clear_history_btn = gr.Button("清除历史对话")
102
+ submit_btn.click(multi_turn_chat, [user_input, state], [chatbot, state])
103
+ clear_history_btn.click(fn=clear_history, inputs=None, outputs=[chatbot, state], queue=False)
104
  user_input.submit(multi_turn_chat, [user_input, state], [chatbot, state])
 
 
105
 
106
+ with gr.Tabs() as main_ui:
107
+ with gr.Tab("单轮对话"):
108
+ single_turn_interface.render()
109
+ with gr.Tab("多轮对话"):
110
+ multi_turn_interface.render()
111
+
112
+ # 启动界面
113
+ main_ui.launch(debug=True, server_name='0.0.0.0', server_port=6006)