Chapter 34Making pyannote's Overlap Loop 26x Faster, Then Proving It in Lean
On an 8,000-segment file, computing diarization error rate with pyannote.metrics took 14.8 seconds. After a change of a few dozen lines in pyannote.core, it takes 0.58 seconds. Roughly 26x, with every metric value identical to the last digit.
A faster loop is easy. Being sure it gives the same answer, including tied start times, nested segments, segments that just touch, and a precision constant that makes "do these intervals overlap?" slightly fuzzy, is hard. So I did something I'd never done for a perf PR: I wrote a Lean 4 proof that the new code returns exactly what the old did, same pairs, same order.
Where the time went#
pyannote.core provides Segment (a time interval), Timeline (a sorted collection of segments) and Annotation (a timeline with speaker labels). pyannote.metrics builds DER on top.
Profiling DiarizationErrorRate on a 4,000-segment file: 92% of the time was in Timeline.co_iter, with around 70 million calls to Segment.intersects.
co_iter answers: given two timelines, which pairs of segments overlap? It sits under crop, get_overlap and Annotation.__mul__, so nearly every metric runs through it.
for segment in self.segments_list_:
# iterate over segments that starts before 'segment' ends
temp = Segment(start=segment.end, end=segment.end)
for other_segment in other.segments_list_.irange(maximum=temp):
if segment.intersects(other_segment):
yield segment, other_segmentEach segment looks at every segment of other that sorts before its end. There's an upper bound but no lower one, so near the end of an hour-long recording each step rescans almost all of other, including segments that ended long ago. That's O(n·m). Timeline.segmentation had the same pattern: support.overlapping(middle) rescanned from the start every time.
The fix: stop looking backwards#
A standard sweep line. Both timelines are sorted, so walk them together keeping a small set of candidates: segments of other that might still overlap something coming up.
The key observation: if a segment of other starts before the current segment and doesn't intersect it, it can't intersect any later segment, since later ones don't start earlier. Once a candidate fails that way, drop it for good.
other: [a] [b--] [c] [d--]
self: [s1-----]
^ pointer admits everything <= temp
active: a b c
kept: (none yet)The pointer pushes segments of other into active, up to the same temp bound as the old code.
The new inner loop:
while pointer < num_others and others[pointer] <= temp:
active.append(others[pointer])
pointer += 1
kept = []
index = 0
num_active = len(active)
while index < num_active:
other_segment = active[index]
if not other_segment <= temp:
break
index += 1
if segment.intersects(other_segment):
kept.append(other_segment)
yield segment, other_segment
elif other_segment.start >= segment.start:
kept.append(other_segment)
if len(kept) < index:
active[:index] = keptsupport (sorted by start): [--a--]
[---b---]
[c]
running max of ends: end(a) end(b) end(b) (c ends earlier)
a middle m is covered <=> running max of ends >= mFor segmentation it's simpler. Middles only increase, so I keep a running maximum of end times over the support segments seen so far. A middle is covered exactly when that maximum is at least the middle.
The numbers#
Synthetic diarization benchmark (4 speakers, about 15% overlapped speech), pyannote.metrics 4.2.0, Python 3.11, Apple M-series:
| segments | DER before | DER after | IER before | IER after |
|---|---|---|---|---|
| 1,000 | 0.30s | 0.06s | 0.26s | 0.04s |
| 4,000 | 3.94s | 0.28s | 3.35s | 0.18s |
| 8,000 | 14.8s | 0.58s | 13.1s | 0.39s |
DER with collar=0.5, skip_overlap=True at 8k segments drops from 27.0s to 0.74s, and 32k segments now runs DER in about 2.5 seconds.
Caveats: at 1,000 segments the old code was already fast enough. The data is synthetic and from one machine. I haven't proved a complexity bound; one enormous segment overlapping everything keeps many candidates alive, and I wouldn't promise linear time there. The proof below is about what the code returns, not how fast.
So how do I know it's still right?#
The PR has new tests comparing both methods against naive references on 500 random timelines each, on a deliberately coarse grid so ties, nesting, touching and duplicates come up often. I also ran 78k cases of differential fuzzing against the previous implementation, including Segment.set_precision(...), zero-length and invalid segments. Every case matched.
But Segment.intersects made me nervous:
(self.start < other.start and other.start < self.end - SEGMENT_PRECISION)
or (self.start > other.start and self.start < other.end - SEGMENT_PRECISION)
or self.start == other.startend - SEGMENT_PRECISION is a float subtraction with a constant defaulting to 1 microsecond, so "intersects" isn't clean interval overlap. The drop rule is the most dangerous line in the PR: if it's wrong at some rounding edge, a real overlap pair is silently dropped and a metric shifts a little. Random tests are bad at showing a bug doesn't exist in a corner shaped by rounding. A proof can settle that.
self [===========] other [===========] self.start < other.start < self.end - P -> intersects
self [===========] other [===========] other.start == self.end, not < self.end - P -> no overlap (an overlap shorter than P counts as no overlap too)
self [=====================] other [=======] self.start < other.start < self.end - P -> intersects
What the theorem says#
Lean 4 is a programming language and proof assistant: if the file compiles, the kernel checked every step. I used Lean core only, no sorry, and #print axioms lists only the three standard axioms.
I wrote both versions of co_iter as small Lean functions over lists: naive is the old nested loop, sweep the new one.
theorem co_iter_exact (sub : α → α) (temp : Seg α → Seg α)
(xs ys : List (Seg α))
(hxs : xs.Pairwise fun a b => O.segLe a b = true)
(hys : ys.Pairwise fun a b => O.segLe a b = true) :
sweep (O.intersects sub) (fun s o => O.segLe o (temp s))
(fun s o => O.le s.start o.start) xs [] ys =
naive (O.intersects sub) (fun s o => O.segLe o (temp s)) xs ys| Parameter | Meaning |
|---|---|
α, O | any type of times, with comparisons behaving like Python's <=, <, == on non-NaN floats |
sub | any function, standing in for end - SEGMENT_PRECISION; holds however the float subtraction rounds |
temp | any function, standing in for Segment(segment.end, segment.end) |
xs, ys | self and other, each sorted by segLe, my model of Segment.__le__ (compares (start, end) like a Python dataclass) |
Starting from an empty active list, the sweep yields exactly the same list of pairs as the nested loop. Same list, so same order: not "the same set", not "close enough".
The crux is drop_ok, the formal "a dropped candidate can never match again": if s comes before s', o doesn't intersect s, and o starts strictly before s, then o doesn't intersect s' either, for every possible sub. It holds for a structural reason: given the first two facts, sub(o.end) is at or before s.start, and s'.start is at or after s.start, so the comparison against s' fails too. Rounding never enters.
How the proof is structured, and the modelling assumptions
The core lemma, sweep_eq_naive, doesn't mention segments at all: any sweep of this shape equals any nested loop of this shape, provided the upper-bound test selects a prefix of a sorted list and the drop rule is safe in the drop_ok sense. co_iter_exact plugs pyannote's definitions into it. A sibling, segmentation_exact, covers the running-maximum trick: it answers exactly what the original "is there a support segment covering this middle?" check answers, for every middle.
Lean never reads the Python. I transcribed co_iter, segmentation, Segment.__le__ and Segment.intersects by hand; a mistake would make the proof about the wrong program. Assumptions:
- Times compare like non-NaN floats:
<=is a total preorder,a < bmeansnot (b <= a),a == bmeans both directions of<=. NaN in a segment breaks everything, as it did in the old code. - The
SortedListinside aTimelinereally is sorted bySegment.__le__. - For
segmentation,Segment(t, t)is monotone int, and middles are visited in nondecreasing order. -math.infis modelled as "no maximum yet" (anOptionstarting asnone).
Proved for everything meeting those assumptions: sweep equals nested loop for every pair of sorted timelines of any length with any ties; for every rounding behaviour of end - SEGMENT_PRECISION; and the segmentation sweep agrees with the original check for every middle. Not sampled, not bounded.
What ties the model to the real code#
The tests do. _naive_co_iter and _naive_segmentation mirror the Lean naive and segNaive closely, and the random generator adds jitter around SEGMENT_PRECISION so the precision-dependent branches of intersects run. The chain:
- Lean proves
sweep=naivefor the model. - The tests check real
co_iter= Python_naive_co_iteron random nasty inputs. - The 78k-case fuzz checks real new code against real old code.
The proof covers inputs the tests never sample; the tests and fuzzer catch me if my Lean transcription drifted. Neither alone would justify saying "identical output" as confidently as I do in the PR.
Where it stands#
The PR is pyannote/pyannote-core#116. Review status lives on the PR itself. The proof is in
lean-perf-proofs/pyannote-core-sweep;
check it with lean pyannote-core-sweep/SweepProof.lean. It's the first entry in a small repo of proofs for other perf fixes I've sent upstream.
The weakest link isn't the proof, it's me copying Python into Lean correctly. Fine for code this small; I'd be much less comfortable with a 400-line kernel. Is there a lightweight way to generate the Lean model from the Python, or check the two mechanically, without a full Python semantics? I don't know yet. Probably the next rabbit hole.