File size: 4,871 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
#!/usr/bin/env python3
"""Evaluate mixed BF16/quantized embedding-index compatibility.

The similarity threshold is selected from BF16 scores only, then frozen and
applied unchanged to both mixed directions.  This avoids tuning the decision
boundary on the candidate representation.
"""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path

import numpy as np


LABELS = ("q4", "oq4", "oq4e", "q6", "oq6", "oq6e", "q8", "oq8", "oq8e")


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 rank_metrics(scores: np.ndarray) -> dict:
    order = np.argsort(-scores, axis=1)
    ranks = np.array([
        int(np.where(order[index] == index)[0][0]) + 1
        for index in range(scores.shape[0])
    ])
    return {
        "top1": float(np.mean(ranks == 1)),
        "recall_at_5": float(np.mean(ranks <= 5)),
        "mrr": float(np.mean(1.0 / ranks)),
        "rank_changes_from_identity": int(np.count_nonzero(ranks != 1)),
        "worst_rank": int(ranks.max()),
    }


def threshold_metrics(scores: np.ndarray, threshold: float) -> dict:
    identity = np.eye(scores.shape[0], dtype=bool)
    predicted = scores >= threshold
    tp = int(np.count_nonzero(predicted & identity))
    fn = int(np.count_nonzero(~predicted & identity))
    fp = int(np.count_nonzero(predicted & ~identity))
    tn = int(np.count_nonzero(~predicted & ~identity))
    tpr = tp / (tp + fn) if tp + fn else 0.0
    tnr = tn / (tn + fp) if tn + fp else 0.0
    return {
        "threshold": threshold,
        "true_positive": tp,
        "false_negative": fn,
        "false_positive": fp,
        "true_negative": tn,
        "balanced_accuracy": (tpr + tnr) / 2.0,
    }


def calibrate_threshold(scores: np.ndarray) -> tuple[float, dict]:
    identity = np.eye(scores.shape[0], dtype=bool)
    values = np.unique(scores)
    candidates = np.concatenate((
        [np.nextafter(values[0], -np.inf)],
        (values[:-1] + values[1:]) / 2.0,
        [np.nextafter(values[-1], np.inf)],
    ))
    evaluated = [(float(value), threshold_metrics(scores, float(value))) for value in candidates]
    # Prefer the most accurate threshold, then the stricter threshold on ties.
    threshold, metrics = max(
        evaluated,
        key=lambda item: (item[1]["balanced_accuracy"], item[0]),
    )
    positives = scores[identity]
    negatives = scores[~identity]
    metrics.update({
        "minimum_positive_score": float(positives.min()),
        "maximum_negative_score": float(negatives.max()),
        "separation_gap": float(positives.min() - negatives.max()),
    })
    return threshold, metrics


def load_vectors(path: Path) -> tuple[np.ndarray, np.ndarray]:
    with np.load(path) as artifact:
        return artifact["queries"], artifact["documents"]


def evaluate_family(quality_dir: Path) -> dict:
    bf16_path = quality_dir / "bf16.npz"
    bf16_queries, bf16_documents = load_vectors(bf16_path)
    bf16_scores = bf16_queries @ bf16_documents.T
    threshold, calibration = calibrate_threshold(bf16_scores)
    candidates = {}
    for label in LABELS:
        path = quality_dir / f"{label}.npz"
        candidate_queries, candidate_documents = load_vectors(path)
        directions = {
            "bf16_query_candidate_index": bf16_queries @ candidate_documents.T,
            "candidate_query_bf16_index": candidate_queries @ bf16_documents.T,
        }
        candidates[label] = {
            "artifact_sha256": sha256(path),
            "directions": {
                name: {
                    "retrieval": rank_metrics(scores),
                    "fixed_threshold": threshold_metrics(scores, threshold),
                }
                for name, scores in directions.items()
            },
        }
    return {
        "bf16_artifact_sha256": sha256(bf16_path),
        "bf16_threshold_calibration": calibration,
        "candidates": candidates,
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--results-root", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    families = {}
    for quality_dir in sorted(args.results_root.glob("*/quality")):
        families[quality_dir.parent.name] = evaluate_family(quality_dir)
    result = {
        "method": "BF16-calibrated fixed threshold applied without retuning",
        "families": families,
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(result, indent=2) + "\n")
    print(json.dumps({
        "output": str(args.output),
        "families": list(families),
    }))


if __name__ == "__main__":
    main()