File size: 7,519 Bytes
aa09fa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import csv
import hashlib
import json
from pathlib import Path

import numpy as np
from sklearn.metrics import roc_curve


EXPECTED_TRIAL_SHA256 = "0bc0a0fe3e557f1a75fb71e566d862d460709e80a4fe28e80e49bc0ab3a536ea"
SNRS = (-10, -5, 0, 5, 10, 15, 20)
CONDITIONS = ("clean",) + tuple(
    f"{category}_{snr}"
    for category in ("speech", "music", "noise")
    for snr in SNRS
)
MODELS = (
    ("titanet_large", "NVIDIA TitaNet-Large"),
    ("campplus_lm_en_voxceleb", "WeSpeaker CAM++-LM English VoxCeleb"),
    ("w2v_bert2_lm", "WeSpeaker W2V-BERT 2.0-LM English VoxCeleb"),
)


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


def read_index(path: Path) -> list[str]:
    with path.open(newline="", encoding="utf-8") as stream:
        rows = list(csv.DictReader(stream))
    rows.sort(key=lambda row: int(row["embedding_index"]))
    return [row["relative_path"] for row in rows]


def interpolated_eer(labels: np.ndarray, scores: np.ndarray) -> float:
    fpr, tpr, _ = roc_curve(labels, scores, drop_intermediate=False)
    fnr = 1.0 - tpr
    delta = fpr - fnr
    crossing = np.flatnonzero(delta >= 0)
    if not len(crossing):
        index = int(np.argmin(np.abs(delta)))
        return float((fpr[index] + fnr[index]) / 2.0)
    high = int(crossing[0])
    if high == 0:
        return float((fpr[0] + fnr[0]) / 2.0)
    low = high - 1
    denominator = float(delta[high] - delta[low])
    weight = 0.0 if denominator == 0 else float(-delta[low] / denominator)
    return float(fpr[low] + weight * (fpr[high] - fpr[low]))


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--run", type=Path, required=True)
    parser.add_argument("--trials", type=Path, required=True)
    args = parser.parse_args()
    if sha256(args.trials) != EXPECTED_TRIAL_SHA256:
        raise RuntimeError("Cleaned trial checksum mismatch")

    labels_list: list[int] = []
    pairs: list[tuple[str, str]] = []
    for line in args.trials.read_text().splitlines():
        if line.strip():
            label, left, right = line.split()
            labels_list.append(int(label))
            pairs.append((left, right))
    labels = np.asarray(labels_list, dtype=np.int8)

    available_models = tuple(
        item for item in MODELS if (args.run / item[0] / "report.json").exists()
    )
    if not available_models:
        raise RuntimeError("No completed model reports found")
    reference_order = read_index(
        args.run / available_models[0][0] / "embedding_index.csv"
    )
    reference_index = {path: index for index, path in enumerate(reference_order)}
    missing = sorted({path for pair in pairs for path in pair if path not in reference_index})
    if missing:
        raise RuntimeError(f"Missing {len(missing)} cleaned-trial references")
    first = np.fromiter((reference_index[pair[0]] for pair in pairs), dtype=np.int32)
    second = np.fromiter((reference_index[pair[1]] for pair in pairs), dtype=np.int32)

    summary_rows: list[dict] = []
    condition_rows: list[dict] = []
    reports = {}
    for key, display in available_models:
        root = args.run / key
        if read_index(root / "embedding_index.csv") != reference_order:
            raise RuntimeError(f"Reference order differs: {key}")
        embeddings = np.load(root / "embeddings.npy", mmap_mode="r")
        if embeddings.shape[0] != len(CONDITIONS):
            raise RuntimeError(f"Condition count differs: {key}")
        norms = np.linalg.norm(embeddings, axis=-1)
        if not bool(np.all((norms > 0.99) & (norms < 1.01))):
            raise RuntimeError(f"Invalid embedding norm: {key}")
        clean_scores = np.einsum(
            "ij,ij->i", embeddings[0, first], embeddings[0, second]
        )
        scores_by_condition: dict[str, np.ndarray] = {}
        for condition_index, condition in enumerate(CONDITIONS[1:], start=1):
            forward = np.einsum(
                "ij,ij->i", embeddings[0, first], embeddings[condition_index, second]
            )
            reverse = np.einsum(
                "ij,ij->i", embeddings[condition_index, first], embeddings[0, second]
            )
            scores = (forward + reverse) / 2.0
            scores_by_condition[condition] = scores
            category, snr = condition.rsplit("_", 1)
            condition_rows.append(
                {
                    "model_key": key,
                    "model": display,
                    "category": "babble" if category == "speech" else category,
                    "snr_db": int(snr),
                    "eer_percent": interpolated_eer(labels, scores) * 100.0,
                }
            )
        groups = {
            "all_noisy": list(CONDITIONS[1:]),
            "babble": [f"speech_{snr}" for snr in SNRS],
            "music": [f"music_{snr}" for snr in SNRS],
            "noise": [f"noise_{snr}" for snr in SNRS],
        }
        aggregates = {}
        for group, selected in groups.items():
            scores = np.concatenate([scores_by_condition[item] for item in selected])
            aggregate_labels = np.tile(labels, len(selected))
            aggregates[group] = interpolated_eer(aggregate_labels, scores) * 100.0
        report = json.loads((root / "report.json").read_text())
        reports[key] = {
            "checkpoint_sha256": report["model"]["checkpoint_sha256"],
            "metadata": report["model"]["metadata"],
        }
        summary_rows.append(
            {
                "model_key": key,
                "model": display,
                "clean_eer_percent": interpolated_eer(labels, clean_scores) * 100.0,
                "all_noisy_eer_percent": aggregates["all_noisy"],
                "babble_eer_percent": aggregates["babble"],
                "music_eer_percent": aggregates["music"],
                "noise_eer_percent": aggregates["noise"],
            }
        )

    for name, rows in (
        ("benchmark_summary_cleaned_protocol.csv", summary_rows),
        ("clean_noisy_per_condition_cleaned_protocol.csv", condition_rows),
    ):
        with (args.run / name).open("w", newline="", encoding="utf-8") as stream:
            writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
            writer.writeheader()
            writer.writerows(rows)
    payload = {
        "status": "PASS",
        "protocol": {
            "name": "VoxCeleb1-O cleaned",
            "trial_file": args.trials.name,
            "trial_sha256": EXPECTED_TRIAL_SHA256,
            "trials": len(labels),
            "positive_trials": int(labels.sum()),
            "negative_trials": int(len(labels) - labels.sum()),
            "unique_references": len({path for pair in pairs for path in pair}),
            "noisy_scoring": "clean enrollment to noisy probe, both directions averaged",
            "aggregate": "scores and labels pooled before EER calculation",
        },
        "models": reports,
        "completed_models": len(available_models),
        "expected_models": len(MODELS),
        "summary": summary_rows,
    }
    (args.run / "benchmark_summary_cleaned_protocol.json").write_text(
        json.dumps(payload, indent=2, sort_keys=True) + "\n"
    )
    print(json.dumps(payload, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()