Skip to content

What is heard: audio tagging, BEATs, CLAP and the CLAP score

Taggers learn hundreds of sound classes from weakly labeled clips (AST, PANNs); BEATs learns general audio without labels; CLAP and AudioCLIP put sounds and words in one space, which also gives a score for generated audio.

Advanced ~17 min11 steps

What runs in CodeSplash

You will be able to

  • Explain weak, multi-label clip tagging and why its scores aren't event times or calibrated probabilities
  • Describe AST's spectrogram patches and PANNs' convolutional taggers
  • Describe BEATs' tokenizer and masked audio modeling
  • Explain contrastive language–audio models, zero-shot labels, and the limits of the CLAP score

Read first

01

Weak labels, many at once

Read

The standard training set for sound tagging, Google's AudioSet, labels each ten-second clip with the sound classesAudioSet tagsGoogle's 527 sound classes (speech, music, dog, siren…); the tagger scores each one from 0 to 1 per file. heard somewhere in it, out of 527: speech, dog, siren, music genres and more. That is weak labeling: no times, and several labels per clip.

So taggers are multi-label: one sigmoid per class, trained with binary cross-entropy, not one softmax. A score says "this class is likely present in the clip", not when, and it isn't a calibrated probability unless someone calibrated it on data like yours.

02

AST: a vision transformer for spectrograms

Read

The Audio Spectrogram TransformerAudio Spectrogram Transformer (AST)A vision transformer applied to 16×16 patches of a log-mel spectrogram; this one was trained on AudioSet by MIT. (AST) cuts the log-mel spectrogram into small overlapping patches, embeds each with a linear map plus a position embedding, and runs a Transformer over the patch sequence, much as a vision transformerVision transformer (ViT)Cuts an image into fixed-size patches, turns each into a token with a position embedding, and runs a Transformer on them. does with image patches. Starting from ImageNet weights helps, despite the change of domain.

The reference's example scores three tags against labels with binary cross-entropy: 0.228.

Reference · AUD052 · Runs in CodeSplashAudio Spectrogram Transformer (AST)A supervised audio-classification architecture treating spectrogram patches as a sequence for a Transformer. It adapts image-style patch attention to audio tagging and can use transfer initialization, while the labels…
03

AST in CodeSplash

Read
Sound tagsRecorded · Python and R agreeRecorded 2026-11-25 · 15 values compared
R

4 recordings (4.5 s) were tagged with the 527 AudioSet classes; the most common top tag is “Sine wave” (2 of 4 files).

Files tagged
4
Mean top score
0.5335

Plots

Tag scores by fileWhat do the values of a square or rectangular result matrix look like at a glance?
View data
TagScoreFileScore
Sine wave0.711. tone_440.wav0.7139
Static0.001. tone_440.wav0.0001
Sound effect0.001. tone_440.wav0.0029
Music0.001. tone_440.wav0.0030
White noise0.001. tone_440.wav0.0002
Electronic music0.001. tone_440.wav0.0002
Synthesizer0.001. tone_440.wav0.0002
Chirp tone0.011. tone_440.wav0.0115
Dial tone0.071. tone_440.wav0.0691
Speech0.001. tone_440.wav0.0033
Beep, bleep0.021. tone_440.wav0.0218
Busy signal0.041. tone_440.wav0.0420
Sine wave0.292. chirp.wav0.2877
Static0.002. chirp.wav0.0002
Sound effect0.032. chirp.wav0.0307
Music0.022. chirp.wav0.0160
White noise0.002. chirp.wav0.0006
Electronic music0.002. chirp.wav0.0017
Synthesizer0.002. chirp.wav0.0050
Chirp tone0.072. chirp.wav0.0738
Dial tone0.012. chirp.wav0.0071
Speech0.012. chirp.wav0.0056
Beep, bleep0.032. chirp.wav0.0319
Busy signal0.002. chirp.wav0.0028
Sine wave0.003. noise.wav0.0003
Static0.763. noise.wav0.7562
Sound effect0.013. noise.wav0.0074
Music0.033. noise.wav0.0293
White noise0.183. noise.wav0.1805
Electronic music0.003. noise.wav0.0011
Synthesizer0.003. noise.wav0.0002
Chirp tone0.003. noise.wav4.379e-5
Dial tone0.003. noise.wav0.0001
Speech0.063. noise.wav0.0551
Beep, bleep0.003. noise.wav0.0006
Busy signal0.003. noise.wav0.0002
Sine wave0.004. ana_1.wav0.0005
Static0.004. ana_1.wav0.0013
Sound effect0.384. ana_1.wav0.3760
Music0.324. ana_1.wav0.3151
White noise0.004. ana_1.wav0.0007
Electronic music0.104. ana_1.wav0.0952
Synthesizer0.094. ana_1.wav0.0924
Chirp tone0.004. ana_1.wav0.0002
Dial tone0.004. ana_1.wav0.0003
Speech0.014. ana_1.wav0.0105
Beep, bleep0.004. ana_1.wav0.0009
Busy signal0.004. ana_1.wav0.0019
Top tag of each fileHow often does each category occur?
View data
Top tag
Sine wave
Sine wave
Static
Sound effect

