Skip to content

Who spoke when: diarization pipelines, EEND, TS-VAD, DER and JER

Split a conversation into speaker turns with a clustering pipeline, which CodeSplash runs, or with end-to-end and target-speaker networks. Score the turns with the diarization and Jaccard error rates, and know what the collar hides.

Advanced ~16 min10 steps

What runs in CodeSplash

You will be able to

  • Describe the clustering pipeline (voice activity, windows, embeddings, clustering) and its weak spot, overlap
  • Explain how EEND predicts every speaker's activity at once with a permutation-invariant loss
  • Explain how TS-VAD uses speaker profiles instead of anonymous outputs
  • Compute DER and JER, and say how the collar and overlap rules change them

Read first

01

The clustering pipeline

Read

Speaker diarizationSpeaker diarizationSplitting a recording into segments by speaker (S1, S2, …), with talk time and speaker changes. labels a recording with who spoke when, without knowing who the speakers are. The classic pipeline has four steps:

  1. Voice activity detectionVoice activity detection (VAD)Finding when someone speaks; here a 25-ms frame is speech when it is within a set number of dB of the loudest frame. finds the stretches with speech.
  2. The speech is cut into short overlapping windows.
  3. Each window becomes a speaker embedding.
  4. Clustering groups the windows by voice; neighboring windows with one label merge into turns.

How many speakers? Either you say, or the clustering decides where to stop merging. Each window gets one label, so two people talking at once is the pipeline's blind spot.

02

The pipeline in CodeSplash

Read
Who spoke whenRecorded · Python and R agreeRecorded 2026-11-25 · 19 values compared
R

2 recordings (13.6 s, 9.9 s of speech) split into 7 segments with 3 speakers at most per recording and 5 changes of speaker. Against the reference turns, the diarization error rate is 0.0% (collar 0.5 s).

Segments
7
Most speakers in a recording
3
DER
0.0%

Plots

Who spoke when: conv_two.wavWho or what is active when — and where do they overlap?
View data
End (s)SpeakerStart (s)
1.915S10.2950
4.165S22.345
5.805S14.595
Who spoke when: conv_three.wavWho or what is active when — and where do they overlap?
View data
End (s)SpeakerStart (s)
1.705S10.2850
3.665S22.145
5.415S34.095
6.865S25.845

Assumptions

  • One speaker at a time — Each moment gets one speaker; overlapping speech counts as an error against references that mark it.
  • Number of speakers — Estimated per recording: groups merge while their average similarity is at least 0.5 (at most 10). Set the number when you know it.
  • Voices identify people — The speaker embeddings used for clustering stay in memory and are never saved; speaker names (S1, S2, …) are per recording.

Who spoke when

pathStart (s)End (s)SecondsSpeaker
media/aud3/conv_two.wav0.29501.9151.620S1
media/aud3/conv_two.wav2.3454.1651.820S2
media/aud3/conv_two.wav4.5955.8051.210S1
media/aud3/conv_three.wav0.28501.7051.420S1
media/aud3/conv_three.wav2.1453.6651.520S2
media/aud3/conv_three.wav4.0955.4151.320S3
media/aud3/conv_three.wav5.8456.8651.020S2

Talk time per speaker

pathSpeakerSecondsShare of speech
media/aud3/conv_two.wavS12.8300.6086
media/aud3/conv_two.wavS21.8200.3914
media/aud3/conv_three.wavS11.4200.2689
media/aud3/conv_three.wavS22.5400.4811
media/aud3/conv_three.wavS31.3200.2500

Diarization error rate (collar 0.5 s)

pathScored secondsMissed speech (s)False alarm (s)Wrong speaker (s)DERReference speakersFound speakers
media/aud3/conv_two.wav3.100000022
media/aud3/conv_three.wav3.200000033
  • Energy voice activity (within 35 dB of the loudest 25-ms frame), 1.5-s windows every 0.75 s, ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), average-linkage clustering on cosine distance, and boundaries halfway between window centers. The embeddings are biometric and are discarded after clustering. DER = (missed speech + false alarm + wrong speaker) / reference speech, with the best one-to-one speaker mapping.
The exact R script · R R version 4.5.1 (2025-06-13)
# Who spoke when (speaker diarization)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.diarize 1.0.1 · spec a92eda9a5f1bbd1b
# Dataset: aud3_conversations (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_diarize_* (voice activity, windows, clustering, segments), cs_ecapa_* (embeddings), cs_eval_der

# %% Audio files listed in the path column
PATH <- "path"
N_SPEAKERS <- NULL  # NULL: estimated from the similarity
SIMILARITY <- 0.5
MAX_SPEAKERS <- as.integer(10)
WIN <- 1.5
STEP <- 0.75
VAD_DB <- 35
MIN_SPEECH <- 0.25
MIN_GAP <- 0.3
COLLAR <- 0.5
SKIP_OVERLAP <- FALSE
REF <- list(file = "file", start = "start",
            end = "end", speaker = "speaker")
SR <- 16000
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud3_conversations.parquet"))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud3_conversations.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\":600,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.diarize/conversations-reference/out-r", df,
                        "tests/parity/fixtures/aud3_conversations.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]]))

# %% Who spoke when: voice activity -> windows -> ECAPA embeddings (kept in memory) -> clustering -> segments
torch::torch_set_num_threads(1L)
model <- cs_ecapa_load(cs_ecapa_locate())
progress <- cs_progress(sprintf("Diarizing %d recordings", length(ok)), total = length(ok))
files <- list()
seg_rows <- list()
for (k in seq_along(ok)) {
  i <- ok[k]
  x <- as.numeric(cs_media_audio(media, media_ids[i])[[1]])
  regions <- cs_diarize_vad(x, SR, VAD_DB, -60, MIN_SPEECH, MIN_GAP)
  wins <- cs_diarize_windows(regions, WIN, STEP)
  if (nrow(wins) > 0) {
    clips <- lapply(seq_len(nrow(wins)), function(w) {
      r <- cs_diarize_sample_range(wins$start[w], wins$end[w], SR, length(x))
      x[r[1]:r[2]]
    })
    E <- cs_ecapa_embed(model, clips)
    labels <- cs_diarize_ahc(E, N_SPEAKERS, SIMILARITY, MAX_SPEAKERS)
    rm(E)  # speaker embeddings are biometric: never saved or shown
    fs <- cs_diarize_segments(regions, wins, labels)
  } else {
    fs <- data.frame(start = numeric(0), end = numeric(0), speaker = integer(0))
  }
  n_spk <- if (nrow(fs)) max(fs$speaker) + 1L else 0L
  files[[k]] <- list(row = i, path = paths[i], seconds = length(x) / SR, speech = sum(fs$end - fs$start), windows = nrow(wins),
                     speakers = n_spk, turns = cs_diarize_turns(fs), talk = cs_diarize_talk_time(fs, n_spk), segs = fs)
  for (q in seq_len(nrow(fs))) seg_rows[[length(seg_rows) + 1L]] <- list(row = as.integer(i - 1L), media_id = media_ids[i], path = paths[i],
    start = fs$start[q], end = fs$end[q], duration = fs$end[q] - fs$start[q], speaker = sprintf("S%d", fs$speaker[q] + 1L))
  cs_progress_update(progress, k)
}
cs_progress_done(progress)
if (!length(seg_rows)) warnings <- c(warnings, "No speech was found: every frame is quieter than the voice-activity threshold allows.")

# %% Against reference turns (diarization error rate)
der_rows <- list()
totals <- NULL
if (!is.null(REF)) {
  ref <- cs_graph_dataset_option("target/academy-parity/run-8142/audio.diarize/conversations-reference/out-r", "reference")
  if (is.null(ref) || nrow(ref) == 0) {
    warnings <- c(warnings, "The reference table is empty; no error rate was computed.")
  } else {
    keys <- character(0)
    owners <- integer(0)
    for (k in seq_along(files)) {
      f <- files[[k]]
      for (key in c(f$path, basename(f$path), media_ids[f$row])) if (!(key %in% keys)) {
        keys <- c(keys, key)
        owners <- c(owners, k)
      }
    }
    rkeys <- as.character(ref[[REF$file]])
    matched <- vector("list", length(files))
    for (j in seq_along(rkeys)) {
      hit <- match(rkeys[j], keys)
      if (is.na(hit)) hit <- match(basename(rkeys[j]), keys)
      if (!is.na(hit)) matched[[owners[hit]]] <- c(matched[[owners[hit]]], j)
    }
    if (all(vapply(matched, is.null, logical(1)))) {
      warnings <- c(warnings, sprintf("No reference row names a diarized file (%s should hold the file path, its name or its media id).", REF$file))
    }
    tot <- c(total = 0, miss = 0, false_alarm = 0, confusion = 0)
    for (k in seq_along(files)) {
      js <- matched[[k]]
      if (is.null(js)) next
      f <- files[[k]]
      r <- data.frame(start = as.numeric(ref[[REF$start]][js]), end = as.numeric(ref[[REF$end]][js]),
                      speaker = as.character(ref[[REF$speaker]][js]), stringsAsFactors = FALSE)
      h <- data.frame(start = f$segs$start, end = f$segs$end, speaker = sprintf("S%d", f$segs$speaker + 1L), stringsAsFactors = FALSE)
      d <- cs_eval_der(r, h, collar = COLLAR, skip_overlap = SKIP_OVERLAP)
      for (key in names(tot)) tot[[key]] <- tot[[key]] + as.numeric(d[[key]])
      der_rows[[length(der_rows) + 1L]] <- list(file = f$path, scored = d$total, miss = d$miss, false_alarm = d$false_alarm,
                                                 confusion = d$confusion, der = d$der, ref_speakers = length(d$ref_speakers),
                                                 hyp_speakers = length(d$hyp_speakers))
    }
    if (length(der_rows)) {
      totals <- as.list(tot)
      totals$der <- if (tot[["total"]] > 0) (tot[["miss"]] + tot[["false_alarm"]] + tot[["confusion"]]) / tot[["total"]] else NULL
    }
  }
}

