File size: 5,162 Bytes
ffdd9aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/env python3
"""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  # noqa: E402
from omlx.oq import quantize_oq_streaming  # noqa: E402


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()