Skip to content

perf(diarize): extract speaker embeddings once per chunk instead of once per speaker - #7

Open
madrover wants to merge 1 commit into
KalebJS:mainfrom
madrover:perf/diarize-per-chunk-embeddings
Open

madrover wants to merge 1 commit into
KalebJS:mainfrom
madrover:perf/diarize-per-chunk-embeddings

Conversation

@madrover

@madrover madrover commented Nov 17, 2026 •

Copy link
Copy Markdown

Summary

Speaker diarization is the slowest stage of the pipeline, and almost all of that time goes into speaker-embedding extraction. pyannote's SpeakerDiarization.get_embeddings runs the WeSpeaker ResNet once for every (chunk, local speaker) pair: each 10 s chunk passes through the full network 3 times, although the speaker mask only enters at the final statistics-pooling layer. That layer already accepts (batch, speakers, frames) weights.

This PR overrides get_embeddings on the loaded pipeline so the frame-wise network runs once per chunk, with all local speakers pooled in the same call. The model, weights and clustering are unchanged, and the output is identical.

How

  • _supports_stacked_masks(embedding) makes one dummy forward pass with stacked masks and checks the output shape. Only pyannote-native embedding models that pass this get the override. SpeechBrain, NeMo and ONNX backends apply masks before the frame-wise network and keep pyannote's per-pair loop.
  • _get_embeddings_per_chunk reproduces pyannote's mask selection exactly, including exclude_overlap (on by default in community-1) and NaN frames from partial stitching. Training mode falls back to the stock implementation.
  • DiarizationPipeline.__init__ binds the override to the pipeline instance only. Nothing in pyannote is patched globally.
  • The progress hook contract is kept: total/completed per batch, and the artifact is reshaped to (batch * speakers, dimension).
  • embedding_batch_size now counts chunks rather than (chunk, speaker) pairs. The frame-wise activations per batch are the same size as before.

Results

End to end through DiarizationPipeline with pyannote/speaker-diarization-community-1, on real meeting recordings (Apple Silicon, after warm-up):

Recording Device pyannote Stock This PR Speedup DER vs stock
6.0 min MPS 4.0.4 12.6 s 5.2 s 2.43× 0.000%
8.7 min MPS 4.0.4 18.0 s 7.2 s 2.49× 0.000%
29.8 min MPS 4.0.4 64.1 s 25.5 s 2.52× 0.000%
51.1 min MPS 4.0.4 112.9 s 40.3 s 2.80× 0.000%
8.7 min MPS 4.1.0 17.4 s 6.8 s 2.56× 0.000%
29.8 min MPS 4.1.0 61.4 s 23.8 s 2.58× 0.000%
6.0 min CPU 4.0.4 185.1 s 98.9 s 1.87× 0.000%

Speaker counts match on every file, and the maximum absolute embedding difference is about 3e-6 (float noise from the different batch shape).

Tests

New tests in tests/test_diarize.py use a randomly initialised WeSpeakerResNet34, so they need no model download or HF token:

  • the per-chunk embeddings match SpeakerDiarization.get_embeddings for batch sizes 1, 4 and 32, with and without exclude_overlap, on inputs that include a fully silent speaker slot and NaN frames
  • the progress hook gets the expected total/completed sequence and artifact shapes
  • the stacked-mask check accepts WeSpeaker and rejects other backends

The full suite passes on pyannote 4.0.4 / Python 3.10 (296 tests), and tests/test_diarize.py passes on pyannote 4.1.0 / Python 3.12. ruff and bandit are clean at the versions pinned in .pre-commit-config.yaml.

Prior work

The same optimisation has been proposed upstream in pyannote/pyannote-audio#2048 (see also pyannote/pyannote-audio#2050 and pyannote/pyannote-audio#1996), where it was checked on VoxConverse dev with identical DER on all 216 files. None of it has been merged as of pyannote-audio 4.1.0. pyannote 4.1.0 also requires Python 3.11+, so whispermlx users on 3.10 would never receive an upstream fix. This override can be removed once a pyannote release that includes it becomes the minimum supported version.

Summary by CodeRabbit

  • Improvements
    • Speaker diarization now processes speaker embeddings in batches for supported models. Models that do not support this approach continue using the existing embedding behavior.
    • Overlap-excluded audio is used when enough frames are available; otherwise, diarization falls back to the full audio chunk.

…nce per speaker

pyannote's SpeakerDiarization.get_embeddings runs the WeSpeaker ResNet once for
every (chunk, local speaker) pair, although the speaker mask only enters at the
final statistics-pooling layer, which already accepts (batch, speakers, frames)
weights. Run the frame-wise network once per chunk and pool all local speakers
in the same call.

The override is installed only when the pipeline's embedding model accepts
stacked masks (probed with a single dummy forward); other backends keep
pyannote's per-pair loop. Embeddings match the stock implementation up to
float noise, and the diarization output is unchanged.
@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The pipeline now uses batched per-chunk speaker embedding extraction when a pyannote embedding model supports stacked speaker masks. Tests compare results with pyannote and check progress events and backend compatibility.

Changes: Per-chunk speaker embeddings

Layer / File(s) Summary
Stacked-mask probe and batched extraction
whispermlx/diarize.py, tests/test_diarize.py
The embedding method batches chunk waveforms and speaker masks for inference. It delegates to pyannote during training and applies the overlap-exclusion fallback. Tests check output shape, NaN placement, numerical agreement, and progress events.
Conditional pipeline enablement
whispermlx/diarize.py, tests/test_diarize.py
The pipeline binds the replacement method only when the model is a SpeakerDiarization instance and its embedding passes the stacked-mask check. Tests check support for WeSpeaker and rejection for another backend.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant DiarizationPipeline
  participant SpeakerDiarization
  participant PyannoteEmbedding
  participant ProgressHook
  DiarizationPipeline->>PyannoteEmbedding: Probe stacked-mask output shape
  DiarizationPipeline->>SpeakerDiarization: Bind replacement when probe matches
  SpeakerDiarization->>PyannoteEmbedding: Run each batch with stacked speaker masks
  PyannoteEmbedding-->>SpeakerDiarization: Return batch embeddings
  SpeakerDiarization->>ProgressHook: Report initial and completed batches
Loading

Suggested reviewers: kalebjs

Merge Risk: Minimal · up to 3a0de

This change speeds up speaker embedding extraction for supported pyannote models and leaves other backends on their existing path. No concrete merge-blocking issue was identified. Normal checks on the target hardware are still advisable.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title states the main change: speaker embeddings are now extracted once per chunk rather than once per speaker, which matches the raw summary (batched per-chunk embedding in diarize.py, tests for …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title states the main change: speaker embeddings are now extracted once per chunk rather than once per speaker, which matches the raw summary (batched per-chunk embedding in diarize.py, tests for _get_embeddings_per_chunk) and the PR objectives (instance-level get_embeddings override for supported pyannote pipelines). The title uses the conventional-commit prefix perf(diarize), which is clear and specific. It does not mention the fallback to pyannote's original path for unsupported backends, but that is a secondary detail.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6a553459-0408-4a27-9f02-debe599d5b40
Commits

Reviewing files that changed from the base of the PR and between 6c05b01 and 3a0de25.

Files selected for processing: 2

  • tests/test_diarize.py
  • whispermlx/diarize.py

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants