Steven10429 commited on
Commit
260542b
·
1 Parent(s): 6e2ff33
Files changed (4) hide show
  1. README.md +65 -1
  2. app.py +280 -50
  3. app.py.bk +64 -0
  4. requirements.txt +9 -1
README.md CHANGED
@@ -11,4 +11,68 @@ license: mit
11
  short_description: apply_lora_and_quantize
12
  ---
13
 
14
- An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  short_description: apply_lora_and_quantize
12
  ---
13
 
14
+ An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
15
+
16
+ # Model Converter for HuggingFace
17
+
18
+ A powerful tool for converting and quantizing Large Language Models (LLMs) with LoRA adapters.
19
+
20
+ ## Features
21
+
22
+ - 🚀 Automatic system resource detection (CPU/GPU)
23
+ - 🔄 Merge base models with LoRA adapters
24
+ - 📊 Support for 4-bit and 8-bit quantization
25
+ - ☁️ Automatic upload to HuggingFace Hub
26
+
27
+ ## Requirements
28
+
29
+ - Python 3.8+
30
+ - CUDA compatible GPU (optional, but recommended)
31
+ - HuggingFace account and token
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pip install -r requirements.txt
37
+ ```
38
+
39
+ ## Configuration
40
+
41
+ Create a `.env` file in the project root:
42
+ ```
43
+ HF_TOKEN=your_huggingface_token
44
+ ```
45
+
46
+ ## Usage
47
+
48
+ Run the script:
49
+ ```bash
50
+ python space_convert.py
51
+ ```
52
+
53
+ You will be prompted to enter:
54
+ 1. Base model path (e.g., "Qwen/Qwen2.5-7B-Instruct")
55
+ 2. LoRA model path
56
+ 3. Target HuggingFace repository name
57
+
58
+ The script will:
59
+ 1. Check available system resources
60
+ 2. Choose the optimal device (GPU/CPU)
61
+ 3. Merge the base model with LoRA
62
+ 4. Create 8-bit and 4-bit quantized versions
63
+ 5. Upload everything to HuggingFace
64
+
65
+ ## Memory Requirements
66
+
67
+ - 7B models: ~16GB RAM/VRAM
68
+ - 14B models: ~32GB RAM/VRAM
69
+ - Additional disk space: 3x model size
70
+
71
+ ## Note
72
+
73
+ The script automatically handles:
74
+ - Resource availability checks
75
+ - Device selection
76
+ - Error handling
77
+ - Progress tracking
78
+ - Model optimization
app.py CHANGED
@@ -1,64 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
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 os
2
+ import torch
3
+ import psutil
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
5
+ from peft import PeftModel, PeftConfig
6
+ from pathlib import Path
7
+ from tqdm import tqdm
8
+ from huggingface_hub import login, create_repo, HfApi
9
+ import subprocess
10
+ import math
11
+ from dotenv import load_dotenv
12
  import gradio as gr
13
+ import threading
14
+ import queue
15
+ import time
16
 
17
+ # 创建一个队列用于存储日志消息
18
+ log_queue = queue.Queue()
19
+ current_logs = []
 
20
 
21
+ def log(msg):
22
+ """统一的日志处理函数"""
23
+ print(msg)
24
+ current_logs.append(msg)
25
+ return "\n".join(current_logs)
26
 
27
+ def get_model_size_in_gb(model_name):
28
+ """估算模型大小(以GB为单位)"""
29
+ try:
30
+ config = AutoConfig.from_pretrained(model_name)
31
+ num_params = config.num_parameters if hasattr(config, 'num_parameters') else None
32
+
33
+ if num_params is None:
34
+ # 手动计算参数量
35
+ if hasattr(config, 'num_hidden_layers') and hasattr(config, 'hidden_size'):
36
+ # 简单估算,可能不够准确
37
+ num_params = config.num_hidden_layers * config.hidden_size * config.hidden_size * 4
38
+
39
+ if num_params:
40
+ # 每个参数占用2字节(float16)
41
+ size_in_gb = (num_params * 2) / (1024 ** 3)
42
+ return size_in_gb
43
+ else:
44
+ # 如果无法计算,返回一个保守的估计
45
+ return 16 # 默认假设是7B模型
46
+ except Exception as e:
47
+ log(f"无法估算模型大小: {str(e)}")
48
+ return 16 # 默认返回16GB
49
 
50
+ def check_system_resources(model_name):
51
+ """检查系统资源并决定使用什么设备"""
52
+ log("正在检查系统资源...")
53
+
54
+ # 获取系统内存信息
55
+ system_memory = psutil.virtual_memory()
56
+ total_memory_gb = system_memory.total / (1024 ** 3)
57
+ available_memory_gb = system_memory.available / (1024 ** 3)
58
+
59
+ log(f"系统总内存: {total_memory_gb:.1f}GB")
60
+ log(f"可用内存: {available_memory_gb:.1f}GB")
61
+
62
+ # 估算模型所需内存
63
+ model_size_gb = get_model_size_in_gb(model_name)
64
+ required_memory_gb = model_size_gb * 2.5 # 需要额外的内存用于计算
65
+ log(f"估计模型需要内存: {required_memory_gb:.1f}GB")
66
+
67
+ # 检查CUDA是否可用
68
+ if torch.cuda.is_available():
69
+ gpu_name = torch.cuda.get_device_name(0)
70
+ gpu_memory_gb = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)
71
+ log(f"发现GPU: {gpu_name}")
72
+ log(f"GPU显存: {gpu_memory_gb:.1f}GB")
73
+
74
+ if gpu_memory_gb >= required_memory_gb:
75
+ log("✅ GPU显存足够,将使用GPU进行转换")
76
+ return "cuda", gpu_memory_gb
77
+ else:
78
+ log(f"⚠️ GPU显存不足 (需要 {required_memory_gb:.1f}GB, 实际 {gpu_memory_gb:.1f}GB)")
79
+ else:
80
+ log("❌ 未检测到可用的GPU")
81
+
82
+ # 检查CPU内存是否足够
83
+ if available_memory_gb >= required_memory_gb:
84
+ log("✅ CPU内存足够,将使用CPU进行转换")
85
+ return "cpu", available_memory_gb
86
+ else:
87
+ raise MemoryError(f"❌ 系统内存不足 (需要 {required_memory_gb:.1f}GB, 可用 {available_memory_gb:.1f}GB)")
88
 
89
+ def setup_environment(model_name):
90
+ """设置环境并返回设备信息"""
91
+ load_dotenv()
92
+ hf_token = os.getenv('HF_TOKEN')
93
+ if not hf_token:
94
+ raise ValueError("请在环境变量中设置HF_TOKEN")
95
+ login(hf_token)
96
+
97
+ # 检查系统资源并决定使用什么设备
98
+ device, available_memory = check_system_resources(model_name)
99
+ return device
100
 
101
+ def create_hf_repo(repo_name, private=True):
102
+ """创建HuggingFace仓库"""
103
+ try:
104
+ repo_url = create_repo(repo_name, private=private)
105
+ log(f"创建仓库成功: {repo_url}")
106
+ return repo_url
107
+ except Exception as e:
108
+ log(f"创建仓库失败: {str(e)}")
109
+ raise
110
 
111
+ def download_and_merge_model(base_model_name, lora_model_name, output_dir, device):
112
+ log(f"正在加��基础模型: {base_model_name}")
113
+
114
+ try:
115
+ # 先加载原始模型
116
+ base_model = AutoModelForCausalLM.from_pretrained(
117
+ base_model_name,
118
+ torch_dtype=torch.float16,
119
+ device_map={"": device}
120
+ )
121
+
122
+ # 加载tokenizer
123
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name)
124
+
125
+ log(f"正在加载LoRA模型: {lora_model_name}")
126
+ log("基础模型配置:" + str(base_model.config))
127
+
128
+ # 加载adapter配置
129
+ adapter_config = PeftConfig.from_pretrained(lora_model_name)
130
+ log("Adapter配置:" + str(adapter_config))
131
+
132
+ model = PeftModel.from_pretrained(base_model, lora_model_name)
133
+ log("正在合并LoRA权重")
134
+ model = model.merge_and_unload()
135
 
136
+ # 创建输出目录
137
+ output_path = Path(output_dir)
138
+ output_path.mkdir(parents=True, exist_ok=True)
139
 
140
+ # 保存合并后的模型
141
+ log(f"正在保存合并后的模型到: {output_dir}")
142
+ model.save_pretrained(output_dir)
143
+ tokenizer.save_pretrained(output_dir)
144
+
145
+ return output_dir
146
+
147
+ except Exception as e:
148
+ log(f"错误: {str(e)}")
149
+ log(f"错误类型: {type(e)}")
150
+ import traceback
151
+ log("详细错误信息:")
152
+ log(traceback.format_exc())
153
+ raise
154
 
155
+ def quantize_and_push_model(model_path, repo_id, bits=8):
156
+ """量化模型并推送到HuggingFace"""
157
+ try:
158
+ from optimum.bettertransformer import BetterTransformer
159
+ from transformers import AutoModelForCausalLM
160
+
161
+ log(f"正在加载模型用于{bits}位量化...")
162
+ model = AutoModelForCausalLM.from_pretrained(model_path)
163
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
164
+
165
+ # 转换为BetterTransformer格式
166
+ model = BetterTransformer.transform(model)
167
+
168
+ # 量化
169
+ if bits == 8:
170
+ from transformers import BitsAndBytesConfig
171
+ quantization_config = BitsAndBytesConfig(
172
+ load_in_8bit=True,
173
+ llm_int8_threshold=6.0
174
+ )
175
+ elif bits == 4:
176
+ from transformers import BitsAndBytesConfig
177
+ quantization_config = BitsAndBytesConfig(
178
+ load_in_4bit=True,
179
+ bnb_4bit_compute_dtype=torch.float16,
180
+ bnb_4bit_quant_type="nf4"
181
+ )
182
+ else:
183
+ raise ValueError(f"不支持的量化位数: {bits}")
184
+
185
+ # 保存量化后的模型
186
+ quantized_model_path = f"{model_path}_q{bits}"
187
+ model.save_pretrained(
188
+ quantized_model_path,
189
+ quantization_config=quantization_config
190
+ )
191
+ tokenizer.save_pretrained(quantized_model_path)
192
+
193
+ # 推送到HuggingFace
194
+ log(f"正在将{bits}位量化模型推送到HuggingFace...")
195
+ api = HfApi()
196
+ api.upload_folder(
197
+ folder_path=quantized_model_path,
198
+ repo_id=repo_id,
199
+ repo_type="model"
200
+ )
201
+ log(f"{bits}位量化模型上传完成")
202
+
203
+ except Exception as e:
204
+ log(f"量化或上传过程中出错: {str(e)}")
205
+ raise
206
 
207
+ def process_model(base_model, lora_model, repo_name, progress=gr.Progress()):
208
+ """处理模型的主函数,用于Gradio界面"""
209
+ try:
210
+ # 清空之前的日志
211
+ current_logs.clear()
212
+
213
+ # 设置环境和检查资源
214
+ device = setup_environment(base_model)
215
+
216
+ # 创建HuggingFace仓库
217
+ repo_url = create_hf_repo(repo_name)
218
+
219
+ # 设置输出目录
220
+ output_dir = os.path.join(".", "output", repo_name)
221
+
222
+ progress(0.1, desc="开始模型转换流程...")
223
+ # 下载并合并模型
224
+ model_path = download_and_merge_model(base_model, lora_model, output_dir, device)
225
+
226
+ progress(0.4, desc="开始8位量化...")
227
+ # 量化并上传模型
228
+ quantize_and_push_model(model_path, repo_name, bits=8)
229
+
230
+ progress(0.7, desc="开始4位量化...")
231
+ quantize_and_push_model(model_path, repo_name, bits=4)
232
+
233
+ final_message = f"全部完成!模型已上传至: https://huggingface.co/{repo_name}"
234
+ log(final_message)
235
+ progress(1.0, desc="处理完成")
236
+
237
+ return "\n".join(current_logs)
238
+ except Exception as e:
239
+ error_message = f"处理过程中出错: {str(e)}"
240
+ log(error_message)
241
+ return "\n".join(current_logs)
242
+
243
+ def create_ui():
244
+ """创建Gradio界面"""
245
+ with gr.Blocks(title="模型转换工具") as app:
246
+ gr.Markdown("""
247
+ # 🤗 模型转换与量化工具
248
+
249
+ 这个工具可以帮助你:
250
+ 1. 合并基础模型和LoRA适配器
251
+ 2. 创建4位和8位量化版本
252
+ 3. 自动上传到HuggingFace Hub
253
+ """)
254
+
255
+ with gr.Row():
256
+ with gr.Column():
257
+ base_model = gr.Textbox(
258
+ label="基础模型路径",
259
+ placeholder="例如: Qwen/Qwen2.5-7B-Instruct",
260
+ value="Qwen/Qwen2.5-7B-Instruct"
261
+ )
262
+ lora_model = gr.Textbox(
263
+ label="LoRA模型路径",
264
+ placeholder="输入你的LoRA模型路径"
265
+ )
266
+ repo_name = gr.Textbox(
267
+ label="HuggingFace仓库名称",
268
+ placeholder="输入要创建的仓库名称"
269
+ )
270
+ convert_btn = gr.Button("开始转换", variant="primary")
271
+
272
+ with gr.Column():
273
+ output = gr.TextArea(
274
+ label="处理日志",
275
+ placeholder="处理日志将在这里显示...",
276
+ interactive=False,
277
+ autoscroll=True,
278
+ lines=20
279
+ )
280
+
281
+ # 设置事件处理
282
+ convert_btn.click(
283
+ fn=process_model,
284
+ inputs=[base_model, lora_model, repo_name],
285
+ outputs=output
286
+ )
287
+
288
+ return app
289
 
290
  if __name__ == "__main__":
291
+ # 创建并启动Gradio界面
292
+ app = create_ui()
293
+ app.queue()
294
+ app.launch()
app.py.bk ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
requirements.txt CHANGED
@@ -1 +1,9 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
 
 
1
+ huggingface_hub==0.25.2
2
+ torch
3
+ transformers
4
+ peft
5
+ huggingface_hub
6
+ psutil
7
+ tqdm
8
+ python-dotenv
9
+ gradio