Skip to content

perf(batch): batch diarization and VAD across a worker flight - #22368

Merged
Git-on-my-level merged 9 commits into
mainfrom
lane/opus-worker-gpu
Oct 19, 2026
Merged

Git-on-my-level merged 9 commits into
mainfrom
lane/opus-worker-gpu

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Summary

The dedicated batch worker repeats pyannote model work inside each locked flight:

  1. Segmentation runs twice per unit. VAD wraps the same community-1 segmentation model as diarization, with the same 10s windows and 1s step, so diarization recomputes the same raw scores.
  2. The embedding trunk runs three times per chunk. SpeakerDiarization.get_embeddings sends the full ResNet34 forward once per (chunk, local speaker) pair, even though all three local speakers of a chunk share the same waveform. Only the statistics-pooling masks differ.
  3. Short units leave ragged tail batches. Units are about 40s on average, and each one ends in a partial forward.

diarizer/batch_pipeline_flight.py (FlightPyannote) removes the duplicated work and packs what remains across the flight's units:

  • One segmentation pass per unit, packed across units. VAD spans are derived on the CPU, using the same pre_aggregation_hook, aggregate, crop and _binarize steps as VoiceActivityDetection.apply. Diarization reads the same scores through its get_segmentations hook.
  • One trunk forward per chunk (WeSpeaker forward_frames / forward_embedding), pooled per local speaker with the masks get_embeddings would build. The mask selection for exclude_overlap is unchanged.
  • Peak VRAM is unchanged. Every forward keeps the pinned BATCH_PIPELINE_MODEL_BATCH_SIZE: segmentation takes B chunks, and the trunk takes B chunks instead of B pairs. Crops are generated lazily, one batch at a time.
  • Speakers are never pooled across units. Clustering, reconstruction and labels stay pyannote's own per-unit apply. The hooks fall through to the original methods whenever no precomputed feature is supplied.

PipelineWorker gets an optional flight_models. The decode loop and the final assemble loop are split so that a single packed call can run between them. Item semantics, failure stages and result types are unchanged.

Composition with #22358 (speech-only diarization, default on)

Speech-only diarization runs the diarizer on a compacted waveform, so full-unit packed embeddings and the cached full-unit segmentation must not reach it. When it is on, the worker skips _flight_diarize, and _diarize_unit keeps its serial pyannote apply. The get_embeddings hook gives that uncached call the per-file shared trunk only: the same masks over the compacted file's own segmentation. Packed segmentation then serves VAD alone. When speech-only is off, full-unit packing applies as described above. The flight tests cover both modes.

Safety and fallback

  • Ships dark. BATCH_PIPELINE_FLIGHT_BATCHING_ENABLED defaults off in code, in env parsing (only the exact value true enables it; unset, false, 0 and yes all mean off), in Helm (worker.flightBatchingEnabled: false) and in the registry (rollout, fail closed, review_by 2026-10-26). Off is exactly the pre-PR serial path: FlightPyannote is never constructed and no hooks are installed.
  • Budget: BATCH_PIPELINE_FLIGHT_BATCH_SECONDS, default 1800 audio seconds per packed group (valid range above 0 up to 7200). Production flights average 287s, p95 795s, max 1,400s. A unit over the budget takes the serial calls.
  • Serial fallback. These cases take the unchanged serial pyannote calls:
    • an unsupported model layout (parity checks at startup, logged as outcome=disabled reason=…);
    • any non-fatal failure in the packed path;
    • a cached-embedding shape mismatch (recomputed serially; the item is not failed);
    • CUDA OOM inside the packed path, after emptying the cache.
  • Quarantine is unchanged for other fatal CUDA errors (device assert, illegal access, cuBLAS alloc). An OOM in the serial path stays fatal, as before.
  • process_batch concurrency and the chain lock are unchanged.

Enablement gate (required before the flag is set on anywhere)

CPU equality on random weights does not cover the L4. Packing moves each unit's last chunk out of its own batch-of-one forward into a shared batch of 8, so cuDNN may choose another kernel. A shift of about 1e-5 in an embedding, or a powerset frame near 0.5, could change a VBx assignment, and that is unmeasured on the production checkpoint.