Assumptions

  • Clip-level tags, not events — AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high).
  • Scores are not probabilities you can trust — Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances.
  • Sounds like AudioSet — Shortest file 1.00 s.

Top 5 tags per file

pathSeconds10-s windowsTags (score)
media/aud3/tone_440.wav11Sine wave 0.71; Dial tone 0.07; Busy signal 0.04; Beep, bleep 0.02; Chirp tone 0.01
media/aud3/chirp.wav11Sine wave 0.29; Chirp tone 0.07; Beep, bleep 0.03; Sound effect 0.03; Music 0.02
media/aud3/noise.wav11Static 0.76; White noise 0.18; Speech 0.06; Music 0.03; Pink noise 0.02
media/aud3/ana_1.wav1.5001Sound effect 0.38; Music 0.32; Electronic music 0.10; Synthesizer 0.09; Techno 0.02

Most common tags (score ≥ 0.2)

TagFilesShare of filesMean score
Sine wave20.50000.2506
Static10.25000.1894
Sound effect10.25000.1043
Music10.25000.0909
White noise000.0455
Electronic music000.0246
Synthesizer000.0245
Chirp tone000.0214
Dial tone000.0192
Speech000.0186
Beep, bleep000.0138
Busy signal000.0117
Techno000.0064
Pink noise000.0059
Musical instrument000.0056
Noise000.0054
Boing000.0053
Sampler000.0042
Cacophony000.0041
Echo000.0037
Waterfall000.0032
Reverberation000.0031
Video game music000.0030
Spray000.0030
Ringtone000.0028
Inside, small room000.0023
Silence000.0023
Keyboard (musical)000.0021
Television000.0019
Vehicle000.0018
  • Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, float64. A file's score for a tag is its largest window score.
The exact R script · R R version 4.5.1 (2025-06-13)
# Tag sounds (AudioSet)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.tag 1.0.0 · spec 9f28f0e5cc1f9da6
# Dataset: aud3_sounds (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ast_* (Audio Spectrogram Transformer)

# %% Audio files listed in the path column
PATH <- "path"
TOP_K <- as.integer(5)
POOLING <- "max"  # max | mean over 10-second windows
THRESHOLD <- 0.2
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud3_sounds.parquet"))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud3_sounds.parquet", col_select = PATH))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
paths <- as.character(df[[PATH]])
paths[is.na(paths) | !nzchar(trimws(paths))] <- NA_character_
if (all(is.na(paths))) cs_error("CS_E_ALL_MISSING", column = PATH)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":60,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.tag/sounds-default/out-r", df,
                        "tests/parity/fixtures/aud3_sounds.parquet")