# %% Artifact: one row per segment (who spoke when; no embeddings)
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.diarize/conversations-reference/out-r")
seg_df <- if (length(seg_rows)) do.call(rbind, lapply(seg_rows, as.data.frame, stringsAsFactors = FALSE)) else
  data.frame(row = integer(0), media_id = character(0), path = character(0), start = numeric(0), end = numeric(0),
             duration = numeric(0), speaker = character(0))
nanoparquet::write_parquet(seg_df, file.path(out, "segments.parquet"))

# %% Assumptions
assumptions <- list(
  list(key = "overlap", label = "One speaker at a time", status = "info",
       detail = "Each moment gets one speaker; overlapping speech counts as an error against references that mark it."),
  list(key = "speaker_count", label = "Number of speakers", status = "info",
       detail = if (!is.null(N_SPEAKERS)) sprintf("Fixed at %d per recording.", as.integer(N_SPEAKERS)) else
         sprintf("Estimated per recording: groups merge while their average similarity is at least %s (at most %d). Set the number when you know it.",
                 format(SIMILARITY), MAX_SPEAKERS)),
  list(key = "biometric", label = "Voices identify people", status = "info",
       detail = "The speaker embeddings used for clustering stay in memory and are never saved; speaker names (S1, S2, …) are per recording.")
)

# %% Result
speech <- sum(vapply(files, function(f) f$speech, numeric(1)))
values <- list(n_rows = nrow(df), n_files = length(ok) + length(unreadable), n_diarized = length(ok), n_unreadable = length(unreadable),
               n_no_path = n_no_path, audio_seconds = sum(vapply(files, function(f) f$seconds, numeric(1))), speech_seconds = speech,
               n_segments = length(seg_rows), n_windows = sum(vapply(files, function(f) f$windows, numeric(1))),
               mean_speakers = mean(vapply(files, function(f) f$speakers, numeric(1))),
               max_speakers_found = as.integer(max(vapply(files, function(f) f$speakers, numeric(1)))),
               n_turns = as.integer(sum(vapply(files, function(f) f$turns, numeric(1)))), collar = COLLAR, n_scored_files = length(der_rows),
               der = if (!is.null(totals)) totals$der else NULL, der_miss = if (!is.null(totals)) totals$miss else NULL,
               der_false_alarm = if (!is.null(totals)) totals$false_alarm else NULL, der_confusion = if (!is.null(totals)) totals$confusion else NULL,
               der_scored_seconds = if (!is.null(totals)) totals$total else NULL)
talk_rows <- list()
for (f in files) for (s_i in seq_along(f$talk)) talk_rows[[length(talk_rows) + 1L]] <- list(file = f$path, speaker = sprintf("S%d", s_i),
  seconds = f$talk[s_i], share = if (f$speech > 0) f$talk[s_i] / f$speech else NULL)
tables <- list(
  list(key = "segments", title = "Who spoke when", columns = list(
    list(key = "path", label = PATH, type = "string"), list(key = "start", label = "Start (s)", type = "number"),
    list(key = "end", label = "End (s)", type = "number"), list(key = "duration", label = "Seconds", type = "number"),
    list(key = "speaker", label = "Speaker", type = "string")),
    rows = lapply(head(seg_rows, 1000), function(s) s[c("path", "start", "end", "duration", "speaker")]),
    note = if (length(seg_rows) > 1000) "First 1,000 segments." else NULL),
  list(key = "talk_time", title = "Talk time per speaker", columns = list(
    list(key = "file", label = PATH, type = "string"), list(key = "speaker", label = "Speaker", type = "string"),
    list(key = "seconds", label = "Seconds", type = "number"), list(key = "share", label = "Share of speech", type = "number")),
    rows = head(talk_rows, 1000))
)
if (length(der_rows)) tables[[length(tables) + 1L]] <- list(key = "der",
  title = sprintf("Diarization error rate (collar %s s%s)", format(COLLAR), if (isTRUE(SKIP_OVERLAP)) ", overlap not scored" else ""),
  columns = list(list(key = "file", label = PATH, type = "string"), list(key = "scored", label = "Scored seconds", type = "number"),
                 list(key = "miss", label = "Missed speech (s)", type = "number"), list(key = "false_alarm", label = "False alarm (s)", type = "number"),
                 list(key = "confusion", label = "Wrong speaker (s)", type = "number"), list(key = "der", label = "DER", type = "number"),
                 list(key = "ref_speakers", label = "Reference speakers", type = "integer"), list(key = "hyp_speakers", label = "Found speakers", type = "integer")),
  rows = der_rows)
