File size: 12,243 Bytes
ffdd9aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a14ee
ffdd9aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a14ee
 
 
 
 
 
 
 
 
 
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#!/usr/bin/env python3
"""Portable entry point for the published embedding quantization evidence."""

from __future__ import annotations

import argparse
import hashlib
import json
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parent
LOCK_PATH = ROOT / "models.lock.json"
DATASET_PATH = ROOT / "inputs/retrieval_pairs.json"
EVAL_SCRIPT = ROOT / "scripts/frozen-original/qwen3_embedding_retrieval_smoke.py"
MIXED_SCRIPT = ROOT / "scripts/frozen-original/mixed_index_compatibility.py"
FAMILIES = (
    "qwen3-embedding-0.6b",
    "gte-qwen2-1.5b",
    "qwen3-embedding-8b",
)
VARIANTS = ("bf16", "q4", "oq4", "oq4e", "q6", "oq6", "oq6e", "q8", "oq8", "oq8e")
QUICK_VARIANTS = ("bf16", "q4", "oq4e", "q6", "oq6e", "q8", "oq8e")
CUDA_VARIANTS = ("bf16", "bnb-int8", "bnb-nf4")
DEFAULT_SPACE = "TiGa-RCE/embedding-quantization-cuda-control"


def run(command: list[str]) -> None:
    print("+", " ".join(command), flush=True)
    subprocess.run(command, check=True)


def load_lock(require_complete: bool = True) -> dict:
    data = json.loads(LOCK_PATH.read_text())
    records = data.get("models", [])
    if len(records) != 30:
        raise RuntimeError(f"models.lock.json contains {len(records)} records, expected 30")
    if require_complete:
        incomplete = [item["repo_id"] for item in records if not item.get("revision")]
        if incomplete:
            raise RuntimeError(
                "model publication is incomplete; missing locked Hub revisions: "
                + ", ".join(incomplete)
            )
    return data


def model_records(family: str, profile: str) -> list[dict]:
    variants = QUICK_VARIANTS if profile == "quick" else VARIANTS
    records = {
        (item["family"], item["variant"]): item
        for item in load_lock()["models"]
    }
    return [records[(family, variant)] for variant in variants]


def mlx_command(args: argparse.Namespace) -> None:
    try:
        from huggingface_hub import snapshot_download
    except ImportError as error:
        raise RuntimeError("install the MLX environment with: uv sync --extra mlx") from error

    if sys.platform != "darwin":
        raise RuntimeError("the MLX reproduction lane requires macOS on Apple Silicon")

    output_root = Path(args.output).resolve()
    model_root = Path(args.models).resolve()
    families = FAMILIES if args.family == "all" else (args.family,)
    for family in families:
        records = model_records(family, args.profile)
        quality_dir = output_root / family / "quality"
        quality_dir.mkdir(parents=True, exist_ok=True)
        for record in records:
            variant = record["variant"]
            model_dir = model_root / family / variant
            snapshot_download(
                repo_id=record["repo_id"],
                revision=record["revision"],
                local_dir=model_dir,
            )
            vectors = quality_dir / f"{variant}.npz"
            if args.force or not vectors.exists():
                run([
                    sys.executable,
                    str(EVAL_SCRIPT),
                    "encode",
                    "--model",
                    str(model_dir),
                    "--dataset",
                    str(DATASET_PATH),
                    "--output",
                    str(vectors),
                ])

        reference = quality_dir / "bf16.npz"
        for record in records:
            variant = record["variant"]
            if variant == "bf16":
                continue
            run([
                sys.executable,
                str(EVAL_SCRIPT),
                "compare",
                "--reference",
                str(reference),
                "--candidate",
                str(quality_dir / f"{variant}.npz"),
                "--output",
                str(quality_dir / f"compare-{variant}.json"),
            ])


def mixed_command(args: argparse.Namespace) -> None:
    results_root = Path(args.results_root).resolve()
    output = Path(args.output).resolve()
    run([
        sys.executable,
        str(MIXED_SCRIPT),
        "--results-root",
        str(results_root),
        "--output",
        str(output),
    ])