The gate is diarizer/batch_pipeline_flight_qualify.py, run on one isolated dev L4 with community-1 revision 3533c8cf8e369892e6b79ff1bf80f7b0286a54ee and batch pin 8. Use public or consented multi-speaker audio, such as AMI far-field meetings or a pendant clip with two voices:

PYTHONPATH=. BATCH_PIPELINE_MODEL_BATCH_SIZE=8 python diarizer/batch_pipeline_flight_qualify.py \
  --audio /public/ami/ES2004a.Array1-01.wav /public/ami/IS1009a.Array1-01.wav \
  --unit-seconds 23,41,67,95,128,30.5,212 --output /receipts/flight-qualify.json
  • Shared construction. The worker and the qualification both build their models with load_pyannote_pair, so the models are identical.
  • What it runs. The inputs are cut into one flight of mixed-length units, so ragged tails share packed forwards across units. All serial references are captured on the unpatched pipeline, before FlightPyannote.create installs its hooks.
  • What it scores: two configurations, serial vs flag-on.
    • speech_only is the Helm default and the configuration that authorizes the flag today. Packed segmentation feeds VAD, then the worker's own _diarize_unit diarizes the compacted waveform through the per-file shared-trunk hook. Evidence is VAD-only because the harness runs no ASR.
    • full_unit applies when speech-only is off. Full-unit diarize_many runs, and raw segmentation and embeddings are compared against the unpatched pipeline.
    • The exit status follows the deployment's --speech-only setting. A full_unit pass never authorizes the flag while speech-only is on.
  • Per-unit records:
    • packed or not;
    • VAD span equality;
    • speaker counts and time-weighted speaker-assignment agreement per configuration;
    • segmentation max abs and active-frame disagreements;
    • embedding max abs against the unpatched serial reference;
    • ChainMemoryProbe peaks for each configuration.
  • Pass (exit 0) fails closed and requires all of:
    • every unit actually packed;
    • VAD spans equal;
    • speaker counts equal;
    • ≥99% agreement on every unit where serial finds ≥2 speakers;
    • at least 5 such units;
    • packed CUDA working-set peak ≤1.10× serial.
  • Exit 2 (insufficient evidence) covers a non-positive serial CUDA baseline or too few multi-speaker units.
  • Host memory. The packed flight must also stay inside the chart's host envelope: 9.795 GiB receipt, 12 GiB request, 14 GiB limit.
  • Timers. Profile batch worker stages and connect queue-age scaling input #22324's vad and diarize timers measure GPU time for this path only once they wrap _flight_segment/vad_spans and _flight_diarize.

Ramp plan for the flag:

  1. Staging runs the gate on dev L4s during the 3-day swarm.
  2. If it passes, set worker.flightBatchingEnabled=true on dev and hold for 24h. Watch two signals:
    • event=batch_chain_memory peaks;
    • batch_flight_fallback and worker_failed counts.
  3. Then enable on prod workers in a single config change, with the gate receipt attached.
  4. The metric that must stay clean in production is the speaker-label correction rate, which must not rise against the pre-flip baseline.
  5. Owner: dazheng, review by 2026-10-26. An unexpanded flag past that date is reported as a blocker.

Equivalence (CPU, real pyannote 4.0.3)

tests/unit/test_batch_pipeline_flight.py:

  • Worker contract tests run everywhere. They cover identical payloads with packing on or off, oversize and serial fallback, fatal quarantine, per-unit failure isolation and silence.
  • Model tests are skipped unless torch and pyannote are installed. They build randomly initialised community-1 architectures (PyanNet powerset segmentation, WeSpeakerResNet34, a synthetic PLDA, VBx and exclude_overlap=True) and compare the packed path with the serial calls on synthetic units of 3.5s, 10s, 12.25s and 21.5s. Results:
    • Raw segmentation: within 1e-5. Measured: bitwise equal (max diff 0.0).
    • VAD spans: exactly equal.
    • Embeddings: within 1e-4. Measured: max diff 1.4e-7.
    • Diarization turns: exactly equal.
    • OOM fallback: output equals the serial path.
    • All 15 pass locally on CPU.