charts <- list()
for (f in head(files, 4)) {
  if (!nrow(f$segs)) next
  lanes <- sprintf("S%d", seq_len(f$speakers))
  charts[[length(charts) + 1L]] <- cs_chart(sprintf("timeline-%d", f$row), "segment-timeline", sprintf("Who spoke when: %s", basename(f$path)), list(
    start = cs_col("Start (s)", f$segs$start),
    end = cs_col("End (s)", f$segs$end),
    lane = cs_col("Speaker", sprintf("S%d", f$segs$speaker + 1L), "categorical", levels = lanes)),
    controls = list(labels = FALSE, overlap = TRUE))
}
summary <- sprintf("%d recording%s (%.1f s, %.1f s of speech) split into %d segments with %d speaker%s at most per recording and %d changes of speaker.",
                   length(ok), if (length(ok) != 1) "s" else "", values$audio_seconds, speech, length(seg_rows), values$max_speakers_found,
                   if (values$max_speakers_found != 1) "s" else "", values$n_turns)
if (!is.null(totals) && !is.null(totals$der)) summary <- paste(summary, sprintf("Against the reference turns, the diarization error rate is %.1f%% (collar %s s).",
                                                                               100 * totals$der, format(COLLAR)))
statistics <- list(list(key = "n_segments", label = "Segments", value = length(seg_rows), format = "integer"),
                   list(key = "max_speakers_found", label = "Most speakers in a recording", value = values$max_speakers_found, format = "integer"))
if (!is.null(totals) && !is.null(totals$der)) statistics[[length(statistics) + 1L]] <- list(key = "der", label = "DER", value = totals$der, format = "percent")
cs_publish(list(
  method = "audio.diarize",
  methodVersion = "1.0.1",
  title = "Who spoke when",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(ok),
  summary = summary,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = as.list(warnings),
  notes = list(sprintf(paste0("Energy voice activity (within %s dB of the loudest 25-ms frame), %s-s windows every %s s, ECAPA-TDNN speaker ",
                              "embeddings by SpeechBrain (Ravanelli et al. 2021), average-linkage clustering on cosine distance, and boundaries halfway ",
                              "between window centers. The embeddings are biometric and are discarded after clustering. DER = (missed speech + false alarm ",
                              "+ wrong speaker) / reference speech, with the best one-to-one speaker mapping."), format(VAD_DB), format(WIN), format(STEP))),
  charts = charts,
  artifacts = list(list(key = "segments", path = file.path(out, "segments.parquet"), format = "parquet")),
  values = values
))
Python

2 recordings (13.6 s, 9.9 s of speech) split into 7 segments with 3 speakers at most per recording and 5 changes of speaker. Against the reference turns, the diarization error rate is 0.0% (collar 0.5 s).

Segments
7
Most speakers in a recording
3
DER
0.0%

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

Assumptions

  • One speaker at a time — Each moment gets one speaker; overlapping speech counts as an error against references that mark it.
  • Number of speakers — Estimated per recording: groups merge while their average similarity is at least 0.5 (at most 10). Set the number when you know it.
  • Voices identify people — The speaker embeddings used for clustering stay in memory and are never saved; speaker names (S1, S2, …) are per recording.

Who spoke when

pathStart (s)End (s)SecondsSpeaker
media/aud3/conv_two.wav0.29501.9151.620S1
media/aud3/conv_two.wav2.3454.1651.820S2
media/aud3/conv_two.wav4.5955.8051.210S1
media/aud3/conv_three.wav0.28501.7051.420S1
media/aud3/conv_three.wav2.1453.6651.520S2
media/aud3/conv_three.wav4.0955.4151.320S3
media/aud3/conv_three.wav5.8456.8651.020S2

Talk time per speaker

pathSpeakerSecondsShare of speech
media/aud3/conv_two.wavS12.8300.6086
media/aud3/conv_two.wavS21.8200.3914
media/aud3/conv_three.wavS11.4200.2689
media/aud3/conv_three.wavS22.5400.4811
media/aud3/conv_three.wavS31.3200.2500

Diarization error rate (collar 0.5 s)

