File size: 8,201 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
"""Diagnostic: the same fixtures through the `laion_clap` package's own pipeline.

This is NOT a gate and NOT evidence about the release. It loads the package's
default weights, which are different models from the HF checkpoints evaluated
here, so it is expected to differ. Kept as an optional cross-check of the fixture
and clip-identity code only; exits nonzero if any requested cell fails.

Nothing here imports the harness's metric code: ranking, recall and AP are
re-implemented from scratch, and the embeddings come from `laion_clap`, a
different package with different weights and its own preprocessing. The only
thing shared with the harness is the fixture and the 10 s slice policy, because a
parity check is meaningless if the two paths score different audio.

    python control_eval.py --datasets clotho5,audiocaps --out results_control
"""
from __future__ import annotations

import argparse
import hashlib
import io
import json
import os
import platform
import sys
import time
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from common import DATASETS, SAMPLE_RATE  # fixture spec only, not metrics

SR = 48_000
TRIM = 10.0


# ---------------------------------------------------------------- fixture

def read_fixture(name: str, limit: int | None = None):
    """Load clips independently of the harness's grouping code."""
    from datasets import Audio, load_dataset

    spec = DATASETS[name]
    if spec.get("files"):
        ds = load_dataset(spec["repo"], data_files=spec["files"], split="train")
    else:
        ds = load_dataset(spec["repo"], split=spec["split"])
    ds = ds.cast_column(spec["audio_col"], Audio(decode=False))
    if limit:
        ds = ds.select(range(min(limit, len(ds))))

    clips, seen = [], {}
    for row in ds:
        audio = row[spec["audio_col"]]
        # "clip_" prefix must match common._clip_key, or the fixture fingerprints
        # differ and the parity check cannot pair the two pipelines
        key = ("clip_" + hashlib.sha1(audio["bytes"]).hexdigest()[:16]) \
            if audio.get("bytes") else str(row[spec["id_col"]])
        if key in seen:
            clip = seen[key]
        else:
            clip = {"clip_id": key, "captions": [], "audio": audio}
            seen[key] = clip
            clips.append(clip)
        cols = spec.get("caption_cols")
        texts = [row.get(c) for c in cols] if cols else [row.get(spec.get("text_col"))]
        for t in texts:
            t = (t or "").strip()
            if t and t not in clip["captions"]:
                clip["captions"].append(t)
    clips = [c for c in clips if c["captions"]]

    h = hashlib.sha1()
    for c in clips:
        h.update("|".join([c["clip_id"], *c["captions"]]).encode())
        h.update(b"\x00")
    return clips, {"clips": len(clips), "captions": sum(len(c["captions"]) for c in clips),
                   "fixture_sha": h.hexdigest()[:16]}


def decode_10s(audio) -> np.ndarray:
    import librosa
    import soundfile as sf

    arr, sr = sf.read(io.BytesIO(audio["bytes"]), dtype="float32", always_2d=False)
    arr = np.asarray(arr, dtype=np.float32)
    if arr.ndim > 1:
        arr = arr.mean(axis=1)
    if sr != SR:
        arr = librosa.resample(arr, orig_sr=sr, target_sr=SR)
    # fixed first 10 s, same policy as the harness, so no random truncation happens
    return np.ascontiguousarray(arr[: int(SR * TRIM)], dtype=np.float32)


# ---------------------------------------------------------------- metrics (independent)

def rank_metrics(sim: np.ndarray, relevance: list[set[int]], ks=(1, 5, 10)) -> dict:
    order = np.argsort(-sim, axis=1, kind="stable")
    out = {}
    for k in ks:
        out[f"r@{k}"] = float(np.mean([any(int(j) in relevance[i] for j in order[i, :k])
                                       for i in range(sim.shape[0])]))
    aps = []
    for i in range(sim.shape[0]):
        rel = relevance[i]
        hits, prec = 0, 0.0
        for pos, j in enumerate(order[i], start=1):
            if int(j) in rel:
                hits += 1
                prec += hits / pos
                if hits == len(rel):
                    break
        aps.append(prec / len(rel))
    out["map"] = float(np.mean(aps))
    out["n_queries"] = int(sim.shape[0])
    return out


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


# ---------------------------------------------------------------- main

def run(model_id: str, dataset: str, out_dir: Path, limit: int | None) -> dict:
    import laion_clap
    import torch

    clips, fx = read_fixture(dataset, limit)
    texts = [t for c in clips for t in c["captions"]]
    print(f"[control | {model_id} | {dataset}] clips={len(clips)} captions={len(texts)}")

    enable_fusion = "unfused" not in model_id
    # No `amodel` argument: passing "HTSAT-base" renames submodules so the package's
    # own checkpoint fails to load. The default architecture is the one its weights
    # were trained for.
    model = laion_clap.CLAP_Module(enable_fusion=enable_fusion)
    model.load_ckpt()  # reference weights from the package's own source

    # chunk the audio: 1045 clips at 48 kHz is ~2 GB of float32 if stacked at once
    wavs = [decode_10s(c["audio"]) for c in clips]
    chunks = []
    with torch.no_grad():
        for start in range(0, len(wavs), 32):
            chunk = wavs[start:start + 32]
            # clips vary in length; pad the chunk to its longest member
            width = max(len(w) for w in chunk)
            batch = np.stack([np.pad(w, (0, width - len(w))) for w in chunk])
            chunks.append(np.asarray(
                model.get_audio_embedding_from_data(x=batch, use_tensor=False)))
        a = np.concatenate(chunks, axis=0)
        t = np.asarray(model.get_text_embedding(texts, use_tensor=False))

    a_u, t_u = unit(a.astype(np.float64)), unit(t.astype(np.float64))
    owner = [i for i, c in enumerate(clips) for _ in c["captions"]]
    t2a = rank_metrics(t_u @ a_u.T, [{o} for o in owner])
    a2t = rank_metrics(a_u @ t_u.T,
                       [set(j for j, o in enumerate(owner) if o == i) for i in range(len(clips))])

    payload = {
        "path": "control-laion-clap",
        "model": model_id,
        "dataset": dataset,
        "fixture_fingerprint": fx["fixture_sha"],
        "fixture": fx,
        "protocol": {"sample_rate": SR, "trim_seconds": TRIM, "enable_fusion": enable_fusion,
                     "similarity": "cosine"},
        "metrics": {"t2a": t2a, "a2t": a2t},
        "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "env": {"python": platform.python_version(), "gpu": torch.cuda.get_device_name(0)
                if torch.cuda.is_available() else None},
    }
    out = out_dir / f"{model_id.replace('/', '__')}__{dataset}__control.json"
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(payload, indent=2), encoding="utf-8", newline="\n")
    print(f"wrote {out}")
    return payload


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--models", default="laion/clap-htsat-fused,laion/clap-htsat-unfused")
    ap.add_argument("--datasets", default="clotho5,audiocaps")
    ap.add_argument("--out", default="results_control")
    ap.add_argument("--limit", type=int, default=0)
    args = ap.parse_args()

    out_dir = Path(args.out)
    failures = []
    for model_id in [m.strip() for m in args.models.split(",") if m.strip()]:
        for dataset in [d.strip() for d in args.datasets.split(",") if d.strip()]:
            try:
                run(model_id, dataset, out_dir, args.limit or None)
            except Exception as exc:  # keep going so one failure does not hide the rest
                print(f"[control] FAILED {model_id} {dataset}: {exc}", file=sys.stderr)
                failures.append(f"{model_id} {dataset}: {exc}")
    if failures:
        # fail closed: a campaign that prints FAILED must not exit 0
        print(f"[control] {len(failures)} cell(s) failed", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())