Skip to content

fix(cli/scoring): make TextNormalizer replacement order deterministic - #921

Merged
Alex-Wengg merged 2 commits into
mainfrom
fix/911-deterministic-normalizer
Sep 14, 2026
Merged

Alex-Wengg merged 2 commits into
mainfrom
fix/911-deterministic-normalizer

Conversation

@Alex-Wengg

Copy link
Copy Markdown
Member

Summary

Fixes #911 — the CI ASR benchmark scored byte-identical hypothesis/reference pairs differently between runs (the 1688-142285-0002.flac record moved between WER 0% and 10% with no code change).

Root cause (proven, and stronger than suspected)

The issue guessed per-process dictionary hashing. It's per-instance: Swift seeds each hash table from its storage allocation, so two identical dictionary literals in the same process iterate in different orders. Since normalize() builds fresh contractions/abbreviations dictionaries on every call, the reference and hypothesis calls inside one calculateWERAndCER() get independent orders. With overlapping keys, don't expands to do not when n't is applied first but don not when 't wins — so ref and hyp can disagree within a single scoring call.

Evidence (standalone harness compiled from the unmodified TextNormalizer.swift):

Fix

Apply all four replacement tables (britishToAmerican, abbreviations, contractions, numberWords) sorted longest key first, lexical tie-break. Deterministic, and the most specific rule now always beats its substring — which is also the semantically correct expansion:

input before (order-dependent) after
don't do not or don not do not
can't can not or ca not can not
I'd been i had been or i would been i had been
it's been it has been or it is been it has been

Verified with the patched file across 50 fresh processes: byte-identical output every run.

Tests

AsrTextNormalizerTests: the exact #911 record scores WER 0/CER 0 across 100 repeated calls; repeated-call byte-determinism; overlapping-key expansion expectations.

Note for reviewers: CI benchmark baselines may shift slightly on merge — historical numbers were sampled from random orderings; the deterministic ordering picks the correct expansions, so WER should move down or stay flat.

🤖 Generated with Claude Code