pathScored secondsMissed speech (s)False alarm (s)Wrong speaker (s)DERReference speakersFound speakers
media/aud3/conv_two.wav3.100000022
media/aud3/conv_three.wav3.200000033
  • Energy voice activity (within 35 dB of the loudest 25-ms frame), 1.5-s windows every 0.75 s, ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), average-linkage clustering on cosine distance, and boundaries halfway between window centers. The embeddings are biometric and are discarded after clustering. DER = (missed speech + false alarm + wrong speaker) / reference speech, with the best one-to-one speaker mapping.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Who spoke when (speaker diarization)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.diarize 1.0.1 · spec a92eda9a5f1bbd1b
# Dataset: aud3_conversations (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 diarize as dz  # voice activity, windows, clustering, segments (twin: codesplashr cs_diarize_*)
from codesplash.audio import ecapa  # ECAPA-TDNN speaker embeddings (twin: codesplashr cs_ecapa_*)
from codesplash.evaluate import intervals  # diarization error rate (twin: codesplashr cs_eval_der)
from codesplash.graph import dataset_option  # the reference table of the `reference` option, written by the host

# %% Audio files listed in the path column
PATH = "path"
N_SPEAKERS = None  # None: estimated from the similarity
SIMILARITY = 0.5
MAX_SPEAKERS = int(10)
WIN, STEP = 1.5, 0.75
VAD_DB, MIN_SPEECH, MIN_GAP = 35, 0.25, 0.3
COLLAR = 0.5
SKIP_OVERLAP = False
REF = {"file": "file", "start": "start",
       "end": "end", "speaker": "speaker"}
SR = 16000
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud3_conversations.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud3_conversations.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\":600,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.diarize/conversations-reference/out-python", df, "tests/parity/fixtures/aud3_conversations.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]]}).")

# %% Who spoke when: voice activity → windows → ECAPA embeddings (kept in memory) → clustering → segments
torch.set_num_threads(1)
model = ecapa.load(ecapa.locate())
progress = cs.progress(f"Diarizing {len(ok)} recordings", total=len(ok))
files, segs = [], []
for k, i in enumerate(ok):
    x = np.asarray(cs_media.audio(media, [media_ids[i]])[0], dtype=np.float64)
    regions = dz.vad(x, SR, VAD_DB, -60.0, MIN_SPEECH, MIN_GAP)
    wins = dz.windows(regions, WIN, STEP)
    if wins:
        clips = [x[slice(*dz.sample_range(s, e, SR, x.size))] for s, e, _ in wins]
        E = ecapa.embed(model, clips)
        labels = dz.ahc(E, N_SPEAKERS, SIMILARITY, MAX_SPEAKERS)
        del E  # speaker embeddings are biometric: never saved or shown
        fs = dz.segments(regions, wins, labels)
    else:
        fs = []
    n_spk = (max(s[2] for s in fs) + 1) if fs else 0
    talk = dz.talk_time(fs, n_spk)
    files.append({"row": i, "path": paths[i], "seconds": x.size / SR, "speech": float(sum(e - s for s, e, _ in fs)), "windows": len(wins),
                  "speakers": n_spk, "turns": dz.turns(fs), "talk": talk, "segs": fs})
    for s, e, spk in fs:
        segs.append({"row": i, "media_id": media_ids[i], "path": paths[i], "start": s, "end": e, "duration": e - s, "speaker": f"S{spk + 1}"})
    progress.update(k + 1)
progress.done()
if not segs:
    warnings.append("No speech was found: every frame is quieter than the voice-activity threshold allows.")

# %% Against reference turns (diarization error rate)
der_rows, totals = [], None
if REF is not None:
    ref = dataset_option("target/academy-parity/run-8142/audio.diarize/conversations-reference/out-python", "reference")
    if ref is None or not len(ref):
        warnings.append("The reference table is empty; no error rate was computed.")
    else:
        keyset = {}
        for f in files:
            for key in (f["path"], os.path.basename(f["path"]), media_ids[f["row"]]):
                keyset.setdefault(str(key), f)
        rkeys = ref[REF["file"]].astype(str).tolist()
        matched = {}
        for j, rk in enumerate(rkeys):
            f = keyset.get(rk) or keyset.get(os.path.basename(rk))
            if f is not None:
                matched.setdefault(f["row"], []).append(j)
        if not matched:
            warnings.append(f"No reference row names a diarized file ({REF['file']} should hold the file path, its name or its media id).")
        tot = {"total": 0.0, "miss": 0.0, "false_alarm": 0.0, "confusion": 0.0}
        for f in files:
            js = matched.get(f["row"])
            if not js:
                continue
            r = [(float(ref[REF["start"]].iloc[j]), float(ref[REF["end"]].iloc[j]), str(ref[REF["speaker"]].iloc[j])) for j in js]
            h = [(s, e, f"S{spk + 1}") for s, e, spk in f["segs"]]
            d = intervals.der(r, h, COLLAR, SKIP_OVERLAP)
            for key in tot:
                tot[key] += float(d[key])
            der_rows.append({"file": f["path"], "scored": d["total"], "miss": d["miss"], "false_alarm": d["false_alarm"], "confusion": d["confusion"],
                             "der": d["der"], "ref_speakers": len(d["ref_speakers"]), "hyp_speakers": len(d["hyp_speakers"])})
        if der_rows:
            totals = tot
            totals["der"] = (tot["miss"] + tot["false_alarm"] + tot["confusion"]) / tot["total"] if tot["total"] > 0 else None