media_ids <- cs_media_ids(media, df)
if (is.null(media$root)) media$root <- DATA_DIR  # outside the app, relative paths start next to the data file
warnings <- character(0)
status <- cs_media_status(media, ifelse(is.na(paths), NA_character_, media_ids))
ok <- which(!is.na(paths) & is.na(status))
n_no_path <- sum(is.na(paths))
unreadable <- which(!is.na(paths) & !is.na(status))
if (!length(ok)) cs_error("CS_E_MEDIA_DECODE", file = paths[unreadable[1]], reason = status[unreadable[1]])
if (n_no_path > 0) warnings <- c(warnings, sprintf("%d rows have no file path and are left out.", n_no_path))
if (length(unreadable)) warnings <- c(warnings, sprintf("%d files couldn't be decoded and are left out (first: %s: %s).",
                                                        length(unreadable), paths[unreadable[1]], status[unreadable[1]]))

# %% AudioSet tags (AST, float64 on one thread: the Parity profile)
torch::torch_set_num_threads(1L)
model <- cs_ast_load(cs_ast_locate())
labels <- model$labels
progress <- cs_progress(sprintf("Tagging %d recordings", length(ok)), total = length(ok))
secs <- numeric(length(ok))
P <- matrix(0, nrow = length(ok), ncol = length(labels))
n_win <- integer(length(ok))
for (k in seq_along(ok)) {
  clip <- as.numeric(cs_media_audio(media, media_ids[ok[k]])[[1]])
  secs[k] <- length(clip) / 16000
  r <- cs_ast_run(model, list(clip), POOLING)
  P[k, ] <- r$probs[1, ]
  n_win[k] <- r$windows[1]
  cs_progress_update(progress, k)
}
cs_progress_done(progress)
tops <- cs_ast_top_k(P, labels, TOP_K)

# %% Artifact: the top tags of every file (long format)
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.tag/sounds-default/out-r")
long <- do.call(rbind, lapply(seq_along(ok), function(k) data.frame(
  row = as.integer(ok[k] - 1L), media_id = media_ids[ok[k]], path = paths[ok[k]], rank = seq_along(tops[[k]]),
  tag = vapply(tops[[k]], function(t) t$label, character(1)), score = vapply(tops[[k]], function(t) t$score, numeric(1)),
  stringsAsFactors = FALSE)))
nanoparquet::write_parquet(long, file.path(out, "tags.parquet"))

# %% Tag summary: files where the tag scores at least the threshold
n_files_tag <- colSums(P >= THRESHOLD)
mean_score <- colMeans(P)
ord <- order(-n_files_tag, -mean_score, seq_along(labels), method = "radix")
summary_rows <- lapply(head(ord, 30), function(j) list(tag = labels[j], files = as.integer(n_files_tag[j]),
                                                         share = n_files_tag[j] / length(ok), mean_score = mean_score[j]))
top1 <- vapply(tops, function(t) t[[1]]$label, character(1))
counts <- table(top1)
cn <- names(counts)
cv <- as.integer(counts)
top_tag <- cn[order(-cv, cn, method = "radix")][1]

# %% Assumptions
assumptions <- list(
  list(key = "weak_labels", label = "Clip-level tags, not events", status = "info",
       detail = "AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high)."),
  list(key = "calibration", label = "Scores are not probabilities you can trust", status = "info",
       detail = "Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances."),
  list(key = "domain", label = "Sounds like AudioSet", status = if (min(secs) < 1) "warn" else "pass",
       detail = paste0(sprintf("Shortest file %.2f s", min(secs)), if (min(secs) < 1) "; very short clips are padded with silence and tag poorly." else "."))
)

# %% Result
values <- list(n_rows = nrow(df), n_files = length(ok) + length(unreadable), n_tagged = length(ok), n_unreadable = length(unreadable),
               n_no_path = n_no_path, audio_seconds = sum(secs), n_windows = sum(n_win), top_tag = top_tag,
               top_tag_files = as.integer(counts[[top_tag]]), n_distinct_top = length(cn), n_labels = length(labels), threshold = THRESHOLD,
               pooling = POOLING, top_k = TOP_K, mean_top_score = mean(vapply(tops, function(t) t[[1]]$score, numeric(1))))
file_rows <- lapply(seq_along(ok), function(k) list(file = paths[ok[k]], seconds = secs[k], windows = n_win[k],
  tags = paste(vapply(tops[[k]], function(t) sprintf("%s %.2f", t$label, t$score), character(1)), collapse = "; ")))
