Skip to content

fix(parakeet): cluster batch diarization offline, not by arrival order - #12471

Merged
kodjima33 merged 3 commits into
BasedHardware:mainfrom
SakashSrivastava:fix/parakeet-offline-ahc-diarization
Sep 9, 2026
Merged

kodjima33 merged 3 commits into
BasedHardware:mainfrom
SakashSrivastava:fix/parakeet-offline-ahc-diarization

Conversation

@SakashSrivastava

@SakashSrivastava SakashSrivastava commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes

Closes #8917 (and the multi-speaker symptom in #5470).

_diarize_segments in backend/parakeet/transcribe.py matched each segment against running-mean centroids while walking the file in time order. The partition was therefore a function of arrival order, not of the embeddings. Two failure modes follow:

  1. Centroid drift — each match folded its embedding into centroids[i] = (centroids[i] * n + emb) / (n + 1). As noisy segments merged, the centroid moved away from the voice it represented, until a genuinely different speaker fell inside its threshold.
  2. Short segments inherited by recency — a clip under MIN_SEGMENT_DURATION was labelled SPEAKER_{len(centroids) - 1}: whichever speaker was created most recently, not the one speaking beside it.

The change

Collect every eligible embedding first, then partition once with average-linkage agglomerative clustering over cosine distance. The result depends only on the members, so the same voices in any order produce the same partition.

  • Short and failed segments inherit the nearest clustered segment in time instead of the most recently created speaker.
  • Clusters are renumbered by first appearance, preserving the contract that SPEAKER_0 is the first voice heard.
  • Non-finite and zero-norm embeddings are dropped before clustering — scipy returns NaN for cosine against a zero vector, which would spread through the linkage matrix into every cluster.
  • /v2/transcribe gains optional num_speakers / min_speakers / max_speakers, each validated positive. min > max is rejected as 422, and so is num_speakers combined with either bound — an exact count and a range are contradictory, and silently preferring one would leave the caller believing a bound they set was honoured. _diarize_segments keeps a precedence warning for direct in-process callers, which are not bound by the endpoint contract.

A separate cut threshold, and why. AHC cuts the dendrogram on cophenetic merge height — the mean distance between two whole clusters. SPEAKER_CLUSTERING_THRESHOLD bounds a different quantity: one embedding against one drifting centroid. The value does not transfer, so the batch path takes SPEAKER_AHC_THRESHOLD (default 0.55, env PARAKEET_SPEAKER_AHC_THRESHOLD). The streaming threshold is untouched at 0.60. The 0.55 default is measured, not guessed — sweep below.

No new dependency. scipy is already pinned in backend/parakeet/requirements.txt (>=1.11.0) and backend/requirements.txt (==1.14.0).

DER measurement

VoxConverse test subset (the 15 clips and RTTMs already committed under backend/tests/container/voxconverse), oracle segmentation. Both algorithms consume identical segments and identical embeddings (pyannote/wespeaker-voxceleb-resnet34-LM, window="whole", T4 GPU), so the delta is attributable to clustering alone. Missed-speech and false-alarm terms are held near zero; this is speaker-confusion DER.

all clips 3+ speakers 1–2 speakers
online centroid @ 0.60 0.1391 0.1742 0.0709
offline AHC @ 0.55 0.1101 0.1303 0.0709

3+ speaker DER falls 25% relative, with no movement at all on 1–2 speaker clips.

Threshold sweep — the choice is a basin, not a tuned point. Every cut in 0.40–0.55 beats the inherited 0.60:

cut all 3+ 1–2
0.40 0.1190 0.1385 0.0812
0.50 0.1149 0.1363 0.0735
0.55 0.1101 0.1303 0.0709
0.60 0.1318 0.1632 0.0709
0.70 0.1553 0.1988 0.0709

0.55 is picked as the point that maximises the 3+ gain while leaving 1–2 speaker DER exactly at baseline.

Per-clip, 12 of 15 are unchanged. The movement:

