| |
| """Build matched standard-Q, oQ, or oQe embedding checkpoints at 4/6/8 bits.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import os |
| import shutil |
| import sys |
| from pathlib import Path |
|
|
|
|
| APP_RESOURCES = Path("/Applications/oMLX.app/Contents/Resources") |
| APP_SITE_PACKAGES = ( |
| APP_RESOURCES |
| / "Python/framework-mlx-base/lib/python3.11/site-packages" |
| ) |
| for dependency_path in (APP_RESOURCES, APP_SITE_PACKAGES): |
| sys.path.insert(0, str(dependency_path)) |
|
|
| from mlx_lm.convert import convert as mlx_lm_convert |
| from omlx.oq import quantize_oq_streaming |
|
|
|
|
| SENTENCE_TRANSFORMERS_FILES = ( |
| ".gitattributes", |
| "LICENSE", |
| "README.md", |
| "config_sentence_transformers.json", |
| "modules.json", |
| "1_Pooling", |
| ) |
|
|
|
|
| def progress(phase: str, pct: float, detail: str = "", meta: dict | None = None) -> None: |
| suffix = f" — {detail}" if detail else "" |
| print(f"[{pct:5.1f}%] {phase}{suffix}", flush=True) |
|
|
|
|
| def preserve_embedding_metadata(source: Path, output: Path) -> None: |
| for relative_name in SENTENCE_TRANSFORMERS_FILES: |
| source_item = source / relative_name |
| output_item = output / relative_name |
| if source_item.is_dir(): |
| shutil.copytree(source_item, output_item, dirs_exist_ok=True) |
| elif source_item.is_file(): |
| output_item.parent.mkdir(parents=True, exist_ok=True) |
| shutil.copy2(source_item, output_item) |
|
|
|
|
| def validate_output(path: Path, mode: str, bits: int, source: Path) -> dict: |
| config_path = path / "config.json" |
| shards = sorted(path.glob("*.safetensors")) |
| if not config_path.is_file() or not shards: |
| raise RuntimeError("incomplete config or weight set") |
| config = json.loads(config_path.read_text()) |
| quantization = config.get("quantization") or config.get("quantization_config") |
| if not quantization or quantization.get("bits") != bits: |
| raise RuntimeError(f"output does not declare {bits}-bit quantization") |
| optional_embedding_metadata = ( |
| "modules.json", |
| "config_sentence_transformers.json", |
| "1_Pooling/config.json", |
| ) |
| for required in optional_embedding_metadata: |
| if (source / required).is_file() and not (path / required).is_file(): |
| raise RuntimeError(f"missing embedding metadata: {required}") |
| report = path / "oq_imatrix_report.json" |
| if mode == "oqe" and not report.is_file(): |
| raise RuntimeError(f"oQ{bits}e output is missing its imatrix application report") |
| return { |
| "mode": mode, |
| "weight_files": len(shards), |
| "weight_bytes": sum(item.stat().st_size for item in shards), |
| "quantization": quantization, |
| "imatrix_report": report.is_file(), |
| } |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--source", type=Path, required=True) |
| parser.add_argument("--output", type=Path, required=True) |
| parser.add_argument("--mode", choices=("q", "oq", "oqe"), required=True) |
| parser.add_argument("--bits", type=int, choices=(4, 6, 8), default=6) |
| parser.add_argument("--imatrix-cache", type=Path) |
| parser.add_argument("--resume-partial", action="store_true") |
| args = parser.parse_args() |
|
|
| source = args.source.resolve() |
| output = args.output.resolve() |
| partial = output.with_name(f".{output.name}.partial") |
| if not (source / "config.json").is_file(): |
| raise FileNotFoundError(source / "config.json") |
| if output.exists(): |
| raise FileExistsError(output) |
| if partial.exists() and not args.resume_partial: |
| raise FileExistsError(f"stale partial output: {partial}") |
|
|
| if args.resume_partial: |
| if not partial.exists(): |
| raise FileNotFoundError(f"partial output not found: {partial}") |
| print(f"Resuming validation from {partial}", flush=True) |
| elif args.mode == "q": |
| mlx_lm_convert( |
| hf_path=str(source), |
| mlx_path=str(partial), |
| quantize=True, |
| q_group_size=64, |
| q_bits=args.bits, |
| q_mode="affine", |
| dtype="bfloat16", |
| ) |
| else: |
| enhanced = args.mode == "oqe" |
| cache_path = "" |
| if enhanced: |
| if args.imatrix_cache is None: |
| raise ValueError(f"--imatrix-cache is required for oQ{args.bits}e") |
| cache_path = str(args.imatrix_cache.resolve()) |
| quantize_oq_streaming( |
| str(source), |
| str(partial), |
| args.bits, |
| group_size=64, |
| progress_callback=progress, |
| dtype="bfloat16", |
| enhanced=enhanced, |
| imatrix_cache_path=cache_path, |
| imatrix_reuse_cache=True, |
| imatrix_strict=False, |
| imatrix_num_samples=128, |
| imatrix_seq_length=512, |
| ) |
|
|
| preserve_embedding_metadata(source, partial) |
| result = validate_output(partial, args.mode, args.bits, source) |
| os.rename(partial, output) |
| result["output"] = str(output) |
| print("VALIDATED_OUTPUT=" + json.dumps(result, sort_keys=True), flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|