Skip to content

Separating and cleaning sound: masks, deep clustering, TasNets, Demucs

From one microphone, pull apart voices, instruments or noise. Start from NMF masks in CodeSplash, then meet the neural separators (deep clustering, Conv-TasNet, DPRNN, SepFormer, Demucs) and enhancers (DCCRN, MetricGAN+).

Advanced ~18 min10 steps

What runs in CodeSplash

You will be able to

  • Explain time–frequency masks and run NMF separation as a baseline
  • Describe deep clustering's permutation-free affinity loss
  • Describe time-domain separators and dual-path processing for long audio
  • Tell anonymous-speaker separation from fixed music stems and from enhancement, and spot a gamed quality metric

Read first

01

Masks: keep each source's share

Read

Most separators share one idea. In a spectrogram, different sources tend to dominate different time–frequency bins. A time–frequency maskTime–frequency maskA weight for every STFT bin that keeps one source's share of the mixture. The masked spectrogram is turned back into audio. gives every bin a weight between 0 and 1 for each source; multiply the mixture's spectrogram by it and invert, and you get that source's estimate.

The separators below differ in how they find the masks, and in whether they use the STFT at all.

02

A baseline that runs here

Read
Separate sounds with NMFRecorded · Python and R agreeRecorded 2026-11-25 · 11 values compared
R

4 files split into 2 components each; mean NMF relative error 0.397.

Files separated
4
Mean NMF relative error
0.3968
Largest gap, tracks vs original
8.882e-16

Assumptions

  • Files decode — Every file processed was decoded.
  • Sounds differ in spectrum — The NMF model leaves 39.7% of the spectrogram unexplained on average; listen to the tracks to judge the split.
  • Components are unnamed — Components are ordered by their total activation, loudest first.

Components by file

FileComponentShare of energyTemplate centroid (Hz)Template peak (Hz)
tone_a.wav10.7871484.06437.50
tone_a.wav20.2129441.31437.50
tone_b.wav10.91151590.58656.25
tone_b.wav20.08851153.48640.63
noise_a.wav10.5168729.1531.250
noise_a.wav20.4832695.620
chirp_loud.wav10.55641336.441968.75
chirp_loud.wav20.44361502.201,375

Fit by file

