File size: 10,865 Bytes
fb47aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared fixtures and metrics for the audio-text retrieval harness.

Protocol (v1, pinned):
  * Query sets come from HF datasets whose audio is embedded in the parquet,
    so nothing is downloaded from YouTube, Kaggle, or Zenodo.
  * One "clip" is a unique row-group id. Its captions are the distinct caption
    strings that appear for that id.
  * Text-to-audio (T2A): every caption is a query; the only relevant item is its
    own clip. Standard single-positive AP.
  * Audio-to-text (A2T): every clip is a query; all captions of that clip are
    relevant. R@k counts a hit if any relevant caption lands in the top k.
  * Similarity is cosine on L2-normalized embeddings.
"""
from __future__ import annotations

import json
import time
from pathlib import Path

import numpy as np

DATASETS = {
    # repo, split, glob of only the shards for that split, id/text/audio columns.
    # The glob matters: loading the repo by split name still fetches every split's
    # shards (11 GB for AudioCaps), while these globs pull only the eval shards.
    "clotho": {
        "repo": "CLAPv2/Clotho",
        "split": "test",
        "files": "data/test/*.parquet",
        "id_col": "index",
        "text_col": "text",
        "audio_col": "audio",
        "captions_per_clip": 1,
    },
    "audiocaps": {
        "repo": "CLAPv2/audiocaps",
        "split": "test",
        "files": "data/test/*.parquet",
        "id_col": "index",
        "text_col": "text",
        "audio_col": "audio",
        "captions_per_clip": 1,
    },
    # Same audio as clotho5 but only the first reference, so the effect of caption
    # multiplicity can be separated from the effect of the audio itself.
    "clotho1": {
        "repo": "gijs/clotho",
        "split": "test",
        "files": None,
        "id_col": "file_name",
        "caption_cols": ["caption_1"],
        "audio_col": "audio",
        "captions_per_clip": 1,
    },
    # The five references joined into one string, matching what CLAPv2/Clotho ships.
    # Same audio and same words as clotho5, so it isolates text length from audio.
    "clotho5cat": {
        "repo": "gijs/clotho",
        "split": "test",
        "files": None,
        "id_col": "file_name",
        "caption_cols": ["caption_1", "caption_2", "caption_3", "caption_4", "caption_5"],
        "join_captions": " ",
        "audio_col": "audio",
        "captions_per_clip": 1,
    },
    # Five references per clip on the same audio as clotho1: this is the fixture
    # that puts the harness on the published protocol and exercises multi-positive AP.
    "clotho5": {
        "repo": "gijs/clotho",
        "split": "test",
        "files": None,  # parquet native; load by split name
        "id_col": "file_name",
        "caption_cols": ["caption_1", "caption_2", "caption_3", "caption_4", "caption_5"],
        "audio_col": "audio",
        "captions_per_clip": 5,
    },
}

SAMPLE_RATE = 48_000  # CLAP feature extractor expects 48 kHz


def load_rows(name: str, limit: int | None = None, revision: str | None = None):
    from datasets import load_dataset

    from datasets import Audio

    spec = DATASETS[name]
    if spec.get("files"):
        # Pull only the shards for this split, then treat them as one split.
        ds = load_dataset(spec["repo"], data_files=spec["files"], split="train",
                          revision=revision)
    else:
        ds = load_dataset(spec["repo"], split=spec["split"], revision=revision)
    # Keep audio as raw encoded bytes and decode with soundfile below. datasets>=3
    # wants torchcodec for its own decoder, and the torchcodec wheel tracks a newer
    # CUDA runtime than the cu128 image provides.
    ds = ds.cast_column(spec["audio_col"], Audio(decode=False))
    if limit:
        ds = ds.select(range(min(limit, len(ds))))
    return ds, spec


def _clip_key(row, spec) -> str:
    """Identity of a clip is its audio, not its row id.

    CLAPv2/audiocaps repeats one clip across caption rows and its `index` column is
    a shard label, not a clip id, so grouping on it collapses the whole split into
    one clip. Hash the encoded audio instead.
    """
    import hashlib

    audio = row.get(spec["audio_col"])
    if isinstance(audio, dict) and audio.get("bytes"):
        return "clip_" + hashlib.sha1(audio["bytes"]).hexdigest()[:16]
    if isinstance(audio, dict) and audio.get("path"):
        return "clip_" + hashlib.sha1(str(audio["path"]).encode()).hexdigest()[:16]
    return str(row[spec["id_col"]])


def group_clips(ds, spec) -> list[dict]:
    """Collapse rows into unique clips, first-seen order.

    Two fixture shapes are supported:
      * caption_cols present  -> one row per clip carrying N caption columns
        (clotho5: caption_1..caption_5), so every clip keeps all references;
      * text_col               -> one caption per row, collapsed by clip identity.
    """
    audio_col = spec["audio_col"]
    caption_cols = spec.get("caption_cols")
    text_col = spec.get("text_col")
    order: list[str] = []
    clips: dict[str, dict] = {}
    for row in ds:
        cid = _clip_key(row, spec)
        if cid not in clips:
            clips[cid] = {"clip_id": cid, "captions": [], "audio": row[audio_col]}
            order.append(cid)
        if caption_cols:
            texts = [(row.get(c) or "").strip() for c in caption_cols]
            if spec.get("join_captions"):
                # one caption built from all references, the CLAPv2 convention
                joined = spec["join_captions"].join(t for t in texts if t)
                texts = [joined]
        else:
            texts = [(row.get(text_col) or "").strip()]
        for text in texts:
            if text and text not in clips[cid]["captions"]:
                clips[cid]["captions"].append(text)
    return [clips[c] for c in order if clips[c]["captions"]]


def fixture_summary(clips: list[dict]) -> dict:
    """Counts plus a stable hash, so a v2 run can be compared to the fixture spec."""
    import hashlib

    h = hashlib.sha1()
    for c in clips:
        h.update(("|".join([c["clip_id"], *c["captions"]])).encode())
        h.update(b"\x00")
    caps = [len(c["captions"]) for c in clips]
    return {
        "clips": len(clips),
        "captions": int(sum(caps)),
        "min_captions_per_clip": int(min(caps)) if caps else 0,
        "max_captions_per_clip": int(max(caps)) if caps else 0,
        "fixture_sha": h.hexdigest()[:16],
    }


def to_mono_48k(audio, orig_sr: int) -> np.ndarray:
    """audio: {'bytes','path'} (decode=False), {'array','sampling_rate'}, or np array."""
    import io

    import librosa
    import soundfile as sf

    if isinstance(audio, dict) and audio.get("bytes"):
        arr, orig_sr = sf.read(io.BytesIO(audio["bytes"]), dtype="float32", always_2d=False)
        arr = np.asarray(arr, dtype=np.float32)
    elif isinstance(audio, dict):
        arr = np.asarray(audio["array"], dtype=np.float32)
        orig_sr = int(audio.get("sampling_rate", orig_sr))
    else:
        arr = np.asarray(audio, dtype=np.float32)
    if arr.ndim > 1:
        arr = arr.mean(axis=1)
    if orig_sr != SAMPLE_RATE:
        arr = librosa.resample(arr, orig_sr=orig_sr, target_sr=SAMPLE_RATE)
    return np.ascontiguousarray(arr, dtype=np.float32)


def l2norm(x: np.ndarray) -> np.ndarray:
    n = np.linalg.norm(x, axis=-1, keepdims=True)
    return x / np.clip(n, 1e-12, None)


def retrieval_metrics(sim: np.ndarray, relevance: list[set[int]], ks=(1, 5, 10),
                      per_query: bool = False, clusters: list[int] | None = None) -> dict:
    """sim: (n_query, n_target), higher is better. relevance: per-query target indices.

    With per_query=True the result also carries the two arrays a bootstrap needs:
    the 1-based rank of the first relevant item for every query, and the AP of
    every query. R@k and MRR are recoverable from the ranks, mAP from the APs.
    """
    n_query = sim.shape[0]
    # stable sort so ties break by target index rather than by memory order
    ranks = np.argsort(-sim, axis=1, kind="stable")
    out = {}
    for k in ks:
        hits = 0
        for i in range(n_query):
            top = ranks[i, :k]
            if any(int(j) in relevance[i] for j in top):
                hits += 1
        out[f"r@{k}"] = hits / n_query if n_query else 0.0

    aps: list[float] = []
    first_ranks: list[int] = []
    for i in range(n_query):
        rel = relevance[i]
        if not rel:
            continue
        found = 0
        prec_sum = 0.0
        first = 0
        for pos, j in enumerate(ranks[i], start=1):
            if int(j) in rel:
                found += 1
                if first == 0:
                    first = pos
                prec_sum += found / pos
                if found == len(rel):
                    break
        aps.append(prec_sum / len(rel))
        first_ranks.append(first if first else len(ranks[i]) + 1)
    out["map"] = float(np.mean(aps)) if aps else 0.0
    out["n_queries"] = n_query
    if per_query:
        out["first_hit_rank"] = first_ranks
        out["ap"] = aps
        # Queries inside one clip are not independent (five captions describe the
        # same audio), so a bootstrap has to resample clips, not queries.
        out["cluster"] = list(clusters) if clusters is not None else list(range(n_query))
    return out


def build_problem(clips: list[dict], audio_emb: np.ndarray, text_emb: np.ndarray,
                  per_query: bool = False):
    """Return (t2a_metrics, a2t_metrics) from per-clip and per-caption embeddings."""
    clip_index = {c["clip_id"]: i for i, c in enumerate(clips)}
    cap_owner: list[int] = []
    for i, c in enumerate(clips):
        cap_owner.extend([i] * len(c["captions"]))
    assert len(cap_owner) == text_emb.shape[0], (len(cap_owner), text_emb.shape)

    a = l2norm(audio_emb)
    t = l2norm(text_emb)

    # T2A: each caption queries for its own clip
    sim_t2a = t @ a.T
    rel_t2a = [{owner} for owner in cap_owner]
    t2a = retrieval_metrics(sim_t2a, rel_t2a, per_query=per_query, clusters=cap_owner)

    # A2T: each clip queries for any of its captions
    sim_a2t = a @ t.T
    rel_a2t = [set(j for j, o in enumerate(cap_owner) if o == i) for i in range(len(clips))]
    a2t = retrieval_metrics(sim_a2t, rel_a2t, per_query=per_query)

    return t2a, a2t, clip_index


def write_result(path: Path, payload: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    # newline="\n" keeps artifacts byte-identical across platforms; the default
    # would emit CRLF on Windows and break byte-level review of the release.
    path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n",
                    encoding="utf-8", newline="\n")
    print(f"[harness] wrote {path}")


def now() -> str:
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())