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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.10"
|
| 4 |
+
# dependencies = [
|
| 5 |
+
# "transformers>=4.36.0",
|
| 6 |
+
# "peft>=0.7.0",
|
| 7 |
+
# "torch>=2.0.0",
|
| 8 |
+
# "accelerate>=0.24.0",
|
| 9 |
+
# "huggingface_hub>=0.20.0",
|
| 10 |
+
# "sentencepiece>=0.1.99",
|
| 11 |
+
# "protobuf>=3.20.0",
|
| 12 |
+
# "numpy",
|
| 13 |
+
# "gguf",
|
| 14 |
+
# ]
|
| 15 |
+
# ///
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
Convert Colby/apertus-8b-soc (LoRA adapter) to GGUF for Ollama.
|
| 19 |
+
|
| 20 |
+
Merges the adapter into swiss-ai/Apertus-8B-2509 base, then produces
|
| 21 |
+
Q4_K_M, Q5_K_M, and Q8_0 quantizations via llama.cpp.
|
| 22 |
+
Output repo: Colby/apertus-8b-soc-gguf
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import os
|
| 26 |
+
import sys
|
| 27 |
+
import subprocess
|
| 28 |
+
import torch
|
| 29 |
+
from huggingface_hub import HfApi
|
| 30 |
+
from peft import PeftModel
|
| 31 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 32 |
+
|
| 33 |
+
ADAPTER_MODEL = "Colby/apertus-8b-soc"
|
| 34 |
+
BASE_MODEL = "swiss-ai/Apertus-8B-2509"
|
| 35 |
+
OUTPUT_REPO = "Colby/apertus-8b-soc-gguf"
|
| 36 |
+
MODEL_NAME = "apertus-8b-soc"
|
| 37 |
+
MERGED_DIR = "/tmp/merged_model"
|
| 38 |
+
GGUF_DIR = "/tmp/gguf_output"
|
| 39 |
+
LLAMA_CPP_DIR = "/tmp/llama.cpp"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def run(cmd, desc):
|
| 43 |
+
print(f" {desc}...")
|
| 44 |
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 45 |
+
if result.returncode != 0:
|
| 46 |
+
print(f" FAILED: {result.stderr[:600]}")
|
| 47 |
+
sys.exit(1)
|
| 48 |
+
if result.stdout:
|
| 49 |
+
print(f" {result.stdout[:200]}")
|
| 50 |
+
return True
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# --- Step 0: Install build tools (MUST happen before cloning llama.cpp) ---
|
| 54 |
+
print("Step 0: Installing build tools...")
|
| 55 |
+
subprocess.run(["apt-get", "update", "-qq"], check=True, capture_output=True)
|
| 56 |
+
subprocess.run(
|
| 57 |
+
["apt-get", "install", "-y", "-qq", "build-essential", "cmake"],
|
| 58 |
+
check=True, capture_output=True
|
| 59 |
+
)
|
| 60 |
+
print(" Build tools ready.")
|
| 61 |
+
|
| 62 |
+
# --- Step 1: Load base model and merge LoRA adapter ---
|
| 63 |
+
print("\nStep 1: Loading base model and merging LoRA adapter...")
|
| 64 |
+
print(f" Base: {BASE_MODEL}")
|
| 65 |
+
print(f" Adapter: {ADAPTER_MODEL}")
|
| 66 |
+
|
| 67 |
+
base = AutoModelForCausalLM.from_pretrained(
|
| 68 |
+
BASE_MODEL,
|
| 69 |
+
torch_dtype=torch.float16,
|
| 70 |
+
device_map="auto",
|
| 71 |
+
trust_remote_code=True,
|
| 72 |
+
)
|
| 73 |
+
print(" Base model loaded.")
|
| 74 |
+
|
| 75 |
+
model = PeftModel.from_pretrained(base, ADAPTER_MODEL)
|
| 76 |
+
print(" Adapter loaded.")
|
| 77 |
+
|
| 78 |
+
merged = model.merge_and_unload()
|
| 79 |
+
print(" Merged.")
|
| 80 |
+
|
| 81 |
+
tokenizer = AutoTokenizer.from_pretrained(ADAPTER_MODEL, trust_remote_code=True)
|
| 82 |
+
|
| 83 |
+
# --- Step 2: Save merged model to disk ---
|
| 84 |
+
print(f"\nStep 2: Saving merged model to {MERGED_DIR}...")
|
| 85 |
+
os.makedirs(MERGED_DIR, exist_ok=True)
|
| 86 |
+
merged.save_pretrained(MERGED_DIR, safe_serialization=True)
|
| 87 |
+
tokenizer.save_pretrained(MERGED_DIR)
|
| 88 |
+
print(" Saved.")
|
| 89 |
+
|
| 90 |
+
# Free GPU memory before llama.cpp conversion
|
| 91 |
+
del merged, model, base
|
| 92 |
+
torch.cuda.empty_cache()
|
| 93 |
+
|
| 94 |
+
# --- Step 3: Clone llama.cpp ---
|
| 95 |
+
print("\nStep 3: Cloning llama.cpp...")
|
| 96 |
+
run(
|
| 97 |
+
["git", "clone", "--depth", "1", "https://github.com/ggerganov/llama.cpp.git", LLAMA_CPP_DIR],
|
| 98 |
+
"Cloning"
|
| 99 |
+
)
|
| 100 |
+
run(
|
| 101 |
+
["pip", "install", "-q", "-r", f"{LLAMA_CPP_DIR}/requirements.txt"],
|
| 102 |
+
"Installing llama.cpp Python requirements"
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# --- Step 4: Convert to FP16 GGUF ---
|
| 106 |
+
print("\nStep 4: Converting to FP16 GGUF...")
|
| 107 |
+
os.makedirs(GGUF_DIR, exist_ok=True)
|
| 108 |
+
fp16_gguf = f"{GGUF_DIR}/{MODEL_NAME}-f16.gguf"
|
| 109 |
+
|
| 110 |
+
run(
|
| 111 |
+
[sys.executable, f"{LLAMA_CPP_DIR}/convert_hf_to_gguf.py",
|
| 112 |
+
MERGED_DIR, "--outfile", fp16_gguf, "--outtype", "f16"],
|
| 113 |
+
"Converting"
|
| 114 |
+
)
|
| 115 |
+
print(f" FP16 GGUF: {os.path.getsize(fp16_gguf) / 1024**3:.1f} GB")
|
| 116 |
+
|
| 117 |
+
# --- Step 5: Build llama-quantize with CMake ---
|
| 118 |
+
print("\nStep 5: Building llama-quantize...")
|
| 119 |
+
build_dir = f"{LLAMA_CPP_DIR}/build"
|
| 120 |
+
os.makedirs(build_dir, exist_ok=True)
|
| 121 |
+
|
| 122 |
+
run(
|
| 123 |
+
["cmake", "-B", build_dir, "-S", LLAMA_CPP_DIR, "-DGGML_CUDA=OFF"],
|
| 124 |
+
"CMake configure"
|
| 125 |
+
)
|
| 126 |
+
run(
|
| 127 |
+
["cmake", "--build", build_dir, "--target", "llama-quantize", "-j", "4"],
|
| 128 |
+
"CMake build"
|
| 129 |
+
)
|
| 130 |
+
quantize_bin = f"{build_dir}/bin/llama-quantize"
|
| 131 |
+
print(f" Binary: {quantize_bin}")
|
| 132 |
+
|
| 133 |
+
# --- Step 6: Quantize ---
|
| 134 |
+
print("\nStep 6: Quantizing...")
|
| 135 |
+
quant_formats = [
|
| 136 |
+
("Q4_K_M", "4-bit medium (recommended for Ollama)"),
|
| 137 |
+
("Q5_K_M", "5-bit medium"),
|
| 138 |
+
("Q8_0", "8-bit"),
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
quantized = []
|
| 142 |
+
for qtype, desc in quant_formats:
|
| 143 |
+
qfile = f"{GGUF_DIR}/{MODEL_NAME}-{qtype.lower()}.gguf"
|
| 144 |
+
run([quantize_bin, fp16_gguf, qfile, qtype], f"{qtype} ({desc})")
|
| 145 |
+
size_mb = os.path.getsize(qfile) / 1024**2
|
| 146 |
+
print(f" {qtype}: {size_mb:.0f} MB")
|
| 147 |
+
quantized.append((qfile, qtype))
|
| 148 |
+
|
| 149 |
+
# --- Step 7: Upload to Hub ---
|
| 150 |
+
print(f"\nStep 7: Uploading to {OUTPUT_REPO}...")
|
| 151 |
+
api = HfApi()
|
| 152 |
+
api.create_repo(repo_id=OUTPUT_REPO, repo_type="model", exist_ok=True)
|
| 153 |
+
|
| 154 |
+
for path, qtype in [(fp16_gguf, "F16")] + quantized:
|
| 155 |
+
fname = os.path.basename(path)
|
| 156 |
+
print(f" Uploading {fname}...")
|
| 157 |
+
api.upload_file(path_or_fileobj=path, path_in_repo=fname, repo_id=OUTPUT_REPO)
|
| 158 |
+
print(f" Done: {fname}")
|
| 159 |
+
|
| 160 |
+
readme = f"""---
|
| 161 |
+
base_model: {BASE_MODEL}
|
| 162 |
+
tags:
|
| 163 |
+
- gguf
|
| 164 |
+
- apertus
|
| 165 |
+
- multi-turn-chat
|
| 166 |
+
- sft
|
| 167 |
+
---
|
| 168 |
+
|
| 169 |
+
# {MODEL_NAME}-gguf
|
| 170 |
+
|
| 171 |
+
GGUF conversion of [{ADAPTER_MODEL}](https://huggingface.co/{ADAPTER_MODEL}),
|
| 172 |
+
a LoRA fine-tune of [{BASE_MODEL}](https://huggingface.co/{BASE_MODEL})
|
| 173 |
+
on [marcodsn/SOC-2508](https://huggingface.co/datasets/marcodsn/SOC-2508)
|
| 174 |
+
(Synthetic Online Conversations).
|
| 175 |
+
|
| 176 |
+
## Quantizations
|
| 177 |
+
|
| 178 |
+
| File | Format | Size |
|
| 179 |
+
|------|--------|------|
|
| 180 |
+
| {MODEL_NAME}-f16.gguf | FP16 | ~16 GB |
|
| 181 |
+
| {MODEL_NAME}-q8_0.gguf | Q8_0 | ~8 GB |
|
| 182 |
+
| {MODEL_NAME}-q5_k_m.gguf | Q5_K_M | ~5 GB |
|
| 183 |
+
| {MODEL_NAME}-q4_k_m.gguf | Q4_K_M | ~4 GB |
|
| 184 |
+
|
| 185 |
+
## Ollama usage
|
| 186 |
+
|
| 187 |
+
```bash
|
| 188 |
+
hf download {OUTPUT_REPO} {MODEL_NAME}-q4_k_m.gguf
|
| 189 |
+
ollama create apertus-soc:8b -f Modelfile # FROM ./{MODEL_NAME}-q4_k_m.gguf
|
| 190 |
+
ollama run apertus-soc:8b
|
| 191 |
+
```
|
| 192 |
+
"""
|
| 193 |
+
api.upload_file(
|
| 194 |
+
path_or_fileobj=readme.encode(),
|
| 195 |
+
path_in_repo="README.md",
|
| 196 |
+
repo_id=OUTPUT_REPO,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
print(f"\nDone! GGUF repo: https://huggingface.co/{OUTPUT_REPO}")
|