letianWoowoof commited on
Commit
4b6a3ce
·
verified ·
1 Parent(s): 4a696af

Update app.py

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