def cuda_command(args: argparse.Namespace) -> None:
    try:
        from gradio_client import Client
        from huggingface_hub import get_token
    except ImportError as error:
        raise RuntimeError(
            "install the ZeroGPU client environment with: uv sync --extra zerogpu"
        ) from error

    client = Client(args.space, hf_token=get_token())
    families = FAMILIES if args.family == "all" else (args.family,)
    variants = CUDA_VARIANTS if args.variant == "all" else (args.variant,)
    output_root = Path(args.output).resolve()
    output_root.mkdir(parents=True, exist_ok=True)
    for family in families:
        for variant in variants:
            if family == "qwen3-embedding-0.6b":
                if variant == "bf16":
                    result = client.predict(api_name="/run_bf16_control")
                else:
                    result = client.predict(variant, api_name="/run_quantized_control")
            elif variant == "bf16":
                result = client.predict(family, api_name="/run_family_bf16_control")
            else:
                result = client.predict(
                    family,
                    variant,
                    api_name="/run_family_quantized_control",
                )
            if not isinstance(result, dict):
                raise RuntimeError(
                    f"unexpected Space response for {family}/{variant}: "
                    f"{type(result).__name__}"
                )
            if "diagnostic_error" in result:
                raise RuntimeError(
                    f"Space control failed for {family}/{variant}: "
                    f"{result['diagnostic_error']}: {result.get('diagnostic_message', '')}"
                )
            destination = output_root / family / f"cuda-{variant}.json"
            destination.parent.mkdir(parents=True, exist_ok=True)
            destination.write_text(json.dumps(result, indent=2) + "\n")
            print(destination)


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def verify_command(_: argparse.Namespace) -> None:
    load_lock()
    checksum_path = ROOT / "checksums.sha256"
    if not checksum_path.exists():
        raise RuntimeError("checksums.sha256 is missing")
    failures = []
    for line in checksum_path.read_text().splitlines():
        if not line.strip():
            continue
        expected, relative = line.split("  ", 1)
        path = ROOT / relative
        if not path.is_file():
            failures.append(f"missing: {relative}")
        elif sha256(path) != expected:
            failures.append(f"checksum: {relative}")

    quality_root = ROOT / "local-results/full-q4-q6-q8"
    expected_pass = {
        "qwen3-embedding-0.6b": {"q8", "oq8", "oq8e"},
        "gte-qwen2-1.5b": {"q6", "oq6", "oq6e", "q8", "oq8", "oq8e"},
        "qwen3-embedding-8b": {"q6", "oq6", "oq6e", "q8", "oq8", "oq8e"},
    }
    for family in FAMILIES:
        for variant in VARIANTS:
            path = quality_root / family / "quality" / f"{variant}.npz"
            if not path.is_file():
                failures.append(f"missing result: {path.relative_to(ROOT)}")
            if variant != "bf16":
                comparison_path = quality_root / family / "quality" / f"compare-{variant}.json"
                if not comparison_path.is_file():
                    failures.append(f"missing comparison: {comparison_path.relative_to(ROOT)}")
                    continue
                passed = bool(json.loads(comparison_path.read_text())["smoke_gate"]["passed"])
                if passed != (variant in expected_pass[family]):
                    failures.append(f"unexpected MLX gate: {family}/{variant}={passed}")

    mixed = json.loads((ROOT / "local-results/mixed-index-compatibility.json").read_text())
    if set(mixed.get("families", {})) != set(FAMILIES):
        failures.append("mixed-index result does not contain all three families")
    direction_count = 0
    maximum_false_negatives = 0
    for family in mixed.get("families", {}).values():
        for candidate in family["candidates"].values():
            for direction in candidate["directions"].values():
                direction_count += 1
                if direction["retrieval"]["top1"] != 1.0:
                    failures.append("a mixed-index direction did not retain Top-1")
                maximum_false_negatives = max(
                    maximum_false_negatives,
                    int(direction["fixed_threshold"]["false_negative"]),
                )
    if direction_count != 54:
        failures.append(f"mixed-index direction count is {direction_count}, expected 54")
    if maximum_false_negatives != 5:
        failures.append(
            f"maximum mixed-index false negatives is {maximum_false_negatives}, expected 5"
        )

    cuda_expectations = {
        "qwen3-embedding-0.6b": {"bnb-int8": True, "bnb-nf4": False},
        "gte-qwen2-1.5b": {"bnb-int8": False, "bnb-nf4": False},
        "qwen3-embedding-8b": {"bnb-int8": True, "bnb-nf4": False},
    }
    for family, variants in cuda_expectations.items():
        for variant, expected in variants.items():
            result = json.loads(
                (ROOT / "cloud-results" / family / f"cuda-{variant}.json").read_text()
            )
            if result["metrics"]["top1"] != 1.0:
                failures.append(f"CUDA Top-1 changed: {family}/{variant}")
            if family == "gte-qwen2-1.5b" and variant == "bnb-int8":
                corrected = json.loads(
                    (ROOT / "cloud-results" / family / "cuda-bnb-int8-corrected-comparison.json").read_text()
                )
                cosine = corrected["minimum_aligned_cosine_int8_vs_direct_bf16"]
            else:
                cosine = result["cuda_bf16_comparison"]["minimum_aligned_cosine_vs_cuda_bf16"]
            if (cosine >= 0.99) != expected:
                failures.append(f"unexpected CUDA gate: {family}/{variant} cosine={cosine}")

    if failures:
        raise RuntimeError("bundle verification failed:\n- " + "\n- ".join(failures))
    print(
        "PASS: locked revisions, checksums, 30 MLX vectors and gates, "
        "54 mixed-index directions, and six CUDA controls verified"
    )


def parser() -> argparse.ArgumentParser:
    root = argparse.ArgumentParser(description=__doc__)
    commands = root.add_subparsers(dest="command", required=True)

    mlx = commands.add_parser("mlx", help="download locked MLX models and rerun the gate")
    mlx.add_argument("--profile", choices=("quick", "full"), default="quick")
    mlx.add_argument("--family", choices=("all",) + FAMILIES, default="qwen3-embedding-0.6b")
    mlx.add_argument("--models", default="./work/models")
    mlx.add_argument("--output", default="./work/mlx")
    mlx.add_argument("--force", action="store_true")
    mlx.set_defaults(func=mlx_command)

    mixed = commands.add_parser("mixed-index", help="rerun the frozen migration test")
    mixed.add_argument(
        "--results-root",
        default=str(ROOT / "local-results/full-q4-q6-q8"),
    )
    mixed.add_argument("--output", default="./work/mixed-index-compatibility.json")
    mixed.set_defaults(func=mixed_command)

    cuda = commands.add_parser("cuda", help="invoke the CUDA controls on ZeroGPU")
    cuda.add_argument("--family", choices=("all",) + FAMILIES, default="qwen3-embedding-0.6b")
    cuda.add_argument("--variant", choices=("all",) + CUDA_VARIANTS, default="all")
    cuda.add_argument("--space", default=DEFAULT_SPACE)
    cuda.add_argument("--output", default="./work/cuda")
    cuda.set_defaults(func=cuda_command)

    verify = commands.add_parser("verify", help="verify the published evidence bundle")
    verify.set_defaults(func=verify_command)
    return root


if __name__ == "__main__":
    arguments = parser().parse_args()
    arguments.func(arguments)