tables <- list(
  list(key = "files", title = sprintf("Top %d tags per file", TOP_K), columns = list(
    list(key = "file", label = PATH, type = "string"), list(key = "seconds", label = "Seconds", type = "number"),
    list(key = "windows", label = "10-s windows", type = "integer"), list(key = "tags", label = "Tags (score)", type = "string")),
    rows = head(file_rows, 500), note = if (length(file_rows) > 500) "First 500 files." else NULL),
  list(key = "tags", title = sprintf("Most common tags (score ≥ %s)", format(THRESHOLD)), columns = list(
    list(key = "tag", label = "Tag", type = "string"), list(key = "files", label = "Files", type = "integer"),
    list(key = "share", label = "Share of files", type = "number"), list(key = "mean_score", label = "Mean score", type = "number")),
    rows = summary_rows)
)
m <- min(length(ok), 40L)
cols_t <- labels[head(ord, 12)]
jt <- match(cols_t, labels)
lv <- sprintf("%d. %s", seq_len(m), basename(paths[ok[seq_len(m)]]))
ia <- rep(seq_len(m), each = length(cols_t))
it <- rep(seq_along(cols_t), times = m)
charts <- list(
  cs_chart("heatmap", "matrix-heatmap", paste0("Tag scores by file", if (length(ok) > 40) " — first 40 files" else ""), list(
    row = cs_col("File", lv[ia], "categorical", levels = lv),
    col = cs_col("Tag", cols_t[it], "categorical", levels = cols_t),
    value = cs_col("Score", P[cbind(ia, jt[it])]),
    label = cs_col("Score", sprintf("%.2f", P[cbind(ia, jt[it])]), "categorical")),
    controls = list(scale = "sequential")),
  cs_chart("top", "bar", "Top tag of each file", list(x = cs_col("Top tag", top1, "categorical")), controls = list(orientation = "horizontal"))
)
summary <- sprintf("%d recordings (%.1f s) were tagged with the 527 AudioSet classes; the most common top tag is “%s” (%d of %d files).",
                   length(ok), sum(secs), top_tag, as.integer(counts[[top_tag]]), length(ok))
cs_publish(list(
  method = "audio.tag",
  methodVersion = "1.0.0",
  title = "Sound tags",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(ok),
  summary = summary,
  statistics = list(list(key = "n_tagged", label = "Files tagged", value = length(ok), format = "integer"),
                    list(key = "mean_top_score", label = "Mean top score", value = values$mean_top_score)),
  tables = tables,
  assumptions = assumptions,
  warnings = as.list(warnings),
  notes = list(sprintf(paste0("Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, ",
                              "float64. A file's score for a tag is its %s window score."), if (POOLING == "max") "largest" else "mean")),
  charts = charts,
  artifacts = list(list(key = "tags", path = file.path(out, "tags.parquet"), format = "parquet")),
  values = values
))
Python

4 recordings (4.5 s) were tagged with the 527 AudioSet classes; the most common top tag is “Sine wave” (2 of 4 files).

Files tagged
4
Mean top score
0.5335

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Clip-level tags, not events — AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high).
  • Scores are not probabilities you can trust — Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances.
  • Sounds like AudioSet — Shortest file 1.00 s.

Top 5 tags per file

pathSeconds10-s windowsTags (score)
media/aud3/tone_440.wav11Sine wave 0.71; Dial tone 0.07; Busy signal 0.04; Beep, bleep 0.02; Chirp tone 0.01
media/aud3/chirp.wav11Sine wave 0.29; Chirp tone 0.07; Beep, bleep 0.03; Sound effect 0.03; Music 0.02
media/aud3/noise.wav11Static 0.76; White noise 0.18; Speech 0.06; Music 0.03; Pink noise 0.02
media/aud3/ana_1.wav1.5001Sound effect 0.38; Music 0.32; Electronic music 0.10; Synthesizer 0.09; Techno 0.02

Most common tags (score ≥ 0.2)