clip speakers before after delta
eguui 3 0.4980 0.3019 −0.1961 — was collapsing all 3 speakers into 1 cluster
tnjoh 5 0.3065 0.1791 −0.1274
bvyvm 3 0.0161 0.0290 +0.0129 — over-splits to 5 clusters against 3 true speakers

Stated plainly: num_speakers is a caller-intent knob, not an accuracy improvement. Feeding the ground-truth speaker count gives aggregate DER 0.1390 — indistinguishable from baseline. It helps eguui (−0.1961) and msbyq (−0.0742) but badly hurts gkiki (+0.2258), where forcing a sixth cluster shreds a good five-way partition. Callers who genuinely know the count can ask for it; nobody should expect it to lower error.

bvyvm is a real regression and I have not tuned it away — doing so would mean fitting 15 clips.

Scope

Batch path only. stream_handler.py keeps online centroid matching — a live stream cannot cluster over segments it has not received yet. That divergence is pre-existing and left for a follow-up rather than widened into this PR.

Two claims in the issue body did not match current code and were not followed. The issue specifies SPEAKER_MATCH_THRESHOLD = 0.45, but that is the enrollment verification threshold; batch clustering used SPEAKER_CLUSTERING_THRESHOLD = 0.60, and a test pins the two apart. The issue also does not mention the existing SPEAKER_CLUSTERING_MAX_SPEAKERS cap, which this change preserves as the default ceiling. The endpoint knobs are Form fields rather than the Query params the issue sketches, matching the existing diarize: bool = Form(True) on the same multipart endpoint.

Product invariants

