yxccai commited on
Commit
fab4895
·
verified ·
1 Parent(s): 543bae6

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +152 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import gradio as gr
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
4
+ from peft import PeftModel
5
+ import torch
6
+
7
+ # --- 配置 (Configuration) ---
8
+
9
+ # 您上传到Hub的仓库ID (基础模型 + LoRA适配器)
10
+ # Your repository ID on the Hugging Face Hub (containing the LoRA adapter)
11
+ hub_repo_id = "yxccai/text-style"
12
+
13
+ # ==============================================================================
14
+ # !! 性能问题的核心原因与解决方案 !!
15
+ # !! CORE PERFORMANCE ISSUE & SOLUTIONS !!
16
+ #
17
+ # 您遇到的5分钟耗时问题,是因为在免费的Hugging Face Space (CPU环境)上运行了
18
+ # 一个1.8B参数的大模型。CPU进行这种规模的计算非常缓慢。
19
+ # The 5-minute delay is caused by running a large 1.8B parameter model on a
20
+ # free Hugging Face Space, which uses a CPU. CPU inference for a model of this
21
+ # size is inherently very slow.
22
+ #
23
+ # --- 解决方案 (Solutions) ---
24
+ #
25
+ # 1. (推荐/免费) 使用更小的基础模型 (Recommended/Free):
26
+ # 将下面的 `base_model_name` 从 "Qwen/Qwen1.5-1.8B-Chat"
27
+ # 更改为 "Qwen/Qwen1.5-0.5B-Chat"。这是最直接有效的免费解决方案。
28
+ # Change `base_model_name` below from "Qwen/Qwen1.5-1.8B-Chat" to
29
+ # "Qwen/Qwen1.5-0.5B-Chat". This is the most effective free solution.
30
+ #
31
+ # 2. (最佳性能) 升级到GPU硬件 (Best Performance):
32
+ # 在Hugging Face Spaces的设置中,将硬件从免费的CPU升级到付费的GPU
33
+ # (例如 T4 small)。这将提供数量级的速度提升。
34
+ # In your Hugging Face Space settings, upgrade the hardware from the free CPU
35
+ # to a paid GPU (e.g., T4 small). This will provide a massive speed-up.
36
+ #
37
+ # 3. (进阶) 使用量化 (Advanced):
38
+ # 加载模型时使用4位或8位量化可以减少内存占用并加速CPU推理,但这会略微
39
+ # 牺牲模型精度。这需要更复杂的代码,如下面的 quantization_config 所示。
40
+ # Using 4-bit or 8-bit quantization can reduce memory usage and speed up CPU
41
+ # inference, at a slight cost to model precision. This requires more complex
42
+ # code, like the `quantization_config` shown below.
43
+ # ==============================================================================
44
+
45
+ # --- 应用解决方案1:使用更小的模型 ---
46
+ # Applying Solution 1: Use a smaller model
47
+ base_model_name = "Qwen/Qwen1.5-0.5B-Chat" # <--- 已修改为0.5B版本以提速
48
+
49
+ device = "cuda" if torch.cuda.is_available() else "cpu"
50
+ print(f"Gradio App: Using device: {device}")
51
+
52
+ # --- (可选) 量化配置示例 (Optional) Quantization Config Example ---
53
+ # 如果您想尝试方案3,可以取消下面的注释。注意:这在CPU上可能仍然不够快。
54
+ # If you want to try Solution 3, you can uncomment the following lines.
55
+ # Note: This might still not be fast enough on a CPU.
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.bfloat16
61
+ # )
62
+
63
+ # --- 加载模型和Tokenizer (Loading Model and Tokenizer) ---
64
+ print(f"Gradio App: Loading base model: {base_model_name}")
65
+ # 1. 加载基础模型 (Load base model)
66
+ base_model = AutoModelForCausalLM.from_pretrained(
67
+ base_model_name,
68
+ torch_dtype="auto",
69
+ device_map="auto", # 使用 "auto" 让transformers库自动处理设备映射
70
+ trust_remote_code=True
71
+ # quantization_config=bnb_config # 如果使用量化,请添加此行
72
+ )
73
+ # base_model.to(device) # device_map="auto" 时不需要手动 .to(device)
74
+
75
+ print(f"Gradio App: Loading tokenizer from: {hub_repo_id}")
76
+ # 2. 加载Tokenizer (Load Tokenizer)
77
+ tokenizer = AutoTokenizer.from_pretrained(hub_repo_id, trust_remote_code=True)
78
+ if tokenizer.pad_token is None:
79
+ print("Gradio App: Tokenizer does not have a pad_token, setting it to eos_token.")
80
+ tokenizer.pad_token = tokenizer.eos_token
81
+ base_model.config.pad_token_id = tokenizer.eos_token_id
82
+
83
+ print(f"Gradio App: Loading LoRA adapter from: {hub_repo_id}")
84
+ # 3. 加载并应用LoRA适配器 (Load and apply LoRA adapter)
85
+ model = PeftModel.from_pretrained(base_model, hub_repo_id)
86
+
87
+ model.eval() # 设置为评估模式 (Set to evaluation mode)
88
+ print("Gradio App: Model and tokenizer loaded successfully.")
89
+
90
+ # --- 推理函数 (Inference Function) ---
91
+ def chat(input_text):
92
+ if not input_text:
93
+ return "请输入一些文本。"
94
+
95
+ print(f"Gradio App: Received input: {input_text}")
96
+ # 构建符合Qwen Chat模板的输入
97
+ # Construct input according to the Qwen Chat template
98
+ messages = [
99
+ {"role": "system", "content": "你是一个文本风格转换助手。请严格按照要求,仅将以下书面文本转换为自然、口语化的简洁表达方式,不要添加任何额外的解释、扩展信息或重复原文。"},
100
+ {"role": "user", "content": input_text}
101
+ ]
102
+
103
+ try:
104
+ prompt = tokenizer.apply_chat_template(
105
+ messages,
106
+ tokenize=False,
107
+ add_generation_prompt=True
108
+ )
109
+ except Exception as e:
110
+ print(f"Error applying chat template: {e}")
111
+ # 如果模板应用失败,提供一个明确的错误信息
112
+ return f"错误:无法应用聊天模板。{e}"
113
+
114
+ print(f"Gradio App: Formatted prompt for model:\n{prompt}")
115
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(device)
116
+
117
+ # 生成时禁用梯度计算以节省资源
118
+ # Disable gradient calculations during generation to save resources
119
+ with torch.no_grad():
120
+ generated_ids = model.generate(
121
+ **inputs,
122
+ max_new_tokens=512, # 减少最大生成长度以加快响应
123
+ do_sample=True,
124
+ temperature=0.7,
125
+ top_p=0.95,
126
+ pad_token_id=tokenizer.eos_token_id
127
+ )
128
+
129
+ # 从生成结果中提取回复
130
+ # Extract the reply from the generated result
131
+ response_ids = generated_ids[0][inputs.input_ids.shape[-1]:]
132
+ result = tokenizer.decode(response_ids, skip_special_tokens=True).strip()
133
+
134
+ print(f"Gradio App: Extracted result: {result}")
135
+ return result
136
+
137
+ # --- 创建Gradio界面 (Create Gradio Interface) ---
138
+ iface = gr.Interface(
139
+ fn=chat,
140
+ inputs=gr.Textbox(lines=5, label="输入书面文本 (Input Formal Text)"),
141
+ outputs=gr.Textbox(lines=5, label="输出口语化文本 (Output Casual Text)"),
142
+ title="文本风格转换器 (Text Style Converter)",
143
+ description="输入一段书面化的中文文本,模型会尝试将其转换为更自然、口语化的表达方式。由Qwen-0.5B模型微调。(已优化速度)",
144
+ examples=[
145
+ ["乙醇的检测方法包括以下几项: 1. 酸碱度检查:取20ml乙醇加20ml水,加2滴酚酞指示剂应无色,再加1ml 0.01mol/L氢氧化钠应显粉红色."],
146
+ ["本公司今日发布了最新的财务业绩报告,数据显示本季度利润实现了显著增长。"]
147
+ ],
148
+ allow_flagging="never" # 禁用flagging以简化界面
149
+ )
150
+
151
+ if __name__ == "__main__":
152
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ accelerate
4
+ peft
5
+ gradio
6
+ bitsandbytes # 如果您的基础Qwen模型加载时或PEFT需要,请取消注释
7
+ sentencepiece # Qwen tokenizer 可能需要