Henrychur commited on
Commit
902df4f
·
verified ·
1 Parent(s): 642d6ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -58
app.py CHANGED
@@ -1,63 +1,67 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
 
 
 
 
58
  ],
 
59
  )
60
 
61
-
62
  if __name__ == "__main__":
63
- demo.launch()
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+
5
+ class MedS_Llama3:
6
+ def __init__(self, model_path: str):
7
+ # 加载模型到CPU
8
+ self.model = AutoModelForCausalLM.from_pretrained(
9
+ model_path,
10
+ device_map='cpu', # 指定加载到CPU
11
+ torch_dtype=torch.float32 # 使用标准的float32精度
12
+ )
13
+ self.model.config.pad_token_id = self.model.config.eos_token_id = 128009
14
+
15
+ self.tokenizer = AutoTokenizer.from_pretrained(
16
+ model_path,
17
+ model_max_length=2048,
18
+ padding_side="right"
19
+ )
20
+ self.tokenizer.pad_token = self.tokenizer.eos_token
21
+ self.model.eval()
22
+ print('Model and tokenizer loaded on CPU!')
23
+
24
+ def chat(self, query: str, instruction: str = "If you are a doctor, please perform clinical consulting with the patient.") -> str:
25
+ input_sentence = f"{instruction}\n\n{query}"
26
+ input_tokens = self.tokenizer(
27
+ input_sentence,
28
+ return_tensors="pt",
29
+ padding=True,
30
+ truncation=True
31
+ )
32
+
33
+ output = self.model.generate(
34
+ **input_tokens,
35
+ max_new_tokens=512, # 降低生成的最大新tokens数目来节省内存
36
+ eos_token_id=128009
37
+ )
38
+
39
+ generated_text = self.tokenizer.decode(
40
+ output[0][input_tokens['input_ids'].shape[1]:],
41
+ skip_special_tokens=True
42
+ )
43
+
44
+ return generated_text.strip()
45
+
46
+ # 实例化模型
47
+ model_path = "Henrychur/MMedS-Llama-3-8B" # 确保这里是模型的正确路径
48
+ chat_model = MedS_Llama3(model_path)
49
+
50
+ # 定义 Gradio 接口中使用的响应函数
51
+ def respond(message, system_message):
52
+ # 每次对话结束后清空历史,只使用当前输入和系统指令
53
+ response = chat_model.chat(query=message, instruction=system_message)
54
+ yield response
55
+
56
+ # 设置 Gradio 聊天界面
57
+ demo = gr.Interface(
58
+ fn=respond,
59
+ inputs=[
60
+ gr.Textbox(label="What is the treatment for diabetes?"),
61
+ gr.Textbox(value="If you are a doctor, please perform clinical consulting with the patient.", label="System message")
62
  ],
63
+ outputs="text"
64
  )
65
 
 
66
  if __name__ == "__main__":
67
+ demo.launch()