larry1129 commited on
Commit
4b226f0
·
verified ·
1 Parent(s): 2721eb7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -47
app.py CHANGED
@@ -1,64 +1,138 @@
 
 
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
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  ],
 
 
 
 
60
  )
61
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+
2
+ import spaces # 必须在最顶部导入
3
  import gradio as gr
4
+ import os
5
+
6
+ # 获取 Hugging Face 访问令牌
7
+ hf_token = os.getenv("HF_API_TOKEN")
8
+
9
+ # 定义基础模型名称
10
+ base_model_name = "larry1129/WooWoof_AI_Vision_merged_16bit_3b"
11
+
12
+ # 定义 adapter 模型名称
13
+ # adapter_model_name = "larry1129/WooWoof_AI"
14
 
15
+ # 定义全局变量用于缓存模型和分词器
16
+ model = None
17
+ tokenizer = None
18
+
19
+ # 定义提示生成函数
20
+ def generate_prompt(instruction, input_text=""):
21
+ if input_text:
22
+ prompt = f"""### Instruction:
23
+ {instruction}
24
+ ### Input:
25
+ {input_text}
26
+ ### Response:
27
  """
28
+ else:
29
+ prompt = f"""### Instruction:
30
+ {instruction}
31
+ ### Response:
32
  """
33
+ return prompt
34
 
35
+ # 定义生成响应的函数,并使用 @spaces.GPU 装饰
36
+ @spaces.GPU(duration=40) # 建议将 duration 增加到 120
37
+ def generate_response(instruction, input_text):
38
+ global model, tokenizer
39
 
40
+ if model is None:
41
+ print("开始加载模型...")
42
+ # 检查 bitsandbytes 是否已安装
43
+ import importlib.util
44
+ if importlib.util.find_spec("bitsandbytes") is None:
45
+ import subprocess
46
+ subprocess.call(["pip", "install", "--upgrade", "bitsandbytes"])
 
 
47
 
48
+ try:
49
+ # 在函数内部导入需要 GPU 的库
50
+ import torch
51
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
 
52
 
53
+ from peft import PeftModel
54
 
55
+ # 创建量化配置
56
+ bnb_config = BitsAndBytesConfig(
57
+ load_in_4bit=True,
58
+ bnb_4bit_use_double_quant=True,
59
+ bnb_4bit_quant_type="nf4",
60
+ bnb_4bit_compute_dtype=torch.float16
61
+ )
62
 
63
+ # 加载分词器
64
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name, use_auth_token=hf_token)
65
+ print("分词器加载成功。")
 
 
 
 
 
66
 
67
+ # 加载基础模型
68
+ base_model = AutoModelForCausalLM.from_pretrained(
69
+ base_model_name,
70
+ quantization_config=bnb_config,
71
+ device_map="auto",
72
+ use_auth_token=hf_token,
73
+ trust_remote_code=True
74
+ )
75
+ print("基础模型加载成功。")
76
 
77
+ # 加载适配器模型
78
+ model = PeftModel.from_pretrained(
79
+ base_model,
80
+ # adapter_model_name,
81
+ torch_dtype=torch.float16,
82
+ use_auth_token=hf_token
83
+ )
84
+ print("适配器模型加载成功。")
85
 
86
+ # 设置 pad_token
87
+ tokenizer.pad_token = tokenizer.eos_token
88
+ model.config.pad_token_id = tokenizer.pad_token_id
89
+
90
+ # 切换到评估模式
91
+ model.eval()
92
+ print("模型已切换到评估模式。")
93
+ except Exception as e:
94
+ print("加载模型时出错:", e)
95
+ raise e
96
+ else:
97
+ # 在函数内部导入需要的库
98
+ import torch
99
+
100
+ # 检查 model 和 tokenizer 是否已正确加载
101
+ if model is None or tokenizer is None:
102
+ print("模型或分词器未正确加载。")
103
+ raise ValueError("模型或分词器未正确加载。")
104
+
105
+ # 生成提示
106
+ prompt = generate_prompt(instruction, input_text)
107
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
108
+
109
+ with torch.no_grad():
110
+ outputs = model.generate(
111
+ input_ids=inputs["input_ids"],
112
+ attention_mask=inputs.get("attention_mask"),
113
+ max_new_tokens=128,
114
+ temperature=0.7,
115
+ top_p=0.95,
116
+ do_sample=True,
117
+ )
118
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
119
+ response = response.split("### Response:")[-1].strip()
120
+ return response
121
+
122
+ # 创建 Gradio 接口
123
+ iface = gr.Interface(
124
+ fn=generate_response,
125
+ inputs=[
126
+ gr.Textbox(lines=2, placeholder="Instruction", label="Instruction"),
127
+ gr.Textbox(lines=2, placeholder="Input", label="Input (Option)")
128
  ],
129
+ outputs="text",
130
+ title="WooWoof AI",
131
+ description="Based on LLAMA 3.1 for pet related",
132
+ allow_flagging="never"
133
  )
134
 
135
+ # 启动 Gradio 接口
136
+ iface.launch(share=True)
137
+
138