diff --git a/tests/test_diarize.py b/tests/test_diarize.py index 6a64fe48c..b96cf68dc 100644 --- a/tests/test_diarize.py +++ b/tests/test_diarize.py @@ -1,11 +1,21 @@ -"""Tests for whispermlx/diarize.py — IntervalTree and assign_word_speakers.""" +"""Tests for whispermlx/diarize.py — IntervalTree, assign_word_speakers, per-chunk embeddings.""" import copy +import numpy as np import pandas as pd import pytest +import torch +from pyannote.audio.core.io import Audio +from pyannote.audio.models.embedding import WeSpeakerResNet34 +from pyannote.audio.pipelines import SpeakerDiarization +from pyannote.audio.pipelines.speaker_verification import PyannoteAudioPretrainedSpeakerEmbedding +from pyannote.core import SlidingWindow +from pyannote.core import SlidingWindowFeature from whispermlx.diarize import IntervalTree +from whispermlx.diarize import _get_embeddings_per_chunk +from whispermlx.diarize import _supports_stacked_masks from whispermlx.diarize import assign_word_speakers @@ -194,3 +204,93 @@ def test_returns_same_object(self, simple_diarize_df, minimal_transcript): result = copy.deepcopy(minimal_transcript) out = assign_word_speakers(simple_diarize_df, result) assert out is result + + +# ── Per-chunk embedding extraction ───────────────────────────────────────────── + + +class _FakeDiarization: + """Just the attributes SpeakerDiarization.get_embeddings reads at inference time.""" + + def __init__(self, embedding, batch_size): + self._embedding = embedding + self._audio = Audio(sample_rate=16000) + self.embedding_batch_size = batch_size + self.training = False + + +@pytest.fixture(scope="module") +def wespeaker_embedding(): + torch.manual_seed(0) + return PyannoteAudioPretrainedSpeakerEmbedding(WeSpeakerResNet34().eval()) + + +@pytest.fixture +def chunked_inputs(): + """Random 8s waveform cut into 2s chunks every 0.5s, with 3 local speakers per chunk.""" + rng = np.random.default_rng(0) + file = { + "waveform": torch.from_numpy(rng.standard_normal((1, 8 * 16000)).astype(np.float32)), + "sample_rate": 16000, + } + num_chunks, num_frames, num_speakers = 13, 50, 3 + data = (rng.random((num_chunks, num_frames, num_speakers)) > 0.5).astype(np.float32) + data[:, :, 2] = 0.0 # a fully silent speaker slot, as is common in practice + data[0, :5, 0] = np.nan # partial stitching may produce NaN + segmentations = SlidingWindowFeature(data, SlidingWindow(start=0.0, duration=2.0, step=0.5)) + return file, segmentations + + +@pytest.mark.parametrize("exclude_overlap", [False, True]) +@pytest.mark.parametrize("batch_size", [1, 4, 32]) +def test_per_chunk_embeddings_match_pyannote( + wespeaker_embedding, chunked_inputs, exclude_overlap, batch_size +): + file, segmentations = chunked_inputs + pipeline = _FakeDiarization(wespeaker_embedding, batch_size) + + expected = SpeakerDiarization.get_embeddings( + pipeline, file, segmentations, exclude_overlap=exclude_overlap + ) + actual = _get_embeddings_per_chunk( + pipeline, file, segmentations, exclude_overlap=exclude_overlap + ) + + assert actual.shape == expected.shape == (13, 3, wespeaker_embedding.dimension) + np.testing.assert_array_equal(np.isnan(actual), np.isnan(expected)) + np.testing.assert_allclose(actual, expected, rtol=1e-4, atol=1e-5, equal_nan=True) + + +def test_per_chunk_embeddings_report_progress(wespeaker_embedding, chunked_inputs): + file, segmentations = chunked_inputs + calls = [] + + def hook(step_name, step_artifact, file=None, total=None, completed=None): + calls.append( + (step_name, total, completed, None if step_artifact is None else step_artifact.shape) + ) + + _get_embeddings_per_chunk( + _FakeDiarization(wespeaker_embedding, 4), file, segmentations, hook=hook + ) + + dim = wespeaker_embedding.dimension + assert calls == [ + ("embeddings", 4, 0, None), + ("embeddings", 4, 1, (12, dim)), + ("embeddings", 4, 2, (12, dim)), + ("embeddings", 4, 3, (12, dim)), + ("embeddings", 4, 4, (3, dim)), + ] + + +def test_supports_stacked_masks_for_wespeaker(wespeaker_embedding): + assert _supports_stacked_masks(wespeaker_embedding) is True + + +def test_supports_stacked_masks_rejects_other_backends(): + class OtherBackend: + def __call__(self, waveforms, masks=None): + return np.zeros((waveforms.shape[0], 192)) + + assert _supports_stacked_masks(OtherBackend()) is False diff --git a/whispermlx/diarize.py b/whispermlx/diarize.py index de884b405..31654dda8 100644 --- a/whispermlx/diarize.py +++ b/whispermlx/diarize.py @@ -1,7 +1,12 @@ +import math +import types + import numpy as np import pandas as pd import torch from pyannote.audio import Pipeline +from pyannote.audio.pipelines import SpeakerDiarization +from pyannote.audio.pipelines.speaker_verification import PyannoteAudioPretrainedSpeakerEmbedding from whispermlx.audio import SAMPLE_RATE from whispermlx.audio import load_audio @@ -90,6 +95,100 @@ def find_nearest(self, time: float) -> str | None: return self.speakers[nearest_idx] +def _supports_stacked_masks(embedding) -> bool: + """ + Check whether an embedding model accepts (batch, speakers, frames) masks in a single call. + + pyannote-native WeSpeaker models only apply masks in their statistics pooling layer, + which already supports a speakers dimension. Other backends (SpeechBrain, NeMo, ONNX) + apply masks before the frame-wise network and must keep pyannote's per-pair loop. + """ + if not isinstance(embedding, PyannoteAudioPretrainedSpeakerEmbedding): + return False + try: + with torch.inference_mode(): + waveforms = torch.zeros(1, 1, embedding.sample_rate, device=embedding.device) + weights = torch.ones(1, 2, 10, device=embedding.device) + output = embedding.model_(waveforms, weights=weights) + except Exception: + return False + return tuple(output.shape) == (1, 2, embedding.dimension) + + +def _get_embeddings_per_chunk( + self: SpeakerDiarization, + file, + binary_segmentations, + exclude_overlap: bool = False, + hook=None, +): + """ + Drop-in replacement for SpeakerDiarization.get_embeddings that runs the embedding + model once per chunk instead of once per (chunk, speaker) pair. + + pyannote feeds the same chunk waveform to the embedding model once for every local + speaker, while the speaker mask only enters at the final pooling layer. Stacking a + chunk's masks and pooling them in one call yields the same embeddings (up to float + noise) with num_speakers times less work in the frame-wise network. + """ + if self.training: + return SpeakerDiarization.get_embeddings( + self, file, binary_segmentations, exclude_overlap=exclude_overlap, hook=hook + ) + + duration = binary_segmentations.sliding_window.duration + num_chunks, num_frames, _ = binary_segmentations.data.shape + data = binary_segmentations.data + # masks may contain NaN (in case of partial stitching) + segmentations = np.nan_to_num(data, nan=0.0).astype(np.float32) + + if exclude_overlap: + # same rule as pyannote: use the overlap-free mask when it is long enough + # to extract an embedding from, otherwise fall back to the full mask. + # Overlap is computed before NaN removal, so frames with NaN never count as clean. + min_num_samples = self._embedding.min_num_samples + num_samples = duration * self._embedding.sample_rate + min_num_frames = math.ceil(num_frames * min_num_samples / num_samples) + clean_frames = np.sum(data, axis=2, keepdims=True) < 2 + clean_segmentations = np.nan_to_num(data * clean_frames, nan=0.0).astype(np.float32) + use_clean = np.sum(clean_segmentations, axis=1, keepdims=True) > min_num_frames + segmentations = np.where(use_clean, clean_segmentations, segmentations) + + # (num_chunks, num_speakers, num_frames) + masks = torch.from_numpy(np.ascontiguousarray(segmentations.transpose(0, 2, 1))) + chunks = [chunk for chunk, _ in binary_segmentations] + + model = self._embedding.model_ + device = self._embedding.device + batch_size = self.embedding_batch_size + batch_count = math.ceil(num_chunks / batch_size) + + if hook is not None: + hook("embeddings", None, total=batch_count, completed=0) + + embedding_batches = [] + for i, start in enumerate(range(0, num_chunks, batch_size), 1): + end = min(start + batch_size, num_chunks) + waveforms = torch.stack( + [self._audio.crop(file, chunks[c], mode="pad")[0] for c in range(start, end)] + ) + with torch.inference_mode(): + embedding_batch = model(waveforms.to(device), weights=masks[start:end].to(device)) + embedding_batch = embedding_batch.cpu().numpy() + embedding_batches.append(embedding_batch) + + if hook is not None: + hook( + "embeddings", + embedding_batch.reshape(-1, embedding_batch.shape[-1]), + total=batch_count, + completed=i, + ) + + # (num_chunks, num_speakers, dimension) + return np.concatenate(embedding_batches, axis=0) + + class DiarizationPipeline: def __init__( self, @@ -105,6 +204,10 @@ def __init__( self.model = Pipeline.from_pretrained(model_config, token=token, cache_dir=cache_dir).to( device ) + if isinstance(self.model, SpeakerDiarization) and _supports_stacked_masks( + self.model._embedding + ): + self.model.get_embeddings = types.MethodType(_get_embeddings_per_chunk, self.model) def __call__( self,