Run audio-to-audio similarity search over a corpus with a CLAP-format audio model, measure retrieval quality, and domain-tune the audio embeddings on caller-supplied triplets.
When to use this pattern. You have a corpus of sounds (clips, stems, loops, recordings) and want to find the ones most similar to a query clip — and a number that tells you how good the retrieval is. This is the audio counterpart of the image eval_embeddings recipe; audio is simply the third embedding modality the engine supports alongside text and images.
6.1 Model
Any HuggingFace CLAP audio model works — its config.json declares model_type = "clap_audio_model" (or lists ClapModel / ClapAudioModelWithProjection in architectures), its checkpoint exposes the audio_model.audio_encoder.* + audio_projection.* HTSAT-Swin tower keys, and a preprocessor_config.json carries the feature-extractor geometry. The encoder is auto-detected from that config, exactly as the image recipe auto-detects OpenCLIP:
By default (no env var) the recipe runs against the hermetic cookbook/fixtures/htsat_clap_tiny fixture so it runs offline in CI — on the order of ten seconds on a laptop, dominated by the three training legs (the projection head, the tower LoRA, and the refused job). That fixture has random weights, so its retrieval numbers are meaningless — it exercises the full pipeline, not model quality. Point JAMMI_AUDIO_MODEL at a real CLAP checkpoint for real numbers.
Same column shape as text triplets — task="audio_embedding" is what tells the loader to read the three columns as encoded audio rather than text.
6.2.2 Audio-tower LoRA sites
target_modules names sites on this architecture. An empty list means “no tower sites” and selects the projection-head mode instead. The HTSAT-Swin audio tower offers query, key, value, attention_output, intermediate_dense, output_dense, reduction, linear1 and linear2; all-linear selects every one. A selector matches a site name exactly or as a suffix of it. A non-empty list matching nothing fails the job with a message that echoes what you submitted and lists the tower’s real names.
6.3 Input schema
column
type
notes
clip_id
utf8
per-row key
audio
binary
raw WAV/FLAC/MP3/Ogg bytes (decoded by the encoder)
Preprocessing (decode → resample to the model’s sample rate → CLAP fusion log-mel spectrogram → HTSAT-Swin tower → L2-normalized output) is handled inside the encoder per the model’s preprocessor_config.json feature-extractor geometry. The audio column may also hold file-path strings instead of inline bytes.
6.4 Golden source shape (audio mode)
eval_embeddings switches to audio-query mode when the golden source carries a query_audio (binary) column instead of query_text / query_image:
column
type
example
query_id
utf8
q_sine
query_audio
binary
raw WAV bytes of the query clip
relevant_id
utf8
clip_sine_0 (matches clip_id)
6.5 Fixtures
cookbook/fixtures/tiny_audio_corpus/ — 20 synthetic mono WAV clips in 5 timbre families (sine / harmonic / square / saw / noise), 4 per family, plus a held-out query clip per family under queries/. Synthesised programmatically by cookbook/fixtures/generate.py — no recorded audio (licensing), no tenant data.
cookbook/fixtures/tiny_audio_golden.json — per-query → expected corpus IDs (same timbre family).
cookbook/fixtures/htsat_clap_tiny/ — tiny offline HTSAT-Swin CLAP fixture used as the default CI model, generated by tests/fixtures/generate_htsat_clap.py.
JAMMI_AUDIO_MODEL names the checkpoint, any CLAP audio model as a Hugging Face repo id or local:<path>; the default is the random-weight htsat_clap_tiny fixture, which runs offline in seconds.
The corpus is 20 synthetic one-second clips in five timbre families, held inline as WAV bytes in a Parquet source: clip_id, and audio.
paths =sorted(AUDIO_CORPUS_DIR.glob("clip_*.wav"))assert paths, f"no corpus clips under {AUDIO_CORPUS_DIR}"pq.write_table( pa.table( {"clip_id": pa.array([p.stem for p in paths], type=pa.utf8()),"audio": pa.array([p.read_bytes() for p in paths], type=pa.binary()), } ), home /"corpus.parquet",)db.add_source("corpus", url=str(home /"corpus.parquet"), format="parquet")
6.7 Embed them
generate_embeddings with modality="audio" runs the audio tower over the audio column. The encoder is read from the checkpoint’s CLAP config and owns decoding, resampling and the log-mel front end; the vectors are L2-normalized.
The golden set holds a held-out query clip per family and the corpus clips of that family. A query_audio (binary) column is what switches eval_embeddings to audio queries. The numbers are reported, not judged: the fixture’s weights are random.
query_ids, query_audios, relevant_ids = [], [], []for q in json.loads(fixtures.path("tiny_audio_golden.json").read_text()): audio_bytes = (AUDIO_CORPUS_DIR / q["query_audio"]).read_bytes()for rid in q["relevant_ids"]: query_ids.append(q["query_id"]) query_audios.append(audio_bytes) relevant_ids.append(str(rid))pq.write_table( pa.table( {"query_id": pa.array(query_ids, type=pa.utf8()),"query_audio": pa.array(query_audios, type=pa.binary()),"relevant_id": pa.array(relevant_ids, type=pa.utf8()), } ), home /"golden.parquet",)db.add_source("golden", url=str(home /"golden.parquet"), format="parquet")base_metrics = db.eval_embeddings(source="corpus", golden_source="golden.public.golden", k=5)for key in METRICS: value = base_metrics["aggregate"][key]assert0.0<= value <=1.0, f"{key} out of range: {value}"print(f"{key:<16}{value:.4f}")assertlen(base_metrics["per_query"]) >0, "per_query must carry one record per query"
(anchor, positive, negative) clip triplets: for each clip, the positive is the next clip of its family and the negative a clip of another family. What makes a clip a “positive” — augmentation-similar, or co-occurring — is the caller’s data; the trainer only minimizes the triplet loss over whatever clips are paired.
With no target_modules, fine-tuning trains a projection head on top of the frozen audio tower: cheap, and the tower is untouched. Re-embedding the corpus with the tuned model and evaluating again compares the two.
job = db.fine_tune( source="triplets", base_model=MODEL, columns=["anchor", "positive", "negative"], method="lora", task="audio_embedding", lora_rank=4, learning_rate=1e-3, epochs=8, batch_size=4, warmup_steps=0, validation_fraction=0.0, early_stopping_metric="train_loss",)job.wait()tuned_model = job.output_model_idassert tuned_model.startswith("jammi:fine-tuned:"), f"unexpected model_id: {tuned_model}"print(f"fine-tuned audio model: {tuned_model}")db.generate_embeddings( source="corpus", model=tuned_model, columns=["audio"], key="clip_id", modality="audio")tuned_metrics = db.eval_embeddings(source="corpus", golden_source="golden.public.golden", k=5)for key in METRICS: value = tuned_metrics["aggregate"][key]assert0.0<= value <=1.0, f"tuned {key} out of range: {value}"for label, run in (("base ", base_metrics), ("tuned", tuned_metrics)):print(f"{label}: "+" ".join(f"{k}={run['aggregate'][k]:.4f}"for k in METRICS))
The same query clip, encoded through the tuned model, must come out different from the base encoding. This checks the vectors, not the metrics above: on a set this small the rankings rarely flip even when the vectors move. It checks change, not improvement — the fixture’s weights are random.
tuned_query_vec = db.encode_query(model=tuned_model, query=query_wav, modality="audio")assertlen(tuned_query_vec) ==len(query_vec), (f"tuned dim {len(tuned_query_vec)} differs from base dim {len(query_vec)}")max_abs_diff =max(abs(b - t) for b, t inzip(query_vec, tuned_query_vec))print(f"query embedding max |Δ| (base vs tuned): {max_abs_diff:.6f}")assert max_abs_diff >1e-4, (f"the tuned query vector equals the base one (max |Δ| = {max_abs_diff:.2e}): ""the projection head did not change the embedding")
query embedding max |Δ| (base vs tuned): 0.010910
6.13 Adapt the tower itself
A non-empty target_modules puts LoRA inside the HTSAT-Swin tower, on the same triplets: query and value are the Swin blocks’ attention projections, linear1 the audio projection’s first linear. The tower’s own representation moves — more capacity for a domain the base checkpoint never saw, at more compute. The adapted model registers under the audio task, and the same query encodes differently through it: an adapter that trained but was dropped at serve time would leave the two vectors identical.
tower_job = db.fine_tune( source="triplets", base_model=MODEL, columns=["anchor", "positive", "negative"], method="lora", task="audio_embedding", target_modules=["query", "value", "linear1"], lora_rank=4, learning_rate=5e-3, epochs=2, batch_size=4, warmup_steps=0, validation_fraction=0.0, early_stopping_metric="train_loss",)tower_job.wait()tower_model = tower_job.output_model_idassert tower_model.startswith("jammi:fine-tuned:"), f"unexpected model_id: {tower_model}"print(f"tower-adapted audio model: {tower_model}")described = db.describe_model(tower_model)assert described isnotNone, f"{tower_model} missing from the catalog"assert described["task"] =="audio_embedding", f"registered under the wrong task: {described}"tower_query_vec = db.encode_query(model=tower_model, query=query_wav, modality="audio")assertlen(tower_query_vec) ==len(query_vec), (f"tower-adapted dim {len(tower_query_vec)} differs from base dim {len(query_vec)}")tower_max_abs_diff =max(abs(b - t) for b, t inzip(query_vec, tower_query_vec))print(f"query embedding max |Δ| (base vs tower-adapted): {tower_max_abs_diff:.6f}")assert tower_max_abs_diff >1e-4, (f"the adapted query vector equals the base one (max |Δ| = {tower_max_abs_diff:.2e}): ""the adapter was trained but is not applied when the model is served")
tower-adapted audio model: jammi:fine-tuned:539ddaf4-ac7d-4a06-ac0d-1f85e24bc04e
query embedding max |Δ| (base vs tower-adapted): 0.214246
6.14 A selector that matches nothing is refused
q_proj is a real site on many decoder checkpoints and on nothing in an HTSAT-Swin tower. Selecting no site would train zero parameters and publish an adapter that changes nothing, so the engine fails the job, and the message names this tower’s real sites. linear1 appears only in this tower’s site list, so it is the part of the message that proves it.
refused = db.fine_tune( source="triplets", base_model=MODEL, columns=["anchor", "positive", "negative"], method="lora", task="audio_embedding", target_modules=["q_proj"], lora_rank=4, epochs=1, batch_size=4, warmup_steps=0, validation_fraction=0.0, early_stopping_metric="train_loss",)try: refused.wait()except TrainingError as error: message =str(error)print(f"refused: {message}")assert"q_proj"in message, f"the refusal must echo the submitted selector: {message}"assert"query"in message and"linear1"in message, (f"the refusal must name this tower's real sites: {message}" )else:raiseAssertionError("a target_modules list matching no site must fail the job")
refused: Fine-tune error: target_modules ["q_proj"] matched no LoRA site on the 'clap_audio_model' audio tower (base model 'local:/__w/jammi-ai/jammi-ai/cookbook/book/jammi_cookbook/_fixtures/htsat_clap_tiny', model_type 'clap_audio_model'), so this job would train zero parameters and publish an adapter that changes nothing. This tower's own LoRA site names are: ["query", "key", "value", "attention_output", "intermediate_dense", "output_dense", "reduction", "linear1", "linear2"] — a selector matches a site name exactly or as a suffix of it (so 'query' selects 'attention.self.query' on a BERT-family tower, whose sites are named by their full dotted checkpoint path), and 'all-linear' selects every site.
2026-10-03T07:43:12.786980Z ERROR jammi_ai::fine_tune::worker: training job failed job_id=c7a0b046-c94a-4625-9896-e8621b2097ed error=Fine-tune error: target_modules ["q_proj"] matched no LoRA site on the 'clap_audio_model' audio tower (base model 'local:/__w/jammi-ai/jammi-ai/cookbook/book/jammi_cookbook/_fixtures/htsat_clap_tiny', model_type 'clap_audio_model'), so this job would train zero parameters and publish an adapter that changes nothing. This tower's own LoRA site names are: ["query", "key", "value", "attention_output", "intermediate_dense", "output_dense", "reduction", "linear1", "linear2"] — a selector matches a site name exactly or as a suffix of it (so 'query' selects 'attention.self.query' on a BERT-family tower, whose sites are named by their full dotted checkpoint path), and 'all-linear' selects every site.