Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,16 +2,17 @@ import gradio as gr
|
|
| 2 |
import torch
|
| 3 |
import os
|
| 4 |
import logging
|
|
|
|
|
|
|
|
|
|
| 5 |
from datetime import datetime
|
| 6 |
from huggingface_hub import HfApi
|
| 7 |
from transformers import AutoConfig, AutoModel, AutoTokenizer
|
| 8 |
from optimum.onnxruntime import ORTQuantizer, ORTModelForCausalLM
|
| 9 |
from optimum.onnxruntime.configuration import AutoQuantizationConfig
|
| 10 |
-
from optimum.exporters.onnx import main_export
|
|
|
|
| 11 |
import torch.nn.utils.prune as prune
|
| 12 |
-
import time
|
| 13 |
-
|
| 14 |
-
# --- 1. SETUP AND CONFIGURATION ---
|
| 15 |
|
| 16 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 17 |
|
|
@@ -23,13 +24,10 @@ api = HfApi()
|
|
| 23 |
OUTPUT_DIR = "optimized_models"
|
| 24 |
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 25 |
|
| 26 |
-
|
| 27 |
-
# --- 2. AMOP CORE PIPELINE FUNCTIONS (Logic is the same) ---
|
| 28 |
-
|
| 29 |
def stage_1_analyze_model(model_id: str):
|
| 30 |
log_stream = "[STAGE 1] Analyzing model...\n"
|
| 31 |
try:
|
| 32 |
-
config = AutoConfig.from_pretrained(model_id, trust_remote_code=True)
|
| 33 |
model_type = config.model_type
|
| 34 |
|
| 35 |
analysis_report = f"""
|
|
@@ -39,13 +37,12 @@ def stage_1_analyze_model(model_id: str):
|
|
| 39 |
"""
|
| 40 |
|
| 41 |
recommendation = ""
|
| 42 |
-
if 'llama' in model_type or 'gpt' in model_type or 'mistral' in model_type:
|
| 43 |
-
recommendation = "**Recommendation:** This is a
|
| 44 |
else:
|
| 45 |
-
recommendation = "**Recommendation:** This is an encoder model
|
| 46 |
|
| 47 |
log_stream += f"Analysis complete. Architecture: {model_type}.\n"
|
| 48 |
-
## UI/UX UPDATE ##: Return an open Accordion instead of a visible Group
|
| 49 |
return log_stream, analysis_report + "\n" + recommendation, gr.Accordion(open=True)
|
| 50 |
except Exception as e:
|
| 51 |
error_msg = f"Failed to analyze model '{model_id}'. Error: {e}"
|
|
@@ -60,21 +57,39 @@ def stage_2_prune_model(model, prune_percentage: float):
|
|
| 60 |
if isinstance(module, torch.nn.Linear):
|
| 61 |
prune.l1_unstructured(module, name='weight', amount=prune_percentage / 100.0)
|
| 62 |
prune.remove(module, 'weight')
|
| 63 |
-
log_stream += f"Pruning complete
|
| 64 |
return model, log_stream
|
| 65 |
|
| 66 |
-
def
|
| 67 |
log_stream = "[STAGE 3 & 4] Converting to ONNX and Quantizing...\n"
|
| 68 |
try:
|
| 69 |
run_id = datetime.now().strftime("%Y%m%d-%H%M%S")
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
| 72 |
log_stream += f"Successfully exported base model to ONNX at: {onnx_path}\n"
|
| 73 |
|
| 74 |
quantizer = ORTQuantizer.from_pretrained(onnx_path)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
log_stream += f"Successfully quantized model to: {quantized_path}\n"
|
| 79 |
return quantized_path, log_stream
|
| 80 |
except Exception as e:
|
|
@@ -82,41 +97,58 @@ def stage_3_and_4_quantize_and_onnx(model_id: str):
|
|
| 82 |
logging.error(error_msg, exc_info=True)
|
| 83 |
raise RuntimeError(error_msg)
|
| 84 |
|
| 85 |
-
def
|
| 86 |
-
log_stream = "[STAGE
|
| 87 |
try:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
ms_per_token = latency / num_tokens if num_tokens > 0 else float('inf')
|
| 98 |
-
eval_report = f"- **Inference Latency:** {latency:.2f} ms\n- **Speed:** {ms_per_token:.2f} ms/token\n"
|
| 99 |
-
log_stream += "Evaluation complete.\n"
|
| 100 |
except Exception as e:
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
| 103 |
|
|
|
|
|
|
|
| 104 |
if not HF_TOKEN:
|
| 105 |
return "Skipping upload: HF_TOKEN not found.", log_stream + "Skipping upload: HF_TOKEN not found."
|
|
|
|
| 106 |
try:
|
| 107 |
-
repo_name = f"{model_id.split('/')[-1]}-amop-cpu"
|
| 108 |
repo_url = api.create_repo(repo_id=repo_name, exist_ok=True, token=HF_TOKEN)
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
model_card_content = template_content.format(
|
| 111 |
repo_name=repo_name, model_id=model_id, optimization_date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 112 |
-
|
| 113 |
-
pruning_percent=options
|
|
|
|
|
|
|
| 114 |
)
|
| 115 |
readme_path = os.path.join(optimized_model_path, "README.md")
|
| 116 |
-
with open(readme_path, "w", encoding="utf-8") as f:
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
api.upload_folder(folder_path=optimized_model_path, repo_id=repo_url.repo_id, repo_type="model", token=HF_TOKEN)
|
|
|
|
| 120 |
final_message = f"Success! Your optimized model is available at: huggingface.co/{repo_url.repo_id}"
|
| 121 |
log_stream += "Upload complete.\n"
|
| 122 |
return final_message, log_stream
|
|
@@ -125,78 +157,91 @@ def stage_5_evaluate_and_package(model_id: str, optimized_model_path: str, pipel
|
|
| 125 |
logging.error(error_msg, exc_info=True)
|
| 126 |
return f"Error: {error_msg}", log_stream + error_msg
|
| 127 |
|
| 128 |
-
|
| 129 |
-
# --- 3. MAIN WORKFLOW GENERATOR (HEAVILY UPDATED FOR UI/UX) ---
|
| 130 |
-
|
| 131 |
-
def run_amop_pipeline(model_id: str, do_prune: bool, prune_percent: float):
|
| 132 |
if not model_id:
|
| 133 |
yield {log_output: "Please enter a Model ID.", final_output: gr.Label(value="Idle", label="Status")}
|
| 134 |
return
|
| 135 |
|
| 136 |
-
|
| 137 |
-
# This provides immediate feedback that the process has started.
|
| 138 |
-
initial_log = "[START] AMOP Pipeline Initiated.\n"
|
| 139 |
yield {
|
| 140 |
run_button: gr.Button(interactive=False, value="π Running..."),
|
| 141 |
analyze_button: gr.Button(interactive=False),
|
| 142 |
-
final_output: gr.Label(value={"label": "RUNNING
|
| 143 |
log_output: initial_log
|
| 144 |
}
|
| 145 |
|
| 146 |
full_log = initial_log
|
|
|
|
| 147 |
try:
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
|
|
|
| 171 |
full_log += log
|
| 172 |
|
| 173 |
-
# Final Step: Done
|
| 174 |
yield {
|
| 175 |
-
final_output: gr.Label(value=
|
| 176 |
log_output: full_log,
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
analyze_button: gr.Button(interactive=True, value="1. Analyze Model")
|
| 181 |
}
|
| 182 |
|
| 183 |
except Exception as e:
|
| 184 |
logging.error(f"AMOP Pipeline failed. Error: {e}", exc_info=True)
|
| 185 |
full_log += f"\n[ERROR] Pipeline failed: {e}"
|
| 186 |
yield {
|
| 187 |
-
final_output: gr.Label(value=
|
| 188 |
log_output: full_log,
|
| 189 |
success_box: gr.Markdown(f"β **An error occurred.** Check the logs for details.", visible=True),
|
| 190 |
-
run_button: gr.Button(interactive=True, value="
|
| 191 |
-
analyze_button: gr.Button(interactive=True, value="
|
| 192 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
with gr.Blocks() as demo:
|
| 198 |
gr.Markdown("# π AMOP: Adaptive Model Optimization Pipeline")
|
| 199 |
-
gr.Markdown("Turn any Hugging Face Hub model into a CPU-optimized
|
| 200 |
|
| 201 |
if not HF_TOKEN:
|
| 202 |
gr.Warning("You have not set your HF_TOKEN in the Space secrets! The final 'upload' step will be skipped. Please add a secret with the key `HF_TOKEN` and your Hugging Face write token as the value.")
|
|
@@ -206,27 +251,53 @@ with gr.Blocks() as demo:
|
|
| 206 |
gr.Markdown("### 1. Select a Model")
|
| 207 |
model_id_input = gr.Textbox(
|
| 208 |
label="Hugging Face Model ID",
|
| 209 |
-
placeholder="e.g., gpt2,
|
| 210 |
-
info="Enter the ID of a model from the Hub."
|
| 211 |
)
|
| 212 |
analyze_button = gr.Button("π Analyze Model", variant="secondary")
|
| 213 |
|
| 214 |
-
## UI/UX UPDATE ##: Use an Accordion. It's closed by default, keeping the UI clean.
|
| 215 |
with gr.Accordion("βοΈ 2. Configure Optimization", open=False) as optimization_accordion:
|
| 216 |
analysis_report_output = gr.Markdown()
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
with gr.Column(scale=2):
|
| 222 |
gr.Markdown("### Pipeline Status & Logs")
|
| 223 |
-
## UI/UX UPDATE ##: Use gr.Label for a clean, prominent status indicator.
|
| 224 |
final_output = gr.Label(value="Idle", label="Status", show_label=True)
|
| 225 |
-
## UI/UX UPDATE ##: Add a dedicated box for the final success/error message.
|
| 226 |
success_box = gr.Markdown(visible=False)
|
| 227 |
log_output = gr.Textbox(label="Live Logs", lines=20, interactive=False, max_lines=20)
|
| 228 |
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
analyze_button.click(
|
| 231 |
fn=stage_1_analyze_model,
|
| 232 |
inputs=[model_id_input],
|
|
@@ -235,7 +306,7 @@ with gr.Blocks() as demo:
|
|
| 235 |
|
| 236 |
run_button.click(
|
| 237 |
fn=run_amop_pipeline,
|
| 238 |
-
inputs=[model_id_input, prune_checkbox, prune_slider],
|
| 239 |
outputs=[run_button, analyze_button, final_output, log_output, success_box]
|
| 240 |
)
|
| 241 |
|
|
|
|
| 2 |
import torch
|
| 3 |
import os
|
| 4 |
import logging
|
| 5 |
+
import time
|
| 6 |
+
import tempfile
|
| 7 |
+
import shutil
|
| 8 |
from datetime import datetime
|
| 9 |
from huggingface_hub import HfApi
|
| 10 |
from transformers import AutoConfig, AutoModel, AutoTokenizer
|
| 11 |
from optimum.onnxruntime import ORTQuantizer, ORTModelForCausalLM
|
| 12 |
from optimum.onnxruntime.configuration import AutoQuantizationConfig
|
| 13 |
+
from optimum.exporters.onnx import main_export as onnx_export
|
| 14 |
+
from optimum.exporters.gguf import main_export as gguf_export
|
| 15 |
import torch.nn.utils.prune as prune
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 18 |
|
|
|
|
| 24 |
OUTPUT_DIR = "optimized_models"
|
| 25 |
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 26 |
|
|
|
|
|
|
|
|
|
|
| 27 |
def stage_1_analyze_model(model_id: str):
|
| 28 |
log_stream = "[STAGE 1] Analyzing model...\n"
|
| 29 |
try:
|
| 30 |
+
config = AutoConfig.from_pretrained(model_id, trust_remote_code=True, token=HF_TOKEN)
|
| 31 |
model_type = config.model_type
|
| 32 |
|
| 33 |
analysis_report = f"""
|
|
|
|
| 37 |
"""
|
| 38 |
|
| 39 |
recommendation = ""
|
| 40 |
+
if 'llama' in model_type or 'gpt' in model_type or 'mistral' in model_type or 'gemma' in model_type:
|
| 41 |
+
recommendation = "**Recommendation:** This is a Large Language Model (LLM). For the best CPU performance and community support, the **GGUF Pipeline** is highly recommended. The ONNX pipeline is a viable alternative."
|
| 42 |
else:
|
| 43 |
+
recommendation = "**Recommendation:** This is likely an encoder model. The **ONNX Pipeline** is recommended. Pruning may offer size reduction, but its impact on performance can vary."
|
| 44 |
|
| 45 |
log_stream += f"Analysis complete. Architecture: {model_type}.\n"
|
|
|
|
| 46 |
return log_stream, analysis_report + "\n" + recommendation, gr.Accordion(open=True)
|
| 47 |
except Exception as e:
|
| 48 |
error_msg = f"Failed to analyze model '{model_id}'. Error: {e}"
|
|
|
|
| 57 |
if isinstance(module, torch.nn.Linear):
|
| 58 |
prune.l1_unstructured(module, name='weight', amount=prune_percentage / 100.0)
|
| 59 |
prune.remove(module, 'weight')
|
| 60 |
+
log_stream += f"Pruning complete with {prune_percentage}% target.\n"
|
| 61 |
return model, log_stream
|
| 62 |
|
| 63 |
+
def stage_3_4_onnx_quantize(model_path: str, calibration_data_path: str):
|
| 64 |
log_stream = "[STAGE 3 & 4] Converting to ONNX and Quantizing...\n"
|
| 65 |
try:
|
| 66 |
run_id = datetime.now().strftime("%Y%m%d-%H%M%S")
|
| 67 |
+
model_name = os.path.basename(model_path)
|
| 68 |
+
onnx_path = os.path.join(OUTPUT_DIR, f"{model_name}-{run_id}-onnx")
|
| 69 |
+
|
| 70 |
+
onnx_export(model_path, output=onnx_path, task="auto", trust_remote_code=True)
|
| 71 |
log_stream += f"Successfully exported base model to ONNX at: {onnx_path}\n"
|
| 72 |
|
| 73 |
quantizer = ORTQuantizer.from_pretrained(onnx_path)
|
| 74 |
+
|
| 75 |
+
if calibration_data_path:
|
| 76 |
+
log_stream += "Performing STATIC quantization with user-provided calibration data.\n"
|
| 77 |
+
dqconfig = AutoQuantizationConfig.avx512_vnni(is_static=True, per_channel=False)
|
| 78 |
+
from datasets import load_dataset
|
| 79 |
+
calibration_dataset = quantizer.get_calibration_dataset(
|
| 80 |
+
"text",
|
| 81 |
+
dataset_args={"path": calibration_data_path, "split": "train"},
|
| 82 |
+
num_samples=100,
|
| 83 |
+
dataset_num_proc=1,
|
| 84 |
+
)
|
| 85 |
+
quantized_path = os.path.join(onnx_path, "quantized-static")
|
| 86 |
+
quantizer.quantize(save_dir=quantized_path, quantization_config=dqconfig, calibration_dataset=calibration_dataset)
|
| 87 |
+
else:
|
| 88 |
+
log_stream += "Performing DYNAMIC quantization.\n"
|
| 89 |
+
dqconfig = AutoQuantizationConfig.avx512_vnni(is_static=False, per_channel=False)
|
| 90 |
+
quantized_path = os.path.join(onnx_path, "quantized-dynamic")
|
| 91 |
+
quantizer.quantize(save_dir=quantized_path, quantization_config=dqconfig)
|
| 92 |
+
|
| 93 |
log_stream += f"Successfully quantized model to: {quantized_path}\n"
|
| 94 |
return quantized_path, log_stream
|
| 95 |
except Exception as e:
|
|
|
|
| 97 |
logging.error(error_msg, exc_info=True)
|
| 98 |
raise RuntimeError(error_msg)
|
| 99 |
|
| 100 |
+
def stage_3_4_gguf_quantize(model_id: str, quantization_strategy: str):
|
| 101 |
+
log_stream = f"[STAGE 3 & 4] Converting to GGUF with '{quantization_strategy}' quantization...\n"
|
| 102 |
try:
|
| 103 |
+
run_id = datetime.now().strftime("%Y%m%d-%H%M%S")
|
| 104 |
+
model_name = model_id.replace('/', '_')
|
| 105 |
+
gguf_path = os.path.join(OUTPUT_DIR, f"{model_name}-{run_id}-gguf")
|
| 106 |
+
os.makedirs(gguf_path, exist_ok=True)
|
| 107 |
+
|
| 108 |
+
gguf_export(model_id, output=os.path.join(gguf_path, "model.gguf"), quantization_strategy=quantization_strategy, trust_remote_code=True)
|
| 109 |
+
|
| 110 |
+
log_stream += f"Successfully exported and quantized model to GGUF at: {gguf_path}\n"
|
| 111 |
+
return gguf_path, log_stream
|
|
|
|
|
|
|
|
|
|
| 112 |
except Exception as e:
|
| 113 |
+
error_msg = f"Failed during GGUF conversion. Error: {e}"
|
| 114 |
+
logging.error(error_msg, exc_info=True)
|
| 115 |
+
raise RuntimeError(error_msg)
|
| 116 |
+
|
| 117 |
|
| 118 |
+
def stage_5_package_and_upload(model_id: str, optimized_model_path: str, pipeline_log: str, options: dict):
|
| 119 |
+
log_stream = "[STAGE 5] Packaging and Uploading...\n"
|
| 120 |
if not HF_TOKEN:
|
| 121 |
return "Skipping upload: HF_TOKEN not found.", log_stream + "Skipping upload: HF_TOKEN not found."
|
| 122 |
+
|
| 123 |
try:
|
| 124 |
+
repo_name = f"{model_id.split('/')[-1]}-amop-cpu-{options['pipeline_type'].lower()}"
|
| 125 |
repo_url = api.create_repo(repo_id=repo_name, exist_ok=True, token=HF_TOKEN)
|
| 126 |
+
|
| 127 |
+
if options['pipeline_type'] == "GGUF":
|
| 128 |
+
template_file = "model_card_template_gguf.md"
|
| 129 |
+
else:
|
| 130 |
+
template_file = "model_card_template.md"
|
| 131 |
+
|
| 132 |
+
with open(template_file, "r", encoding="utf-8") as f:
|
| 133 |
+
template_content = f.read()
|
| 134 |
+
|
| 135 |
model_card_content = template_content.format(
|
| 136 |
repo_name=repo_name, model_id=model_id, optimization_date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 137 |
+
pruning_status="Enabled" if options.get('prune', False) else "Disabled",
|
| 138 |
+
pruning_percent=options.get('prune_percent', 0),
|
| 139 |
+
quant_type=options.get('quant_type', 'N/A'),
|
| 140 |
+
repo_id=repo_url.repo_id, pipeline_log=pipeline_log
|
| 141 |
)
|
| 142 |
readme_path = os.path.join(optimized_model_path, "README.md")
|
| 143 |
+
with open(readme_path, "w", encoding="utf-8") as f:
|
| 144 |
+
f.write(model_card_content)
|
| 145 |
+
|
| 146 |
+
if options['pipeline_type'] == "ONNX":
|
| 147 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 148 |
+
tokenizer.save_pretrained(optimized_model_path)
|
| 149 |
+
|
| 150 |
api.upload_folder(folder_path=optimized_model_path, repo_id=repo_url.repo_id, repo_type="model", token=HF_TOKEN)
|
| 151 |
+
|
| 152 |
final_message = f"Success! Your optimized model is available at: huggingface.co/{repo_url.repo_id}"
|
| 153 |
log_stream += "Upload complete.\n"
|
| 154 |
return final_message, log_stream
|
|
|
|
| 157 |
logging.error(error_msg, exc_info=True)
|
| 158 |
return f"Error: {error_msg}", log_stream + error_msg
|
| 159 |
|
| 160 |
+
def run_amop_pipeline(model_id: str, pipeline_type: str, do_prune: bool, prune_percent: float, onnx_quant_type: str, calibration_file, gguf_quant_type: str):
|
|
|
|
|
|
|
|
|
|
| 161 |
if not model_id:
|
| 162 |
yield {log_output: "Please enter a Model ID.", final_output: gr.Label(value="Idle", label="Status")}
|
| 163 |
return
|
| 164 |
|
| 165 |
+
initial_log = f"[START] AMOP {pipeline_type} Pipeline Initiated.\n"
|
|
|
|
|
|
|
| 166 |
yield {
|
| 167 |
run_button: gr.Button(interactive=False, value="π Running..."),
|
| 168 |
analyze_button: gr.Button(interactive=False),
|
| 169 |
+
final_output: gr.Label(value={"label": f"RUNNING ({pipeline_type})"}, show_label=True),
|
| 170 |
log_output: initial_log
|
| 171 |
}
|
| 172 |
|
| 173 |
full_log = initial_log
|
| 174 |
+
temp_model_dir = None
|
| 175 |
try:
|
| 176 |
+
repo_name_suffix = f"-amop-cpu-{pipeline_type.lower()}"
|
| 177 |
+
repo_id_for_link = f"{api.whoami()['name']}/{model_id.split('/')[-1]}{repo_name_suffix}"
|
| 178 |
+
|
| 179 |
+
if pipeline_type == "ONNX":
|
| 180 |
+
full_log += "Loading base model for pruning...\n"
|
| 181 |
+
yield {final_output: gr.Label(value="Loading model (1/5)"), log_output: full_log}
|
| 182 |
+
model = AutoModel.from_pretrained(model_id, trust_remote_code=True)
|
| 183 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 184 |
+
full_log += f"Successfully loaded base model '{model_id}'.\n"
|
| 185 |
+
|
| 186 |
+
yield {final_output: gr.Label(value="Pruning model (2/5)"), log_output: full_log}
|
| 187 |
+
if do_prune:
|
| 188 |
+
model, log = stage_2_prune_model(model, prune_percent)
|
| 189 |
+
full_log += log
|
| 190 |
+
else:
|
| 191 |
+
full_log += "[STAGE 2] Pruning skipped by user.\n"
|
| 192 |
+
|
| 193 |
+
temp_model_dir = tempfile.mkdtemp()
|
| 194 |
+
model.save_pretrained(temp_model_dir)
|
| 195 |
+
tokenizer.save_pretrained(temp_model_dir)
|
| 196 |
+
full_log += f"Saved intermediate model to temporary directory: {temp_model_dir}\n"
|
| 197 |
|
| 198 |
+
yield {final_output: gr.Label(value="Converting to ONNX (3/5)"), log_output: full_log}
|
| 199 |
+
calib_path = calibration_file.name if onnx_quant_type == "Static" and calibration_file else None
|
| 200 |
+
optimized_path, log = stage_3_4_onnx_quantize(temp_model_dir, calib_path)
|
| 201 |
+
full_log += log
|
| 202 |
+
options = {'pipeline_type': 'ONNX', 'prune': do_prune, 'prune_percent': prune_percent, 'quant_type': onnx_quant_type}
|
| 203 |
+
|
| 204 |
+
elif pipeline_type == "GGUF":
|
| 205 |
+
full_log += "[STAGE 1 & 2] Loading and Pruning are skipped for GGUF pipeline.\n"
|
| 206 |
+
yield {final_output: gr.Label(value="Converting to GGUF (3/5)"), log_output: full_log}
|
| 207 |
+
optimized_path, log = stage_3_4_gguf_quantize(model_id, gguf_quant_type)
|
| 208 |
+
full_log += log
|
| 209 |
+
options = {'pipeline_type': 'GGUF', 'quant_type': gguf_quant_type}
|
| 210 |
|
| 211 |
+
else:
|
| 212 |
+
raise ValueError("Invalid pipeline type selected.")
|
| 213 |
+
|
| 214 |
+
yield {final_output: gr.Label(value="Packaging & Uploading (4/5)"), log_output: full_log}
|
| 215 |
+
final_message, log = stage_5_package_and_upload(model_id, optimized_path, full_log, options)
|
| 216 |
full_log += log
|
| 217 |
|
|
|
|
| 218 |
yield {
|
| 219 |
+
final_output: gr.Label(value="SUCCESS", label="Status"),
|
| 220 |
log_output: full_log,
|
| 221 |
+
success_box: gr.Markdown(f"β
**Success!** Your optimized model is available here: [{repo_id_for_link}](https://huggingface.co/{repo_id_for_link})", visible=True),
|
| 222 |
+
run_button: gr.Button(interactive=True, value="Run Optimization Pipeline", variant="primary"),
|
| 223 |
+
analyze_button: gr.Button(interactive=True, value="Analyze Model")
|
|
|
|
| 224 |
}
|
| 225 |
|
| 226 |
except Exception as e:
|
| 227 |
logging.error(f"AMOP Pipeline failed. Error: {e}", exc_info=True)
|
| 228 |
full_log += f"\n[ERROR] Pipeline failed: {e}"
|
| 229 |
yield {
|
| 230 |
+
final_output: gr.Label(value="ERROR", label="Status"),
|
| 231 |
log_output: full_log,
|
| 232 |
success_box: gr.Markdown(f"β **An error occurred.** Check the logs for details.", visible=True),
|
| 233 |
+
run_button: gr.Button(interactive=True, value="Run Optimization Pipeline", variant="primary"),
|
| 234 |
+
analyze_button: gr.Button(interactive=True, value="Analyze Model")
|
| 235 |
}
|
| 236 |
+
finally:
|
| 237 |
+
if temp_model_dir and os.path.exists(temp_model_dir):
|
| 238 |
+
shutil.rmtree(temp_model_dir)
|
| 239 |
+
logging.info(f"Cleaned up temporary directory: {temp_model_dir}")
|
| 240 |
|
| 241 |
|
| 242 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
|
|
|
|
|
| 243 |
gr.Markdown("# π AMOP: Adaptive Model Optimization Pipeline")
|
| 244 |
+
gr.Markdown("Turn any Hugging Face Hub model into a CPU-optimized version using ONNX or GGUF.")
|
| 245 |
|
| 246 |
if not HF_TOKEN:
|
| 247 |
gr.Warning("You have not set your HF_TOKEN in the Space secrets! The final 'upload' step will be skipped. Please add a secret with the key `HF_TOKEN` and your Hugging Face write token as the value.")
|
|
|
|
| 251 |
gr.Markdown("### 1. Select a Model")
|
| 252 |
model_id_input = gr.Textbox(
|
| 253 |
label="Hugging Face Model ID",
|
| 254 |
+
placeholder="e.g., gpt2, meta-llama/Llama-2-7b-chat-hf",
|
|
|
|
| 255 |
)
|
| 256 |
analyze_button = gr.Button("π Analyze Model", variant="secondary")
|
| 257 |
|
|
|
|
| 258 |
with gr.Accordion("βοΈ 2. Configure Optimization", open=False) as optimization_accordion:
|
| 259 |
analysis_report_output = gr.Markdown()
|
| 260 |
+
|
| 261 |
+
pipeline_type_radio = gr.Radio(
|
| 262 |
+
["ONNX", "GGUF"], label="Select Optimization Pipeline", info="GGUF is recommended for LLMs, ONNX for others."
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
with gr.Group(visible=False) as onnx_options:
|
| 266 |
+
gr.Markdown("#### ONNX Pipeline Options")
|
| 267 |
+
prune_checkbox = gr.Checkbox(label="Enable Pruning", value=False, info="Removes redundant weights. Applied before ONNX conversion.")
|
| 268 |
+
prune_slider = gr.Slider(minimum=0, maximum=90, value=20, step=5, label="Pruning Percentage (%)")
|
| 269 |
+
onnx_quant_radio = gr.Radio(["Dynamic", "Static"], label="ONNX Quantization Type", value="Dynamic", info="Static may offer better performance but requires calibration data.")
|
| 270 |
+
calibration_file_upload = gr.File(label="Upload Calibration Data (.txt)", visible=False, file_types=['.txt'])
|
| 271 |
+
|
| 272 |
+
with gr.Group(visible=False) as gguf_options:
|
| 273 |
+
gr.Markdown("#### GGUF Pipeline Options")
|
| 274 |
+
gguf_quant_dropdown = gr.Dropdown(
|
| 275 |
+
["q4_k_m", "q5_k_m", "q8_0", "f16"],
|
| 276 |
+
label="GGUF Quantization Strategy",
|
| 277 |
+
value="q4_k_m",
|
| 278 |
+
info="q4_k_m is a good balance of size and quality."
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
run_button = gr.Button("π Run Optimization Pipeline", variant="primary")
|
| 282 |
|
| 283 |
with gr.Column(scale=2):
|
| 284 |
gr.Markdown("### Pipeline Status & Logs")
|
|
|
|
| 285 |
final_output = gr.Label(value="Idle", label="Status", show_label=True)
|
|
|
|
| 286 |
success_box = gr.Markdown(visible=False)
|
| 287 |
log_output = gr.Textbox(label="Live Logs", lines=20, interactive=False, max_lines=20)
|
| 288 |
|
| 289 |
+
def update_ui_for_pipeline(pipeline_type):
|
| 290 |
+
return {
|
| 291 |
+
onnx_options: gr.Group(visible=pipeline_type == "ONNX"),
|
| 292 |
+
gguf_options: gr.Group(visible=pipeline_type == "GGUF")
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
def update_ui_for_quant_type(quant_type):
|
| 296 |
+
return gr.File(visible=quant_type == "Static")
|
| 297 |
+
|
| 298 |
+
pipeline_type_radio.change(fn=update_ui_for_pipeline, inputs=pipeline_type_radio, outputs=[onnx_options, gguf_options])
|
| 299 |
+
onnx_quant_radio.change(fn=update_ui_for_quant_type, inputs=onnx_quant_radio, outputs=[calibration_file_upload])
|
| 300 |
+
|
| 301 |
analyze_button.click(
|
| 302 |
fn=stage_1_analyze_model,
|
| 303 |
inputs=[model_id_input],
|
|
|
|
| 306 |
|
| 307 |
run_button.click(
|
| 308 |
fn=run_amop_pipeline,
|
| 309 |
+
inputs=[model_id_input, pipeline_type_radio, prune_checkbox, prune_slider, onnx_quant_radio, calibration_file_upload, gguf_quant_dropdown],
|
| 310 |
outputs=[run_button, analyze_button, final_output, log_output, success_box]
|
| 311 |
)
|
| 312 |
|