TagFilesShare of filesMean score
Sine wave20.50000.2506
Static10.25000.1894
Sound effect10.25000.1043
Music10.25000.0909
White noise000.0455
Electronic music000.0246
Synthesizer000.0245
Chirp tone000.0214
Dial tone000.0192
Speech000.0186
Beep, bleep000.0138
Busy signal000.0117
Techno000.0064
Pink noise000.0059
Musical instrument000.0056
Noise000.0054
Boing000.0053
Sampler000.0042
Cacophony000.0041
Echo000.0037
Waterfall000.0032
Reverberation000.0031
Video game music000.0030
Spray000.0030
Ringtone000.0028
Inside, small room000.0023
Silence000.0023
Keyboard (musical)000.0021
Television000.0019
Vehicle000.0018
  • Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, float64. A file's score for a tag is its largest window score.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Tag sounds (AudioSet)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.tag 1.0.0 · spec 9f28f0e5cc1f9da6
# Dataset: aud3_sounds (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd
import torch

import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import ast  # Audio Spectrogram Transformer (twin: codesplashr cs_ast_*)

# %% Audio files listed in the path column
PATH = "path"
TOP_K = int(5)
POOLING = "max"  # max | mean over 10-second windows
THRESHOLD = 0.2
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud3_sounds.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud3_sounds.parquet", columns=[PATH])
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
paths = [None if (pd.isna(p) or not str(p).strip()) else str(p) for p in df[PATH].tolist()]  # None, NaN, pd.NA: no path
if all(p is None for p in paths):
    cs.cs_error("CS_E_ALL_MISSING", column=PATH)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":60,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.tag/sounds-default/out-python", df, "tests/parity/fixtures/aud3_sounds.parquet")
media_ids = cs_media.ids_of(media, df)
if media.get("root") is None:
    media["root"] = DATA_DIR  # outside the app, relative paths start next to the data file
warnings = []
status = cs_media.status(media, [m if p is not None else None for m, p in zip(media_ids, paths)])
ok = [i for i, (p, s) in enumerate(zip(paths, status)) if p is not None and s is None]
n_no_path = sum(p is None for p in paths)
unreadable = [i for i, (p, s) in enumerate(zip(paths, status)) if p is not None and s is not None]
if not ok:
    i = unreadable[0]
    cs.cs_error("CS_E_MEDIA_DECODE", file=paths[i], reason=status[i])
if n_no_path:
    warnings.append(f"{n_no_path} rows have no file path and are left out.")
if unreadable:
    warnings.append(f"{len(unreadable)} files couldn't be decoded and are left out (first: {paths[unreadable[0]]}: {status[unreadable[0]]}).")

# %% AudioSet tags (AST, float64 on one thread: the Parity profile)
torch.set_num_threads(1)
model = ast.load(ast.locate())
labels = model["labels"]
progress = cs.progress(f"Tagging {len(ok)} recordings", total=len(ok))
secs, P, n_win = [], np.zeros((len(ok), len(labels))), np.zeros(len(ok), dtype=np.int64)
for k, i in enumerate(ok):
    clip = np.asarray(cs_media.audio(media, [media_ids[i]])[0], dtype=np.float64)
    secs.append(clip.size / 16000.0)
    r = ast.run(model, [clip], POOLING)
    P[k] = r["probs"][0]
    n_win[k] = int(r["windows"][0])
    progress.update(k + 1)
progress.done()
tops = ast.top_k(P, labels, TOP_K)

# %% Artifact: the top tags of every file (long format)
out = csml.out_dir("target/academy-parity/run-8142/audio.tag/sounds-default/out-python")
long = pd.DataFrame([{"row": i, "media_id": media_ids[i], "path": paths[i], "rank": r + 1, "tag": t, "score": s}
                     for k, i in enumerate(ok) for r, (t, s) in enumerate(tops[k])])
long["row"] = long["row"].astype(np.int64)
long["rank"] = long["rank"].astype(np.int64)
long.to_parquet(os.path.join(out, "tags.parquet"), index=False)