# %% Artifact: one row per segment (who spoke when; no embeddings)
out = csml.out_dir("target/academy-parity/run-8142/audio.diarize/conversations-reference/out-python")
seg_df = pd.DataFrame(segs, columns=["row", "media_id", "path", "start", "end", "duration", "speaker"])
seg_df["row"] = seg_df["row"].astype(np.int64)
seg_df.to_parquet(os.path.join(out, "segments.parquet"), index=False)

# %% Assumptions
assumptions = [
    {"key": "overlap", "label": "One speaker at a time", "status": "info",
     "detail": "Each moment gets one speaker; overlapping speech counts as an error against references that mark it."},
    {"key": "speaker_count", "label": "Number of speakers", "status": "info",
     "detail": (f"Fixed at {N_SPEAKERS} per recording." if N_SPEAKERS is not None else
                f"Estimated per recording: groups merge while their average similarity is at least {SIMILARITY:g} (at most {MAX_SPEAKERS}). Set the number when you know it.")},
    {"key": "biometric", "label": "Voices identify people", "status": "info",
     "detail": "The speaker embeddings used for clustering stay in memory and are never saved; speaker names (S1, S2, …) are per recording."},
]

# %% Result
speech = float(sum(f["speech"] for f in files))
values = {"n_rows": len(df), "n_files": len(ok) + len(unreadable), "n_diarized": len(ok), "n_unreadable": len(unreadable), "n_no_path": n_no_path,
          "audio_seconds": float(sum(f["seconds"] for f in files)), "speech_seconds": speech, "n_segments": len(segs),
          "n_windows": int(sum(f["windows"] for f in files)), "mean_speakers": float(np.mean([f["speakers"] for f in files])),
          "max_speakers_found": int(max(f["speakers"] for f in files)), "n_turns": int(sum(f["turns"] for f in files)),
          "collar": COLLAR, "n_scored_files": len(der_rows),
          "der": totals["der"] if totals else None, "der_miss": totals["miss"] if totals else None,
          "der_false_alarm": totals["false_alarm"] if totals else None, "der_confusion": totals["confusion"] if totals else None,
          "der_scored_seconds": totals["total"] if totals else None}
talk_rows = []
for f in files:
    for s_i, t in enumerate(f["talk"]):
        talk_rows.append({"file": f["path"], "speaker": f"S{s_i + 1}", "seconds": float(t), "share": float(t / f["speech"]) if f["speech"] > 0 else None})
tables = [
    {"key": "segments", "title": "Who spoke when", "columns": [
        {"key": "path", "label": PATH, "type": "string"}, {"key": "start", "label": "Start (s)", "type": "number"},
        {"key": "end", "label": "End (s)", "type": "number"}, {"key": "duration", "label": "Seconds", "type": "number"},
        {"key": "speaker", "label": "Speaker", "type": "string"}],
     "rows": [{k: s[k] for k in ("path", "start", "end", "duration", "speaker")} for s in segs[:1000]],
     "note": "First 1,000 segments." if len(segs) > 1000 else None},
    {"key": "talk_time", "title": "Talk time per speaker", "columns": [
        {"key": "file", "label": PATH, "type": "string"}, {"key": "speaker", "label": "Speaker", "type": "string"},
        {"key": "seconds", "label": "Seconds", "type": "number"}, {"key": "share", "label": "Share of speech", "type": "number"}],
     "rows": talk_rows[:1000]},
]
if der_rows:
    tables.append({"key": "der", "title": f"Diarization error rate (collar {COLLAR:g} s{', overlap not scored' if SKIP_OVERLAP else ''})", "columns": [
        {"key": "file", "label": PATH, "type": "string"}, {"key": "scored", "label": "Scored seconds", "type": "number"},
        {"key": "miss", "label": "Missed speech (s)", "type": "number"}, {"key": "false_alarm", "label": "False alarm (s)", "type": "number"},
        {"key": "confusion", "label": "Wrong speaker (s)", "type": "number"}, {"key": "der", "label": "DER", "type": "number"},
        {"key": "ref_speakers", "label": "Reference speakers", "type": "integer"}, {"key": "hyp_speakers", "label": "Found speakers", "type": "integer"}],
        "rows": der_rows})