FileNMF relative errorTracks vs original (relative gap)
tone_a.wav0.13716.716e-16
tone_b.wav0.08428.882e-16
noise_a.wav0.44026.301e-16
chirp_loud.wav0.92576.918e-16
The exact R script · R R version 4.5.1 (2025-06-13)
# Separate sounds with NMF
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.separate_nmf 1.0.0 · spec d4e4ebaf0ce6f7aa
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud1_clips.parquet", col_select = c("path")))
n_input <- nrow(df)
df[["path"]] <- factor(df[["path"]], levels = sort(unique(df[["path"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("path")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("path"))  # infinite values stop the run (registry/errors.yaml)
# %% 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\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.separate_nmf/two_components/out-r", df,
                        "tests/parity/fixtures/aud1_clips.parquet")
media_ids <- cs_media_ids(media, df)
if (is.null(media$root) || !nzchar(media$root)) {
  media$root <- dirname(normalizePath("tests/parity/fixtures/aud1_clips.parquet", mustWork = FALSE))  # relative paths start next to the data file
}

# %% Settings
PATH <- "path"
SR <- as.numeric(media$transform$sample_rate)
K <- 2; ITER <- 60; N_FFT <- 1024; HOP <- 256
POWER <- as.numeric("1")
MAX_FILES <- 4
SEED <- 42
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.separate_nmf/two_components/out-r")
TRACKS <- file.path(out, "tracks")
dir.create(TRACKS, showWarnings = FALSE, recursive = TRUE)

# %% Separate each file: NMF on the spectrogram, soft masks, inverse STFT
status <- cs_media_status(media, media_ids)
paths <- as.character(df[[PATH]])
rows <- list(); files <- list(); bad <- list(); first <- NULL
for (i in seq_along(media_ids)) {
  if (length(files) >= MAX_FILES) break
  x <- NULL
  if (is.na(status[i])) x <- tryCatch(as.numeric(cs_media_audio(media, media_ids[i])[[1]]), cs_error = function(e) NULL)
  name <- basename(paths[i])
  if (is.null(x)) {
    bad[[length(bad) + 1]] <- list(file = name, path = paths[i])
    next
  }
  r <- cs_audio_nmf_separate(x, SR, K, N_FFT, HOP, ITER, SEED, POWER)
  energy <- rowSums(r$tracks^2)
  total <- sum(energy)
  xn <- sqrt(sum(x^2))
  gap <- if (xn > 0) sqrt(sum((colSums(r$tracks) - x)^2)) / xn else 0
  stem <- paste0(sprintf("%03d_", length(files) + 1), substr(gsub("[^A-Za-z0-9_-]", "_", tools::file_path_sans_ext(name)), 1, 60))
  for (k in seq_len(K)) {
    wav <- file.path(TRACKS, sprintf("%s_c%d.wav", stem, k))
    cs_audio_write_wav(wav, r$tracks[k, ], SR)
    rows[[length(rows) + 1]] <- list(file = name, media_id = media_ids[i], component = k,
                                     energy_share = if (total > 0) energy[k] / total else NULL,
                                     centroid_hz = sum(r$freqs * r$templates[k, ]),
                                     peak_hz = r$freqs[which.max(r$templates[k, ])],
                                     track = wav)
  }
  files[[length(files) + 1]] <- list(file = name, rel_error = r$rel_error, sum_error = gap)
  if (is.null(first)) first <- list(name = name, x = x, r = r)
}
if (!length(files)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an audio file that exists and can be decoded", count = length(bad))
if (length(bad)) warnings <- c(warnings, sprintf("%d listed files could not be read and were skipped.", length(bad)))

# %% Artifacts: one WAV per file and component, and a table of the components
art <- data.frame(
  file = vapply(rows, function(r) r$file, ""), media_id = vapply(rows, function(r) r$media_id, ""),
  component = vapply(rows, function(r) as.integer(r$component), 0L),
  energy_share = vapply(rows, function(r) if (is.null(r$energy_share)) NA_real_ else r$energy_share, 0),
  centroid_hz = vapply(rows, function(r) r$centroid_hz, 0), peak_hz = vapply(rows, function(r) r$peak_hz, 0),
  track = vapply(rows, function(r) r$track, ""), stringsAsFactors = FALSE
)
art_path <- file.path(out, "components.parquet")
nanoparquet::write_parquet(art, art_path)

# %% Result
rel <- vapply(files, function(f) f$rel_error, 0)
values <- list(n_rows = length(media_ids), n_files = length(files) + length(bad), n_separated = length(files), n_components = K,
               rel_error_mean = mean(rel), rel_error_max = max(rel), sum_error_max = max(vapply(files, function(f) f$sum_error, 0)))
for (k in seq_len(K)) {
  sh <- art$energy_share[art$component == k & !is.na(art$energy_share)]
  if (length(sh)) values[[sprintf("energy_share[%d]", k)]] <- mean(sh)
  values[[sprintf("centroid_hz[%d]", k)]] <- mean(art$centroid_hz[art$component == k])
}
top <- rows[seq_len(min(200, length(rows)))]
tables <- list(
  list(key = "components", title = "Components by file",
       columns = list(list(key = "file", label = "File"), list(key = "component", label = "Component", type = "integer"),
                      list(key = "energy_share", label = "Share of energy", type = "number"), list(key = "centroid_hz", label = "Template centroid (Hz)", type = "number"),
                      list(key = "peak_hz", label = "Template peak (Hz)", type = "number")),
       rows = lapply(top, function(r) list(file = r$file, media_id = r$media_id, component = r$component, energy_share = r$energy_share, centroid_hz = r$centroid_hz, peak_hz = r$peak_hz))),
  list(key = "fit", title = "Fit by file",
       columns = list(list(key = "file", label = "File"), list(key = "rel_error", label = "NMF relative error", type = "number"),
                      list(key = "sum_error", label = "Tracks vs original (relative gap)", type = "number")),
       rows = files[seq_len(min(200, length(files)))])
)
if (length(bad)) {
  tables[[3]] <- list(key = "unreadable", title = "Files that could not be read", columns = list(list(key = "file", label = "File"), list(key = "path", label = "Path")),
                      rows = bad[seq_len(min(50, length(bad)))])
}
labels <- sprintf("Component %d", seq_len(K))
charts <- list(cs_chart("energy", "cleveland-dot", "Share of energy by component", list(
  category = cs_col("Component", labels[art$component], "categorical", labels),
  value = cs_col("Share of energy", art$energy_share, "numeric")
), note = "Mean over the separated files; components are ordered loudest first."))
x <- first$x; r <- first$r
seg <- as.integer(min(length(x), 10 * SR))
S <- Mod(cs_audio_stft(x[seq_len(seg)], N_FFT, HOP))
D <- cs_audio_power_to_db(S^2, "max", 1e-10, 80)
T <- cs_audio_frame_times(ncol(D), SR, HOP)
F <- cs_audio_fft_frequencies(SR, N_FFT)
charts[[2]] <- cs_chart("spectrogram", "spectrogram", paste0("Spectrogram: ", first$name), list(
  x = cs_col("Time (s)", rep(T, each = length(F)), "numeric"),
  y = cs_col("Frequency (Hz)", rep(F, length(T)), "numeric"),
  z = cs_col("Level (dB re max)", as.vector(D), "numeric")
), controls = list(scale = "linear"), note = sprintf("Hann frames of %d samples every %d at %d Hz; the first 10 s.", N_FFT, HOP, as.integer(SR)))
t0 <- numeric(0); t1 <- numeric(0); lo <- numeric(0); hi <- numeric(0); rm <- numeric(0); trk <- character(0)
sigs <- c(list(Original = x), stats::setNames(lapply(seq_len(K), function(k) r$tracks[k, ]), labels))
for (label in names(sigs)) {
  e <- cs_audio_envelope(sigs[[label]], SR, 600)
  t0 <- c(t0, e$start); t1 <- c(t1, e$end); lo <- c(lo, e$min); hi <- c(hi, e$max); rm <- c(rm, e$rms); trk <- c(trk, rep(label, length(e$min)))
}
charts[[3]] <- cs_chart("tracks", "waveform", paste0("Original and separated tracks: ", first$name), list(
  time = cs_col("Time (s)", t0, "numeric"), end = cs_col("End (s)", t1, "numeric"),
  min = cs_col("Min", lo, "numeric"), max = cs_col("Max", hi, "numeric"), rms = cs_col("RMS", rm, "numeric"),
  track = cs_col("Track", trk, "categorical", c("Original", labels))
))
assumptions <- list(
  list(key = "decoded", label = "Files decode", status = if (length(bad)) "warn" else "pass",
       detail = if (length(bad)) sprintf("%d files could not be read and were skipped.", length(bad)) else "Every file processed was decoded."),
  list(key = "different_spectra", label = "Sounds differ in spectrum", status = "info",
       detail = sprintf("The NMF model leaves %.1f%% of the spectrogram unexplained on average; listen to the tracks to judge the split.", 100 * values$rel_error_mean)),
  list(key = "component_order", label = "Components are unnamed", status = "info", detail = "Components are ordered by their total activation, loudest first.")
)
cs_publish(list(
  title = "Separate sounds with NMF",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(files),
  summary = sprintf("%d files split into %d components each; mean NMF relative error %.3f.", length(files), K, values$rel_error_mean),
  statistics = list(
    list(key = "n_separated", label = "Files separated", value = length(files)),
    list(key = "rel_error_mean", label = "Mean NMF relative error", value = values$rel_error_mean),
    list(key = "sum_error_max", label = "Largest gap, tracks vs original", value = values$sum_error_max)
  ),
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "components", path = art_path, format = "parquet"), list(key = "audio_tracks", path = TRACKS, format = "folder"))
))
Python

4 files split into 2 components each; mean NMF relative error 0.397.

Files separated
4
Mean NMF relative error
0.3968
Largest gap, tracks vs original
1.969e-16

Assumptions

  • Files decode — Every file processed was decoded.
  • Sounds differ in spectrum — The NMF model leaves 39.7% of the spectrogram unexplained on average; listen to the tracks to judge the split.
  • Components are unnamed — Components are ordered by their total activation, loudest first.

Components by file

FileComponentShare of energyTemplate centroid (Hz)Template peak (Hz)
tone_a.wav10.7871484.06437.50
tone_a.wav20.2129441.31437.50
tone_b.wav10.91151590.58656.25
tone_b.wav20.08851153.48640.63
noise_a.wav10.5168729.1531.250
noise_a.wav20.4832695.620
chirp_loud.wav10.55641336.441968.75
chirp_loud.wav20.44361502.201,375

Fit by file

FileNMF relative errorTracks vs original (relative gap)
tone_a.wav0.13711.808e-16
tone_b.wav0.08421.969e-16
noise_a.wav0.44021.842e-16
chirp_loud.wav0.92571.953e-16
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Separate sounds with NMF
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.separate_nmf 1.0.0 · spec d4e4ebaf0ce6f7aa
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import describe as ad
from codesplash.audio import dsp
from codesplash.audio import separate as asep
from codesplash.errors import CsError

# %% Data
df = pd.read_parquet("tests/parity/fixtures/aud1_clips.parquet", columns=["path"])
n_input = len(df)
df["path"] = pd.Categorical(df["path"], categories=sorted(df["path"].dropna().unique()))
df = df.dropna(subset=["path"])  # listwise deletion over the analysis columns
df["path"] = df["path"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["path"])  # infinite values stop the run (registry/errors.yaml)
# %% 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\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.separate_nmf/two_components/out-python", df, "tests/parity/fixtures/aud1_clips.parquet")
media_ids = cs_media.ids_of(media, df)
if not media.get("root"):
    media["root"] = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud1_clips.parquet"))  # relative paths start next to the data file

# %% Settings
PATH = "path"
SR = float(media["transform"]["sample_rate"])
K, ITER, N_FFT, HOP = 2, 60, 1024, 256
POWER = float("1")
MAX_FILES = 4
SEED = 42
out = csml.out_dir("target/academy-parity/run-8142/audio.separate_nmf/two_components/out-python")
TRACKS = os.path.join(out, "tracks")
os.makedirs(TRACKS, exist_ok=True)

# %% Separate each file: NMF on the spectrogram, soft masks, inverse STFT
status = cs_media.status(media, media_ids)
paths = df[PATH].astype(str).tolist()
rows, files, bad, first = [], [], [], None
for i, mid in enumerate(media_ids):
    if len(files) >= MAX_FILES:
        break
    x = None
    if status[i] is None:
        try:
            x = np.asarray(cs_media.audio(media, [mid])[0], dtype=np.float64)
        except CsError:
            x = None
    name = os.path.basename(paths[i])
    if x is None:
        bad.append({"file": name, "path": paths[i]})
        continue
    r = asep.nmf_separate(x, SR, K, N_FFT, HOP, ITER, SEED, POWER)
    energy = np.sum(r["tracks"] ** 2, axis=1)
    total = float(np.sum(energy))
    xn = float(np.linalg.norm(x))
    gap = float(np.linalg.norm(np.sum(r["tracks"], axis=0) - x)) / xn if xn > 0 else 0.0
    stem = f"{len(files) + 1:03d}_" + "".join(ch if (ch.isascii() and ch.isalnum()) or ch in "-_" else "_" for ch in os.path.splitext(name)[0])[:60]
    for k in range(K):
        wav = os.path.join(TRACKS, f"{stem}_c{k + 1}.wav")
        asep.write_wav(wav, r["tracks"][k], int(SR))
        rows.append({"file": name, "media_id": mid, "component": k + 1,
                     "energy_share": float(energy[k] / total) if total > 0 else None,
                     "centroid_hz": float(np.sum(r["freqs"] * r["templates"][k])),
                     "peak_hz": float(r["freqs"][int(np.argmax(r["templates"][k]))]),
                     "track": wav})
    files.append({"file": name, "rel_error": r["rel_error"], "sum_error": gap})
    if first is None:
        first = (name, x, r)
if not files:
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an audio file that exists and can be decoded", count=len(bad))
warnings = list(warnings)
if bad:
    warnings.append(f"{len(bad)} listed files could not be read and were skipped.")

# %% Artifacts: one WAV per file and component, and a table of the components
art = pd.DataFrame(rows, columns=["file", "media_id", "component", "energy_share", "centroid_hz", "peak_hz", "track"])
for c in ("file", "media_id", "track"):
    art[c] = art[c].astype("string")
art["component"] = art["component"].astype("int64")
art["energy_share"] = pd.to_numeric(art["energy_share"], errors="coerce").astype("float64")
art_path = os.path.join(out, "components.parquet")
art.to_parquet(art_path, index=False)

# %% Result
values = {"n_rows": len(media_ids), "n_files": len(files) + len(bad), "n_separated": len(files), "n_components": K,
          "rel_error_mean": float(np.mean([f["rel_error"] for f in files])), "rel_error_max": float(np.max([f["rel_error"] for f in files])),
          "sum_error_max": float(np.max([f["sum_error"] for f in files]))}
for k in range(1, K + 1):
    sh = [r["energy_share"] for r in rows if r["component"] == k and r["energy_share"] is not None]
    if sh:
        values[f"energy_share[{k}]"] = float(np.mean(sh))
    values[f"centroid_hz[{k}]"] = float(np.mean([r["centroid_hz"] for r in rows if r["component"] == k]))
tables = [
    {"key": "components", "title": "Components by file",
     "columns": [{"key": "file", "label": "File"}, {"key": "component", "label": "Component", "type": "integer"},
                 {"key": "energy_share", "label": "Share of energy", "type": "number"}, {"key": "centroid_hz", "label": "Template centroid (Hz)", "type": "number"},
                 {"key": "peak_hz", "label": "Template peak (Hz)", "type": "number"}],
     "rows": [{k: r[k] for k in ("file", "media_id", "component", "energy_share", "centroid_hz", "peak_hz")} for r in rows[:200]]},
    {"key": "fit", "title": "Fit by file",
     "columns": [{"key": "file", "label": "File"}, {"key": "rel_error", "label": "NMF relative error", "type": "number"},
                 {"key": "sum_error", "label": "Tracks vs original (relative gap)", "type": "number"}], "rows": files[:200]},
]
if bad:
    tables.append({"key": "unreadable", "title": "Files that could not be read", "columns": [{"key": "file", "label": "File"}, {"key": "path", "label": "Path"}], "rows": bad[:50]})
name, x, r = first
labels = [f"Component {k + 1}" for k in range(K)]
charts = [cs.chart("energy", "cleveland-dot", "Share of energy by component", {
    "category": cs.col("Component", [labels[r_["component"] - 1] for r_ in rows], "categorical", labels),
    "value": cs.col("Share of energy", [r_["energy_share"] for r_ in rows], "numeric"),
}, note="Mean over the separated files; components are ordered loudest first.")]
seg = int(min(len(x), 10 * SR))
S = np.abs(dsp.stft(x[:seg], N_FFT, HOP))
D = dsp.power_to_db(S**2, "max", 1e-10, 80.0)
T = dsp.frame_times(D.shape[1], SR, HOP)
F = dsp.fft_frequencies(SR, N_FFT)
charts.append(cs.chart("spectrogram", "spectrogram", f"Spectrogram: {name}", {
    "x": cs.col("Time (s)", np.repeat(T, len(F)), "numeric"),
    "y": cs.col("Frequency (Hz)", np.tile(F, len(T)), "numeric"),
    "z": cs.col("Level (dB re max)", D.T.ravel(), "numeric"),
}, controls={"scale": "linear"}, note=f"Hann frames of {N_FFT} samples every {HOP} at {int(SR)} Hz; the first 10 s."))
t0, t1, lo, hi, rm, trk = [], [], [], [], [], []
for label, sig in [("Original", x)] + [(labels[k], r["tracks"][k]) for k in range(K)]:
    e = ad.envelope(sig, SR, 600)
    t0 += e["start"]; t1 += e["end"]; lo += e["min"]; hi += e["max"]; rm += e["rms"]; trk += [label] * len(e["min"])
charts.append(cs.chart("tracks", "waveform", f"Original and separated tracks: {name}", {
    "time": cs.col("Time (s)", t0, "numeric"), "end": cs.col("End (s)", t1, "numeric"),
    "min": cs.col("Min", lo, "numeric"), "max": cs.col("Max", hi, "numeric"), "rms": cs.col("RMS", rm, "numeric"),
    "track": cs.col("Track", trk, "categorical", ["Original"] + labels),
}))
assumptions = [
    {"key": "decoded", "label": "Files decode", "status": "warn" if bad else "pass",
     "detail": f"{len(bad)} files could not be read and were skipped." if bad else "Every file processed was decoded."},
    {"key": "different_spectra", "label": "Sounds differ in spectrum", "status": "info",
     "detail": f"The NMF model leaves {values['rel_error_mean']:.1%} of the spectrogram unexplained on average; listen to the tracks to judge the split."},
    {"key": "component_order", "label": "Components are unnamed", "status": "info", "detail": "Components are ordered by their total activation, loudest first."},
]
cs.publish({
    "title": "Separate sounds with NMF",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": len(files),
    "summary": f"{len(files)} files split into {K} components each; mean NMF relative error {values['rel_error_mean']:.3f}.",
    "statistics": [
        {"key": "n_separated", "label": "Files separated", "value": len(files)},
        {"key": "rel_error_mean", "label": "Mean NMF relative error", "value": values["rel_error_mean"]},
        {"key": "sum_error_max", "label": "Largest gap, tracks vs original", "value": values["sum_error_max"]},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "components", "path": art_path, "format": "parquet"}, {"key": "audio_tracks", "path": TRACKS, "format": "folder"}],
})

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

Separate sounds with NMF factorizes each file's magnitude spectrogram into a few spectral templates and their activations, then builds soft masks from them: NMF separationNMF separationSplitting a recording by factorizing its spectrogram into templates and activations, then masking the original into one track each.. The 4 files split into 2 tracks each, and because the masks add up to one, the tracks add back up to the original exactly.

NMF needs no training data, which makes it a useful baseline. It works when sources differ in pitch or timbre and fails when they overlap in frequency, as two similar voices do. That is where trained separators come in.

Notebook exercise · ~15 min

Split two notes with NMF

Factor a synthetic magnitude spectrogram of two overlapping notes into spectral templates and activations, and check each part against the note it should be.

  1. How well do two parts fit?

    Store the relative reconstruction error ‖V − W H‖ / ‖V‖ (Frobenius norms) of the fitted parts in err.

    Show a solution
    Python
    err = np.linalg.norm(V - W @ H) / np.linalg.norm(V)
    R
    err <- norm(V - W %*% H, "F") / norm(V, "F")
  2. Match the templates to the notes

    For each true template, find the fitted column of W it is most similar to (cosine). Store the two best cosines, for w1 first and w2 second, in template_cos.

    Show a solution
    Python
    template_cos = [max(cosine(w, W[:, k]) for k in range(2)) for w in (w1, w2)]
    R
    template_cos <- sapply(list(w1, w2), function(w) max(cosine(w, W[, 1]), cosine(w, W[, 2])))
  3. When does each note play?

    Use the same matching on the activations: for each true activation, the best correlation with a row of H. Store the two, for h1 first, in activation_r.

    Show a solution
    Python
    activation_r = [max(np.corrcoef(h, H[k])[0, 1] for k in range(2)) for h in (h1, h2)]
    R
    activation_r <- sapply(list(h1, h2), function(h) max(cor(h, H[1, ]), cor(h, H[2, ])))

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

03

Deep clustering

Read

Deep clusteringDeep clustering (separation)Learns a vector for every time–frequency bin so bins of one source cluster together; k-means on them gives the masks. trains a network to give every time–frequency bin a unit vector, so that bins dominated by the same speaker point the same way. Its loss compares affinities, not labels:

L=∥VV⊤−YY⊤∥F2,\mathcal{L} = \lVert V V^{\top} - Y Y^{\top} \rVert_F^2,

with rows of VV the bin vectors and rows of YY one-hot source memberships. YY⊤YY^\top only says which bins share a source, so naming the speakers in another order changes nothing. At inference, k-means on the vectors gives the masks. In the reference's example the loss is 1.172.

Training is supervised: it needs the true sources. Only the grouping at inference is unsupervised.

Reference · AUD040 · Explained hereDeep clustering for speech separationA supervised speech-separation representation method that embeds time–frequency bins so bins from the same source cluster together. Despite the name, training uses source membership labels;
04

Conv-TasNet: learn the transform too

Read

The STFT is a fixed choice. Conv-TasNet learns its own: a 1-D convolution encodes short waveform windows into a latent representation, a temporal convolutional network predicts a mask per source in that space, and a learned decoder turns each masked latent back into a waveform. This is time-domain separationTime-domain separationSeparating with a learned encoder in place of the STFT, a mask per source, and a learned decoder back to waveforms., trained with a permutation-invariant SI-SDR loss (next lesson).

In the reference's example, a mask and its complement split one encoded frame: the two rows start with 0.36 and 0.04, and add back up to the frame.

Reference · AUD042 · Explained hereConv-TasNetA supervised time-domain speech separator using a learned waveform encoder, temporal convolutional mask estimator, and decoder.
05

DPRNN and SepFormer: chunk the sequence

Read

Learned encoders use short windows, so a few seconds become thousands of frames: too long for one recurrent pass, and too costly for full attention. Dual-path processingDual-path processingCutting a long sequence into overlapping chunks and alternating a model within chunks and across them, so long audio stays cheap. cuts the sequence into overlapping chunks and alternates two passes: within each chunk (local detail) and across chunks at the same position (long context).

DPRNN uses recurrent layers for both passes. A 100-frame sequence in chunks of 24 with a hop of 12 makes 8 chunks over 108 padded frames. SepFormer uses Transformers instead; with 8 chunks of 16 frames it computes 3,072 attention scores per head, against 1282128^2 for full attention over all 128 frames.

Reference · AUD043 · Explained hereDual-path recurrent neural network (DPRNN)A sequence architecture for long audio separation that splits latent sequences into overlapping chunks and alternates intra-chunk and inter-chunk recurrent modeling. Reference · AUD044 · Explained hereSepFormerA supervised speech-separation architecture using dual-path Transformers to model local chunks and global relationships between chunks.
06

Demucs: stems have names

Read

Separating two anonymous speakers, the outputs have no fixed order. Separating music into stemsMusic stemsFixed named music sources such as vocals, drums and bass. Outputs keep their names, so scoring needs no permutation search., they do: vocals, drums, bass, other. Demucs is a waveform encoder–decoder with skip connections and a recurrent bottleneck, trained to output each named stem, for example with an L1 loss per stem. No permutation search is needed; scoring vocals against drums would be wrong.

The reference's example scores two fixed stems, each offset by a constant: L1 of 0.03. Later Demucs versions are hybrid and Transformer-based; name the version you used.

Reference · AUD045 · Explained hereDemucsA supervised music-source-separation family originating with waveform encoder–decoder modeling and recurrent bottleneck context. It separates stems such as vocals, drums, bass, and other accompaniment.
07

Enhancement: DCCRN and MetricGAN+

Read

Speech enhancementSpeech enhancementCleaning one speaker's recording of noise or echo. Unlike separation, the other sounds are thrown away, not kept as sources. keeps one voice and discards the rest. DCCRN predicts a complex maskComplex maskA mask with real and imaginary parts, so it changes both the magnitude and the phase of each STFT bin, not only its size., with real and imaginary parts, so it can correct the phase of each bin as well as its size; magnitude-only masks reuse the noisy phase.

MetricGAN+ trains a network to predict a speech-quality score, then trains the enhancer to raise that prediction: a learned metric surrogateLearned metric surrogateA network trained to predict a quality score, then used as an enhancer's target. The enhancer can learn to fool the predictor.. The enhancer may learn to please the surrogate rather than listeners. In the reference's toy example the surrogate misses the target scores by a squared error of 0.01. Check enhanced audio with independent measures and listening.

Reference · AUD046 · Explained hereDeep complex convolution recurrent network (DCCRN)A supervised speech-enhancement model processing complex time–frequency representations with convolutional and recurrent components. Reference · AUD047 · Explained hereMetricGAN+A supervised enhancement framework that trains a discriminator to approximate a target quality metric and trains the enhancer against that learned surrogate.
08

Where it stands in CodeSplash

Read
EntryIn CodeSplash
NMF separation (baseline)Runs in CodeSplash (Experimental): Separate sounds with NMF, identical in Python and R
Deep clustering (AUD040)Explained here
Conv-TasNet (AUD042)Explained here
DPRNN (AUD043)Explained here
SepFormer (AUD044)Explained here
Demucs (AUD045)Explained here
DCCRN (AUD046)Explained here
MetricGAN+ (AUD047)Explained here

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

09

Check: separators

Checkpoint

Check yourself

Why doesn't deep clustering's loss care which speaker is called "speaker 1"?

Show the answer

Answer: b

Affinities are permutation-invariant by construction, so no matching step is needed during training.

Check yourself

Is deep clustering an unsupervised method?

Show the answer

Answer: b

The name refers to the k-means step. The embedding network learns from labeled mixtures.

Check yourself

What does Conv-TasNet use in place of the STFT?

Show the answer

Answer: b

Learning the transform lets the model choose a representation where sources are easier to mask.

Check yourself

In Conv-TasNet, where are the masks applied?

Show the answer

Answer: a

Masked latents go through the decoder, one per source, to give the separated waveforms.

Check yourself

Why does DPRNN cut the sequence into chunks?

Show the answer

Answer: b

Each pass runs over short sequences: chunk length within, chunk count across.

Check yourself

A 120-frame sequence is cut into chunks of 24 frames with a hop of 12, padding the end as needed. How many chunks are there? Use 1+⌈(120−24)/12⌉1 + \lceil (120 - 24)/12 \rceil.

Show the answer

Answer: 9

(120−24)/12=8(120 - 24)/12 = 8, so 1+8=91 + 8 = 9 chunks.

Check yourself

Why does SepFormer attend within and across chunks instead of over the whole sequence?

Show the answer

Answer: b

With NN chunks of length LL, the cost is about NL2+LN2NL^2 + LN^2 scores instead of (NL)2(NL)^2.

Check yourself

Which training objective do SepFormer and Conv-TasNet commonly use for anonymous speakers?

Show the answer

Answer: b

Outputs have no fixed order, so the loss takes the best matching of outputs to sources.

Check yourself

Why does Demucs not need permutation-invariant training?

Show the answer

Answer: b

With fixed identities, matching outputs to sources by best fit would be wrong: vocals must be scored against vocals.

Check yourself

A report says "we separated stems with Demucs." What should it add?

Show the answer

Answer: a

The family changed a lot across versions; results don't transfer between them.

Check yourself

What can DCCRN's complex mask do that a magnitude mask can't?

Show the answer

Answer: b

A magnitude mask keeps the noisy phase. A complex multiply rotates and scales each bin.

Check yourself

DCCRN is an enhancement model. How does that differ from separation?

Show the answer

Answer: b

The goals differ, and so do the outputs and the right evaluation.

Check yourself

An enhancer trained with MetricGAN+ scores very high on the learned quality predictor. What is the risk?

Show the answer

Answer: b

Optimizing against a learned score invites exploiting its blind spots.

Check yourself

What does MetricGAN+'s discriminator learn?

Show the answer

Answer: b

It approximates a quality metric so the enhancer can be trained toward a desired score.

10

Recap

Recap
  • Masks keep each source's share of every bin; NMF finds them without training and runs in CodeSplash.
  • Deep clustering embeds bins with a permutation-free affinity loss; Conv-TasNet learns its own transform.
  • DPRNN and SepFormer chunk long sequences; Demucs separates named stems.
  • DCCRN corrects phase with complex masks; MetricGAN+ can game its learned metric. The neural models are explained here.

Concepts in this lesson