interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / src / mojollama / quantizer.py

1389 lines · 52626 bytes Raw Blame History
1"""
2MojoLlama Quantizer — GGUF quantization CLI tool.
3
4Converts HuggingFace models to GGUF format and applies various quantization types.
5Wraps llama.cpp's convert_hf_to_gguf.py and llama-quantize, with a pure Python
6Q4_0 fallback for when those tools aren't available.
7
8Usage:
9 python3 -m mojollama.quantizer convert hf_model_name --outtype f16 --outfile model.gguf
10 python3 -m mojollama.quantizer quantize model.gguf --type q4_k_m
11 python3 -m mojollama.quantizer info model.gguf
12 python3 -m mojollama.quantizer validate model.gguf --reference ref.gguf
13 python3 -m mojollama.quantizer benchmark model.gguf --prompt "Hello"
14 python3 -m mojollama.quantizer batch hf_model_name --types q4_0,q4_k_m,q8_0
15
16Importable:
17 from mojollama.quantizer import quantize, convert, get_info, Q4Block, quantize_q4, dequantize_q4
18"""
19
20import argparse
21import json
22import os
23import shutil
24import struct
25import subprocess
26import sys
27import time
28from pathlib import Path
29from typing import Optional, List, Dict, Any, Tuple
30import numpy as np
31
32# ─── Paths ──────────────────────────────────────────────────────────────────
33
34# Allow overriding with env vars
35LLAMA_CPP_DIR = Path(os.environ.get("LLAMA_CPP_DIR", "/tmp/llama.cpp"))
36CONVERT_SCRIPT = LLAMA_CPP_DIR / "convert_hf_to_gguf.py"
37QUANTIZE_BIN = LLAMA_CPP_DIR / "build" / "bin" / "llama-quantize"
38
39# Default HF cache
40HF_HOME = Path(os.environ.get("HF_HOME", os.path.expanduser("~/.cache/huggingface")))
41
42# Known quantization types with descriptions and approximate bpw
43QUANT_TYPES = {
44 "q4_0": {"desc": "4-bit (4.34G/7B)", "bpw": 4.34, "type_id": 2},
45 "q4_1": {"desc": "4-bit (4.78G/7B)", "bpw": 4.78, "type_id": 3},
46 "q5_0": {"desc": "5-bit (5.21G/7B)", "bpw": 5.21, "type_id": 8},
47 "q5_1": {"desc": "5-bit (5.65G/7B)", "bpw": 5.65, "type_id": 9},
48 "q8_0": {"desc": "8-bit (7.96G/7B)", "bpw": 7.96, "type_id": 7},
49 "q2_k": {"desc": "2-bit K-quant", "bpw": 2.96, "type_id": 10},
50 "q2_k_s": {"desc": "2-bit K-quant small", "bpw": 2.96, "type_id": 21},
51 "q3_k_s": {"desc": "3-bit K-quant small", "bpw": 3.41, "type_id": 11},
52 "q3_k_m": {"desc": "3-bit K-quant medium", "bpw": 3.74, "type_id": 12},
53 "q3_k_l": {"desc": "3-bit K-quant large", "bpw": 4.03, "type_id": 13},
54 "q4_k_s": {"desc": "4-bit K-quant small", "bpw": 4.37, "type_id": 14},
55 "q4_k_m": {"desc": "4-bit K-quant medium", "bpw": 4.58, "type_id": 15},
56 "q5_k_s": {"desc": "5-bit K-quant small", "bpw": 5.21, "type_id": 16},
57 "q5_k_m": {"desc": "5-bit K-quant medium", "bpw": 5.33, "type_id": 17},
58 "q6_k": {"desc": "6-bit K-quant (6.14G/7B)", "bpw": 6.14, "type_id": 18},
59 "f16": {"desc": "16-bit float (14G/7B)", "bpw": 16.0, "type_id": 1},
60 "f32": {"desc": "32-bit float (26G/7B)", "bpw": 32.0, "type_id": 0},
61 "bf16": {"desc": "BFloat16 (14G/7B)", "bpw": 16.0, "type_id": 32},
62 "iq1_s": {"desc": "1.56 bpw quantization", "bpw": 1.56, "type_id": 24},
63 "iq1_m": {"desc": "1.75 bpw quantization", "bpw": 1.75, "type_id": 31},
64 "iq2_xxs":{"desc": "2.06 bpw quantization", "bpw": 2.06, "type_id": 19},
65 "iq2_xs": {"desc": "2.31 bpw quantization", "bpw": 2.31, "type_id": 20},
66 "iq2_s": {"desc": "2.5 bpw quantization", "bpw": 2.5, "type_id": 28},
67 "iq2_m": {"desc": "2.7 bpw quantization", "bpw": 2.7, "type_id": 29},
68 "iq3_xxs":{"desc": "3.06 bpw quantization", "bpw": 3.06, "type_id": 23},
69 "iq3_xs": {"desc": "3.3 bpw quantization", "bpw": 3.3, "type_id": 22},
70 "iq3_s": {"desc": "3.44 bpw quantization", "bpw": 3.44, "type_id": 26},
71 "iq3_m": {"desc": "3.66 bpw quantization mix", "bpw": 3.66, "type_id": 27},
72 "iq4_nl": {"desc": "4.50 bpw nonlinear", "bpw": 4.50, "type_id": 25},
73 "iq4_xs": {"desc": "4.25 bpw nonlinear", "bpw": 4.25, "type_id": 30},
74}
75
76# ─── Helpers ─────────────────────────────────────────────────────────────────
77
78def _check_tools():
79 """Check availability of llama.cpp tools, return status dict."""
80 status = {
81 "convert_script": CONVERT_SCRIPT.exists(),
82 "quantize_bin": QUANTIZE_BIN.exists(),
83 "gguf_package": False,
84 }
85 try:
86 import gguf
87 status["gguf_package"] = True
88 except ImportError:
89 pass
90 return status
91
92
93def _find_llama_quantize() -> Optional[Path]:
94 """Find llama-quantize binary, checking common locations."""
95 candidates = [
96 QUANTIZE_BIN,
97 LLAMA_CPP_DIR / "build" / "bin" / "Release" / "llama-quantize",
98 LLAMA_CPP_DIR / "build" / "llama-quantize",
99 Path("/usr/local/bin/llama-quantize"),
100 Path("/usr/bin/llama-quantize"),
101 ]
102 for p in candidates:
103 if p.exists():
104 return p
105 return None
106
107
108def _format_size(size_bytes: int) -> str:
109 """Format byte size to human-readable string."""
110 for unit in ["B", "KB", "MB", "GB", "TB"]:
111 if size_bytes < 1024:
112 return f"{size_bytes:.2f} {unit}"
113 size_bytes /= 1024
114 return f"{size_bytes:.2f} PB"
115
116
117def _run_subprocess(cmd: List[str], desc: str = "") -> Tuple[int, str, str]:
118 """Run a subprocess, return (returncode, stdout, stderr)."""
119 desc_str = f" ({desc})" if desc else ""
120 print(f" Running: {' '.join(cmd)}{desc_str}")
121 proc = subprocess.Popen(
122 cmd,
123 stdout=subprocess.PIPE,
124 stderr=subprocess.PIPE,
125 universal_newlines=True,
126 )
127 stdout, stderr = proc.communicate()
128 return proc.returncode, stdout, stderr
129
130
131# ─── Pure Python Q4_0 Quantization (fallback) ───────────────────────────────
132# Reference: q4_matmul.py
133
134class Q4Block:
135 """A single Q4_0 quantization block (16 values, 10 bytes).
136
137 Format:
138 - 1x float16 scale (2 bytes)
139 - 8x uint8 (2x 4-bit values each, 16 values total)
140 - 10 bytes per 16 values
141 """
142
143 def __init__(self, scale: np.float16 = np.float16(0.0), quants: np.ndarray = None):
144 self.scale = scale
145 self.quants = np.zeros(8, dtype=np.uint8) if quants is None else quants
146
147 def dequantize(self) -> np.ndarray:
148 """Dequantize block to 16 float32 values."""
149 result = np.zeros(16, dtype=np.float32)
150 for i in range(8):
151 lo = int(self.quants[i] & 0x0F)
152 hi = int((self.quants[i] >> 4) & 0x0F)
153 result[i*2] = (lo - 8) * float(self.scale)
154 result[i*2+1] = (hi - 8) * float(self.scale)
155 return result
156
157 def pack(self) -> bytes:
158 """Pack block to 10 bytes: float16 scale + 8 uint8."""
159 buf = struct.pack('<e', float(self.scale))
160 buf += self.quants.tobytes()
161 return buf
162
163 @classmethod
164 def unpack(cls, data: bytes) -> "Q4Block":
165 """Unpack 10 bytes into Q4Block."""
166 scale = np.float16(struct.unpack('<e', data[:2])[0])
167 quants = np.frombuffer(data[2:10], dtype=np.uint8).copy()
168 return cls(scale, quants)
169
170
171def quantize_q4(values: np.ndarray) -> List[Q4Block]:
172 """Quantize float32 array to Q4_0 blocks. Returns list of blocks."""
173 n = len(values)
174 n_blocks = (n + 15) // 16
175 blocks = []
176 for b in range(n_blocks):
177 start = b * 16
178 end = min(start + 16, n)
179 chunk = values[start:end]
180 if len(chunk) < 16:
181 chunk = np.pad(chunk, (0, 16 - len(chunk)))
182 amax = np.max(np.abs(chunk))
183 scale = np.float16(amax / 7.0 if amax > 0 else 1.0)
184 s = float(scale)
185 quants = np.zeros(8, dtype=np.uint8)
186 for i in range(8):
187 lo = max(0, min(15, int(round(chunk[i*2] / s)) + 8))
188 hi = max(0, min(15, int(round(chunk[i*2+1] / s)) + 8))
189 quants[i] = (hi << 4) | lo
190 blocks.append(Q4Block(scale, quants))
191 return blocks
192
193
194def dequantize_q4(blocks: List[Q4Block], n: int) -> np.ndarray:
195 """Dequantize blocks back to float32 array."""
196 result = np.zeros(n, dtype=np.float32)
197 for b_idx, block in enumerate(blocks):
198 start = b_idx * 16
199 end = min(start + 16, n)
200 values = block.dequantize()
201 result[start:end] = values[:end-start]
202 return result
203
204
205def quantize_gguf_q4_0(input_path: str, output_path: str) -> Dict[str, Any]:
206 """Pure Python Q4_0 quantization of a GGUF file.
207
208 Reads an F32/F16 GGUF file, quantizes all weight tensors to Q4_0,
209 and writes a new GGUF file. This is a fallback when llama-quantize
210 is not available.
211
212 Returns stats dict.
213 """
214 try:
215 import gguf
216 from gguf.constants import GGMLQuantizationType, GGML_TYPE
217 except ImportError:
218 raise ImportError("gguf package required for pure Python quantization")
219
220 print(f" Reading: {input_path}")
221 reader = gguf.GGUFReader(input_path)
222
223 # Collect metadata
224 output_tensors = []
225 stats = {
226 "tensors_quantized": 0,
227 "bytes_before": 0,
228 "bytes_after": 0,
229 "skipped": 0,
230 }
231
232 for tensor in reader.tensors:
233 # Get the raw data as numpy array
234 data = tensor.data
235 shape = tensor.shape
236
237 # Determine if it's a weight tensor (quantizable)
238 name = tensor.name
239 is_weight = any(name.endswith(suffix) for suffix in [
240 ".weight", "attn_q.weight", "attn_k.weight", "attn_v.weight",
241 "attn_output.weight", "ffn_gate.weight", "ffn_up.weight",
242 "ffn_down.weight", "output.weight", "token_embd.weight",
243 ])
244
245 # Only quantize weight tensors that are float type
246 current_type = tensor.tensor_type if hasattr(tensor, 'tensor_type') else GGML_TYPE.F32
247
248 if is_weight and current_type in (GGML_TYPE.F32, GGML_TYPE.F16):
249 print(f" Quantizing: {name} shape={shape}")
250 # Convert to float32 for quantization
251 if data.dtype != np.float32:
252 data = data.astype(np.float32)
253
254 # Store original bytes
255 orig_bytes = data.nbytes
256 stats["bytes_before"] += orig_bytes
257
258 # Quantize per row
259 rows = data.shape[0]
260 q_blocks = []
261 for r in range(rows):
262 row_blocks = quantize_q4(data[r])
263 q_blocks.extend(row_blocks)
264
265 # Pack to bytes
266 packed = b''.join(b.pack() for b in q_blocks)
267 stats["bytes_after"] += len(packed)
268 stats["tensors_quantized"] += 1
269
270 # Create new GGUF tensor info
271 # For Q4_0: shape is (rows, pack_size) where pack_size = (cols+15)//16 * 10
272 cols = data.shape[1]
273 pack_size = ((cols + 15) // 16) * 10
274 new_shape = [rows, pack_size]
275
276 output_tensors.append({
277 "name": name,
278 "shape": new_shape,
279 "data": packed,
280 "type": GGMLQuantizationType.Q4_0,
281 })
282 else:
283 # Pass through (embeddings, norm weights, etc.)
284 stats["skipped"] += 1
285 output_tensors.append({
286 "name": name,
287 "shape": list(shape),
288 "data": data.tobytes(),
289 "type": current_type if hasattr(current_type, 'value') else 0,
290 })
291
292 # Write output GGUF
293 print(f" Writing: {output_path}")
294 writer = gguf.GGUFWriter(output_path, reader.get_field("general.architecture"))
295
296 # Copy metadata fields
297 for field in reader.fields.values():
298 try:
299 if field.name.startswith("general.") or field.name.startswith("llama.") or field.name.startswith("tokenizer."):
300 writer.add_key(field.name)
301 except Exception:
302 pass
303
304 # Add tensors
305 for t in output_tensors:
306 # We need to convert bytes back to the appropriate type for GGUFWriter
307 try:
308 arr = np.frombuffer(t["data"], dtype=np.uint8).reshape(t["shape"])
309 writer.add_tensor(t["name"], arr, raw_dtype=t["type"])
310 except Exception as e:
311 print(f" Warning: could not add tensor {t['name']}: {e}")
312
313 writer.write_header_to_file()
314 writer.write_kv_data_to_file()
315 writer.write_tensors_to_file()
316 writer.close()
317
318 stats["output_path"] = output_path
319 return stats
320
321
322def quantize_python(input_path: str, output_path: str, quant_type: str = "q4_0") -> Dict[str, Any]:
323 """Pure Python quantization of a GGUF file.
324
325 Currently only supports Q4_0. Falls back to llama-quantize for other types.
326 """
327 if quant_type.lower() == "q4_0":
328 return quantize_gguf_q4_0(input_path, output_path)
329 else:
330 raise ValueError(
331 f"Pure Python quantization does not support '{quant_type}'. "
332 f"Only 'q4_0' is supported. Use llama-quantize for other types."
333 )
334
335
336# ─── Core Operations ─────────────────────────────────────────────────────────
337
338def convert(
339 model_name_or_path: str,
340 outtype: str = "f16",
341 outfile: Optional[str] = None,
342 verbose: bool = False,
343 **kwargs,
344) -> Dict[str, Any]:
345 """Convert HuggingFace model to GGUF format.
346
347 Wraps llama.cpp's convert_hf_to_gguf.py.
348
349 Args:
350 model_name_or_path: HF model name or local path
351 outtype: Output format (f32, f16, bf16, q8_0, auto)
352 outfile: Output file path
353 verbose: Enable verbose output
354
355 Returns:
356 Dict with status, output path, and stats
357 """
358 # Check for convert script
359 if not CONVERT_SCRIPT.exists():
360 raise FileNotFoundError(
361 f"convert_hf_to_gguf.py not found at {CONVERT_SCRIPT}. "
362 f"Set LLAMA_CPP_DIR environment variable to point to your llama.cpp directory."
363 )
364
365 # Build command
366 cmd = [sys.executable, str(CONVERT_SCRIPT), model_name_or_path]
367 cmd.extend(["--outtype", outtype])
368 if outfile:
369 cmd.extend(["--outfile", outfile])
370 if verbose:
371 cmd.append("--verbose")
372
373 # Add any extra kwargs as flags
374 for key, value in kwargs.items():
375 flag = "--" + key.replace("_", "-")
376 if isinstance(value, bool):
377 if value:
378 cmd.append(flag)
379 else:
380 cmd.extend([flag, str(value)])
381
382 print(f"Converting HF model '{model_name_or_path}' to GGUF ({outtype})...")
383 t0 = time.time()
384 retcode, stdout, stderr = _run_subprocess(cmd, "convert_hf_to_gguf.py")
385 elapsed = time.time() - t0
386
387 if retcode != 0:
388 error_msg = stderr.strip() or stdout.strip()
389 raise RuntimeError(f"Conversion failed (exit code {retcode}):\n{error_msg}")
390
391 # Try to find the output file
392 if outfile and os.path.exists(outfile):
393 output_path = outfile
394 else:
395 # Try to derive from stdout
396 output_path = _parse_output_path(stdout, model_name_or_path, outtype)
397
398 size = os.path.getsize(output_path) if output_path and os.path.exists(output_path) else 0
399
400 result = {
401 "status": "success",
402 "output_path": str(output_path) if output_path else None,
403 "outtype": outtype,
404 "size_bytes": size,
405 "size_human": _format_size(size),
406 "elapsed_seconds": elapsed,
407 "stdout": stdout.strip() if verbose else "",
408 "stderr": stderr.strip() if verbose else "",
409 }
410
411 print(f" Output: {result['output_path']}")
412 print(f" Size: {result['size_human']}")
413 print(f" Time: {elapsed:.1f}s")
414
415 return result
416
417
418def _parse_output_path(stdout: str, model_input: str, outtype: str) -> Optional[str]:
419 """Try to find the output file path from conversion script output."""
420 import re
421 # Look for "Writing to: /path/to/file.gguf" or similar
422 for line in stdout.split("\n"):
423 line = line.strip()
424 if "writing" in line.lower() and ".gguf" in line.lower():
425 m = re.search(r'(/[^\s]+\.gguf)', line)
426 if m:
427 return m.group(1)
428
429 # Default: model name + outtype
430 base = os.path.basename(model_input.rstrip("/"))
431 if not base:
432 base = "model"
433 return f"{base}-{outtype}.gguf"
434
435
436def quantize(
437 input_path: str,
438 quant_type: str = "q4_k_m",
439 output_path: Optional[str] = None,
440 allow_requantize: bool = False,
441 leave_output: bool = False,
442 pure_python: bool = False,
443 override_kv: Optional[Dict[str, str]] = None,
444 dry_run: bool = False,
445) -> Dict[str, Any]:
446 """Quantize a GGUF file.
447
448 Wraps llama.cpp's llama-quantize, or uses pure Python fallback for Q4_0.
449
450 Args:
451 input_path: Path to GGUF file
452 quant_type: Quantization type (e.g., q4_0, q4_k_m, q8_0, f16)
453 output_path: Output file path (default: auto-generated)
454 allow_requantize: Allow requantizing already quantized tensors
455 leave_output: Leave output.weight unquantized
456 pure_python: Force pure Python quantization (only Q4_0)
457 override_kv: Dict of metadata overrides (KEY=TYPE:VALUE)
458 dry_run: Calculate size without performing quantization
459
460 Returns:
461 Dict with stats
462 """
463 quant_type = quant_type.lower()
464 input_path = str(Path(input_path).resolve())
465
466 if not os.path.exists(input_path):
467 raise FileNotFoundError(f"Input file not found: {input_path}")
468
469 input_size = os.path.getsize(input_path)
470
471 # Default output path
472 if output_path is None:
473 stem = Path(input_path).stem
474 # Remove existing quant suffix if any
475 for qt in QUANT_TYPES:
476 if stem.lower().endswith(f"-{qt}") or stem.lower().endswith(f"_{qt}"):
477 stem = stem[:-(len(qt)+1)]
478 break
479 output_path = str(Path(input_path).parent / f"{stem}-{quant_type}.gguf")
480
481 # Check if we can use pure Python fallback
482 if pure_python:
483 return quantize_python(input_path, output_path, quant_type)
484
485 # Check for llama-quantize
486 quant_bin = _find_llama_quantize()
487 if quant_bin is None:
488 if quant_type == "q4_0":
489 print(" llama-quantize not found, using pure Python Q4_0 fallback...")
490 return quantize_python(input_path, output_path, quant_type)
491 else:
492 raise FileNotFoundError(
493 f"llama-quantize not found. Searched paths include: {QUANTIZE_BIN}. "
494 f"Set LLAMA_CPP_DIR environment variable. "
495 f"For Q4_0 only, use --pure-python flag."
496 )
497
498 # Build command
499 cmd = [str(quant_bin)]
500 if dry_run:
501 cmd.append("--dry-run")
502 if allow_requantize:
503 cmd.append("--allow-requantize")
504 if leave_output:
505 cmd.append("--leave-output-tensor")
506 if override_kv:
507 for key, val in override_kv.items():
508 cmd.extend(["--override-kv", f"{key}" if ":" in key else f"{key}:{val}"])
509
510 cmd.extend([input_path, output_path, quant_type.upper()])
511
512 desc = f"{quant_type} quantization"
513 print(f"Quantizing: {input_path}")
514 print(f" Input size: {_format_size(input_size)}")
515 print(f" Output: {output_path}")
516 print(f" Type: {quant_type}")
517
518 t0 = time.time()
519 retcode, stdout, stderr = _run_subprocess(cmd, desc)
520 elapsed = time.time() - t0
521
522 if retcode != 0:
523 error_msg = stderr.strip() or stdout.strip()
524 raise RuntimeError(f"Quantization failed (exit code {retcode}):\n{error_msg}")
525
526 # Parse output for stats
527 output_size = 0
528 if os.path.exists(output_path):
529 output_size = os.path.getsize(output_path)
530
531 compression_ratio = input_size / output_size if output_size > 0 else 0
532
533 result = {
534 "status": "success",
535 "input_path": input_path,
536 "output_path": output_path,
537 "quant_type": quant_type,
538 "input_size_bytes": input_size,
539 "output_size_bytes": output_size,
540 "input_size_human": _format_size(input_size),
541 "output_size_human": _format_size(output_size),
542 "compression_ratio": round(compression_ratio, 2),
543 "elapsed_seconds": round(elapsed, 1),
544 "stdout": stdout.strip(),
545 "stderr": stderr.strip(),
546 }
547
548 # Print summary
549 print(f" Output size: {result['output_size_human']}")
550 print(f" Compression: {result['compression_ratio']}x")
551 print(f" Time: {elapsed:.1f}s")
552
553 # Print size estimate from stdout if dry run
554 if dry_run:
555 for line in stdout.split("\n"):
556 if "size" in line.lower():
557 print(f" {line.strip()}")
558
559 return result
560
561
562def get_info(gguf_path: str, verbose: bool = False) -> Dict[str, Any]:
563 """Get information about a GGUF file.
564
565 Args:
566 gguf_path: Path to GGUF file
567 verbose: Show all tensors
568
569 Returns:
570 Dict with model info
571 """
572 try:
573 import gguf
574 from gguf.constants import GGMLQuantizationType
575 except ImportError:
576 raise ImportError("gguf package required for info command. Install with: pip install gguf")
577
578 if not os.path.exists(gguf_path):
579 raise FileNotFoundError(f"File not found: {gguf_path}")
580
581 file_size = os.path.getsize(gguf_path)
582 reader = gguf.GGUFReader(gguf_path)
583
584 # Extract metadata
585 info = {
586 "path": str(Path(gguf_path).resolve()),
587 "file_size_bytes": file_size,
588 "file_size_human": _format_size(file_size),
589 "header_size": reader.header_size if hasattr(reader, 'header_size') else 0,
590 "tensor_count": len(reader.tensors) if hasattr(reader, 'tensors') else 0,
591 "metadata": {},
592 "tensors": [],
593 "quantization_types": set(),
594 }
595
596 # Get fields/metadata
597 if hasattr(reader, 'fields'):
598 for name, field in reader.fields.items():
599 try:
600 if hasattr(field, 'parts') and len(field.parts) > 0:
601 val = field.parts[-1]
602 if isinstance(val, bytes):
603 try:
604 val = val.decode('utf-8', errors='replace').strip('\x00')
605 except Exception:
606 val = str(val)
607 elif isinstance(val, np.ndarray) or hasattr(val, '__len__'):
608 # memmap or ndarray — try to convert
609 if val.ndim == 0:
610 val = val.item()
611 elif val.dtype.kind in ('S', 'U'):
612 # String data stored as bytes
613 try:
614 val = bytes(val).decode('utf-8', errors='replace').strip('\x00')
615 except Exception:
616 val = str(val)
617 elif val.dtype.kind == 'u' and val.size > 1:
618 # uint8 array — likely a stored string, decode as bytes then utf-8
619 try:
620 val = bytes(val).decode('utf-8', errors='replace').strip('\x00')
621 except Exception:
622 val = val.tolist()
623 elif val.size == 1:
624 val = val.item()
625 elif val.dtype.kind in ('i', 'u', 'f'):
626 # Numeric array — keep as list
627 val = val.tolist()
628 else:
629 val = str(val)
630 elif hasattr(val, 'item'):
631 val = val.item()
632 elif hasattr(val, 'tolist'):
633 val = val.tolist()
634 info["metadata"][name] = val
635 except Exception:
636 continue
637
638 # Get tensor info
639 if hasattr(reader, 'tensors'):
640 tensor_type_counts = {}
641 total_params = 0
642
643 for tensor in reader.tensors:
644 t_info = {
645 "name": tensor.name,
646 "shape": list(tensor.shape) if hasattr(tensor, 'shape') and tensor.shape is not None and len(tensor.shape) > 0 else [],
647 "n_elements": int(np.prod(tensor.shape)) if hasattr(tensor, 'shape') and tensor.shape is not None and len(tensor.shape) > 0 else 0,
648 }
649
650 # Get quantization type
651 if hasattr(tensor, 'tensor_type') and tensor.tensor_type is not None:
652 t_type = tensor.tensor_type
653 if hasattr(t_type, 'name'):
654 t_info["type"] = t_type.name
655 else:
656 t_info["type"] = str(t_type)
657
658 if isinstance(t_type, GGMLQuantizationType):
659 tensor_type_counts[t_type.name] = tensor_type_counts.get(t_type.name, 0) + 1
660 info["quantization_types"].add(t_type.name)
661 else:
662 t_info["type"] = "unknown"
663
664 # Get data size
665 if hasattr(tensor, 'data') and tensor.data is not None:
666 t_info["data_bytes"] = tensor.data.nbytes
667 else:
668 t_info["data_bytes"] = 0
669
670 info["tensors"].append(t_info)
671 total_params += t_info["n_elements"]
672
673 info["total_parameters"] = total_params
674 info["tensor_type_counts"] = tensor_type_counts
675
676 # Determine primary quantization type
677 quantization_counts = info.get("tensor_type_counts", {})
678 if quantization_counts:
679 # The type with the most tensors is likely the primary quant
680 primary = max(quantization_counts, key=quantization_counts.get)
681 info["primary_quantization"] = primary
682 else:
683 info["primary_quantization"] = "unknown"
684
685 # Print info
686 print(f"\n{'='*60}")
687 print(f" GGUF Model Info")
688 print(f"{'='*60}")
689 print(f" Path: {info['path']}")
690 print(f" Size: {info['file_size_human']} ({info['file_size_bytes']:,} bytes)")
691 print(f" Tensors: {info['tensor_count']}")
692 print(f" Parameters: {info.get('total_parameters', 0):,}")
693 print(f" Quantization: {info.get('primary_quantization', 'unknown')}")
694
695 # Print key metadata
696 if info["metadata"]:
697 print(f"\n Metadata:")
698 for key in sorted(info["metadata"].keys()):
699 val = info["metadata"][key]
700 if isinstance(val, str) and len(val) > 80:
701 val = val[:77] + "..."
702 print(f" {key}: {val}")
703
704 # Print tensor type distribution
705 if info.get("tensor_type_counts"):
706 print(f"\n Tensor type distribution:")
707 for ttype, count in sorted(info["tensor_type_counts"].items()):
708 print(f" {ttype}: {count} tensors")
709
710 # Print tensors (verbose)
711 if verbose and info["tensors"]:
712 print(f"\n Tensors:")
713 print(f" {'Name':50s} {'Shape':30s} {'Type':10s} {'Size':>10s}")
714 print(f" {'-'*50} {'-'*30} {'-'*10} {'-'*10}")
715 for t in info["tensors"]:
716 shape_str = str(t["shape"]) if "shape" in t else "?"
717 type_str = t.get("type", "?")
718 size_str = _format_size(t.get("data_bytes", 0))
719 print(f" {t['name']:50s} {shape_str:30s} {type_str:10s} {size_str:>10s}")
720
721 print()
722
723 return info
724
725
726def validate(
727 quantized_path: str,
728 reference_path: Optional[str] = None,
729 num_tokens: int = 3,
730 prompt: str = "Hello world",
731) -> Dict[str, Any]:
732 """Validate a quantized model by comparing against a reference.
733
734 If a reference GGUF is provided, compares final layer logits.
735 Otherwise, validates structural integrity.
736
737 Args:
738 quantized_path: Path to quantized GGUF file
739 reference_path: Path to reference GGUF (unquantized or different quant)
740 num_tokens: Number of tokens to generate for comparison
741 prompt: Input prompt
742
743 Returns:
744 Dict with validation results
745 """
746 try:
747 import gguf
748 from gguf.constants import GGMLQuantizationType
749 except ImportError:
750 raise ImportError("gguf package required for validate command")
751
752 result = {
753 "quantized_path": quantized_path,
754 "status": "unknown",
755 "checks": [],
756 }
757
758 print(f"\n{'='*60}")
759 print(f" Validate: {Path(quantized_path).name}")
760 print(f"{'='*60}")
761
762 # Check 1: File exists and readable
763 if not os.path.exists(quantized_path):
764 result["status"] = "error"
765 result["error"] = "File not found"
766 return result
767
768 file_size = os.path.getsize(quantized_path)
769 print(f" File size: {_format_size(file_size)}")
770 result["file_size"] = file_size
771
772 # Check 2: Can be read by gguf
773 try:
774 reader = gguf.GGUFReader(quantized_path)
775 tensor_count = len(reader.tensors) if hasattr(reader, 'tensors') else 0
776 print(f" Tensors loaded: {tensor_count}")
777 result["tensor_count"] = tensor_count
778 result["checks"].append({"check": "gguf_readable", "passed": True})
779 except Exception as e:
780 print(f" ERROR: Cannot read GGUF: {e}")
781 result["checks"].append({"check": "gguf_readable", "passed": False, "error": str(e)})
782 result["status"] = "corrupt"
783 return result
784
785 # Check 3: Can load all tensor data
786 errors = []
787 for tensor in reader.tensors:
788 try:
789 _ = tensor.data.shape
790 except Exception as e:
791 errors.append((tensor.name, str(e)))
792
793 if errors:
794 print(f" WARNING: {len(errors)} tensor(s) failed to load:")
795 for name, err in errors[:5]:
796 print(f" {name}: {err}")
797 result["checks"].append({"check": "tensor_data_accessible", "passed": False, "errors": errors})
798 else:
799 print(f" All tensors accessible: YES")
800 result["checks"].append({"check": "tensor_data_accessible", "passed": True})
801
802 # Check 4: Metadata integrity
803 if hasattr(reader, 'fields'):
804 required_fields = ['general.architecture', 'general.file_type']
805 missing = [f for f in required_fields if f not in reader.fields]
806 if missing:
807 print(f" Missing metadata fields: {missing}")
808 result["checks"].append({"check": "metadata_integrity", "passed": False, "missing": missing})
809 else:
810 print(f" Metadata integrity: OK")
811 result["checks"].append({"check": "metadata_integrity", "passed": True})
812
813 # Check 5: Compare with reference if provided
814 if reference_path and os.path.exists(reference_path):
815 print(f"\n Comparing with reference: {Path(reference_path).name}")
816 try:
817 ref_reader = gguf.GGUFReader(reference_path)
818
819 # Compare tensor names and shapes
820 ref_tensors = {t.name: t for t in ref_reader.tensors}
821 q_tensors = {t.name: t for t in reader.tensors}
822
823 common_names = set(ref_tensors.keys()) & set(q_tensors.keys())
824 missing_in_q = set(ref_tensors.keys()) - set(q_tensors.keys())
825 extra_in_q = set(q_tensors.keys()) - set(ref_tensors.keys())
826
827 if missing_in_q:
828 print(f" Missing tensors in quantized: {len(missing_in_q)}")
829 for n in sorted(missing_in_q)[:5]:
830 print(f" {n}")
831 if extra_in_q:
832 print(f" Extra tensors in quantized: {len(extra_in_q)}")
833
834 # Compare shapes
835 shape_mismatches = []
836 for name in sorted(common_names):
837 ref_shape = list(ref_tensors[name].shape)
838 q_shape = list(q_tensors[name].shape)
839 if ref_shape != q_shape:
840 shape_mismatches.append((name, ref_shape, q_shape))
841
842 if shape_mismatches:
843 print(f" Shape mismatches: {len(shape_mismatches)}")
844 for name, rs, qs in shape_mismatches[:5]:
845 print(f" {name}: ref={rs} vs quantized={qs}")
846
847 result["checks"].append({
848 "check": "reference_comparison",
849 "passed": len(missing_in_q) == 0 and len(shape_mismatches) == 0,
850 "common_tensors": len(common_names),
851 "missing_in_quantized": list(missing_in_q),
852 "shape_mismatches": shape_mismatches,
853 })
854
855 except Exception as e:
856 print(f" Reference comparison failed: {e}")
857 result["checks"].append({"check": "reference_comparison", "passed": False, "error": str(e)})
858
859 # Overall status
860 all_passed = all(c["passed"] for c in result["checks"])
861 result["status"] = "passed" if all_passed else "warnings" if any(not c["passed"] for c in result["checks"]) else "unknown"
862
863 print(f"\n Validation: {result['status'].upper()}")
864 print()
865
866 return result
867
868
869def benchmark(
870 gguf_path: str,
871 prompt: str = "Hello",
872 max_tokens: int = 10,
873 n_warmup: int = 2,
874) -> Dict[str, Any]:
875 """Quick performance benchmark of a GGUF model.
876
877 Uses the project's existing inference engine to measure tokens/second.
878
879 Args:
880 gguf_path: Path to GGUF file
881 prompt: Input prompt
882 max_tokens: Number of tokens to generate
883 n_warmup: Number of warmup tokens
884
885 Returns:
886 Dict with benchmark results
887 """
888 if not os.path.exists(gguf_path):
889 raise FileNotFoundError(f"File not found: {gguf_path}")
890
891 file_size = os.path.getsize(gguf_path)
892
893 print(f"\n{'='*60}")
894 print(f" Benchmark: {Path(gguf_path).name}")
895 print(f"{'='*60}")
896 print(f" Prompt: {prompt!r}")
897 print(f" Max tokens: {max_tokens}")
898 print(f" File size: {_format_size(file_size)}")
899
900 # Try to use MojoLlama inference
901 try:
902 sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
903 from mojollama.model.inference import LLMInference
904
905 import gc
906 gc.collect()
907
908 print(f" Loading model...")
909 t0 = time.time()
910 model = LLMInference(gguf_path, device="cpu")
911 load_time = time.time() - t0
912 print(f" Load time: {load_time:.1f}s")
913
914 # Get model info
915 arch_info = {}
916 if hasattr(model, 'arch'):
917 arch_info["architecture"] = model.arch
918 if hasattr(model, 'n_layers'):
919 arch_info["layers"] = model.n_layers
920 if hasattr(model, 'n_embd'):
921 arch_info["dim"] = model.n_embd
922 if hasattr(model, 'n_head'):
923 arch_info["heads"] = model.n_head
924
925 # Warmup
926 if n_warmup > 0:
927 print(f" Warmup ({n_warmup} tokens)...")
928 _ = model.generate(prompt, max_tokens=n_warmup)
929
930 # Benchmark
931 print(f" Generating {max_tokens} tokens...")
932 t0 = time.time()
933 output = model.generate(prompt, max_tokens=max_tokens)
934 elapsed = time.time() - t0
935
936 # Token counting
937 try:
938 prompt_tokens = len(model.encode(prompt))
939 output_tokens = len(model.encode(output))
940 total_tokens = prompt_tokens + output_tokens
941 except Exception:
942 prompt_tokens = 0
943 output_tokens = max_tokens
944 total_tokens = max_tokens
945
946 tokens_per_second = output_tokens / elapsed if elapsed > 0 else 0
947
948 result = {
949 "model_path": gguf_path,
950 "file_size_bytes": file_size,
951 "file_size_human": _format_size(file_size),
952 "prompt": prompt,
953 "architecture": arch_info,
954 "load_time_seconds": round(load_time, 2),
955 "max_tokens": max_tokens,
956 "generated_tokens": output_tokens,
957 "elapsed_seconds": round(elapsed, 3),
958 "tokens_per_second": round(tokens_per_second, 2),
959 "output": output,
960 }
961
962 print(f"\n Results:")
963 print(f" Generated: {output_tokens} tokens in {elapsed:.2f}s")
964 print(f" Speed: {tokens_per_second:.2f} tok/s")
965 print(f" Output: {output[:100]!r}{'...' if len(output) > 100 else ''}")
966
967 return result
968
969 except ImportError as e:
970 print(f" WARNING: Could not load MojoLlama inference: {e}")
971 print(f" Falling back to file-based benchmark...")
972 return _benchmark_fast(gguf_path, prompt, max_tokens)
973 except Exception as e:
974 print(f" WARNING: Inference benchmark failed: {e}")
975 print(f" Falling back to file-based benchmark...")
976 return _benchmark_fast(gguf_path, prompt, max_tokens)
977
978
979def _benchmark_fast(gguf_path: str, prompt: str, max_tokens: int) -> Dict[str, Any]:
980 """Quick file-based benchmark when inference isn't available."""
981 file_size = os.path.getsize(gguf_path)
982
983 # Read metadata for info
984 info = {}
985 try:
986 import gguf
987 reader = gguf.GGUFReader(gguf_path)
988 if hasattr(reader, 'fields'):
989 f = reader.fields
990 arch = None
991 if 'general.architecture' in f:
992 arch = str(f['general.architecture'].parts[-1])
993 info["architecture"] = arch
994 info["tensors"] = len(reader.tensors) if hasattr(reader, 'tensors') else 0
995 except Exception:
996 pass
997
998 result = {
999 "model_path": gguf_path,
1000 "file_size_bytes": file_size,
1001 "file_size_human": _format_size(file_size),
1002 "prompt": prompt,
1003 "architecture": info,
1004 "load_time_seconds": None,
1005 "max_tokens": max_tokens,
1006 "generated_tokens": None,
1007 "elapsed_seconds": None,
1008 "tokens_per_second": None,
1009 "output": None,
1010 "note": "Inference engine not available; metadata only"
1011 }
1012
1013 print(f"\n Model info collected. To benchmark, install MojoLlama inference dependencies.")
1014 print(f" Architecture: {info.get('architecture', 'unknown')}")
1015 print(f" Tensors: {info.get('tensors', 0)}")
1016
1017 return result
1018
1019
1020def batch_convert_and_quantize(
1021 model_name_or_path: str,
1022 types: List[str],
1023 outtype: str = "f16",
1024 output_dir: Optional[str] = None,
1025) -> List[Dict[str, Any]]:
1026 """Convert and quantize a model to multiple quantization types.
1027
1028 Args:
1029 model_name_or_path: HF model name or local path
1030 types: List of quantization types
1031 outtype: Intermediate float type for conversion
1032 output_dir: Output directory (default: current dir)
1033
1034 Returns:
1035 List of result dicts for each quantization
1036 """
1037 if output_dir is None:
1038 output_dir = "."
1039 output_dir = Path(output_dir)
1040 output_dir.mkdir(parents=True, exist_ok=True)
1041
1042 model_base = Path(model_name_or_path.rstrip("/")).name
1043 if not model_base:
1044 model_base = "model"
1045
1046 results = []
1047
1048 # Step 1: Convert to float GGUF
1049 fp_gguf = str(output_dir / f"{model_base}-{outtype}.gguf")
1050 print(f"\n{'='*60}")
1051 print(f" Step 1: Convert to {outtype} GGUF")
1052 print(f"{'='*60}")
1053
1054 try:
1055 convert_result = convert(
1056 model_name_or_path,
1057 outtype=outtype,
1058 outfile=fp_gguf,
1059 )
1060 results.append({"step": "convert", **convert_result})
1061 except Exception as e:
1062 print(f" Conversion failed: {e}")
1063 results.append({"step": "convert", "status": "error", "error": str(e)})
1064 return results
1065
1066 # Step 2: Quantize to each type
1067 for qt in types:
1068 qt = qt.lower()
1069 if qt not in QUANT_TYPES:
1070 print(f" Unknown quant type '{qt}', skipping...")
1071 results.append({"step": "quantize", "quant_type": qt, "status": "skipped", "reason": "unknown type"})
1072 continue
1073
1074 print(f"\n{'-'*60}")
1075 print(f" Step 2: Quantize to {qt}")
1076 print(f"{'-'*60}")
1077
1078 try:
1079 quant_result = quantize(
1080 fp_gguf,
1081 quant_type=qt,
1082 output_path=str(output_dir / f"{model_base}-{qt}.gguf"),
1083 )
1084 results.append({"step": "quantize", "quant_type": qt, **quant_result})
1085 except Exception as e:
1086 print(f" Quantization to {qt} failed: {e}")
1087 results.append({"step": "quantize", "quant_type": qt, "status": "error", "error": str(e)})
1088
1089 # Summary
1090 print(f"\n{'='*60}")
1091 print(f" Batch Summary")
1092 print(f"{'='*60}")
1093 for r in results:
1094 if r.get("status") == "success":
1095 if r["step"] == "convert":
1096 print(f" CONVERT: {r.get('output_path', '?')} ({r.get('size_human', '?')})")
1097 else:
1098 print(f" {r.get('quant_type', '?'):8s}: {r.get('output_path', '?')} ({r.get('output_size_human', '?')})")
1099 elif r.get("status") == "error":
1100 print(f" ERROR: {r.get('step', '?')} - {r.get('error', '?')}")
1101
1102 return results
1103
1104
1105# ─── Init .env ──────────────────────────────────────────────────────────────
1106
1107def init_env(env_path: Optional[str] = None, hf_cache: Optional[str] = None):
1108 """Initialize .env file with common HF cache paths.
1109
1110 Args:
1111 env_path: Path to .env file (default: .env in current dir)
1112 hf_cache: Custom HF cache path (default: auto-detect)
1113 """
1114 if env_path is None:
1115 env_path = ".env"
1116
1117 env_path = Path(env_path)
1118
1119 if hf_cache is None:
1120 # Auto-detect common HF cache locations
1121 candidates = [
1122 os.environ.get("HF_HOME", ""),
1123 os.environ.get("HUGGINGFACE_HUB_CACHE", ""),
1124 str(Path.home() / ".cache" / "huggingface"),
1125 "/root/.cache/huggingface",
1126 "/tmp/huggingface",
1127 ]
1128 hf_cache = next((c for c in candidates if c and Path(c).exists()), candidates[2])
1129
1130 env_vars = {
1131 "HF_HOME": hf_cache,
1132 "HUGGINGFACE_HUB_CACHE": str(Path(hf_cache) / "hub"),
1133 "LLAMA_CPP_DIR": str(LLAMA_CPP_DIR),
1134 "TRANSFORMERS_CACHE": str(Path(hf_cache) / "hub"),
1135 "HF_DATASETS_CACHE": str(Path(hf_cache) / "datasets"),
1136 }
1137
1138 # Read existing .env
1139 existing = {}
1140 if env_path.exists():
1141 with open(env_path) as f:
1142 for line in f:
1143 line = line.strip()
1144 if line and not line.startswith("#") and "=" in line:
1145 k, v = line.split("=", 1)
1146 existing[k.strip()] = v.strip()
1147
1148 # Merge (existing values take precedence)
1149 for k, v in env_vars.items():
1150 if k not in existing:
1151 existing[k] = v
1152
1153 # Write .env
1154 with open(env_path, "w") as f:
1155 f.write("# MojoLlama Quantizer Environment\n")
1156 f.write(f"# Auto-generated: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
1157 f.write("# Uncomment and edit as needed\n\n")
1158 for k, v in existing.items():
1159 f.write(f'{k}="{v}"\n')
1160
1161 print(f" Wrote {env_path}")
1162 print(f" HF_HOME: {existing.get('HF_HOME', 'not set')}")
1163 print(f" LLAMA_CPP_DIR: {existing.get('LLAMA_CPP_DIR', str(LLAMA_CPP_DIR))}")
1164
1165
1166# ─── CLI ─────────────────────────────────────────────────────────────────────
1167
1168def _build_parser() -> argparse.ArgumentParser:
1169 """Build the argument parser."""
1170 parser = argparse.ArgumentParser(
1171 description="MojoLlama Quantizer — GGUF quantization CLI tool",
1172 formatter_class=argparse.RawDescriptionHelpFormatter,
1173 epilog="""
1174Examples:
1175 %(prog)s convert meta-llama/Llama-2-7b --outtype f16 --outfile model.gguf
1176 %(prog)s quantize model.gguf --type q4_k_m
1177 %(prog)s info model.gguf -v
1178 %(prog)s validate model.gguf --reference ref.gguf
1179 %(prog)s benchmark model.gguf --prompt "Hello world"
1180 %(prog)s batch meta-llama/Llama-2-7b --types q4_0,q4_k_m,q8_0
1181 %(prog)s init-env
1182 """,
1183 )
1184 parser.add_argument(
1185 "--debug", action="store_true", help="Enable debug output"
1186 )
1187
1188 subparsers = parser.add_subparsers(dest="command", help="Sub-command")
1189
1190 # ── convert ──
1191 p_convert = subparsers.add_parser("convert", help="Convert HF model to GGUF")
1192 p_convert.add_argument("model", help="HF model name or local path")
1193 p_convert.add_argument(
1194 "--outtype", default="f16", choices=["f32", "f16", "bf16", "q8_0", "auto"],
1195 help="Output format (default: f16)",
1196 )
1197 p_convert.add_argument("--outfile", "-o", help="Output file path")
1198 p_convert.add_argument("--verbose", action="store_true", help="Verbose output")
1199 p_convert.add_argument("--vocab-only", action="store_true", help="Extract only vocab")
1200 p_convert.add_argument("--model-name", help="Model name override")
1201
1202 # ── quantize ──
1203 p_quant = subparsers.add_parser("quantize", help="Quantize a GGUF file")
1204 p_quant.add_argument("input", help="Input GGUF file")
1205 p_quant.add_argument(
1206 "--type", "-t", dest="quant_type", default="q4_k_m",
1207 help=f"Quantization type (default: q4_k_m). Options: {', '.join(sorted(QUANT_TYPES.keys()))}",
1208 )
1209 p_quant.add_argument("--output", "-o", help="Output file path")
1210 p_quant.add_argument("--allow-requantize", action="store_true",
1211 help="Allow requantizing already quantized tensors")
1212 p_quant.add_argument("--leave-output", action="store_true",
1213 help="Leave output.weight unquantized")
1214 p_quant.add_argument("--pure-python", action="store_true",
1215 help="Use pure Python Q4_0 fallback (no llama-quantize needed)")
1216 p_quant.add_argument("--dry-run", action="store_true",
1217 help="Calculate size without performing quantization")
1218 p_quant.add_argument("--override-kv", action="append",
1219 help="Override metadata KEY=TYPE:VALUE")
1220
1221 # ── info ──
1222 p_info = subparsers.add_parser("info", help="Inspect a GGUF file")
1223 p_info.add_argument("input", help="GGUF file path")
1224 p_info.add_argument("--verbose", "-v", action="store_true", help="Show all tensors")
1225
1226 # ── validate ──
1227 p_val = subparsers.add_parser("validate", help="Validate quantized model")
1228 p_val.add_argument("input", help="Quantized GGUF file")
1229 p_val.add_argument("--reference", "-r", help="Reference GGUF file for comparison")
1230 p_val.add_argument("--num-tokens", type=int, default=3, help="Tokens for comparison")
1231 p_val.add_argument("--prompt", default="Hello world", help="Input prompt")
1232
1233 # ── benchmark ──
1234 p_bench = subparsers.add_parser("benchmark", help="Benchmark model performance")
1235 p_bench.add_argument("input", help="GGUF file path")
1236 p_bench.add_argument("--prompt", default="Hello", help="Input prompt")
1237 p_bench.add_argument("--max-tokens", type=int, default=10, help="Tokens to generate")
1238 p_bench.add_argument("--no-warmup", action="store_true", help="Skip warmup")
1239
1240 # ── batch ──
1241 p_batch = subparsers.add_parser("batch", help="Batch convert and quantize")
1242 p_batch.add_argument("model", help="HF model name or local path")
1243 p_batch.add_argument(
1244 "--types", default="q4_0,q4_k_m,q8_0",
1245 help="Comma-separated quantization types (default: q4_0,q4_k_m,q8_0)",
1246 )
1247 p_batch.add_argument(
1248 "--outtype", default="f16", choices=["f32", "f16", "bf16"],
1249 help="Intermediate float type (default: f16)",
1250 )
1251 p_batch.add_argument("--output-dir", "-o", help="Output directory")
1252
1253 # ── init-env ──
1254 p_env = subparsers.add_parser("init-env", help="Initialize .env file")
1255 p_env.add_argument("--env-file", default=".env", help="Path to .env file")
1256 p_env.add_argument("--hf-cache", help="Custom HF cache path")
1257
1258 # ── list-types ──
1259 p_list = subparsers.add_parser("list-types", help="List supported quantization types")
1260
1261 return parser
1262
1263
1264def main(argv: Optional[List[str]] = None) -> int:
1265 """Main entry point."""
1266 parser = _build_parser()
1267 args = parser.parse_args(argv)
1268
1269 if args.debug:
1270 print(f"Debug: args={args}")
1271
1272 if not args.command:
1273 parser.print_help()
1274 return 1
1275
1276 try:
1277 if args.command == "convert":
1278 kwargs = {}
1279 if args.vocab_only:
1280 kwargs["vocab_only"] = True
1281 if args.model_name:
1282 kwargs["model_name"] = args.model_name
1283
1284 result = convert(
1285 args.model,
1286 outtype=args.outtype,
1287 outfile=args.outfile,
1288 verbose=args.verbose,
1289 **kwargs,
1290 )
1291 if args.debug:
1292 print(json.dumps(result, default=str, indent=2))
1293
1294 elif args.command == "quantize":
1295 override_kv = None
1296 if args.override_kv:
1297 override_kv = {}
1298 for kv in args.override_kv:
1299 if ":" in kv:
1300 k, v = kv.split(":", 1)
1301 override_kv[k] = v
1302 else:
1303 override_kv[kv] = ""
1304
1305 result = quantize(
1306 args.input,
1307 quant_type=args.quant_type,
1308 output_path=args.output,
1309 allow_requantize=args.allow_requantize,
1310 leave_output=args.leave_output,
1311 pure_python=args.pure_python,
1312 override_kv=override_kv,
1313 dry_run=args.dry_run,
1314 )
1315 if args.debug:
1316 print(json.dumps(result, default=str, indent=2))
1317
1318 elif args.command == "info":
1319 result = get_info(args.input, verbose=args.verbose)
1320 if args.debug:
1321 print(json.dumps(result, default=str, indent=2))
1322
1323 elif args.command == "validate":
1324 result = validate(
1325 args.input,
1326 reference_path=args.reference,
1327 num_tokens=args.num_tokens,
1328 prompt=args.prompt,
1329 )
1330 if args.debug:
1331 print(json.dumps(result, default=str, indent=2))
1332
1333 elif args.command == "benchmark":
1334 result = benchmark(
1335 args.input,
1336 prompt=args.prompt,
1337 max_tokens=args.max_tokens,
1338 n_warmup=0 if args.no_warmup else 2,
1339 )
1340 if args.debug:
1341 print(json.dumps(result, default=str, indent=2))
1342
1343 elif args.command == "batch":
1344 types = [t.strip().lower() for t in args.types.split(",")]
1345 result = batch_convert_and_quantize(
1346 args.model,
1347 types=types,
1348 outtype=args.outtype,
1349 output_dir=args.output_dir,
1350 )
1351 if args.debug:
1352 print(json.dumps(result, default=str, indent=2))
1353
1354 elif args.command == "init-env":
1355 init_env(env_path=args.env_file, hf_cache=args.hf_cache)
1356
1357 elif args.command == "list-types":
1358 print(f"\nSupported quantization types:\n")
1359 print(f" {'Type':12s} {'Description':35s} {'BPW':8s}")
1360 print(f" {'-'*12} {'-'*35} {'-'*8}")
1361 for name, info in sorted(QUANT_TYPES.items()):
1362 print(f" {name:12s} {info['desc']:35s} {info['bpw']:<8.2f}")
1363 print()
1364
1365 else:
1366 parser.print_help()
1367 return 1
1368
1369 return 0
1370
1371 except FileNotFoundError as e:
1372 print(f"ERROR: {e}", file=sys.stderr)
1373 return 1
1374 except RuntimeError as e:
1375 print(f"ERROR: {e}", file=sys.stderr)
1376 return 1
1377 except ImportError as e:
1378 print(f"ERROR: {e}", file=sys.stderr)
1379 return 1
1380 except Exception as e:
1381 print(f"ERROR: {e}", file=sys.stderr)
1382 if args.debug:
1383 import traceback
1384 traceback.print_exc()
1385 return 1
1386
1387
1388if __name__ == "__main__":
1389 sys.exit(main())