import os import shutil import subprocess import signal os.environ["GRADIO_ANALYTICS_ENABLED"] = "False" import gradio as gr from huggingface_hub import HfApi from huggingface_hub import whoami from huggingface_hub import ModelCard from gradio_huggingfacehub_search import HuggingfaceHubSearch from apscheduler.schedulers.background import BackgroundScheduler from textwrap import dedent HF_TOKEN = os.environ.get("HF_TOKEN") class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def upload_reme_to_hf(model_id, lora_id, new_repo_id, api, oauth_token: gr.OAuthToken | None): try: card = ModelCard.load(model_id, token=oauth_token.token) except: card = ModelCard("") if card.data.tags is None: card.data.tags = [] card.data.tags.append("llama-cpp") card.data.tags.append("LoRA-GGUF") card.data.base_model = model_id card.text = dedent( f""" # {new_repo_id} This LoRA was converted to GGUF format from [`{lora_id}`](https://huggingface.co/{lora_id}) using llama.cpp.\n The base Model is [`{model_id}`](https://huggingface.co/{model_id}). ## Use with llama.cpp You can use the merged model via Ollama、LMStudio... ## Note The behavior may change depending on how it is quantized. """ ) card.save(f"README.md") api.upload_file( path_or_fileobj=f"README.md", path_in_repo=f"README.md", repo_id=new_repo_id, ) print(f"Uploaded successfully!") def upload_file_to_hf(upload_file_name, new_repo_id, api): try: print(f"Uploading: {upload_file_name}") api.upload_file( path_or_fileobj=upload_file_name, path_in_repo=upload_file_name, repo_id=new_repo_id, ) except Exception as e: raise Exception(f"Error uploading: {e}") def export_lora_to_gguf(model_fp16, lora_fp16, merged_name): script = f"./build/bin/llama-export-lora -m {model_fp16} -o {merged_name}-fp16.gguf --lora {lora_fp16}" export_result = subprocess.run(script, shell=True, capture_output=True) print(export_result) if export_result.returncode != 0: raise Exception(f"Error converting to fp16: {export_result.stderr}") print("LoRA converted to fp16 successfully!") print(f"Converted GGUF path: {merged_name}-fp16.gguf") return merged_name def quantize_merged_gguf(merged_fp16, method): script = f"./build/bin/llama-quantize {merged_fp16}-fp16.gguf {merged_fp16}-{method}.gguf {method}" quantize_result = subprocess.run(script, shell=True, capture_output=True) print(quantize_result) if quantize_result.returncode != 0: raise Exception(f"Error quantizing to {method}: {quantize_result.stderr}") print(f"Merged GGUF quantized to {method} successfully!") print(f"{method} GGUF file path: {merged_fp16}-{method}.gguf") return f"{merged_fp16}-{method}.gguf" def process_lora(model_id, lora_id, merged_name, methods, private_repo, oauth_token: gr.OAuthToken | None): if oauth_token.token is None: raise ValueError("You must log in to use") if merged_name is None: raise ValueError("You must enter the final model name!") model_name = model_id.split('/')[-1] lora_name = lora_id.split('/')[-1] model_fp16 = f"{model_name}-f16.gguf" lora_fp16 = f"{lora_name}-fp16.gguf" items_to_remove = [] try: api = HfApi(token=oauth_token) dl_pattern = ["*.md", "*.json", "*.model"] pattern = ( "*.safetensors" if any( file.path.endswith(".safetensors") for file in api.list_repo_tree( repo_id=model_id, recursive=True, ) ) else "*.bin" ) dl_pattern += pattern current_directory = os.getcwd() print(f"Current working directory: {current_directory}") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") # Download Raw Model from HF api.snapshot_download(repo_id=model_id, local_dir=model_name, allow_patterns=dl_pattern) items_to_remove.append(model_name) print("Model downloaded successfully!") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") print(f"{bcolors.OKBLUE}Model directory contents: {os.listdir(model_name)} {bcolors.ENDC}") # Download LoRA adapter from HF api.snapshot_download(repo_id=lora_id, local_dir=lora_name, allow_patterns=dl_pattern) items_to_remove.append(lora_name) print("LoRA downloaded successfully!") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") print(f"{bcolors.OKBLUE}LoRA directory contents: {os.listdir(lora_name)} {bcolors.ENDC}") # Convert LoRA adapter to GGUF-fp16 lora_conversion_script = "convert_lora_to_gguf.py" lora_fp16_conversion = f"python llama.cpp/{lora_conversion_script} --base {model_name} {lora_name} --outtype f16 --outfile {lora_fp16}" lora_result = subprocess.run(lora_fp16_conversion, shell=True, capture_output=True) items_to_remove.append(lora_fp16) print(lora_result) if lora_result.returncode != 0: raise Exception(f"Error converting to fp16: {lora_result.stderr}") print("LoRA converted to fp16 successfully!") print(f"Converted LoRA-GGUF path: {lora_fp16}") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") # Create a new repo username = whoami(oauth_token.token)["name"] new_repo_url = api.create_repo(repo_id=f"{username}/{merged_name}", exist_ok=True, private=private_repo) new_repo_id = new_repo_url.repo_id print("Repo created successfully!", new_repo_url) # Upload ReadME & LoRA-GGUF to HF upload_reme_to_hf(model_id, lora_id, new_repo_id, api, oauth_token) upload_file_to_hf(lora_fp16, new_repo_id, api) # Convert Raw Model to GGUF-fp16 base_conversion_script = "convert_hf_to_gguf.py" base_fp16_conversion = f"python llama.cpp/{base_conversion_script} {model_name} --outtype f16 --outfile {model_fp16}" base_result = subprocess.run(base_fp16_conversion, shell=True, capture_output=True) items_to_remove.append(model_fp16) print(base_result) if base_result.returncode != 0: raise Exception(f"Error converting to fp16: {base_result.stderr}") print("Raw Model converted to fp16 successfully!") print(f"Converted GGUF path: {model_fp16}") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") # Clean storage: hf-model & hf-lora shutil.rmtree(model_name, ignore_errors=True) shutil.rmtree(lora_name, ignore_errors=True) items_to_remove.remove(model_name) items_to_remove.remove(lora_name) print("HF model & LoRA cleaned up successfully!") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") # Merge LoRA with Raw Model to GGUF-fp16 print(f"Merging LoRA with Model => fp16") merged_fp16 = export_lora_to_gguf(model_fp16, lora_fp16, merged_name) items_to_remove.append(f"{merged_fp16}-fp16.gguf") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") # Upload Merged GGUF-fp16 to HF upload_file_to_hf(f"{merged_name}-fp16.gguf", new_repo_id, api) # Remove LoRA-GGUF & Model-GGUF os.remove(model_fp16) os.remove(lora_fp16) items_to_remove.remove(model_fp16) items_to_remove.remove(lora_fp16) if methods is not None: # Quantize GGUF-fp16 one by one for method in methods: print(f"Quantizing merged fp16-gguf to {method}") quantized_name = quantize_merged_gguf(merged_fp16, method) items_to_remove.append(quantized_name) print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") upload_file_to_hf(quantized_name, new_repo_id, api) os.remove(quantized_name) items_to_remove.remove(quantized_name) print("Removed the uploaded model.") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") os.remove(f"{merged_fp16}-fp16.gguf") items_to_remove.remove(f"{merged_fp16}-fp16.gguf") print("Remove the fp16 GGUF file.") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") return ( f'Everything done! Find your repo {new_repo_id}' ) except Exception as e: return (f"Error: {e}") finally: current_directory = os.getcwd() all_items = os.listdir(current_directory) for item in all_items: item_path = os.path.join(current_directory, item) if os.path.isfile(item_path) and item in items_to_remove: os.remove(item_path) print(f"Delete file: {item_path}") elif os.path.isdir(item_path) and item in items_to_remove: shutil.rmtree(item_path, ignore_errors=True) print(f"Delete folder: {item_path}") print("Folder cleaned up successfully!") print(f"{bcolors.OKGREEN}Files in current working directory: {os.listdir(current_directory)} {bcolors.ENDC}") css = """ #output { height: 500px; overflow: auto; border: 1px solid #ccc; } """ with gr.Blocks(css=css) as demo: with gr.Row(): with gr.Column(): gr.Markdown("# You must log in to create your repo!") gr.LoginButton(min_width=300) gr.Markdown("### For Llama-3.1-8B:\n#### Only fp16: 6.5 mins\n#### fp16 + Q4_K_S: 18mins\n#### All: 48mins") model_id = HuggingfaceHubSearch( label="Huggingface Hub Model ID", placeholder="Search for model id on Huggingface", search_type="model", ) lora_id = HuggingfaceHubSearch( label="Huggingface Hub LoRA Model ID", placeholder="Search for LoRA model id on Huggingface", search_type="model", ) private_repo = gr.Checkbox( value=False, label="Private Repo", info="Create a private repo under your username." ) quantize_methods = gr.CheckboxGroup(["Q4_K_S", "Q4_K_M", "Q5_K_S", "Q5_K_M", "Q6_K", "Q8_0"], value="Q4_K_S", label="Quantize Methods", info="If not selected, it will only merge LoRA and model in fp16 precision!\nFor Llama-3.1-8B\nOnly fp16: 6.5 mins\nfp16 + Q4_K_S: 18mins\nAll: 47mins") cool_name = gr.Textbox(label="Your final model name", placeholder="Enter a cool name:") iface = gr.Interface( fn=process_lora, inputs=[ model_id, lora_id, cool_name, quantize_methods, private_repo, ], outputs=[ gr.Markdown(label="Output") ], title="🔬Merge LoRA into GGUF, Create Custom Model🤖!", description="""## 🧐The space need a Model and a LoRA adapter, merge them, quantize and create your own repo.\n### 😦Step 1: Convert LoRA adapter to GGUF-fp16.\n### 😧Step 2: Convert Raw Model to GGUF-fp16.\n### 😨Step 3: Merge LoRA-GGUF with Model-GGUF.\n### 🤯Step 4: Quantize the Custom Model.""", api_name=False ) def restart_space(): HfApi().restart_space(repo_id="lee-ite/LoRA-To-GGUF", token=HF_TOKEN, factory_reboot=True) scheduler = BackgroundScheduler() scheduler.add_job(restart_space, "interval", seconds=43200) scheduler.start() demo.queue(default_concurrency_limit=1, max_size=5).launch(debug=True, show_api=False)