Datasets:
File size: 7,263 Bytes
9bd1d61 | 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 | # /// script
# requires-python = ">=3.10"
# dependencies = [
# "numpy>=1.26",
# "pandas>=2",
# "librosa>=0.10",
# "torch>=2.4",
# "transformers>=4.45,<5",
# "nnAudio>=0.3.3",
# "laion-clap==1.1.5",
# "torchvision", "torchaudio", # used by laion_clap but not declared
# "huggingface_hub",
# ]
# ///
"""Extract one feature vector per FreeTZAN clip, for scripts/run_baselines.py.
Representations:
mfcc 20 MFCCs and their deltas (librosa defaults at 22.05 kHz), mean and std over time: 80 dims
fma FMA's precomputed librosa feature set (fma_metadata/features.csv; chroma, tonnetz, MFCC,
spectral and zero-crossing statistics), computed by FMA on the same 30 s clips: 518 dims
clap LAION-CLAP audio embedding (laion_clap package, HTSAT-base music checkpoint
music_audioset_epoch_15_esc_90.14.pt), L2-normalized and averaged over three 10 s windows: 512 dims.
(The Hugging Face transformers port, laion/larger_clap_music, gives embeddings unrelated to this
checkpoint's and chance-level zero-shot accuracy on FreeTZAN, so the reference code is used.)
mert MERT-v1-95M hidden states, averaged over time, three 10 s windows and all 13 layers: 768 dims
Output: <out-dir>/<name>.npz with arrays track_id (n,) and X (n, d), rows in metadata.csv order.
Existing files are skipped unless --overwrite is given.
Usage: uv run scripts/extract_features.py --fma-dir /path/to/fma [--features mfcc fma clap mert] [--out-dir ...]
"""
import argparse
import subprocess
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from pathlib import Path
import numpy as np
import pandas as pd
REPO = Path(__file__).resolve().parent.parent
N_WINDOWS, WINDOW_S = 3, 10
# Pinned model revisions (MERT runs code from its model repository).
CLAP = ('lukewys/laion_clap', 'b3708341862f581175dba5c356a4ebf74a9b6651', 'music_audioset_epoch_15_esc_90.14.pt')
MERT = ('m-a-p/MERT-v1-95M', '12af15fef9d0ac838c3f475bfbbf26d2060dd4f5')
def load_audio(path, sr):
p = subprocess.run(['ffmpeg', '-nostdin', '-v', 'error', '-i', str(path), '-ac', '1', '-ar', str(sr),
'-f', 'f32le', '-'], capture_output=True, check=True)
return np.frombuffer(p.stdout, np.float32)
def windows(x, sr):
"""N_WINDOWS evenly spaced WINDOW_S windows spanning the clip (clips are 29-30 s long)."""
w = WINDOW_S * sr
starts = np.linspace(0, max(len(x) - w, 0), N_WINDOWS).astype(int)
return [x[s:s + w] for s in starts]
def mfcc_one(path):
import librosa
y = load_audio(path, 22050)
m = librosa.feature.mfcc(y=y, sr=22050, n_mfcc=20)
f = np.concatenate([m, librosa.feature.delta(m)])
return np.concatenate([f.mean(1), f.std(1)])
def extract_mfcc(paths, args):
with ProcessPoolExecutor(args.workers) as ex:
return np.stack(list(ex.map(mfcc_one, paths, chunksize=8)))
def extract_fma(md, args):
f = pd.read_csv(Path(args.fma_dir) / 'fma_metadata' / 'features.csv', index_col=0, header=[0, 1, 2])
missing = set(md.track_id) - set(f.index)
assert not missing, f'{len(missing)} tracks missing from features.csv'
return f.loc[md.track_id].to_numpy(np.float32)
def embed_all(paths, sr, embed, args):
"""Decode in background threads while embedding on the GPU."""
out = []
with ThreadPoolExecutor(args.workers) as ex:
for i, x in enumerate(ex.map(lambda p: load_audio(p, sr), paths)):
out.append(embed(windows(x, sr)))
if (i + 1) % 200 == 0:
print(f' {i + 1}/{len(paths)}', flush=True)
return np.stack(out)
def extract_clap(paths, args):
import sys
import torch
from huggingface_hub import hf_hub_download
argv, sys.argv = sys.argv, sys.argv[:1] # laion_clap parses sys.argv on import
import laion_clap
sys.argv = argv
repo, rev, fname = CLAP
scalar = (np._core if hasattr(np, '_core') else np.core).multiarray.scalar
# weights_only load; the checkpoint's optimizer state also contains numpy float64 scalars
with torch.serialization.safe_globals([(scalar, 'numpy.core.multiarray.scalar'), np.dtype,
type(np.dtype(np.float64))]):
ck = torch.load(hf_hub_download(repo, fname, revision=rev), map_location='cpu', weights_only=True)
sd = ck['state_dict']
sd = {k.removeprefix('module.'): v for k, v in sd.items()}
sd.pop('text_branch.embeddings.position_ids', None) # buffer that newer transformers no longer stores
model = laion_clap.CLAP_Module(enable_fusion=False, amodel='HTSAT-base', device=args.device)
model.model.load_state_dict(sd, strict=True)
model.eval()
@torch.no_grad()
def embed(wins):
x = np.stack(wins).clip(-1, 1)
x = (x * 32767).astype(np.int16).astype(np.float32) / 32767 # 16-bit quantization, as in laion_clap's usage
return model.get_audio_embedding_from_data(x=x).mean(0) # windows are L2-normalized by laion_clap
return embed_all(paths, 48000, embed, args)
def extract_mert(paths, args):
import torch
from transformers import AutoModel, Wav2Vec2FeatureExtractor
name, rev = MERT
fe = Wav2Vec2FeatureExtractor.from_pretrained(name, revision=rev, trust_remote_code=True)
model = AutoModel.from_pretrained(name, revision=rev, trust_remote_code=True).to(args.device).eval()
@torch.no_grad()
def embed(wins):
inp = fe(wins, sampling_rate=fe.sampling_rate, return_tensors='pt')
out = model(**{k: v.to(args.device) for k, v in inp.items()}, output_hidden_states=True)
return torch.stack(out.hidden_states).mean(dim=(0, 1, 2)).cpu().numpy() # layers x windows x time
return embed_all(paths, fe.sampling_rate, embed, args)
EXTRACTORS = {'mfcc': extract_mfcc, 'fma': extract_fma, 'clap': extract_clap, 'mert': extract_mert}
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('--features', nargs='+', default=list(EXTRACTORS), choices=list(EXTRACTORS))
ap.add_argument('--fma-dir', help='FMA root with fma_metadata/; needed for "fma"')
ap.add_argument('--out-dir', default=str(Path.home() / '.cache' / 'freetzan' / 'features'))
ap.add_argument('--device', default='cuda')
ap.add_argument('--workers', type=int, default=16)
ap.add_argument('--overwrite', action='store_true')
args = ap.parse_args()
if 'fma' in args.features and not args.fma_dir:
ap.error('--fma-dir is required for the "fma" features')
md = pd.read_csv(REPO / 'metadata.csv')
paths = [REPO / p for p in md.path]
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
for name in args.features:
dst = out_dir / f'{name}.npz'
if dst.exists() and not args.overwrite:
print(f'{name}: exists, skipping ({dst})')
continue
print(f'{name}: extracting', flush=True)
X = EXTRACTORS[name](md if name == 'fma' else paths, args)
assert X.shape[0] == len(md) and np.isfinite(X).all(), name
np.savez(dst, track_id=md.track_id.to_numpy(), X=X.astype(np.float32))
print(f'{name}: {X.shape} -> {dst}', flush=True)
if __name__ == '__main__':
main()
|