The CI ASR benchmark scored byte-identical hypothesis/reference pairs
differently between runs (#911): the same test-other record moved
between WER 0% and 10% with no code change.

Root cause is stronger than the per-process hashing suspected in the
issue: Swift dictionaries iterate in a per-INSTANCE random order (the
hash seed incorporates the storage allocation), so the two normalize()
calls inside one calculateWERAndCER() each build fresh contraction /
abbreviation dictionaries with independent orders. With overlapping
keys, "don't" expands to "do not" when "n't" is applied first but
"don not" when "'t" wins — reference and hypothesis can disagree
within a single process. Reproduced in a standalone harness: 144 of
300 processes diverged on the exact #911 record, and two identical
dictionary literals in one process iterate differently 5/5 times.

Fix: apply all four replacement tables (britishToAmerican,
abbreviations, contractions, numberWords) sorted longest-key-first
with a lexical tie-break. This is deterministic and also picks the
semantically correct expansion — the specific rule now always beats
its substring ("'d been" -> "had been" over "'d" -> "would",
"can't" -> "can not" over "n't", "it's been" -> "it has been").

Verified with the patched file across 50 fresh processes: identical
output every run, correct expansions for all overlapping-key cases.

Fixes #911
@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown

Offline VBx Pipeline Results

Speaker Diarization Performance (VBx Batch Mode)

Optimal clustering with Hungarian algorithm for maximum accuracy

Metric Value Target Status Description
DER 10.4% <20% Diarization Error Rate (lower is better)
RTFx 9.16x >1.0x Real-Time Factor (higher is faster)

Offline VBx Pipeline Timing Breakdown

Time spent in each stage of batch diarization

Stage Time (s) % Description
Model Download 27.967 24.4 Fetching diarization models
Model Compile 11.986 10.5 CoreML compilation
Audio Load 0.077 0.1 Loading audio file
Segmentation 29.675 25.9 VAD + speech detection
Embedding 114.182 99.7 Speaker embedding extraction
Clustering (VBx) 0.170 0.1 Hungarian algorithm + VBx clustering
Total 114.577 100 Full VBx pipeline

Speaker Diarization Research Comparison

Offline VBx achieves competitive accuracy with batch processing

Method DER Mode Description
FluidAudio (Offline) 10.4% VBx Batch On-device CoreML with optimal clustering
FluidAudio (Streaming) 17.7% Chunk-based First-occurrence speaker mapping
Research baseline 18-30% Various Standard dataset performance

Pipeline Details:

  • Mode: Offline VBx with Hungarian algorithm for optimal speaker-to-cluster assignment
  • Segmentation: VAD-based voice activity detection
  • Embeddings: WeSpeaker-compatible speaker embeddings
  • Clustering: PowerSet with VBx refinement
  • Accuracy: Higher than streaming due to optimal post-hoc mapping

🎯 Offline VBx Test • AMI Corpus ES2004a • 1049.0s meeting audio • 144.0s processing • Test runtime: 2m 40s • 09/14/2026, 10:58 AM EST

@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown

PocketTTS Smoke Test ✅

Check Result
Build
Model download
Model load
Synthesis pipeline
Output WAV ✅ (153.8 KB)

Runtime: 0m12s

Note: PocketTTS uses CoreML MLState (macOS 15) KV cache + Mimi streaming state. CI VM lacks physical GPU — audio quality and performance may differ from Apple Silicon.

@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown

Supertonic3 Smoke Test ✅

Check Result
Build
Model download (incl. VectorEstimatorVariants/ int4 buckets)
Model load
Synthesis pipeline (--ve-variant int4)
Output WAV ✅ (364.7 KB)

Runtime: 0m36s

Note: CI VMs lack a physical Neural Engine; the ANE-bucketed VectorEstimator falls back to CPU here. This validates download + variant resolution + synthesis, not ANE residency/perf.

@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown

VAD Benchmark Results

Performance Comparison

Dataset Accuracy Precision Recall F1-Score RTFx Files
MUSAN 94.0% 89.3% 100.0% 94.3% 707.0x faster 50
VOiCES 94.0% 89.3% 100.0% 94.3% 734.5x faster 50

Dataset Details

  • MUSAN: Music, Speech, and Noise dataset - standard VAD evaluation
  • VOiCES: Voices Obscured in Complex Environmental Settings - tests robustness in real-world conditions

✅: Average F1-Score above 70%

@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown

Parakeet EOU Benchmark Results ✅

Status: Benchmark passed
Chunk Size: 320ms
Files Tested: 100/100

Performance Metrics

Metric Value Description
WER (Avg) 7.03% Average Word Error Rate
WER (Med) 4.17% Median Word Error Rate
RTFx 5.77x Real-time factor (higher = faster)
Total Audio 470.6s Total audio duration processed
Total Time 82.2s Total processing time

Streaming Metrics

Metric Value Description
Avg Chunk Time 0.082s Average chunk processing time
Max Chunk Time 0.164s Maximum chunk processing time
EOU Detections 0 Total End-of-Utterance detections

Test runtime: 1m30s • 09/14/2026, 10:45 AM EST

RTFx = Real-Time Factor (higher is better) • Processing includes: Model inference, audio preprocessing, state management, and file I/O

@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown

Speaker Diarization Benchmark Results

Speaker Diarization Performance

Evaluating "who spoke when" detection accuracy

Metric Value Target Status Description
DER 15.1% <30% Diarization Error Rate (lower is better)
JER 24.9% <25% Jaccard Error Rate
RTFx 25.31x >1.0x Real-Time Factor (higher is faster)

Diarization Pipeline Timing Breakdown

Time spent in each stage of speaker diarization

Stage Time (s) % Description
Model Download 12.103 29.2 Fetching diarization models
Model Compile 5.187 12.5 CoreML compilation
Audio Load 0.086 0.2 Loading audio file
Segmentation 12.427 30.0 Detecting speech regions
Embedding 20.712 50.0 Extracting speaker voices
Clustering 8.285 20.0 Grouping same speakers
Total 41.459 100 Full pipeline

Speaker Diarization Research Comparison

Research baselines typically achieve 18-30% DER on standard datasets

Method DER Notes
FluidAudio 15.1% On-device CoreML
Research baseline 18-30% Standard dataset performance

Note: RTFx shown above is from GitHub Actions runner. On Apple Silicon with ANE:

  • M2 MacBook Air (2022): Runs at 150 RTFx real-time
  • Performance scales with Apple Neural Engine capabilities

🎯 Speaker Diarization Test • AMI Corpus ES2004a • 1049.0s meeting audio • 41.4s diarization time • Test runtime: 2m 16s • 09/14/2026, 10:46 AM EST

@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown

ASR Benchmark Results ✅

Status: All benchmarks passed

Parakeet v3 (multilingual)

Dataset WER Avg WER Med RTFx Status
test-clean 0.57% 0.00% 2.77x
test-other 1.19% 0.00% 2.56x

Parakeet v2 (English-optimized)

Dataset WER Avg WER Med RTFx Status
test-clean 0.80% 0.00% 5.02x
test-other 1.00% 0.00% 2.96x

Streaming (v3)

Metric Value Description
WER 0.00% Word Error Rate in streaming mode
RTFx 0.38x Streaming real-time factor
Avg Chunk Time 2.342s Average time to process each chunk
Max Chunk Time 3.362s Maximum chunk processing time
First Token 2.886s Latency to first transcription token
Total Chunks 31 Number of chunks processed

Streaming (v2)

Metric Value Description
WER 0.00% Word Error Rate in streaming mode
RTFx 0.51x Streaming real-time factor
Avg Chunk Time 1.775s Average time to process each chunk
Max Chunk Time 2.792s Maximum chunk processing time
First Token 1.918s Latency to first transcription token
Total Chunks 31 Number of chunks processed

Streaming tests use 5 files with 0.5s chunks to simulate real-time audio streaming

25 files per dataset • Test runtime: 9m9s • 09/14/2026, 10:56 AM EST

RTFx = Real-Time Factor (higher is better) • Calculated as: Total audio duration ÷ Total processing time
Processing time includes: Model inference on Apple Neural Engine, audio preprocessing, state resets between files, token-to-text conversion, and file I/O
Example: RTFx of 2.0x means 10 seconds of audio processed in 5 seconds (2x faster than real-time)

Expected RTFx Performance on Physical M1 Hardware:

• M1 Mac: ~28x (clean), ~25x (other)
• CI shows ~0.5-3x due to virtualization limitations

Testing methodology follows HuggingFace Open ASR Leaderboard

@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown

Sortformer High-Latency Benchmark Results

ES2004a Performance (30.4s latency config)

Metric Value Target Status
DER 30.3% <35%
Miss Rate 28.2% - -
False Alarm 0.9% - -
Speaker Error 1.2% - -
RTFx 14.3x >1.0x
Speakers 4/4 - -

Sortformer High-Latency • ES2004a • Runtime: 2m 47s • 2026-09-14T14:55:27.490Z

…fixes

Post-review cleanup on the #911 fix:

- Hoist abbreviations/contractions/numberWords out of normalize() into
  static tables and pre-sort all four (incl. britishToAmerican) once
  via longestKeyFirst static lets, instead of rebuilding and sorting
  per call. Output verified byte-identical to the per-call-sort version
  across 30 fresh processes on the harness corpus. This also makes the
  ordering structural: a future table reuses the sorted statics rather
  than relying on remembering .sorted(by:) at each loop.

- Rename AsrTextNormalizerTests -> AsrScoringNormalizerTests: the
  trait-gating CI job selects classes with an unanchored
  --filter 'TextNormalizerTests|...' (tests.yml), which
  substring-matched the old name and swept this suite into a job that
  exists only to prove NemoTextProcessing trait behavior.

- Cut test loops 100 -> 10 iterations (~6s of -O runtime at 100; each
  iteration still samples fresh state, 10 is ample).

- Note in Unified benchmark.md that recorded WER rows predate the
  deterministic ordering (#911) so reruns are not comparable to the
  tenth of a point.
@Alex-Wengg
Alex-Wengg merged commit 74ad822 into main Sep 14, 2026
16 of 17 checks passed
@Alex-Wengg
Alex-Wengg deleted the fix/911-deterministic-normalizer branch September 14, 2026 15:03
Alex-Wengg added a commit that referenced this pull request Sep 14, 2026
…deterministic (#923)

## Summary

Fixes #922 — same nondeterminism class as #911/#921, in the diarization
scorer.

`computeSpeakerMapping` built its speaker index orders with
`Array(predicted.keys)` / `Array(groundTruth.keys)`. Swift dictionary
iteration order is per-instance random (the hash seed incorporates the
storage allocation — re-confirmed empirically on Swift 6.2.3), and both
assignment paths (the subset DP and the greedy fallback) tie-break by
first-encountered index via strict `>` comparisons. The confusion matrix
rounds overlaps to integer milliseconds, so exact ties are realistic —
and whenever two pairings tie, the winning speaker mapping (and JER)
depended on random key enumeration order.

## Evidence

Standalone harness on the scenario in the new test (two predicted
speakers each overlapping one ground-truth speaker by exactly 4.75 s
after the 0.25 s collar): the pre-fix code produced **2 distinct speaker
mappings within a single 200-call process** (3/3 runs), and fails the
new test's predicate in **20/20 processes**. With the fix: 1 mapping,
always (`right → spk_a`, pinned in the test).

## Fixes (commit 2 adds the full sweep from adversarial review)

1. `computeSpeakerMapping`: sort both key arrays — ties resolve by the
solver's fixed index-order rule over lexicographically sorted speaker
ids; unambiguous assignments unchanged.
2. `offlineMetrics`: the `correctlyAssigned`, `jaccardScores`, and
unmapped-pred loops accumulated Doubles in dictionary order. Addition is
not associative, and both DER and JER pass through near-zero
cancellation (`max(0, overlapSpeech - correctlyAssigned)`, `1.0 -
averageJaccard`) where a ulp-level reorder survives the Float cast —
with 3+ speakers, DER/JER were still not bit-deterministic. All three
loops now iterate in sorted key order.
3. Streaming path (`DiarizationBenchmark.calculateStreamingMetrics`):
`overlapsByGtSpeaker.max(by: { $0.value < $1.value })` kept the
first-encountered element among tied overlaps in random dictionary order
— same class. Ties now break by smaller speaker id.

## Tests

`DiarizationSpeakerMappingTests`: tied-overlap stability across 50 calls
(each call regroups segments into fresh dictionaries, each with an
independent per-allocation key order — the unfixed code fails this 20/20
processes), the exact tied winner pinned so silent tie-break changes
fail loudly, plus an unambiguous-mapping correctness check.
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.

CI ASR benchmark scores identical hypothesis text differently between runs (test-other 1.19% vs 1.59% on one record)

1 participant