charts = []
for f in files[:4]:
    if not f["segs"]:
        continue
    lanes = [f"S{s_i + 1}" for s_i in range(f["speakers"])]
    charts.append(cs.chart(f"timeline-{f['row'] + 1}", "segment-timeline", f"Who spoke when: {os.path.basename(f['path'])}", {
        "start": cs.col("Start (s)", [s for s, _, _ in f["segs"]]),
        "end": cs.col("End (s)", [e for _, e, _ in f["segs"]]),
        "lane": cs.col("Speaker", [f"S{k + 1}" for _, _, k in f["segs"]], "categorical", levels=lanes)},
        controls={"labels": False, "overlap": True}))
summary = (f"{len(ok)} recording{'s' if len(ok) != 1 else ''} ({values['audio_seconds']:.1f} s, {speech:.1f} s of speech) split into "
           f"{len(segs)} segments with {values['max_speakers_found']} speaker{'s' if values['max_speakers_found'] != 1 else ''} at most per recording "
           f"and {values['n_turns']} changes of speaker.")
if totals and totals["der"] is not None:
    summary += f" Against the reference turns, the diarization error rate is {100 * totals['der']:.1f}% (collar {COLLAR:g} s)."
cs.publish({
    "method": "audio.diarize",
    "methodVersion": "1.0.1",
    "title": "Who spoke when",
    "engine": cs.engine_info("numpy", "torch"),
    "n": len(ok),
    "summary": summary,
    "statistics": [{"key": "n_segments", "label": "Segments", "value": len(segs), "format": "integer"},
                   {"key": "max_speakers_found", "label": "Most speakers in a recording", "value": values["max_speakers_found"], "format": "integer"}]
                  + ([{"key": "der", "label": "DER", "value": totals["der"], "format": "percent"}] if totals and totals["der"] is not None else []),
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Energy voice activity (within {VAD_DB:g} dB of the loudest 25-ms frame), {WIN:g}-s windows every {STEP:g} s, ECAPA-TDNN speaker "
              "embeddings by SpeechBrain (Ravanelli et al. 2021), average-linkage clustering on cosine distance, and boundaries halfway "
              "between window centers. The embeddings are biometric and are discarded after clustering. DER = (missed speech + false alarm "
              "+ wrong speaker) / reference speech, with the best one-to-one speaker mapping."],
    "charts": charts,
    "artifacts": [{"key": "segments", "path": os.path.join(out, "segments.parquet"), "format": "parquet"}],
    "values": values,
})

Who spoke when (speaker diarization) runs this pipeline: energy-based voice activity, windowed ECAPA-TDNN embeddings, average-linkage clustering, then timed segments labeled S1, S2 and so on, with talk time per speaker. Python and R give the same segments. Given reference turns, it scores itself with the diarization error rate. On two synthetic conversations with seven turns in all it finds 7 segments and a DER of 0.0%, with a collar of 0.5 s.

The window embeddings are biometric: the method keeps them in memory and never saves them.

03

How many voices?

Explore

AExplorable · Cut a dendrogram

How do you choose clusters from a tree of merges?

Draw a horizontal line at this height across the tree. How many clusters does it cut into?

16
How sure?

Data

Linkage

0.12
36
cut

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.

Average-linkage clustering builds a tree of merges; the number of speakers is where you cut it. Try Two blobs and a chain between them: a cut that looks natural for one data set merges or splits groups in another. In diarization, a quiet speaker with few windows is easy to merge into a louder one.

04

EEND: every speaker, every frame

Read

End-to-end neural diarizationEnd-to-end neural diarizationA network that outputs every speaker's activity in every frame at once, overlap included, trained with a permutation-invariant loss. (EEND) skips embeddings and clustering. A network reads the whole recording and outputs, for each frame, an activity probability for each of KK speaker slots. Several slots can be on at once, so overlap is handled directly.

The slots are anonymous, so training uses a permutation-invariant loss:

L=min⁡π∈SK∑t,kBCE⁡(yt,π(k),y^t,k).\mathcal{L} = \min_{\pi \in S_K} \sum_{t,k} \operatorname{BCE}\bigl(y_{t,\pi(k)}, \hat y_{t,k}\bigr).

In the reference's example, two speakers with one overlapping frame give a loss of 0.184 under the better of the two assignments.

Reference · AUD050 · Explained hereEnd-to-end neural diarization (EEND)A supervised diarization formulation predicting multiple speakers’ activity at each frame, including overlap. Permutation-invariant multi-label training avoids assigning globally meaningful output speaker numbers and…
05

TS-VAD: activity for known profiles

Read