# %% Tag summary: files where the tag scores at least the threshold
present = P >= THRESHOLD
n_files_tag = present.sum(axis=0)
mean_score = P.mean(axis=0)
order = np.lexsort((np.arange(len(labels)), -mean_score, -n_files_tag))
summary_rows = [{"tag": labels[j], "files": int(n_files_tag[j]), "share": float(n_files_tag[j] / len(ok)), "mean_score": float(mean_score[j])}
                for j in order[:30]]
top1 = [t[0][0] for t in tops]
counts = {}
for t in top1:
    counts[t] = counts.get(t, 0) + 1
top_tag = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]

# %% Assumptions
assumptions = [
    {"key": "weak_labels", "label": "Clip-level tags, not events", "status": "info",
     "detail": "AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high)."},
    {"key": "calibration", "label": "Scores are not probabilities you can trust", "status": "info",
     "detail": "Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances."},
    {"key": "domain", "label": "Sounds like AudioSet", "status": "warn" if min(secs) < 1.0 else "pass",
     "detail": f"Shortest file {min(secs):.2f} s" + ("; very short clips are padded with silence and tag poorly." if min(secs) < 1.0 else ".")},
]

# %% Result
values = {"n_rows": len(df), "n_files": len(ok) + len(unreadable), "n_tagged": len(ok), "n_unreadable": len(unreadable), "n_no_path": n_no_path,
          "audio_seconds": float(sum(secs)), "n_windows": int(n_win.sum()), "top_tag": top_tag, "top_tag_files": counts[top_tag],
          "n_distinct_top": len(counts), "n_labels": len(labels), "threshold": THRESHOLD, "pooling": POOLING, "top_k": TOP_K,
          "mean_top_score": float(np.mean([t[0][1] for t in tops]))}
file_rows = [{"file": paths[i], "seconds": secs[k], "windows": int(n_win[k]),
              "tags": "; ".join(f"{t} {s:.2f}" for t, s in tops[k])} for k, i in enumerate(ok)]
tables = [
    {"key": "files", "title": f"Top {TOP_K} tags per file", "columns": [
        {"key": "file", "label": PATH, "type": "string"}, {"key": "seconds", "label": "Seconds", "type": "number"},
        {"key": "windows", "label": "10-s windows", "type": "integer"}, {"key": "tags", "label": "Tags (score)", "type": "string"}],
     "rows": file_rows[:500], "note": "First 500 files." if len(file_rows) > 500 else None},
    {"key": "tags", "title": f"Most common tags (score ≥ {THRESHOLD:g})", "columns": [
        {"key": "tag", "label": "Tag", "type": "string"}, {"key": "files", "label": "Files", "type": "integer"},
        {"key": "share", "label": "Share of files", "type": "number"}, {"key": "mean_score", "label": "Mean score", "type": "number"}],
     "rows": summary_rows},
]
m = min(len(ok), 40)
cols_t = [labels[j] for j in order[:12]]
lv = [f"{k + 1}. {os.path.basename(paths[ok[k]])}" for k in range(m)]
charts = [
    cs.chart("heatmap", "matrix-heatmap", "Tag scores by file" + (" — first 40 files" if len(ok) > 40 else ""), {
        "row": cs.col("File", [lv[a] for a in range(m) for _ in cols_t], "categorical", levels=lv),
        "col": cs.col("Tag", [t for _ in range(m) for t in cols_t], "categorical", levels=cols_t),
        "value": cs.col("Score", [float(P[a, labels.index(t)]) for a in range(m) for t in cols_t]),
        "label": cs.col("Score", [f"{P[a, labels.index(t)]:.2f}" for a in range(m) for t in cols_t], "categorical")},
        controls={"scale": "sequential"}),
    cs.chart("top", "bar", "Top tag of each file", {"x": cs.col("Top tag", top1, "categorical")}, controls={"orientation": "horizontal"}),
]
summary = (f"{len(ok)} recordings ({sum(secs):.1f} s) were tagged with the 527 AudioSet classes; the most common top tag is "
           f"“{top_tag}” ({counts[top_tag]} of {len(ok)} files).")
