← Back to all chapters

Chapter 34Making pyannote's Overlap Loop 26x Faster, Then Proving It in Lean

7 min read
performancelean4formal-verificationpythonopen-source

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_segment

Each 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.

other (sorted)abcdeold: rescans everything that starts before s1 ends, from the very startselfs1new: only candidates still alive (b and c)
Which segments of other get examined for s1. Schematic layout, not real data.

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.

1/3Admit
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.

Sweep over a few segments. Dropped candidates are never looked at again.

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] = kept
support (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 >= m
The segmentation trick: one running maximum replaces a rescan. Schematic.

For 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:

segmentsDER beforeDER afterIER beforeIER after
1,0000.30s0.06s0.26s0.04s
4,0003.94s0.28s3.35s0.18s
8,00014.8s0.58s13.1s0.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.

  • DER, before14.8s
  • DER, after0.58s
  • IER, before13.1s
  • IER, after0.39s
  • DER with collar, before27s
  • DER with collar, after0.74s
Metric time at 8,000 segments (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.start

end - 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
Three cases intersects must get right. P is SEGMENT_PRECISION. Schematic.

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
ParameterMeaning
α, Oany type of times, with comparisons behaving like Python's <=, <, == on non-NaN floats
subany function, standing in for end - SEGMENT_PRECISION; holds however the float subtraction rounds
tempany function, standing in for Segment(segment.end, segment.end)
xs, ysself 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 < b means not (b <= a), a == b means both directions of <=. NaN in a segment breaks everything, as it did in the old code.
  • The SortedList inside a Timeline really is sorted by Segment.__le__.
  • For segmentation, Segment(t, t) is monotone in t, and middles are visited in nondecreasing order.
  • -math.inf is modelled as "no maximum yet" (an Option starting as none).

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:

  1. Lean proves sweep = naive for the model.
  2. The tests check real co_iter = Python _naive_co_iter on random nasty inputs.
  3. 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.

© 2026 Bharat Kaurav. Built with Next.js & Tailwind.

>_ bk@netherwatcheresc to close

Welcome, reader. Type help to see what this shell can do.