Documented tolerance: on a GPU, packing changes batch composition, so cuDNN may pick different kernels. Expect float-level differences (on the order of 1e-6) in segmentation scores and embeddings, the same class of difference the existing batch-size pin already allows. A borderline clustering decision could in principle flip. The quantities computed are mathematically identical.

Expected GPU-time saving once enabled (estimate, not measured on an L4)

Local CPU measurement on a 285s, 7-unit synthetic flight (M5, 4 threads, so not GPU timing):

Stage Serial Packed
Embeddings 296.9s 81.4s (3.65× faster)
Segmentation (VAD and diarization) 18.0s + 19.9s 18.2s (about 2× faster)

These ratios come from the code structure: about 3× fewer trunk forwards, about 2× fewer segmentation forwards, and fewer partial batches.

Mapping that to an L4 is an estimate. pyannote turns TF32 off, so the trunk runs in FP32. ResNet34 costs about 47 GFLOP per 10s chunk, and the serial path runs about 3 pairs per audio-second, so an average flight is about 40 TFLOP, roughly 2.5–4.5s of GPU time. Parakeet BF16 ASR is about 0.1–0.2s per flight. Removing about two-thirds of the trunk work and half of the segmentation work should save about 2–3.5 GPU-seconds per flight. The flight interval averages 20.25s, so if these stages stay on the serial critical path that is roughly +10–17% jobs/min per L4 (about 22 → 24–26/min). Confirming it needs the stage timers from #22324 (vad, diarization) on a matched-mix hold.

Caveat after #22358: speech-only diarization is on by default. The embedding saving (about 3× fewer trunk forwards) now applies to the compacted audio actually diarized, and the segmentation dedupe benefits VAD only. Treat the figure above as an upper bound; the real number depends on the compaction ratio of production audio.

Not changed

ASR batching and windows, padded retry, the chain lock, process concurrency, VRAM per forward, admission and merge.

Test plan (after the gate re-review): targeted batch-pipeline suites (flight, flight_qualify, worker, worker_io, two_workers, runtime, chart, dispositions, gpu_skip/diarization_gate), plus characterization and sim (317 passed). Real-pyannote CPU equivalence: 17 passed. These include the speech-only compacted composition and serial embeddings captured before the hooks are installed. Gate unit tests lock the fail-closed rules: not packed fails; a zero CUDA baseline exits 2; a full-unit pass cannot authorize while speech-only is on. Typecheck is clean for the changed files. The qualification's GPU path has not been run; that is the staging gate.

Failure-Class: none

The fix(batch) commit is a review fix to code that is unreleased and inside this PR, not a production defect class.

🤖 Generated with Claude Code

The locked GPU chain ran community-1 segmentation twice per unit (inside
VAD and again inside diarization) and the WeSpeaker ResNet trunk once per
(chunk, local speaker) pair, although the three local speakers of a chunk
share one waveform.

FlightPyannote removes that duplicated model work and packs the remaining
forwards across one flight's units:
- one raw segmentation pass per unit feeds VAD (CPU aggregation and
  binarization, same as VoiceActivityDetection.apply) and diarization
  (get_segmentations hook);
- one trunk forward per 10s chunk, pooled per local speaker with the same
  masks (get_embeddings hook);
- chunks pack across units at the pinned model batch size, so no forward
  is larger than the serial one and peak VRAM does not grow.

Clustering, reconstruction and labels stay pyannote's own per-unit apply.
Units above BATCH_PIPELINE_FLIGHT_BATCH_SECONDS (default 1800), unsupported
model layouts, non-fatal packed failures and CUDA OOM inside the packed
path take the unchanged serial calls; other fatal CUDA errors still
quarantine the chain. BATCH_PIPELINE_FLIGHT_BATCHING_ENABLED is a kill
switch, on by default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-19T04:14:27.927612Z 05da934 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

