Download reproduce.py from TiGa-RCE/embedding-quant-repro-2026-07-28: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/TiGa-RCE/embedding-quant-repro-2026-07-28/resolve/main/reproduce.py
- Command line
-
hf download hf://datasets/TiGa-RCE/embedding-quant-repro-2026-07-28/reproduce.py
-
curl -L -o reproduce.py https://huggingface.co/datasets/TiGa-RCE/embedding-quant-repro-2026-07-28/resolve/main/reproduce.py
12.2 kB
| #!/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) | |