chaddy81 commited on
Commit
0ab2061
Β·
verified Β·
1 Parent(s): 9b7021f

Upload convert_gguf.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. convert_gguf.py +147 -0
convert_gguf.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # dependencies = [
3
+ # "transformers>=4.36.0",
4
+ # "torch>=2.0.0",
5
+ # "accelerate>=0.24.0",
6
+ # "huggingface_hub>=0.20.0",
7
+ # "sentencepiece>=0.1.99",
8
+ # "protobuf>=3.20.0",
9
+ # "numpy",
10
+ # "gguf",
11
+ # ]
12
+ # ///
13
+
14
+ """GGUF Conversion for Full Model (not LoRA adapter)"""
15
+
16
+ import os
17
+ import subprocess
18
+
19
+ print("πŸ”„ GGUF Conversion Script")
20
+ print("=" * 60)
21
+
22
+ MODEL_ID = os.environ.get("MODEL_ID", "chaddy81/qwen3-0.6b-multicode-grpo")
23
+ OUTPUT_REPO = os.environ.get("OUTPUT_REPO", "chaddy81/qwen3-0.6b-multicode-grpo-gguf")
24
+ username = os.environ.get("HF_USERNAME", MODEL_ID.split('/')[0])
25
+
26
+ print(f"\nπŸ“¦ Configuration:")
27
+ print(f" Model: {MODEL_ID}")
28
+ print(f" Output repo: {OUTPUT_REPO}")
29
+
30
+ # Step 1: Download model
31
+ print("\nπŸ“₯ Step 1: Downloading model...")
32
+ from huggingface_hub import snapshot_download
33
+ model_dir = snapshot_download(repo_id=MODEL_ID, local_dir="/tmp/model")
34
+ print(f" βœ… Model downloaded to {model_dir}")
35
+
36
+ # Step 2: Install build tools
37
+ print("\nπŸ”§ Step 2: Installing build tools...")
38
+ subprocess.run(["apt-get", "update", "-qq"], check=True, capture_output=True)
39
+ subprocess.run(["apt-get", "install", "-y", "-qq", "build-essential", "cmake"], check=True, capture_output=True)
40
+ print(" βœ… Build tools installed")
41
+
42
+ # Step 3: Setup llama.cpp
43
+ print("\nπŸ“₯ Step 3: Setting up llama.cpp...")
44
+ subprocess.run(["git", "clone", "--depth", "1", "https://github.com/ggerganov/llama.cpp.git", "/tmp/llama.cpp"], check=True, capture_output=True)
45
+ subprocess.run(["pip", "install", "-q", "-r", "/tmp/llama.cpp/requirements.txt"], check=True, capture_output=True)
46
+ subprocess.run(["pip", "install", "-q", "sentencepiece", "protobuf"], check=True, capture_output=True)
47
+ print(" βœ… llama.cpp ready")
48
+
49
+ # Step 4: Convert to GGUF
50
+ print("\nπŸ”„ Step 4: Converting to GGUF format (FP16)...")
51
+ gguf_output_dir = "/tmp/gguf_output"
52
+ os.makedirs(gguf_output_dir, exist_ok=True)
53
+
54
+ model_name = MODEL_ID.split('/')[-1]
55
+ gguf_file = f"{gguf_output_dir}/{model_name}-f16.gguf"
56
+
57
+ try:
58
+ result = subprocess.run(
59
+ ["python", "/tmp/llama.cpp/convert_hf_to_gguf.py", model_dir, "--outfile", gguf_file, "--outtype", "f16"],
60
+ check=True, capture_output=True, text=True
61
+ )
62
+ print(result.stdout[-2000:] if len(result.stdout) > 2000 else result.stdout)
63
+ except subprocess.CalledProcessError as e:
64
+ print(f"❌ Conversion failed! STDERR: {e.stderr}")
65
+ raise
66
+ print(f" βœ… FP16 GGUF created: {gguf_file}")
67
+
68
+ # Step 5: Build quantize tool and quantize
69
+ print("\nβš™οΈ Step 5: Building quantize tool and creating quantized versions...")
70
+ os.makedirs("/tmp/llama.cpp/build", exist_ok=True)
71
+ subprocess.run(["cmake", "-B", "/tmp/llama.cpp/build", "-S", "/tmp/llama.cpp", "-DGGML_CUDA=OFF"], check=True, capture_output=True, text=True)
72
+ subprocess.run(["cmake", "--build", "/tmp/llama.cpp/build", "--target", "llama-quantize", "-j", "4"], check=True, capture_output=True, text=True)
73
+ print(" βœ… Quantize tool built")
74
+
75
+ quantize_bin = "/tmp/llama.cpp/build/bin/llama-quantize"
76
+ quant_formats = [("Q4_K_M", "4-bit"), ("Q5_K_M", "5-bit"), ("Q8_0", "8-bit")]
77
+ quantized_files = []
78
+
79
+ for quant_type, desc in quant_formats:
80
+ print(f" Creating {quant_type} ({desc})...")
81
+ quant_file = f"{gguf_output_dir}/{model_name}-{quant_type.lower()}.gguf"
82
+ subprocess.run([quantize_bin, gguf_file, quant_file, quant_type], check=True, capture_output=True)
83
+ quantized_files.append((quant_file, quant_type))
84
+ size_mb = os.path.getsize(quant_file) / (1024 * 1024)
85
+ print(f" βœ… {quant_type}: {size_mb:.1f} MB")
86
+
87
+ # Step 6: Upload to Hub
88
+ print("\n☁️ Step 6: Uploading to Hugging Face Hub...")
89
+ from huggingface_hub import HfApi
90
+ api = HfApi()
91
+
92
+ api.create_repo(repo_id=OUTPUT_REPO, repo_type="model", exist_ok=True)
93
+ print(f" βœ… Repository {OUTPUT_REPO} ready")
94
+
95
+ print(" Uploading FP16 GGUF...")
96
+ api.upload_file(path_or_fileobj=gguf_file, path_in_repo=f"{model_name}-f16.gguf", repo_id=OUTPUT_REPO)
97
+
98
+ for quant_file, quant_type in quantized_files:
99
+ print(f" Uploading {quant_type}...")
100
+ api.upload_file(path_or_fileobj=quant_file, path_in_repo=f"{model_name}-{quant_type.lower()}.gguf", repo_id=OUTPUT_REPO)
101
+
102
+ # Create README
103
+ readme = f"""---
104
+ base_model: {MODEL_ID}
105
+ tags:
106
+ - gguf
107
+ - llama.cpp
108
+ - quantized
109
+ - trl
110
+ - grpo
111
+ ---
112
+
113
+ # {OUTPUT_REPO.split('/')[-1]}
114
+
115
+ GGUF conversion of [{MODEL_ID}](https://huggingface.co/{MODEL_ID}), trained using GRPO (Group Relative Policy Optimization).
116
+
117
+ ## Available Quantizations
118
+
119
+ | File | Quant | Description |
120
+ |------|-------|-------------|
121
+ | {model_name}-f16.gguf | F16 | Full precision |
122
+ | {model_name}-q8_0.gguf | Q8_0 | 8-bit, high quality |
123
+ | {model_name}-q5_k_m.gguf | Q5_K_M | 5-bit, good quality |
124
+ | {model_name}-q4_k_m.gguf | Q4_K_M | 4-bit, recommended |
125
+
126
+ ## Usage
127
+
128
+ ### With Ollama
129
+ ```bash
130
+ huggingface-cli download {OUTPUT_REPO} {model_name}-q4_k_m.gguf
131
+ echo "FROM ./{model_name}-q4_k_m.gguf" > Modelfile
132
+ ollama create {model_name} -f Modelfile
133
+ ollama run {model_name}
134
+ ```
135
+
136
+ ### With llama.cpp
137
+ ```bash
138
+ ./llama-cli -m {model_name}-q4_k_m.gguf -p "Your prompt"
139
+ ```
140
+ """
141
+ api.upload_file(path_or_fileobj=readme.encode(), path_in_repo="README.md", repo_id=OUTPUT_REPO)
142
+ print(" βœ… README uploaded")
143
+
144
+ print("\n" + "=" * 60)
145
+ print("βœ… GGUF Conversion Complete!")
146
+ print(f"πŸ“¦ Repository: https://huggingface.co/{OUTPUT_REPO}")
147
+ print("=" * 60)