chaddy81 commited on
Commit
40468d7
Β·
verified Β·
1 Parent(s): 8034635

Upload convert_to_gguf_q8km.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. convert_to_gguf_q8km.py +236 -0
convert_to_gguf_q8km.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # dependencies = [
4
+ # "transformers>=4.36.0",
5
+ # "peft>=0.7.0",
6
+ # "torch>=2.0.0",
7
+ # "accelerate>=0.24.0",
8
+ # "huggingface_hub>=0.20.0",
9
+ # "sentencepiece>=0.1.99",
10
+ # "protobuf>=3.20.0",
11
+ # "numpy",
12
+ # "gguf",
13
+ # ]
14
+ # ///
15
+
16
+ """
17
+ GGUF Conversion - Q8_K_M Quantization
18
+ Converts LoRA fine-tuned model to GGUF with Q8_K_M quantization.
19
+ """
20
+
21
+ import os
22
+ import torch
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer
24
+ from peft import PeftModel
25
+ from huggingface_hub import HfApi
26
+ import subprocess
27
+
28
+ print("πŸ”„ GGUF Conversion Script - Q8_K_M")
29
+ print("=" * 60)
30
+
31
+ # Configuration
32
+ ADAPTER_MODEL = "chaddy81/qwen3-0.6b-multicode-sft"
33
+ BASE_MODEL = "Qwen/Qwen3-0.6B"
34
+ OUTPUT_REPO = "chaddy81/qwen3-0.6b-multicode-sft-gguf"
35
+ username = "chaddy81"
36
+
37
+ print(f"\nπŸ“¦ Configuration:")
38
+ print(f" Base model: {BASE_MODEL}")
39
+ print(f" Adapter model: {ADAPTER_MODEL}")
40
+ print(f" Output repo: {OUTPUT_REPO}")
41
+ print(f" Quantization: Q8_K_M")
42
+
43
+ # Step 1: Load base model and adapter
44
+ print("\nπŸ”§ Step 1: Loading base model and LoRA adapter...")
45
+ base_model = AutoModelForCausalLM.from_pretrained(
46
+ BASE_MODEL,
47
+ torch_dtype=torch.float16,
48
+ device_map="auto",
49
+ trust_remote_code=True,
50
+ )
51
+ print(" βœ… Base model loaded")
52
+
53
+ model = PeftModel.from_pretrained(base_model, ADAPTER_MODEL)
54
+ print(" βœ… Adapter loaded")
55
+
56
+ merged_model = model.merge_and_unload()
57
+ print(" βœ… Models merged!")
58
+
59
+ tokenizer = AutoTokenizer.from_pretrained(ADAPTER_MODEL, trust_remote_code=True)
60
+ print(" βœ… Tokenizer loaded")
61
+
62
+ # Step 2: Save merged model
63
+ print("\nπŸ’Ύ Step 2: Saving merged model...")
64
+ merged_dir = "/tmp/merged_model"
65
+ merged_model.save_pretrained(merged_dir, safe_serialization=True)
66
+ tokenizer.save_pretrained(merged_dir)
67
+ print(f" βœ… Merged model saved to {merged_dir}")
68
+
69
+ # Step 3: Install llama.cpp
70
+ print("\nπŸ“₯ Step 3: Setting up llama.cpp...")
71
+
72
+ print(" Installing build tools...")
73
+ subprocess.run(["apt-get", "update", "-qq"], check=True, capture_output=True)
74
+ subprocess.run(["apt-get", "install", "-y", "-qq", "build-essential", "cmake"], check=True, capture_output=True)
75
+ print(" βœ… Build tools installed")
76
+
77
+ print(" Cloning llama.cpp repository...")
78
+ subprocess.run(["git", "clone", "--depth", "1", "https://github.com/ggerganov/llama.cpp.git", "/tmp/llama.cpp"], check=True, capture_output=True)
79
+ print(" βœ… llama.cpp cloned")
80
+
81
+ print(" Installing Python dependencies...")
82
+ subprocess.run(["pip", "install", "-r", "/tmp/llama.cpp/requirements.txt"], check=True, capture_output=True)
83
+ subprocess.run(["pip", "install", "sentencepiece", "protobuf"], check=True, capture_output=True)
84
+ print(" βœ… Dependencies installed")
85
+
86
+ # Step 4: Convert to GGUF (FP16)
87
+ print("\nπŸ”„ Step 4: Converting to GGUF format (FP16)...")
88
+ gguf_output_dir = "/tmp/gguf_output"
89
+ os.makedirs(gguf_output_dir, exist_ok=True)
90
+
91
+ convert_script = "/tmp/llama.cpp/convert_hf_to_gguf.py"
92
+ model_name = "qwen3-0.6b-multicode-sft"
93
+ gguf_file = f"{gguf_output_dir}/{model_name}-f16.gguf"
94
+
95
+ try:
96
+ result = subprocess.run(
97
+ ["python", convert_script, merged_dir, "--outfile", gguf_file, "--outtype", "f16"],
98
+ check=True, capture_output=True, text=True
99
+ )
100
+ print(result.stdout)
101
+ except subprocess.CalledProcessError as e:
102
+ print(f"❌ Conversion failed!")
103
+ print("STDOUT:", e.stdout)
104
+ print("STDERR:", e.stderr)
105
+ raise
106
+ print(f" βœ… FP16 GGUF created: {gguf_file}")
107
+
108
+ # Step 5: Build quantize tool and create Q8_K_M
109
+ print("\nβš™οΈ Step 5: Creating Q8_K_M quantization...")
110
+
111
+ print(" Building quantize tool with CMake...")
112
+ os.makedirs("/tmp/llama.cpp/build", exist_ok=True)
113
+ subprocess.run(
114
+ ["cmake", "-B", "/tmp/llama.cpp/build", "-S", "/tmp/llama.cpp", "-DGGML_CUDA=OFF"],
115
+ check=True, capture_output=True, text=True
116
+ )
117
+ subprocess.run(
118
+ ["cmake", "--build", "/tmp/llama.cpp/build", "--target", "llama-quantize", "-j", "4"],
119
+ check=True, capture_output=True, text=True
120
+ )
121
+ print(" βœ… Quantize tool built")
122
+
123
+ quantize_bin = "/tmp/llama.cpp/build/bin/llama-quantize"
124
+
125
+ # Create Q8_K_M quantization
126
+ quant_file = f"{gguf_output_dir}/{model_name}-q8_k_m.gguf"
127
+ print(f" Creating Q8_K_M quantization...")
128
+ subprocess.run([quantize_bin, gguf_file, quant_file, "Q8_K_M"], check=True, capture_output=True)
129
+ size_mb = os.path.getsize(quant_file) / (1024 * 1024)
130
+ print(f" βœ… Q8_K_M: {size_mb:.1f} MB")
131
+
132
+ # Step 6: Upload to Hub
133
+ print("\n☁️ Step 6: Uploading to Hugging Face Hub...")
134
+ api = HfApi()
135
+
136
+ print(f" Creating repository: {OUTPUT_REPO}")
137
+ try:
138
+ api.create_repo(repo_id=OUTPUT_REPO, repo_type="model", exist_ok=True)
139
+ print(" βœ… Repository created")
140
+ except Exception as e:
141
+ print(f" ℹ️ Repository may already exist: {e}")
142
+
143
+ # Upload Q8_K_M version
144
+ print(" Uploading Q8_K_M GGUF...")
145
+ api.upload_file(
146
+ path_or_fileobj=quant_file,
147
+ path_in_repo=f"{model_name}-q8_k_m.gguf",
148
+ repo_id=OUTPUT_REPO,
149
+ )
150
+ print(" βœ… Q8_K_M uploaded")
151
+
152
+ # Create README
153
+ print("\nπŸ“ Creating README...")
154
+ readme_content = f"""---
155
+ base_model: {BASE_MODEL}
156
+ tags:
157
+ - gguf
158
+ - llama.cpp
159
+ - quantized
160
+ - trl
161
+ - sft
162
+ - qwen3
163
+ - code
164
+ ---
165
+
166
+ # {model_name} GGUF
167
+
168
+ GGUF conversion of [{ADAPTER_MODEL}](https://huggingface.co/{ADAPTER_MODEL}), a LoRA fine-tuned version of [{BASE_MODEL}](https://huggingface.co/{BASE_MODEL}).
169
+
170
+ ## Model Details
171
+
172
+ - **Base Model:** {BASE_MODEL}
173
+ - **Fine-tuned Model:** {ADAPTER_MODEL}
174
+ - **Training:** SFT on multi-language code datasets (Codeforces, Golang, Vue/Nuxt, React)
175
+ - **Format:** GGUF Q8_K_M quantization
176
+
177
+ ## Available Files
178
+
179
+ | File | Quant | Description |
180
+ |------|-------|-------------|
181
+ | {model_name}-q8_k_m.gguf | Q8_K_M | 8-bit K-quant medium - high quality |
182
+
183
+ ## Usage
184
+
185
+ ### With llama.cpp
186
+
187
+ ```bash
188
+ huggingface-cli download {OUTPUT_REPO} {model_name}-q8_k_m.gguf
189
+ ./llama-cli -m {model_name}-q8_k_m.gguf -p "Write a React component"
190
+ ```
191
+
192
+ ### With Ollama
193
+
194
+ ```bash
195
+ # Download
196
+ huggingface-cli download {OUTPUT_REPO} {model_name}-q8_k_m.gguf
197
+
198
+ # Create Modelfile
199
+ echo "FROM ./{model_name}-q8_k_m.gguf" > Modelfile
200
+
201
+ # Create and run
202
+ ollama create qwen3-multicode -f Modelfile
203
+ ollama run qwen3-multicode
204
+ ```
205
+
206
+ ### With LM Studio
207
+
208
+ 1. Download the `.gguf` file
209
+ 2. Import into LM Studio
210
+ 3. Start chatting!
211
+
212
+ ## Training Data
213
+
214
+ This model was fine-tuned on:
215
+ - open-r1/codeforces-cots (competitive programming)
216
+ - smcleod/golang-coder (Go)
217
+ - kevind13/vuejs-nuxt-tailwind-codellama (Vue/Nuxt)
218
+ - cfahlgren1/react-code-instructions (React)
219
+
220
+ ---
221
+ *Converted to GGUF with Q8_K_M quantization using llama.cpp*
222
+ """
223
+
224
+ api.upload_file(
225
+ path_or_fileobj=readme_content.encode(),
226
+ path_in_repo="README.md",
227
+ repo_id=OUTPUT_REPO,
228
+ )
229
+ print(" βœ… README uploaded")
230
+
231
+ print("\n" + "=" * 60)
232
+ print("βœ… GGUF Conversion Complete!")
233
+ print(f"πŸ“¦ Repository: https://huggingface.co/{OUTPUT_REPO}")
234
+ print(f"\nπŸ“₯ Download:")
235
+ print(f" huggingface-cli download {OUTPUT_REPO} {model_name}-q8_k_m.gguf")
236
+ print("=" * 60)