CI note: two failures are pre-existing on origin/main 0d8e125 and are not caused by this PR. Both reproduce locally on a clean detached origin/main worktree with no changes from this PR:

  • tests/unit/test_pipeline_sim_scenarios.py::test_provider_exhaustion_turns_empty_asr_into_paid_recovery_and_a_quarantine_tail (assert 89.7 > 300)
  • Sync Cloud Tasks Stack Gauntlet: quarantined job reported 'processing' while recovery was pending

The stack gauntlet does not construct flight models, so it runs the serial worker path. I merged origin/main into the branch (644e436).

# Conflicts:
#	backend/diarizer/batch_pipeline.py
#	config/deployment-setting-classification.json
@Git-on-my-level

Copy link
Copy Markdown
Member Author

CI at 33f49ff (merged origin/main, including #22352). Every remaining failure is pre-existing on origin/main 267b255. I reproduced each one on a clean detached main worktree with none of this PR's changes:

  • test_pipeline_characterization.py::test_trace_matches_golden[empty_asr_terminal | privacy_fence_midflight | provider_failure_quarantine]
  • test_pipeline_sim_scenarios.py::test_provider_exhaustion_turns_empty_asr_into_paid_recovery_and_a_quarantine_tail
  • Sync Cloud Tasks Stack Gauntlet: quarantined job reported 'processing' while recovery was pending

The Hermetic Merge Gate and Backend unit suite failures are aggregates of these. The batch_pipeline flight, worker, worker_io, runtime, chart and disposition suites all pass (201 passed).

Merge resolution with #22352: when flight packing is off, decode and VAD stay interleaved per item, so prefetch still overlaps them. When packing is on, the group is decoded through prefetch, then one packed segmentation pass runs. Async persist still bounds in-flight writes in the final loop.

Git-on-my-level and others added 4 commits October 18, 2026 22:35
Review: CPU equivalence on random weights does not cover the L4. Packing
moves a unit's tail chunk out of its own batch-of-one forward, so cuDNN may
choose another kernel; on the production checkpoint that is unmeasured.

- BATCH_PIPELINE_FLIGHT_BATCHING_ENABLED now defaults off in code, env
  parsing (only the exact value true enables it), Helm and the registry
  (rollout, fail closed, review_by 2026-10-26).
- A cached-embedding shape mismatch now recomputes serially instead of
  failing the item.
- diarizer/batch_pipeline_flight_qualify.py: paired serial vs packed run
  on one L4 with community-1 3533c8cf and batch pin 8 over a mixed-length
  multi-speaker flight. Gates on VAD span equality, speaker counts,
  speaker-assignment agreement and the CUDA peak of both paths.
- load_pyannote_pair is shared by the worker and the qualification, so
  both build identical models.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ker-gpu

Compose flight packing with speech-only diarization. When speech-only is
on, the compacted waveform keeps its serial pyannote apply: there is no
full-unit packed embedding or cached segmentation, and the uncached
get_embeddings hook uses the per-file shared trunk only. Packed
segmentation still feeds VAD.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	backend/docs/feature-flag-registry.md
Git-on-my-level and others added 2 commits October 19, 2026 14:32
Re-review: the gate compared the shared trunk with itself, scored a path
that speech-only skips, and failed open.

- Serial references (VAD, diarization, compacted diarization, raw
  segmentation, embeddings) are captured on the unpatched pipeline before
  FlightPyannote.create, in the qualify script and in the CPU test.
- The gate scores two configurations. speech_only (Helm default) runs
  packed VAD and then the worker's own _diarize_unit on the compacted
  waveform through the per-file trunk hook. full_unit runs diarize_many.
  The exit status follows the deployment's speech-only setting, so a
  full_unit pass cannot authorize the flag while speech-only is on.
- Fail closed: an unpacked unit fails; a non-positive serial CUDA baseline
  is insufficient evidence (exit 2).
- The pyannote fixture is function-scoped, so each test's serial references
  come from an unhooked pipeline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…and GPU paired-run gates (#22426)

* feat(parity): contract (j) parity gate, (h) soak checks, F6 corpus and GPU paired-run gates

Lane 5 of the legacy-retire swarm (M1 slice):
- scripts/parity/parity_gate.py: rows 1-8 of contract (j) on --surface staging
  and --surface prod-shadow (rows 3-6 gate ladder ADVANCE), parity_report.json,
  PARITY_PASS/FAIL/PENDING last line, data_loss for rows 5/7 (ROLLBACK_ZERO).
- scripts/parity/soak_check.py: the ten 12h legacy-dark soak checks; the
  lost-recording census must start at draining; all four legacy queues
  including sync-backfill-fresh; read-only live collectors.
- scripts/parity/fleet_sample.py: rows 3/4 from the fleet gate's JSON sample
  (strict 121s dispatch breach) and the gate's data-loss tokens.
- testing/quality_corpus: pinned public corpus (AMI/LibriSpeech/VoxConverse +
  silence), production-chain runner, scorer, and the paired runs gating
  #22368 (flight batching: qualify receipt re-verified plus chain pair) and
  #22358 (short-speech skip: fired units vs full diarizer), with an L4 Job
  template for staging.

No GCP access in tests; reports carry aggregates and opaque keys only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(parity): load scipy/jiwer at import so timed unit calls stay under the CPU guard

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…ebt list for workers/consumer.py

recovery_disposition.py is reverted to integration's version (freeze table);
re-add the enum-derived constants after #22368 lands. REASON_UNKNOWN_TOTAL
keeps the stub's name and both counters are pre-initialised per family.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit ec5f367 into main Oct 19, 2026
62 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/opus-worker-gpu branch October 19, 2026 09:34
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…esh ratchet baselines

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
 sync)

Conflict in .github/actions/sync-backfill-lifecycle/action.yml: main's #22460 and lane 7's B4
(#22455) both stop trains re-pointing backfill at the retired sync-backfill queue. Resolved to
one resolution step (ops-queues): prod reads the ops file (fail-closed, lane 7); other projects
take the manifest's SYNC_BACKFILL_TASKS_QUEUE/SYNC_TASKS_QUEUE (main), sync-backfill only as
default. The queue reconcile step keeps main's manifest-driven queue name. #22460's test is
adapted to the single resolution step.
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…atchet (lane 14 M1) (#22422)

* feat(observability): reason enums, label AST check and batch-stage env ratchet (lane 14 M1)

Contract (e): utils/observability/reasons.py with ReasonFamily, per-family
enums, reason_label() and omi_reason_unknown_total. live_reason and
recovery_disposition now derive their frozensets from the enums
(behaviour-neutral; misses are also counted). Adds the shrink-only
label-argument AST check and the batch-stage env-read ratchet.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* refactor(batch): derive worker validation constants from the reason enums (lane 14)

Values unchanged.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Hold recovery_disposition.py until #22368; adopt stub counter name; debt list for workers/consumer.py

recovery_disposition.py is reverted to integration's version (freeze table);
re-add the enum-derived constants after #22368 lands. REASON_UNKNOWN_TOTAL
keeps the stub's name and both counters are pre-initialised per family.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* env ratchet: pending allowances for reads lane 9 moves (C2)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* reason-label debt: lane 10 legacy_dark sites (closed via own enum helper)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Re-add enum-derived recovery_disposition constants after #22368; refresh ratchet baselines

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Drop the pending alert-metric allowances now that reasons.py produces both counters

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* feat(listen): populate app_build on omi_listen_accepted_total from X-App-Version (lane 14)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* refactor(observability): derive fallback ALLOWED_REASONS from FallbackReason (#21932 landed)

Adds the nine reasons #21932 introduced; set unchanged (65 values).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* reasons: add ShadowParityOutcome (lane 12); debt entry for external_list_reads

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* refactor(batch): WorkResult/RecoveryWork closed sets from WorkOutcome and WorkerValidationReason (values unchanged)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* chore(changelog): none fragment (integration carries app edits relative to main; lane 14 is backend-only)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Restore app/ from integration (formatter collateral); drop none changelog fragment

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Restore app/ exactly from integration (undo formatter collateral)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* fix(listen): read app_version fail-safe so partial device contexts cannot break session start

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
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.

1 participant