Target-speaker voice activity detectionTarget-speaker voice activity detectionFrame-by-frame activity for each enrolled speaker, given their profiles. Outputs are tied to known speakers, so no permutation search. (TS-VAD) takes a speaker profile for each candidate, often from a first clustering pass or from enrollment audio, and predicts each one's activity frame by frame. Its outputs are tied to the profiles, so no permutation search is needed; plain binary cross-entropy trains it. In the reference's example that loss is 0.145.

TS-VAD often refines a clustering pipeline's first answer, especially in overlap. It inherits that answer's mistakes: a missing profile can't be recovered.

Reference · AUD051 · Explained hereTarget-speaker voice activity detection (TS-VAD)A supervised diarization model conditioned on representations of candidate speakers. It predicts per-frame activity for each target speaker, making an initial speaker-profile stage part of the overall pipeline.
06

Diarization error rate

Read

The diarization error rateDiarization error rate (DER)(Missed speech + false alarm + wrong speaker) / reference speech, after the best one-to-one speaker mapping. adds three kinds of wrongly labeled time and divides by the reference speech time:

DER=Tmiss+Tfalse alarm+TconfusionTref.\mathrm{DER} = \frac{T_{\text{miss}} + T_{\text{false alarm}} + T_{\text{confusion}}}{T_{\text{ref}}}.

System labels are first mapped to reference speakers by the best one-to-one matching. In the reference's example, 10 seconds missed, 4 false alarm and 8 confused out of 100 give 0.22. DER can exceed 1, since false alarms are unbounded.

Reference · EVA045 · Partly runs in CodeSplashDiarization error rate and Jaccard error rateEvaluate who-spoke-when predictions after mapping arbitrary system speaker labels to reference speakers.
07

JER, collars and overlap

Read

DER weights speakers by how much they talk, so a speaker with little time barely moves it. The Jaccard error rateJaccard error rateAverages, over reference speakers, one minus the overlap of matched speaker time over its union, so every speaker counts equally. averages, over reference speakers, one minus the intersection over union of each speaker's time and its matched system speaker's time. Every speaker counts equally. One speaker with 70 of 90 seconds overlapping gives 0.222 in the reference's example.

Two settings change both scores: the collarCollar (diarization)A band around each reference turn boundary that isn't scored, so small timing slips don't count. Compare scores only at one collar., a band around reference boundaries left unscored, and whether overlapping speech is scored. A wide collar with overlap skipped can lower an error rate a lot. Compare scores only with the same rules, and always report them.

08

Where it stands in CodeSplash

Read
EntryIn CodeSplash
EEND (AUD050)Explained here. Who spoke when (speaker diarization) runs a clustering pipeline instead (Experimental)
TS-VAD (AUD051)Explained here
DER and JER (EVA045)Partly runs: Who spoke when reports DER with collar and overlap options when given reference turns; JER is explained here

The reference programs are small calculations, verified in Python and R.

09

Check: diarization

Checkpoint

Check yourself

What can EEND do that a pipeline giving each window one cluster label can't?

Show the answer

Answer: b

EEND outputs one activity probability per speaker slot per frame, so overlap is a normal output.

Check yourself

Why does EEND train with a permutation-invariant loss?

Show the answer

Answer: a

Like separation outputs, diarization slots have no fixed identity.

Check yourself

Why doesn't TS-VAD need a permutation-invariant loss?

Show the answer

Answer: b

Conditioning on profiles fixes which output belongs to which speaker.

Check yourself

A TS-VAD system gets profiles from a first clustering pass that merged two speakers into one. What happens?

Show the answer

Answer: b

TS-VAD refines activity for the profiles it is given; it doesn't invent new speakers.

Check yourself

Reference speech totals 200 seconds. A system misses 12 seconds, adds 6 seconds of false alarm and gives 12 seconds to the wrong speaker. What is the DER?

Show the answer

Answer: 0.15

(12+6+12)/200=0.15(12 + 6 + 12)/200 = 0.15.

Check yourself

A meeting has one dominant speaker and three who say little. The system mislabels most of the quiet speakers' time. Which score shows it more clearly?

Show the answer

Answer: b

DER weights by talk time, so the dominant speaker's correct turns hide the others' errors. JER averages per speaker.

Check yourself

Paper A reports DER with a 0.5-second collar and overlap skipped; paper B with no collar and overlap scored. Can you compare their numbers?

Show the answer

Answer: b

Collars forgive boundary slips and skipping overlap removes the hardest time; both lower DER.

10

Recap

Recap
  • The clustering pipeline (VAD, windows, embeddings, clustering) runs in CodeSplash; overlap is its blind spot.
  • EEND outputs every speaker's activity per frame with a permutation-invariant loss; TS-VAD conditions on profiles.
  • DER adds missed, false-alarm and confused time over reference time; JER weights speakers equally.
  • Report the collar and overlap rule with every score.

Concepts in this lesson