Repository navigation
Expand file tree
/
Copy pathexport_tab.py
More file actions
144 lines (121 loc) · 5.4 KB
/
Copy pathexport_tab.py
File metadata and controls
144 lines (121 loc) · 5.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""
export_tab.py - Model Export, Standalone Weights Merging & Ollama Deployment Studio.
Allows users to merge LoRA adapters into standalone models and export to Ollama / GGUF in 1 click.
"""
import os
import glob
import json
import gradio as gr
import merge_lora
import trainer_utils
def find_available_adapters():
adapters = []
if os.path.exists("output_qlora/final_adapter"):
adapters.append("output_qlora/final_adapter")
for p in glob.glob("runs/**/adapter_config.json", recursive=True):
parent = os.path.dirname(p)
if parent not in adapters:
adapters.append(parent)
return adapters if adapters else ["(No adapters found yet - train one first!)"]
def execute_merge(adapter_path, export_name, quant_choice):
if not adapter_path or "(No adapters" in adapter_path:
return "❌ Please select a valid adapter path first.", None, None
cfg_file = os.path.join(adapter_path, "adapter_config.json")
if not os.path.exists(cfg_file):
return f"❌ Missing adapter_config.json in {adapter_path}", None, None
trainer_utils.clear_gpu_memory()
out_dir = os.path.join("runs", "exported", export_name or "my_merged_model")
os.makedirs(out_dir, exist_ok=True)
try:
# 1. Merge into standalone weights
merge_lora.merge(adapter_path, out_dir)
abs_path = os.path.abspath(out_dir).replace("\\", "/")
# 2. Generate Ollama Modelfile
modelfile_content = f"""# Ollama Modelfile for {export_name}
FROM {abs_path}
TEMPLATE \"\"\"{{{{ if .System }}}}<|im_start|>system
{{{{ .System }}}}<|im_end|>
{{{{ end }}}}{{{{ if .Prompt }}}}<|im_start|>user
{{{{ .Prompt }}}}<|im_end|>
{{{{ end }}}}<|im_start|>assistant
{{{{ .Response }}}}<|im_end|>\"\"\"
PARAMETER stop "<|im_end|>"
PARAMETER stop "<|endoftext|>"
PARAMETER temperature 0.7
PARAMETER top_p 0.9
"""
modelfile_path = os.path.join(out_dir, "Modelfile")
with open(modelfile_path, "w", encoding="utf-8") as f:
f.write(modelfile_content)
# 3. Generate 1-click batch script for Ollama
run_bat_content = f"""@echo off
echo Importing {export_name} into Ollama...
ollama create {export_name} -f "%~dp0Modelfile"
if errorlevel 1 (
echo Error importing into Ollama. Make sure Ollama is installed and running.
pause
exit /b 1
)
echo.
echo Model successfully imported! Starting chat...
ollama run {export_name}
pause
"""
bat_path = os.path.join(out_dir, "run_in_ollama.bat")
with open(bat_path, "w", encoding="utf-8") as f:
f.write(run_bat_content)
success_msg = f"""### ✅ Model Successfully Exported!
- **Standalone 16-Bit Weights:** `{os.path.abspath(out_dir)}`
- **Ollama Modelfile Generated:** `{os.path.abspath(modelfile_path)}`
- **1-Click Ollama Launcher:** `{os.path.abspath(bat_path)}`
#### How to use with Ollama:
Double-click `{bat_path}` or run in terminal:
```powershell
ollama create {export_name} -f "{modelfile_path}"
ollama run {export_name}
```
"""
return success_msg, modelfile_content, bat_path
except Exception as e:
return f"❌ Error during model export: {str(e)}", None, None
def build_tab():
with gr.TabItem("📦 Export", id="export"):
gr.Markdown("### 📦 Export, Merge & Deploy Your Trained Models")
gr.Markdown("Turn fine-tuned LoRA adapters into standalone 16-bit models and generate 1-click **Ollama / LM Studio** packages.")
with gr.Row():
with gr.Column(scale=3):
adapter_choices = find_available_adapters()
adapter_dropdown = gr.Dropdown(
choices=adapter_choices,
value=adapter_choices[0] if adapter_choices else None,
label="Select Trained LoRA Adapter",
allow_custom_value=True
)
refresh_adapters_btn = gr.Button("🔄 Refresh Adapter List", size="sm")
export_name_input = gr.Textbox(
label="Export Model Name (e.g. for Ollama)",
value="my-custom-model"
)
export_format = gr.Radio(
choices=["Standalone 16-Bit (Safetensors) + Ollama Modelfile", "Standalone Weights Only"],
value="Standalone 16-Bit (Safetensors) + Ollama Modelfile",
label="Export Target"
)
merge_btn = gr.Button("🚀 Merge & Export Model", variant="primary")
with gr.Column(scale=3):
status_box = gr.Markdown("ℹ️ Select an adapter on the left and click **'Merge & Export Model'** to create deployment packages.")
modelfile_preview = gr.Code(label="Generated Ollama Modelfile", language="dockerfile", lines=8)
download_bat = gr.File(label="Download 1-Click Ollama Launcher (.bat)")
refresh_adapters_btn.click(
lambda: gr.update(choices=find_available_adapters()),
outputs=[adapter_dropdown]
)
merge_btn.click(
execute_merge,
inputs=[adapter_dropdown, export_name_input, export_format],
outputs=[status_box, modelfile_preview, download_bat]
)
return {
"adapter_dropdown": adapter_dropdown,
"merge_btn": merge_btn
}