none — no invariant in product/invariants/ covers backend/parakeet/**. Confirmed with scripts/pr-preflight --suggest.

Failure-Class: new

FC-partition-depends-on-arrival-order is added in this PR. A grouping over an already-complete input must be a function of its members, never of the order they were visited; folding each element into mutable accumulated state makes the accumulator a function of history instead, so the same members in a different order yield a different grouping and neither result is defensible. The guard surface is the offline partition in _diarize_segments plus the order-independence tests in backend/tests/unit/test_parakeet_offline_diarization.py.

Unit verification

The regression test fails on the pre-fix code. With the production change stashed and the new test file left in place:

pytest tests/unit/test_parakeet_offline_diarization.py
-> 10 failed, 10 passed
test_chain_partition_is_identical_under_reversed_arrival
E   assert [(0, 1), (2,)] == [(0,), (1, 2)]

Three voices at 0°, 45° and 100° form a chain. Arriving forwards the old code grouped {A,B} and left C alone; arriving backwards it grouped {B,C} and left A alone. Same voices, same distances, different answer.

test_non_finite_embedding_is_excluded_from_clustering
E   AssertionError: assert 'SPEAKER_1' in {'SPEAKER_0', 'SPEAKER_2'}

The old code minted a phantom SPEAKER_1 from a NaN embedding.

The remaining 8 pre-fix failures are the constraint and threshold-contract tests, which exercise parameters and a constant that did not exist before.

After the change:

Command Result
pytest tests/unit/test_parakeet_offline_diarization.py 20 passed
pytest tests/unit/test_parakeet_endpoints.py 42 passed (36 before the new endpoint tests)
Regression set across 6 parakeet modules 119 passed
scripts/backend-python-format --check (4 files) clean
scripts/failure-class validate ok, declaration new
make preflight 25 of 26 checks pass

The one preflight failure is desktop-backend-release-boundary-fixtures, which fails identically on unmodified upstream/main because jq is not installed on this machine — verified in a clean worktree. CI has jq.

Not run locally: the full backend/test.sh suite (the rest of the backend dependency set does not build on Windows without MSVC build tools) and the container DER benchmark, which needs a GPU with a running Parakeet server. The DER numbers above were measured on a Colab T4 against this branch.

Credit

This picks up abandoned work from #8919 by @thesohamdatta, which established that offline AHC is the right approach here and drew detailed maintainer review before going quiet. The implementation is independent, but the direction is theirs.

`_diarize_segments` matched each segment against running-mean centroids as it
walked the file in time order, so the partition was a function of arrival order
rather than of the embeddings. Two failure modes followed: a centroid drifted as
noisy segments folded into its mean until a later speaker fell inside it, and a
segment too short to embed inherited `SPEAKER_{len(centroids) - 1}` — whichever
speaker happened to be created most recently, not the one speaking next to it.
Both concentrate in meetings with three or more participants, where labels get
merged or swapped (BasedHardware#8917, BasedHardware#5470).

Collect every eligible embedding first, then partition once with average-linkage
agglomerative clustering over cosine distance. The result depends only on the
members, so the same voices in any order produce the same partition. Short and
failed segments now inherit the nearest clustered segment in time. Clusters are
renumbered by first appearance, preserving the existing contract that SPEAKER_0
is the first voice heard.

AHC cuts the dendrogram on cophenetic merge height — the mean distance between
two whole clusters — which is not the quantity SPEAKER_CLUSTERING_THRESHOLD
bounds for the online path (one embedding to one drifting centroid). That value
does not transfer, so the batch path takes its own constant,
SPEAKER_AHC_THRESHOLD, defaulting to 0.55 and overridable via
PARAKEET_SPEAKER_AHC_THRESHOLD. The streaming threshold is untouched at 0.60.

/v2/transcribe gains optional num_speakers / min_speakers / max_speakers, each
validated as positive, with min > max rejected as 422. These express caller
intent; they are not an accuracy improvement (measured below). Without them the
configured speaker cap still bounds the partition as before. scipy was already
pinned in backend/parakeet/requirements.txt and backend/requirements.txt, so no
dependency is added.

Non-finite and zero-norm embeddings are now dropped before clustering; scipy
returns NaN for cosine against a zero vector, which would spread through the
linkage matrix into every cluster.

Scope: the batch path only. `stream_handler.py` keeps online centroid matching —
a live stream cannot cluster over segments it has not received yet. That
divergence is pre-existing and left for a follow-up.

Failure-Class: new

Verification — unit (Windows, backend/.venv on Python 3.11.15):
- `pytest tests/unit/test_parakeet_offline_diarization.py` — 20 passed
- Same file against the pre-fix `_diarize_segments` (production change stashed):
  7 failed, 12 passed. `test_chain_partition_is_identical_under_reversed_arrival`
  failed with `assert [(0, 1), (2,)] == [(0,), (1, 2)]` — three voices at 0/45/100
  degrees grouped {A,B} arriving forwards and {B,C} arriving backwards, the exact
  order dependence this fixes. `test_non_finite_embedding_is_excluded_from_clustering`
  failed with a phantom `SPEAKER_1` minted from a NaN embedding.
- Regression set (endpoints, offline_diarization, builtin_embedding,
  stream_session, batch_routing, diarizer_embedding_decoder_bypass) — 117 passed.
- `scripts/backend-python-format --check` on all four changed files — clean.
- `scripts/failure-class validate` — ok, declaration `new`.
- `make preflight` — 25 of 26 checks pass. `desktop-backend-release-boundary-fixtures`
  fails identically on unmodified upstream/main because `jq` is not installed
  locally; verified in a clean worktree.

Verification — DER, VoxConverse test subset, oracle segmentation:
Both algorithms consume identical segments and identical embeddings
(pyannote/wespeaker-voxceleb-resnet34-LM, window="whole"), so the delta is
attributable to clustering alone.

                    all clips   3+ speakers   1-2 speakers
  online centroid     0.1391      0.1742        0.0709
  offline AHC @0.55   0.1101      0.1303        0.0709

3+ speaker DER falls 25% relative with no movement on 1-2 speaker clips. Largest
gains: eguui 0.4980 -> 0.3019 (was collapsing all three speakers into one
cluster), tnjoh 0.3065 -> 0.1791. One regression: bvyvm 0.0161 -> 0.0290, which
over-splits to 5 clusters against 3 true speakers. Twelve of fifteen clips are
unchanged. Every cut in 0.40-0.55 beats the inherited 0.60, so the choice is a
basin rather than a single tuned point.

Passing the true speaker count through num_speakers does not improve aggregate
DER (0.1390): it helps eguui (-0.1961) and msbyq (-0.0742) but hurts gkiki
(+0.2258), where forcing a sixth cluster splits a good five-way partition.

Not run locally: the full `backend/test.sh` suite and the container DER
benchmark. The rest of the backend dependency set does not build on this Windows
machine without MSVC build tools, and the container benchmark needs a GPU with a
running Parakeet server; the measurement above was run on a Colab T4 against this
branch.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified locally (CPU, using the repo's own testing.import_isolation fixtures): tests/unit/test_parakeet_offline_diarization.py passes 20/20 on this branch, and 10 of those fail against main's _diarize_segments — including test_chain_partition_is_identical_under_reversed_arrival, which reproduces the arrival-order bug exactly ({A,B},{C} forwards vs {B,C},{A} backwards for voices at 0/45/100 degrees; the pairwise distances 0.293/0.426/1.174 check out independently). tests/unit/test_parakeet_endpoints.py is 40/40 with the four new constraint tests.

Per-file notes:

  • backend/parakeet/transcribe.py — the collect-then-partition rewrite is the right shape. _embedding_vector drops non-finite and zero-norm embeddings before linkage(method="average", metric="cosine") (a NaN pair would otherwise propagate through the whole dendrogram); _cut_to_count clamps maxclust into [1, total] (scipy tolerates t > n by returning singletons, verified); _assign_speaker_labels renumbers by first appearance so SPEAKER_0 stays "first voice heard", which is what downstream speaker identification reads; and the no-explicit-max path correctly preserves SPEAKER_CLUSTERING_MAX_SPEAKERS as the ceiling, as the online path had. The separate SPEAKER_AHC_THRESHOLD is a sound distinction — cophenetic merge height is a genuinely different quantity from distance-to-a-drifting-centroid — and the streaming threshold staying at 0.60 is pinned by test_batch_cut_is_separate_from_the_online_clustering_threshold.
  • backend/parakeet/main.py — forward-only wiring. Form(None, gt=0) rejects non-positive counts at the framework layer, the min > max 422 short-circuits before any temp file is written, and both executor paths (with and without gpu_result) receive the bounds.
  • speaker_math.py (unchanged) — select_speaker_cluster remains for the streaming path; stream_handler.py imports it from speaker_math directly, so dropping the re-export from transcribe.py breaks nothing (nothing else imports it via transcribe).
  • .github/failure-classes/FC-partition-depends-on-arrival-order.json — matches the schema and style of the existing FC corpus on main; canonical_prevention_artifact points at real files in this PR.
  • Both test files — the order-independence, constraint-precedence/clamping, short-segment inheritance, NaN/zero-vector exclusion, and gating tests all drive the real _diarize_segments rather than a reimplementation. Genuinely good suite.

Two things for a maintainer before merge:

  1. This changes batch diarization output for every existing /v2/transcribe caller, not just opt-in knob users — new algorithm plus a re-tuned cut. The VoxConverse evidence in the description is measured, with the bvyvm regression disclosed honestly rather than tuned away, but it is 15 clips on one embedding model, so the shipped default deserves a human sign-off.
  2. CI has not actually run on this head: all workflows are action_required pending first-time-contributor workflow approval, so the current green check state only reflects the neutral cubic review. Once approved, Backend Unit Tests should pick up both files via the backend/** path filter.

Minor nit, not blocking: when both num_speakers and min/max_speakers are supplied, precedence is only logged (logger.warning), not rejected — fine for an internal knob, but if these params are ever exposed beyond internal callers, a 422 there would be consistent with the min > max case.

Thanks also for the explicit credit to #8919 — the offline-AHC direction rightly belongs to that earlier work.

Maintainer sign-off wanted on the batch-default clustering change and the new /v2/transcribe parameters; workflow approval is also needed so CI can validate this head on real runners.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge labels Aug 31, 2026
Review follow-up on BasedHardware#12471. An exact speaker count and a range are contradictory
requests. The endpoint previously accepted both and `_cluster_embeddings` only
logged which one won, so a caller who set `max_speakers` alongside `num_speakers`
was left believing a bound they set had been honoured.

/v2/transcribe now rejects the combination with 422, consistent with the existing
min > max rejection. `_diarize_segments` keeps its precedence warning for direct
in-process callers, which are not bound by the endpoint contract.

No failure-class declaration: this strengthens an API contract introduced in the
previous commit of this PR; there is no triggering defect in shipped behavior.

Verification (Windows, backend/.venv on Python 3.11.15):
- `pytest tests/unit/test_parakeet_endpoints.py` — 42 passed (40 before)
- Regression set across 6 parakeet modules — 119 passed
- `scripts/backend-python-format --check` on both changed files — clean

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well-documented fix with real DER measurements, but diff exceeds the 300-line scoped-fix bar and CI hasn't run on this branch yet, so confidence is 3/5 — approve-only, not merging.

@Git-on-my-level Git-on-my-level left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the follow-up commit — the num_speakers + range combination is now rejected with a 422 at the endpoint (verified: test_v2_rejects_num_speakers_combined_with_bounds passes, and the in-process precedence warning is kept for direct callers), which resolves the one nit from the earlier review of a543fd7. The failure-class declaration also validates cleanly against the PR body (scripts/failure-class validate → OK).

Blocking: _cut_to_count is scipy-version-sensitive and silently ignores the speaker constraints on the stack CI uses

Repro on this head (2b0534f), on the backend unit-test environment installed from backend/pylock.toml (scipy 1.14.0, numpy 1.26.4, Python 3.11.15). Note: this lands alongside kodjima33's approval of this head — the algorithmic direction has maintainer sign-off; this request is only about the reproducible defect below, which CI has not been able to surface because the workflows are still awaiting first-time-contributor approval:

  • tests/unit/test_parakeet_endpoints.py — 42/42 pass.
  • tests/unit/test_parakeet_offline_diarization.py — 3 failures:
    • TestSpeakerConstraints::test_num_speakers_forces_exact_partition_size
    • TestSpeakerConstraints::test_min_speakers_splits_a_partition_the_threshold_would_merge
    • TestSpeakerConstraints::test_num_speakers_takes_precedence_over_min_and_max

num_speakers=3 over three near-orthogonal _voice(i) embeddings yields ['SPEAKER_0', 'SPEAKER_0', 'SPEAKER_0'] — one cluster. The cause is in backend/parakeet/transcribe.py: _cut_to_count uses fcluster(tree, t=bounded, criterion="maxclust"), and scipy 1.14.0's maxclust collapses near-tied merge heights (here 0.99761 vs 0.99900) into a single cluster, while scipy 1.18.1 returns two. Your 20/20 was real — on a newer scipy. But:

  • CI installs from backend/pylock.toml → scipy 1.14.0, so Backend Unit Tests will go red on this head once the pending workflow approval lands.
  • backend/requirements.txt pins scipy==1.14.0 while backend/parakeet/requirements.txt floats scipy>=1.11.0 (resolves to 1.18.x today), so the constraint parameters would honor num/min/max_speakers on one deployed stack and silently ignore them on the other — no error, just wrong labels.

Verified fix direction: cut on merge heights rather than maxclust — sort Z[:, 2], cut just below the (n−k)-th height (np.nextafter(height, -inf)) with criterion="distance". Checked on both scipy 1.14.0 and 1.18.1: it returns exactly k clusters for these geometries, including the two-identical-vectors edge case. A post-cut assertion that len(set(labels)) == bounded (logging rather than silently returning fewer clusters) would harden it further.

The rest is in good shape

  • backend/parakeet/transcribe.py — collect-then-partition, the non-finite/zero-norm guard ahead of linkage(method="average", metric="cosine"), first-appearance renumbering preserving SPEAKER_0-is-first-heard, and keeping SPEAKER_CLUSTERING_MAX_SPEAKERS as the implicit ceiling all check out; the 17 non-constraint tests pass on both stacks.
  • backend/parakeet/main.py — forward-only wiring: both executor paths receive the bounds, and both 422s short-circuit before any temp file is written.
  • backend/tests/unit/test_parakeet_offline_diarization.py — the contracts themselves are right; three currently fail for the production reason above, not a harness issue.
  • backend/tests/unit/test_parakeet_endpoints.py — clean helper (_post_v2_with_mocked_transcriber); all four rejection/forwarding behaviors covered.
  • .github/failure-classes/FC-partition-depends-on-arrival-order.json — matches the corpus schema and style; canonical_prevention_artifact paths are real.

Requesting changes for the _cut_to_count rework plus a run of the suite on the pylock stack. Beyond that, this still merits maintainer sign-off on the shipped-default change: every existing /v2/transcribe response would come from the new clustering, the three new parameters are a public API surface, and the scipy pin divergence between the two requirements stacks needs a decision.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

Review catch on BasedHardware#12471. `_cut_to_count` used
`fcluster(tree, t=k, criterion="maxclust")`, whose handling of near-tied merge
heights varies across scipy releases. On scipy 1.14.0 — what backend/pylock.toml
installs and what CI runs — three near-orthogonal embeddings merging at 0.997606
and 0.999002 collapse into one cluster whether 2 or 3 are requested; scipy 1.17.1
returns 2 and 3. My earlier 20/20 was real but measured on 1.17.1, not the locked
stack.

The consequence was worse than a red test: backend/requirements.txt pins
scipy==1.14.0 while backend/parakeet/requirements.txt floats scipy>=1.11.0, so
num_speakers / min_speakers / max_speakers would have been honoured on one
deployed stack and silently ignored on the other — no error, just wrong labels.

Cut on merge height instead. `total - 1` merges ascend; keeping the first
`total - bounded` leaves `bounded` clusters, so cut immediately below the next
height with `np.nextafter(..., -inf)` and `criterion="distance"`. This is
expressed in the dendrogram's own units and does not depend on how a scipy
release resolves ties.

Exactly-tied heights remain unreachable by any single distance cut. The cut now
errs toward more clusters — safer for diarization than merging two speakers — and
logs the shortfall rather than returning a different count in silence.

Verification (Windows, Python 3.11.15, both stacks):
- New venv matching backend/pylock.toml exactly (numpy 1.26.4, scipy 1.14.0).
  Before this commit, on that stack: 3 failed, 17 passed —
  test_num_speakers_forces_exact_partition_size,
  test_min_speakers_splits_a_partition_the_threshold_would_merge,
  test_num_speakers_takes_precedence_over_min_and_max. Exactly the three named in
  review.
- After: 120 passed on scipy 1.14.0 and 120 passed on scipy 1.17.1, across
  test_parakeet_offline_diarization, test_parakeet_endpoints,
  test_parakeet_builtin_embedding, test_parakeet_stream_session,
  test_parakeet_batch_routing, test_diarizer_embedding_decoder_bypass.
- Direct probe of `_cluster_embeddings` on both stacks now returns identical
  labels for num_speakers=2, num_speakers=3, and the two-identical-vectors
  min_speakers=2 edge case.
- New test `test_exactly_tied_merge_heights_report_the_shortfall` covers the tie
  branch and asserts the warning.
- `scripts/backend-python-format --check` on both changed files — clean.
@SakashSrivastava

Copy link
Copy Markdown
Contributor Author

Confirmed and fixed in d7dd4a5. Built a venv matching backend/pylock.toml exactly (numpy 1.26.4, scipy 1.14.0) and got precisely the three failures you named, my earlier 20/20 was on scipy 1.17.1, which was my mistake for installing latest instead of the lock.

Went with your suggested direction: cut on merge height rather than maxclust. Sort Z[:, 2], keep the first total - k merges, cut just below the next height with np.nextafter(..., -inf) and criterion="distance". It's expressed in the dendrogram's own units so it doesn't depend on how a scipy release resolves ties. 120 passed on 1.14.0 and 120 on 1.17.1, and a direct probe of _cluster_embeddings returns identical labels on both.

Added the assertion you suggested too, exactly-tied heights still can't be split by any single cut, so it now errs toward more clusters (safer than merging two speakers) and logs the shortfall instead of silently returning a different count. test_exactly_tied_merge_heights_report_the_shortfall covers that branch.

On the scipy pin divergence: this makes both stacks produce identical labels, so it no longer changes behaviour but whether parakeet/requirements.txt should stop floating is your call, and I've left it alone.

@Git-on-my-level
Git-on-my-level dismissed their stale review September 2, 2026 14:51

Resolved in d7dd4a5: _cut_to_count now cuts on merge heights (criterion="distance" just below the (n-k)-th height via np.nextafter) instead of scipy's version-sensitive maxclust tie-breaking, and reports tied-height shortfalls instead of silently mis-partitioning. Reproduced on the CI stack (scipy 1.14.0 / numpy 1.26.4 from backend/pylock.toml): all three previously-failing constraint tests now pass, 21/21 in test_parakeet_offline_diarization.py and 42/42 in test_parakeet_endpoints.py.


by AI on behalf of David — if you need David's attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on the CI stack — the blocking concern from the previous review is resolved.

_cut_to_count in backend/parakeet/transcribe.py no longer uses criterion="maxclust". It sorts the merge heights, cuts just below the (n − k)-th height with np.nextafter(height, -inf) and criterion="distance", short-circuits bounded == 1 to [1] * total, and logs a warning when exactly-tied heights make the requested count unreachable instead of silently returning a different partition. The cut is now expressed in the dendrogram's own merge-height quantity on every scipy release rather than each release's maxclust tie-breaking, which is what removed the version sensitivity.

Reproduced the CI environment (scipy 1.14.0, numpy 1.26.4 — what backend/pylock.toml installs) and ran the suites at this head:

  • tests/unit/test_parakeet_offline_diarization.py — 21/21, including the three that failed at 2b0534f on this stack (test_num_speakers_forces_exact_partition_size, test_min_speakers_splits_a_partition_the_threshold_would_merge, test_num_speakers_takes_precedence_over_min_and_max) and the new test_exactly_tied_merge_heights_report_the_shortfall, which pins the tie behavior: four voices 90° apart tie two merges at exactly 1.0, asking for 3 yields 4 clusters plus the shortfall warning. Erring toward more clusters rather than merging two speakers is the right failure mode for diarization.
  • tests/unit/test_parakeet_endpoints.py — 42/42 (unchanged by this commit, re-checked).

Also spot-checked the cut numerically on scipy 1.14.0: the chain geometry from the earlier review (merge heights 0.29289 / 0.80004) returns exactly 3 clusters for num_speakers=3; an exact-duplicate pair asking for 2 warns and keeps the duplicate merged; num_speakers == total returns singletons.

On this commit specifically:

  • backend/parakeet/transcribe.py — the new docstring records the 1.14.0 vs 1.18.x maxclust divergence with the concrete heights (0.99761 vs 0.99900); good place for that history. The bounded == 1 branch also avoids a degenerate cut below the smallest merge.
  • backend/tests/unit/test_parakeet_offline_diarization.py — the _voice docstring now explains the anti-tie perturbation and points at the new tie test, and the suite covers the tie contract explicitly.

backend/parakeet/main.py, backend/tests/unit/test_parakeet_endpoints.py, and .github/failure-classes/FC-partition-depends-on-arrival-order.json are unchanged by this commit; the endpoint wiring was re-verified as part of the 42/42 run (all three parameters forwarded on both executor paths, both 422s short-circuit before any temp file is written).

The earlier changes-requested review is dismissed as resolved. Still with a maintainer before merge: sign-off on the shipped default — every existing /v2/transcribe response now comes from the new clustering, not just callers of the new num/min/max_speakers parameters — and approving the workflows so CI can run; no check has executed on any commit of this PR yet, and Backend Unit Tests will pick up both files via the backend/** filter once approved.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the positive-signal Automation verified a genuine fix/quality contribution label Sep 2, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug fix, high confidence (root cause + DER data, fixes #8917/#5470, regression tests proven to fail pre-fix, not already fixed on main). Holding at approve, not merge: Hygiene check fails on a real (non-flaky, reran and still fails) firestore-query-coverage baseline drift unrelated to this diff — hard floor requires no failing required check.

@Git-on-my-level

Copy link
Copy Markdown
Member

Checked the Hygiene red on this head, because the code is not its cause.

What failed: firestore-query-coverage inside the Hygiene job's shared PR contract preflight — baseline registered_serving is 62, current inventory reports 73 and baseline eligible_serving is 102, current inventory reports 113. Every other selected check at this head passed, including the failure-class protocol for the new FC entry.

Why: this branch forked from main on Sep 1 (fork point 17721ce) a few hours before two same-day fixes landed — 52d70a6 refreshed backend/scripts/firestore_query_coverage_baseline.json to the then-current inventory, and 42e22fd ("stop firestore query-coverage baseline equality from flapping") made count increases advisory instead of errors. The merge-lane checkout (Merge d7dd4a5 into 17721cea) therefore executes the branch's own stale copies — the old baseline (62/102) with the old exact-equality semantics — against an inventory that has since grown to 73/113. Main has been green on this check all week.

Verified it is not this diff: overlaying this PR's two backend files onto current main leaves the query inventory fingerprint-identical (127 shapes, registered 80 / eligible 120 either way) and python3 backend/scripts/firestore_query_coverage.py --check-ratchet exits 0. The PR touches no Firestore query code.

Fix: a plain rebase onto current main should turn Hygiene green — nothing in the diarization change needs to move. Every other check at this head is green.

State of the changed files, unchanged since the prior automated verification at this head:

  • backend/parakeet/transcribe.py — _cut_to_count cuts on sorted merge heights with np.nextafter(height, -inf) and criterion="distance" (stable across scipy releases), _embedding_vector drops non-finite and zero-norm vectors before linkage(..., method="average", metric="cosine"), and _assign_speaker_labels renumbers clusters by first appearance so SPEAKER_0 stays the first voice heard.
  • backend/parakeet/main.py — forward-only wiring: Form(None, gt=0) rejects non-positive counts at the framework layer, both 422s (min > max, and num_speakers combined with either bound) short-circuit before any temp file is written, and both executor paths receive the bounds.
  • backend/tests/unit/test_parakeet_offline_diarization.py — drives the real _diarize_segments with hand-placed unit vectors (the 0/45/100-degree chain makes order-dependence arithmetic, not luck), including the tied-merge-heights shortfall contract; 21/21 when last run on the CI stack (scipy 1.14.0) at this head.
  • backend/tests/unit/test_parakeet_endpoints.py — six new endpoint tests covering parameter forwarding, both 422 rejections, and non-positive counts; 42/42 at this head.
  • .github/failure-classes/FC-partition-depends-on-arrival-order.json — matches the existing FC corpus schema, and canonical_prevention_artifact points at real files in this PR.

Also noting with thanks: @kodjima33's approval of this head covers the shipped-default sign-off the earlier review asked for, the workflows have now run on real runners, and combining num_speakers with min/max now returns 422 at the endpoint as previously suggested. Once Hygiene is green after the rebase, this looks ready from my side.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level removed the needs-maintainer-review Needs a human maintainer to sign off before merge label Sep 8, 2026
@kodjima33
kodjima33 merged commit 8d592a2 into BasedHardware:main Sep 9, 2026
39 of 41 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Backend: Offline agglomerative clustering for robust 3+ speaker diarization (#5470)

3 participants