# /// script # dependencies = ["peft", "transformers", "torch", "huggingface_hub", "sentencepiece", "cmake"] # /// import os import subprocess from peft import PeftModel from transformers import AutoModelForCausalLM, AutoTokenizer from huggingface_hub import HfApi, create_repo import torch # Configuration BASE_MODEL_ID = "Qwen/Qwen2.5-32B-Instruct" ADAPTER_ID = "sunkencity/survival-expert-qwen-32b" OUTPUT_REPO = "sunkencity/survival-expert-qwen-32b-gguf" MERGED_DIR = "merged_model" GGUF_FILE = "survival-expert-qwen-32b.Q4_K_M.gguf" print(f"Loading base model: {BASE_MODEL_ID}") # Load in bfloat16 to save memory and match training base_model = AutoModelForCausalLM.from_pretrained( BASE_MODEL_ID, device_map="auto", torch_dtype=torch.bfloat16, trust_remote_code=True ) print(f"Loading adapter: {ADAPTER_ID}") model = PeftModel.from_pretrained(base_model, ADAPTER_ID) print("Merging model...") model = model.merge_and_unload() print(f"Saving merged model to {MERGED_DIR}...") model.save_pretrained(MERGED_DIR) tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID) tokenizer.save_pretrained(MERGED_DIR) print("Cloning llama.cpp...") if os.path.exists("llama.cpp"): subprocess.run(["rm", "-rf", "llama.cpp"]) subprocess.run(["git", "clone", "https://github.com/ggerganov/llama.cpp"], check=True) print("Installing llama.cpp requirements...") subprocess.run(["pip", "install", "-r", "llama.cpp/requirements.txt"], check=True) print("Building llama-quantize with CMake...") os.makedirs("llama.cpp/build", exist_ok=True) subprocess.run(["cmake", "-B", "llama.cpp/build", "-S", "llama.cpp"], check=True) subprocess.run(["cmake", "--build", "llama.cpp/build", "--config", "Release", "-j"], check=True) print("Converting to GGUF (FP16)...") # Convert to GGUF (BF16/FP16 preserved from model) subprocess.run([ "python", "llama.cpp/convert_hf_to_gguf.py", MERGED_DIR, "--outfile", "merged_model.gguf", "--outtype", "bf16" ], check=True) print("Quantizing to Q4_K_M...") quantize_bin = "llama.cpp/build/bin/llama-quantize" subprocess.run([ quantize_bin, "merged_model.gguf", GGUF_FILE, "Q4_K_M" ], check=True) print(f"Creating repo {OUTPUT_REPO}...") api = HfApi() create_repo(OUTPUT_REPO, repo_type="model", exist_ok=True) print(f"Uploading {GGUF_FILE}...") api.upload_file( path_or_fileobj=GGUF_FILE, path_in_repo=GGUF_FILE, repo_id=OUTPUT_REPO, repo_type="model" ) print("Done! GGUF available at:", f"https://huggingface.co/{OUTPUT_REPO}")