cs.publish({
    "method": "audio.tag",
    "methodVersion": "1.0.0",
    "title": "Sound tags",
    "engine": cs.engine_info("numpy", "torch"),
    "n": len(ok),
    "summary": summary,
    "statistics": [{"key": "n_tagged", "label": "Files tagged", "value": len(ok), "format": "integer"},
                   {"key": "mean_top_score", "label": "Mean top score", "value": values["mean_top_score"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, "
              f"float64. A file's score for a tag is its {'largest' if POOLING == 'max' else 'mean'} window score."],
    "charts": charts,
    "artifacts": [{"key": "tags", "path": os.path.join(out, "tags.parquet"), "format": "parquet"}],
    "values": values,
})

Tag sounds (AudioSet) runs MIT's AST checkpoint, fine-tuned on AudioSet, written out in Python and R. It scores every file on all 527 classes, window by window, and pools each class over windows (highest or mean). On four computed sounds the most common top tag is Sine wave, the first tag of 2 files: the steady tone and the rising chirp. Map recordings by sound uses the same network's embeddings to find recordings that sound alike.

Read the tags as "heard somewhere in a window", and check a few files by ear before trusting a threshold.

04

PANNs: convolutional taggers at scale

Read

Pretrained audio neural networks (PANNs) are a family of convolutional taggers trained on all of AudioSet, the best known reading log-mel spectrograms through stacked convolutions. Frame features are pooled into a clip embedding and class probabilities. Their main use beyond tagging is transfer: the clip embedding feeds small classifiers for new sound tasks.

On the reference's toy clip their weak-label loss is 0.364. Count the family once; its layer-count variants aren't separate methods.

Reference · AUD053 · Explained herePretrained Audio Neural Networks (PANNs)A family of supervised convolutional audio-tagging models trained at scale, providing transferable audio embeddings. The family includes spectrogram and waveform-related designs;
05

BEATs: learn sounds without labels

Read

BEATs brings masked prediction to general audio. An acoustic tokenizer turns spectrogram patches into discrete labels; a Transformer predicts the labels of masked patches. The two then take turns: the trained model's features teach a better tokenizer, which gives better targets for the next round, much as HuBERT re-clusters speech.

The reference's example scores masked positions only: 0.434. Fine-tuned afterwards, BEATs-style encoders tag sounds well with fewer labels.

Reference · AUD065 · Explained hereBEATsA self-supervised general-audio representation framework alternating acoustic tokenization and masked audio modeling.
06

CLAP: sounds and words in one space

Read

CLAPCLAP (contrastive language–audio pretraining)Audio and text encoders trained so matching clips and captions land close together. It powers text search and zero-shot labels. trains an audio encoder and a text encoder on pairs of clips and captions so matching pairs land close together. With unit-length embeddings, similarities Sij=ai⊤tj/τS_{ij} = a_i^\top t_j / \tau fill a matrix, and a symmetric cross-entropy pushes the diagonal up in both directions, as contrastive learningContrastive learningLearning representations without labels by pulling two views of the same row together and pushing other rows' views away. does for images and text. The reference's example, with τ=0.2\tau = 0.2, gets 0.334.

That shared space gives two tools: text-to-audio search ("a door slams") and zero-shot labels, by comparing a clip with prompts such as "the sound of rain".

Reference · AUD054 · Explained hereContrastive Language–Audio Pretraining (CLAP)A paired audio–text representation approach aligning audio clips with natural-language descriptions. It enables text-to-audio retrieval and prompt-based zero-shot classification.

The same loss on a toy: change the temperature and the batch.

DExplorable · InfoNCE: temperature, negatives, collapse

How does contrastive learning learn useful embeddings without labels, and what keeps it from collapsing?

After training with this objective, where do the embeddings end up?

How sure?
0.20

Batch size

Each item's negatives are the rest of the batch.

Objective

Without labels, a batch can't tell them apart. Off: they're masked out.

0.30
300
0.80

Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.

Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

07

AudioCLIP: three modalities

Read

AudioCLIP extends an existing image–text model with an audio encoder and trains three contrastive terms: audio–text, audio–image and image–text. Any modality can then retrieve any other. The reference's example sums the three terms: 1.10.

It showed the idea early. Dedicated language–audio models trained on far more audio–text pairs have since replaced it for search and labels.

Reference · AUD055 · Explained hereAudioCLIPA tri-modal embedding model aligning audio with image and text representations. It extends contrastive image–text modeling with an audio pathway, enabling cross-modal retrieval and classification through a common…
08

The CLAP score

Read

Text-to-audio generators are often scored by the CLAP score: the cosine between the prompt's text embedding and the generated clip's audio embedding, averaged over prompts. In the reference's example one pair scores 0.979.

It is a proxy with blind spots. CLAP can miss order ("a dog barks, then a car passes"), subtle artifacts and counting, and generic sound mixtures can score well. The evaluator is part of the metric: report which CLAP checkpoint, and never fine-tune the evaluator on the generator's outputs.

Reference · EVA047 · Runs as a notebookCLAP text–audio similarityScores alignment between audio and text using a fixed contrastively trained dual encoder.
09

Where it stands in CodeSplash

Read
EntryIn CodeSplash
AST (AUD052)Runs in CodeSplash (Experimental): Tag sounds (AudioSet) and Map recordings by sound
PANNs (AUD053)Explained here
BEATs (AUD065)Explained here
CLAP (AUD054)Explained here. CodeSplash has no language–audio model, so it can't search audio by text
AudioCLIP (AUD055)Explained here
CLAP score (EVA047)Runs as a notebook (the reference program); no method computes it

The reference programs are component checks, verified in Python and R.

10

Check: tagging and audio–text

Checkpoint

Check yourself

What sequence does the Audio Spectrogram Transformer attend over?

Show the answer

Answer: b

AST borrows the vision transformer's recipe: patches become tokens.

Check yourself

Why does an AudioSet tagger use one sigmoid per class instead of one softmax?

Show the answer

Answer: a

Multi-label tagging needs independent per-class scores, trained with binary cross-entropy.

Check yourself

Besides tagging AudioSet classes, what are PANNs mostly used for?

Show the answer

Answer: b

A small classifier on top of pretrained embeddings often needs far fewer labeled clips.

Check yourself

A PANNs tagger gives "siren" a high score for a 10-second clip. What does that tell you?

Show the answer

Answer: c

Weak clip labels teach presence, not timing, and raw scores aren't calibrated probabilities.

Check yourself

What alternates during BEATs pretraining?

Show the answer

Answer: b

Each round improves the targets for the next, as HuBERT does with its clusters.

Check yourself

Does BEATs need labeled clips?

Show the answer

Answer: a

Pretraining predicts its own tokenizer's labels; tasks still need labels to fine-tune or evaluate.

Check yourself

How does CLAP label a clip with a class it never trained on?

Show the answer

Answer: b

The shared space turns any text into a candidate label.

Check yourself

What does CLAP's training push up?

Show the answer

Answer: b

A symmetric cross-entropy over the similarity matrix favors the diagonal.

Check yourself

What does AudioCLIP add to an image–text model?

Show the answer

Answer: b

Three paired terms put audio, images and text in one space.

Check yourself

For searching a sound library by text today, why prefer a dedicated language–audio model over AudioCLIP?

Show the answer

Answer: b

AudioCLIP showed the tri-modal idea early; it isn't the strongest choice now.

Check yourself

Prompt: "a dog barks, then a car passes." A generated clip has the car first, then the dog. What might the CLAP score do?

Show the answer

Answer: b

A clip-level embedding summarizes what is present more than when. Check order and timing separately.

Check yourself

A team fine-tunes its CLAP evaluator on its own generator's outputs, then reports a higher CLAP score. What's wrong?

Show the answer

Answer: b

The evaluator is part of the metric. Changing it toward the system under test inflates the result.

11

Recap

Recap
  • Taggers learn weak, multi-label clip classes; scores mean "present somewhere", not times or calibrated probabilities.
  • AST attends over spectrogram patches and runs in CodeSplash (Experimental); PANNs are convolutional taggers for transfer.
  • BEATs alternates a tokenizer and masked audio modeling.
  • CLAP and AudioCLIP align sounds and words; the CLAP score is a proxy with blind spots. These are explained here.

Concepts in this lesson