File size: 4,005 Bytes
1d5cf8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Frozen-model replication on the CosyVoice 2 extension subset (data/experiment2/).

Reads only released files. For each of the 60 analysed pairs it computes the
listener agreement rate P(same) (choice 3 or 4 on the 4-point scale), scores
every model with the cosine similarity between the claimed speaker's reference
clip and the comparison clip, and reports the Pearson r with P(same), a
95% cluster-bootstrap interval over the 10 speakers, and the Spearman rank
correlation with the main-benchmark Task 1 ranking.

Models are applied frozen. Supervised models use their native embedding; SSL
models and Whisper use the layer selected on the main benchmark (the modal
layer of the nested 10-fold selection).

Usage:
    python3 extension_cosyvoice2.py
"""

import numpy as np
import pandas as pd
from scipy.stats import pearsonr, spearmanr

from extraction_utils import DEFAULT_BASE_DIR

EXT = DEFAULT_BASE_DIR / "data" / "experiment2"
SEED = 42
N_BOOT = 2000

SUPERVISED = ["resemblyzer", "ecapa_tdnn", "titanet", "rawnet3", "xvector"]
SSL_LAYER = {"wavlm": 0, "wav2vec2": 0, "xlsr": 1, "hubert": 0, "whisper": 3}

# Task 1 Pearson r on the 9,800 main-benchmark pairs, as reported in the paper
# (SSL and Whisper at the nested best layer).
MAIN_TASK1_R = {
    "resemblyzer": 0.656, "ecapa_tdnn": 0.646, "titanet": 0.638, "rawnet3": 0.617,
    "xvector": 0.597, "wavlm": 0.510, "wav2vec2": 0.471, "xlsr": 0.465,
    "hubert": 0.458, "whisper": 0.226,
}
EXTRA = ["wespeaker_resnet34_lm"]  # added after review; not in the paper's 10-model ranking


def cosine(a, b):
    return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-10))


def main():
    pairs = pd.read_csv(EXT / "pairs.csv")
    pairs = pairs[pairs["analysed"]].reset_index(drop=True)
    responses = pd.read_csv(EXT / "responses.csv")
    responses["same"] = responses["choice"].isin([3, 4]).astype(int)
    votes = responses.groupby("stimulus_id")["same"].agg(["mean", "count"])
    pairs["p_same"] = pairs["stimulus_id"].map(votes["mean"])
    pairs["n_votes"] = pairs["stimulus_id"].map(votes["count"])
    print(f"{len(pairs)} analysed pairs, {int(pairs.n_votes.sum())} judgments, "
          f"{responses[responses.stimulus_id.isin(pairs.stimulus_id)].listener_id.nunique()} "
          f"listeners, median {pairs.n_votes.median():.0f} votes per pair")

    for m in SUPERVISED + EXTRA + list(SSL_LAYER):
        if m in SSL_LAYER:
            emb = np.load(EXT / "embeddings" / "layers" / f"{m}.npz")
            get = lambda k, e=emb, L=SSL_LAYER[m]: e[k][L]
        else:
            emb = np.load(EXT / "embeddings" / f"{m}.npz")
            get = lambda k, e=emb: e[k]
        pairs[m] = [cosine(get(f"{r.claimed_speaker_id}R"), get(r.comparison_clip_id))
                    for r in pairs.itertuples()]

    models = list(MAIN_TASK1_R) + EXTRA
    ext_r = {m: pearsonr(pairs[m], pairs["p_same"])[0] for m in models}

    rng = np.random.default_rng(SEED)
    speakers = sorted(pairs["claimed_speaker_id"].unique())
    boot = {m: [] for m in models}
    for _ in range(N_BOOT):
        draw = rng.choice(speakers, size=len(speakers), replace=True)
        sub = pd.concat([pairs[pairs["claimed_speaker_id"] == s] for s in draw])
        for m in models:
            ok = sub[m].std() > 1e-10 and sub["p_same"].std() > 1e-10
            boot[m].append(pearsonr(sub[m], sub["p_same"])[0] if ok else np.nan)

    print(f"\n{'model':24s} {'main r':>7s} {'ext r':>7s}   95% CI (speaker bootstrap)")
    for m in sorted(models, key=lambda k: -ext_r[k]):
        lo, hi = np.nanpercentile(boot[m], [2.5, 97.5])
        main_r = f"{MAIN_TASK1_R[m]:.3f}" if m in MAIN_TASK1_R else "    -"
        print(f"{m:24s} {main_r:>7s} {ext_r[m]:7.3f}   [{lo:.3f}, {hi:.3f}]")

    ten = list(MAIN_TASK1_R)
    rho = spearmanr([MAIN_TASK1_R[m] for m in ten], [ext_r[m] for m in ten])[0]
    print(f"\nSpearman rho, main vs extension ranking (10 paper models): {rho:.3f}")


if __name__ == "__main__":
    main()