b4ph's picture
CLAP audio-text retrieval: pinned-protocol measurement release (v15)
fb47aa2 verified
Raw History Blame Contribute Delete
10.9 kB
"""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())