1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Per-window score aggregation for long clips: [`ScorePooling`] +
//! [`aggregate_windows`], folding a clip's per-window log-probability rows into
//! one clip-level [`LogProbabilities`].
//!
//! # A third domain, and why neither neighbour's answer transfers
//!
//! `windit`'s aggregation engine is not used: its built-ins are renormalizing
//! unit-vector policies, which is the embedding domain, not this one.
//! `audio::ced`'s Mean/Max is not copied either: CED emits 527 INDEPENDENT
//! sigmoids, so "mean" there has exactly one reading. This graph's last op is a
//! log-softmax over [`NUM_LANGUAGES`] MUTUALLY EXCLUSIVE classes, a row that
//! already sums to 1 under `exp` — so "mean" is ambiguous, and the two readings
//! are different operations that give different answers:
//!
//! - the **linear opinion pool** ([`ScorePooling::MeanProbability`]) averages
//! the distributions, and reports what fraction of the clip each language
//! accounts for;
//! - the **logarithmic opinion pool** ([`ScorePooling::MeanLogProbability`])
//! averages the log-probabilities — a renormalized geometric mean — and
//! treats the windows as independent evidence about ONE language, so a
//! language any window rejects confidently is rejected overall.
//!
//! Both are standard; they answer different questions. Which one this door
//! defaults to was measured, not assumed — see the module docs' "Clips longer
//! than 30 s" section for the table and the two oracles behind it.
//!
//! # Duration weighting is always on
//!
//! Every window contributes in proportion to the REAL audio it saw
//! ([`Span::len`], equivalently [`Span::coverage`] — the window length is fixed
//! within a plan, so the two differ by a constant that cancels). Under
//! [`TailPolicy::SlideBack`] and [`TailPolicy::Drop`] every span is exactly one
//! window long, so the weights are equal and this is precisely the unweighted
//! mean; it only bites under [`TailPolicy::Partial`], where it stops a 0.1 s
//! tail from outvoting a 10 s window. There is no unweighted knob because
//! there is no case where the equal-weight answer is the better one.
//!
//! # Precision
//!
//! The fold runs in **f64** and narrows once at the end. `audio::ced` pins f32
//! accumulation because its aggregation values are golden-pinned upstream;
//! nothing upstream pins these, so the fold uses the wider type — which matters
//! here in a way it does not there, since [`ScorePooling::MeanProbability`]
//! sums `exp` of numbers as low as −25 alongside numbers near 1.
//!
//! Width alone does not save that sum, though: `exp` underflows to exactly zero
//! below about −744.4 (the log of `f64`'s smallest subnormal), so
//! [`ScorePooling::MeanProbability`] never exponentiates a log-probability on
//! its own. It runs an online **log-sum-exp** — each language's weighted sum is
//! held relative to the largest log-probability that language has been given,
//! and the shift is added back at the end. A finite score therefore keeps a
//! finite pooled value, and its rank, however far below the row maximum it
//! sits; a literal `ln(Σ w·exp(x))` re-emits the whole tail as `-∞` and ranks
//! it by the tie-break, from inputs that were every one of them finite. The two
//! forms agree to f32 on anything this model produces (its measured tail is
//! −37.27) — they part company only where the literal one has already lost the
//! answer.
//!
//! A **single** window is returned bit-for-bit unchanged, without folding or
//! renormalizing. That is what makes [`Identifier::identify_long`] on a clip
//! that already fits one window agree exactly — not approximately — with
//! [`Identifier::identify`].
//!
//! # A row's own scale is not evidence
//!
//! A row's RATIOS are what it says about the languages; its overall scale says
//! nothing. Straight off the graph a row is a log-softmax and `exp` over it
//! should sum to 1 — and it does not, quite: fp16 arithmetic leaves it up to
//! as much as 7.7e-3 away from 1 on [`ComputeUnits::CpuOnly`] and 1.5e-4 with
//! the ANE — on either side of it, the deviation being signed. That gap is a
//! fact about how the row was computed, not about what was spoken.
//!
//! Folded raw it becomes a per-window WEIGHT, because three of the four
//! poolings fold VALUES. Two equal 160 000-sample windows, each one-hot and so
//! each perfectly certain — one on column 0 at `ln(0.99235)`, one on column 1
//! at exactly `0.0` — used to pool to p(0) = 0.498080 against p(1) = 0.501920
//! under [`ScorePooling::MeanProbability`], and to the same split under
//! [`ScorePooling::Max`]: the clip went to whichever window's row had rounded
//! better. The pooled row's mass was 1.0000000086, four orders of magnitude
//! inside `MAX_MASS_DEVIATION`, so the postcondition could not see it.
//!
//! How much it was worth on real audio depends entirely on the compute unit,
//! which is why the door's measurement tables (`audio::lid`'s own module docs)
//! did not move when this was fixed. Over `MAX_MASS_DEVIATION`'s 192-fold
//! sweep, normalizing at the door
//! changed the pooled row by at most 3.8e-6 nats under `ComputeUnits::All` and
//! `CpuAndGpu`, and 2.6e-4 on the ANE — but by 1.0e-2 on
//! [`ComputeUnits::CpuOnly`], whose rows carry the 7.7e-3 gap. No fold in
//! that sweep changed its top-1 language, and [`ScorePooling::MeanLogProbability`]
//! and [`ScorePooling::Vote`] came back bit-identical on every one of the 192.
//!
//! Every row is therefore made a distribution AT THE DOOR, in `push`, under the
//! same shift the fold's exit uses — one `DistributionShift`, called from both
//! ends, rather than the arithmetic restated per caller. Rescaling one window's
//! row by a constant now moves the pooled row by no more than the f32 narrowing
//! at the exit. Measured over two overlapping-support rows with one rescaled by
//! `ln(0.99235)`, the largest per-column gap that rescale opens:
//!
//! | pooling | folding raw rows | folding normalized rows |
//! |--------------------------------------|------------------|-------------------------|
//! | [`ScorePooling::MeanLogProbability`] | 0.0 | 0.0 |
//! | [`ScorePooling::MeanProbability`] | 1.28e-3 | 0.0 |
//! | [`ScorePooling::Max`] | 4.04e-3 | 5.96e-8 |
//! | [`ScorePooling::Vote`] | 0.0 | 0.0 |
//!
//! The logarithmic pool was already immune, and for a reason rather than by
//! luck: a constant added to one row adds a constant to the mean of the logs,
//! and the closing renormalization takes exactly that constant back off.
//!
//! [`ScorePooling::Vote`] is the one pooling still folding the RAW row, and is
//! exactly invariant either way. Its ballot is an `argmax` — a comparison, not
//! arithmetic — so a shift cannot reorder it, and shifting first could only
//! round two distinct values onto one and hand the outcome to the ranking
//! tie-break. `the_fold_is_invariant_to_a_rows_own_scale` holds the table.
//!
//! # Totality: a distribution comes back, or an error does
//!
//! [`LogProbabilities`] accepts `-∞`. It has to: that is the exact log of a
//! zero probability, and [`ScorePooling::Vote`] emits it for every language no
//! window chose. So a pooling can be handed rows it cannot fold into a
//! distribution at all. The module answers that with one PRECONDITION on every
//! window and one POSTCONDITION on every fold, both stated here rather than
//! inside whichever pooling last provoked them — so a pooling added later
//! inherits both without having to remember to, and so does a future edit to
//! one of these four.
//!
//! **Precondition: a window must be normalizable.** The fold asks one thing of
//! every row it is handed — that `DistributionShift` can turn it into a
//! distribution — and that is exactly that it has a **finite maximum**, a bound
//! that is finite AND that the whole row actually sits under. Three rows fail
//! it, and none is one any pooling could have folded:
//!
//! - `-∞` in every column says no language is possible. It is not evidence
//! about which language was spoken, and each pooling would mishandle it in
//! its own way: the logarithmic pool zeroes the whole clip out; the linear
//! pool skips all of its terms (that is what keeps `(-∞) − (-∞)` unreachable)
//! while still counting its duration in the denominator, so every other
//! window comes out diluted; and [`ScorePooling::Vote`] casts its ballot for
//! whatever column the ranking tie-break surfaces, handing a share of the
//! clip to a language nothing chose.
//! - `+∞` anywhere is not a log-probability row at all: `exp` over it sums to
//! `∞`, and no constant makes that a distribution. It used to be let through
//! here and left to the postcondition, which caught it under only two of the
//! four poolings ([`Error::NotADistribution`], carrying a mass of `∞`).
//! [`ScorePooling::Vote`] returned a clean-looking distribution putting the
//! whole clip on whichever column held the `∞`; [`ScorePooling::MeanProbability`]
//! returned a row of 107 NaNs, which the postcondition cannot see because
//! every comparison against NaN is false; and a LONE `+∞` window took the
//! identity path back to the caller verbatim, as a [`LogProbabilities`]
//! holding a positive value.
//! - A NaN anywhere is under no bound at all, `+∞` included, so there is no
//! shift and no ranking. It survived the `+∞` round because that round's
//! guard folded the row with `f32::max`, whose documented `maxNum` semantics
//! are to IGNORE a NaN operand: `[-1, NaN, -1, …]` reported a maximum of `-1`
//! and was let through. Past it the four poolings lost it in three different
//! directions, and the postcondition could see only one of them.
//! [`ScorePooling::MeanLogProbability`] spread the NaN over all 107 columns —
//! one NaN anywhere in `DistributionShift`'s sum poisons the whole shift —
//! for a mass of NaN. [`ScorePooling::Max`] and [`ScorePooling::MeanProbability`]
//! DROPPED the window instead, `f64::max` ignoring the NaN and the
//! log-sum-exp skipping it exactly as it skips a `-∞`: a NaN window beside a
//! real one answered from the real one alone at mass 1, and a clip of nothing
//! but NaN came back as [`Error::ZeroMassAggregate`], a refusal naming the
//! wrong reason. [`ScorePooling::Vote`] handed the window's whole ballot to
//! the NaN's column, also at mass 1, because `total_cmp` ranks a NaN above
//! every real value. And a LONE NaN window took the identity path back to the
//! caller verbatim under all four — a [`LogProbabilities`] holding a NaN,
//! which this type's invariant forbids, whose `top_k` reports the NaN's
//! language first, and which the postcondition does not apply to at all.
//!
//! [`aggregate_windows`] refuses all three with [`Error::UnnormalizableWindow`],
//! naming the window, before any of that. It costs one pass and no `exp`.
//!
//! **What the precondition must NOT decide is a row's SCALE.**
//! `[-800, -801, …, -906]` and `[0, -1, …, -106]` differ by exactly 800 in
//! every column, so no probability ratio differs between them and they
//! normalize to the identical distribution. An earlier form of this guard —
//! `exp(max) > 0.0`, i.e. "the row's total is positive" — refused the first and
//! folded the second, because `exp` underflows f64 to exactly zero below
//! −744.44. That was this module's own "a row's own scale is not evidence"
//! leak, taken out of the fold and left standing in the door in front of it.
//! `the_door_is_invariant_to_a_rows_own_scale` holds the property now; what
//! makes it true is that `DistributionShift` forms `(v − max)` before anything
//! else, which is well-conditioned for any finite maximum.
//!
//! **Postcondition: what comes back sums to 1.** Two windows each certain of a
//! DIFFERENT language, `-∞` everywhere else, both pass the precondition and
//! still have no pool: the logarithmic pool is a geometric mean, so a language
//! any window scores at zero is zero in the pool, and between them the two
//! windows zero out every language. The arithmetic is right and the result is
//! not a distribution — its exponentials sum to zero, so its "top" languages
//! are whichever ones the tie-break surfaces, each at probability zero. That is
//! [`Error::ZeroMassAggregate`], and it is the one deviation from 1 that is an
//! honest answer rather than a defect. Any OTHER deviation is a defect, and is
//! [`Error::NotADistribution`] carrying the mass the fold actually left — the
//! tolerance and the measurements behind it are on `MAX_MASS_DEVIATION`.
//!
//! It is written as the predicate that ACCEPTS — `|mass − 1| <=
//! MAX_MASS_DEVIATION`, returned from — rather than as the `>` that refuses,
//! because those two are the same test only over an ORDERED domain and f64 is
//! not one. Every ordered comparison against a NaN is false, so the refusing
//! form reads a NaN mass as "not outside the tolerance" and hands the caller
//! 107 NaNs; the accepting form reads it as "not inside", and it lands in the
//! refusal. A postcondition stated once so that whatever is added later
//! inherits it has to be TOTAL, or what it is inherited by is a hole.
//!
//! The postcondition applies to a FOLDED row only. A lone window is returned
//! verbatim, and holding a row this module did not compute to "sums to 1" would
//! break the [`Identifier::identify_long`] == [`Identifier::identify`] promise
//! on real audio rather than only in principle: a model row's own mass is off
//! by up to 7.7e-3 on [`ComputeUnits::CpuOnly`] and 1.5e-4 on the ANE. The
//! precondition covers that path instead, which is the property a row this
//! module did not compute can be held to — it normalizes, so it ranks. A lone
//! window written at a very low scale is therefore returned verbatim with an
//! f64 mass of exactly zero, and that is the right answer: it is what
//! [`Identifier::identify`] returns for the same row.
//!
//! Both are unreachable from the model. [`Identifier::log_probabilities`]
//! rejects a non-finite score, so no window `identify_long` folds can have a
//! non-finite maximum, and a log-softmax row's largest entry is at least
//! `ln(1/107)`.
//!
//! [`NUM_LANGUAGES`]: crate::audio::lid::NUM_LANGUAGES
//! [`Span::len`]: crate::audio::lid::Span::len
//! [`Span::coverage`]: crate::audio::lid::Span::coverage
//! [`TailPolicy::SlideBack`]: crate::audio::lid::TailPolicy::SlideBack
//! [`TailPolicy::Drop`]: crate::audio::lid::TailPolicy::Drop
//! [`TailPolicy::Partial`]: crate::audio::lid::TailPolicy::Partial
//! [`Identifier::identify`]: crate::audio::lid::Identifier::identify
//! [`Identifier::identify_long`]: crate::audio::lid::Identifier::identify_long
//! [`Identifier::log_probabilities`]: crate::audio::lid::Identifier::log_probabilities
//! [`ComputeUnits::CpuOnly`]: crate::ComputeUnits::CpuOnly
use Ordering;
use crate;
/// How a long clip's per-window log-probability rows combine into one
/// clip-level row.
///
/// Every variant returns a row that is still a natural-log distribution (`exp`
/// over it sums to 1), so the result is interchangeable with a single-window
/// row everywhere downstream. Only [`Self::Vote`] is a distribution by
/// construction, from the shares it divides; the other three close with a
/// renormalization, which is a constant shift and so cannot change the ranking.
///
/// Where a pooling's honest answer is that EVERY language has probability zero
/// — the logarithmic pool over windows with disjoint supports — there is no
/// distribution to return, and [`aggregate_windows`] refuses with
/// [`Error::ZeroMassAggregate`] rather than hand back a row that ranks
/// arbitrarily. See the module docs' "Totality" section.
///
/// **`Display` is persisted by downstream derivation fingerprints — change it
/// only with a major bump.** It prints the SAME snake_case word `serde` does
/// (`rename_all = "snake_case"` below): `"mean_log_probability"`,
/// `"mean_probability"`, `"max"`, `"vote"`.
/// Streaming fold shared by [`aggregate_windows`] and
/// [`Identifier::identify_long`], one window at a time — `identify_long` folds
/// each window's row in and never materializes the per-window vectors, so a
/// long clip retains O([`NUM_LANGUAGES`]) state rather than one 107-float row
/// per window.
///
/// Bit-identical to the batch fold by construction: both drive this same type
/// with the same op sequence over the same window order.
///
/// [`NUM_LANGUAGES`]: crate::audio::lid::NUM_LANGUAGES
/// [`Identifier::identify_long`]: crate::audio::lid::Identifier::identify_long
pub
/// The one constant that turns a row of natural-log values into a distribution:
/// subtract it from every value and `exp` over the row sums to 1.
///
/// **One definition, called from both ends of the fold.** The row a pooling
/// FOLDS is normalized by [`Accumulator::push`] and the row a pooling PRODUCES
/// is normalized by [`renormalize`], and both take the shift from here rather
/// than spelling it out for themselves. Two ends that each spell it out are two
/// places to get it wrong and two places to fix it, and this module has been
/// both: the exit's arithmetic had to be corrected once for the fusion the next
/// paragraph describes, while the entrance — which had no normalization at all
/// — went on folding raw rows for another two review rounds. Whatever the next
/// change to "the shift that makes a row a distribution" is, there is now one
/// place to make it.
///
/// Held in TWO parts — the row's maximum and the log of the shifted sum — which
/// [`Self::apply`] subtracts one after the other and which nothing may fold
/// into one. Forming `max + log_sum` and subtracting that loses `log_sum`
/// entirely whenever `max` is large enough that the sum's log falls below its
/// ULP: at −5e19 the f64 ULP is 8192, so `max + ln(2)` IS `max`, every leading
/// column comes back as exactly `0.0`, and the row's mass is its number of
/// leading columns instead of 1. Subtracting the maximum first lands each value
/// near zero, where the small constant is representable. The two forms agree
/// everywhere the fused one has not already lost the constant.
/// Shift `values` down by their log-sum-exp so `exp` over the row sums to 1 —
/// the fold's EXIT normalizer, closing [`ScorePooling::MeanLogProbability`],
/// [`ScorePooling::MeanProbability`] and [`ScorePooling::Max`].
///
/// The max-subtraction form is what keeps [`ScorePooling::Max`] finite when the
/// row's maximum is far from zero; [`DistributionShift`] carries the arithmetic
/// and the reason its two subtractions must stay apart. The row maximum is
/// never `-∞` in practice (a model row is a log-softmax and its argmax is
/// finite), and an all-`-∞` row is left alone rather than turned into NaN. It
/// stays infallible and total for that reason: the row it declines to touch is
/// not a distribution, and refusing it is [`Accumulator::finish`]'s
/// postcondition, which catches it for every pooling rather than only for the
/// ones that renormalize.
/// `row` as a distribution, in f64 — the fold's ENTRANCE normalizer, and the
/// values [`Accumulator::push`] actually folds.
///
/// A row's own total mass is fp noise: a model row comes back as much as 7.7e-3
/// away from 1 on [`ComputeUnits::CpuOnly`] and 1.5e-4 with the ANE, on either
/// side of it, and that gap says nothing about any language, only about the
/// graph's fp16 arithmetic. Folded raw it acts as a per-window WEIGHT — see the module docs'
/// "A row's own scale is not evidence" section for the two windows it flipped.
///
/// [`ComputeUnits::CpuOnly`]: crate::ComputeUnits::CpuOnly
/// Whether `row` has a finite maximum — the fold's precondition, and the exact
/// condition under which [`DistributionShift`] can make the row a distribution.
///
/// The two rows it refuses are the two [`DistributionShift::of`] has no shift
/// for: `-∞` in every column, and `+∞` anywhere. `aggregate`'s module docs
/// ("Totality") carry what each of them would have done to each pooling.
///
/// **It deliberately says nothing about a row's absolute SCALE**, and an
/// earlier form of it did. The guard used to be `exp(max) > 0.0`, which is
/// "the row's total is positive" — and `exp` underflows f64 to exactly zero
/// below `ln(f64::MIN_POSITIVE)` ≈ −744.44, so `[-800, -801, …, -906]` was
/// refused while `[0, -1, …, -106]` was folded. Those two rows carry the
/// identical evidence: every column sits the same distance below its own row's
/// maximum, and both normalize to the identical distribution. Refusing one of
/// them was the module's "a row's own scale is not evidence" leak still
/// standing in the door after it had been taken out of the fold.
///
/// The old test was defensible while nothing could normalize a row of enormous
/// negatives, and that stopped being true when [`DistributionShift`] gained one
/// anchored definition: it forms `(v − max)` before anything else, which is
/// well-conditioned for ANY finite maximum however far from zero it sits.
///
/// **Why the maximum is checked to be an upper bound as well as finite.**
/// [`f32::max`] IGNORES a NaN operand — that is its documented `maxNum`
/// semantics — so folding a row with it returns the maximum of the row's
/// non-NaN values, which for `[-1, NaN, -1, …]` is a perfectly finite `-1`.
/// The row is not normalizable: `DistributionShift::of` sums `exp(v − max)`
/// over EVERY value, so the NaN poisons the sum, its log, and every column the
/// shift is then applied to. Naming the fold's result `max` and then asking
/// whether the row actually sits `<=` it is what makes the predicate total: a
/// NaN compares false against every bound, which is the same reason the row has
/// no maximum. The alternative spelling — a separate `is_nan` scan beside the
/// finiteness test — is the pair of partial predicates this door already had
/// one of.
/// How far a FOLDED row's probability mass may sit from 1 before
/// [`Accumulator::finish`] refuses it.
///
/// Measured, not chosen. Every row that ENTERS the fold is normalized at the
/// door and every row that LEAVES it is a distribution by construction
/// ([`ScorePooling::Vote`], from the shares it divides) or by a closing
/// renormalization (the other three), so the only deviation that should survive
/// is the narrowing to f32 at the exit. Two numbers bound that:
///
/// - **Derived.** A row that sums to 1 in f64 has mass error at most
/// `Σ p·2⁻²⁴·|ln p|`, maximized by the uniform row at
/// `2⁻²⁴·ln(107) = 2.8e-7`.
/// - **Observed.** Over the committed Thai clip repeated to 39 s and 52 s, that
/// clip spliced with English, and English alone, at three geometries
/// (10 s/10 s, 5 s/2.5 s, 3 s/3 s), on all four compute units and all four
/// poolings — 192 folds over 2 to 20 windows each — the largest deviation
/// any fold produced was **3.9e-8** (`Max`, on the ANE). It was 5.7e-8 while
/// the fold still took raw rows; normalizing each row before folding it
/// removed the input deficit the exit shift had been absorbing.
///
/// That sweep is a committed model gate rather than a remembered run:
/// `every_fold_in_the_published_sweep_lands_far_inside_the_mass_tolerance`, in
/// `tests/lid/long_clip.rs`, runs all 192 folds and prints the per-compute-unit
/// table, so both numbers above are re-derivable from this tree.
///
/// `1e-5` is 36× the derived bound and 258× the largest observed, and still
/// four orders of magnitude below either defect this postcondition was written
/// for (mass 2 and mass 0.5). What it is NOT derived from is the model: the
/// same sweep's raw per-window rows are off by up to **7.7e-3**, five orders
/// looser, because a fold's mass is something the poolings establish rather
/// than inherit. That is also why it is applied ONLY to a folded row — the
/// single-window identity path returns a row this module did not compute, and
/// refusing that would break the `identify_long` == `identify` promise on real
/// audio.
const MAX_MASS_DEVIATION: f64 = 1e-5;
/// The row's total probability mass: `exp` summed over it, in f64.
///
/// Wider than the row it reads, on purpose — the narrowing to f32 is the thing
/// being measured, so the measurement must not be narrowed too.
///
/// It is `NUM_LANGUAGES`-bounded and NaN-free for every row the four poolings
/// currently produce, because each of them emits values that are `<= 0` and
/// non-NaN, so every term lands in `(0, 1]`. That is a fact about those four
/// and NOT a guarantee this function makes: `exp` of a NaN is a NaN and the sum
/// carries it, so a fifth pooling that left one would be reported here as a NaN
/// mass. [`Accumulator::finish`] is written to refuse that rather than to
/// assume it cannot happen.
///
/// [`NUM_LANGUAGES`]: crate::audio::lid::NUM_LANGUAGES
/// Model column of the row's largest value, ties broken by ascending column —
/// the crate's ranking tie-break, so a window's vote agrees with what
/// `top_k(1)` on that same window would have returned.
/// Combine per-window rows into one clip-level [`LogProbabilities`] under
/// `pooling`, weighting each window by the real audio its [`Span`] covered.
///
/// This is the batch form of what [`Identifier::identify_long`] streams, driven
/// by the same private accumulator, so the two agree bit for bit. Reach for it when
/// the per-window rows are already in hand — from
/// [`Identifier::log_probabilities_windows`], or hand-built via
/// [`LogProbabilities::try_from_slice`] with no model at all.
///
/// # Errors
/// [`Error::EmptyWindows`] if `windows` is empty. (Unreachable through
/// `identify_long` — a clip long enough to reach the model always plans at
/// least one span.)
///
/// [`Error::UnnormalizableWindow`], naming the window, if one of them has no
/// finite maximum — `-∞` throughout (which is not evidence about any language),
/// `+∞` anywhere (which is not a log-probability row), or a NaN anywhere (which
/// sits under no bound at all). Every pooling refuses those alike. A row's
/// absolute SCALE is not among the things refused: a row whose largest value is
/// `-800` folds exactly as one shifted up to `0` does.
///
/// [`Error::ZeroMassAggregate`] if the pooled row assigns probability zero to
/// every language, which is not a distribution and cannot be ranked — see the
/// module docs' "Totality" section for when a pooling honestly answers that.
///
/// [`Error::NotADistribution`] if the pooled row's mass is neither zero nor 1,
/// which is a defect in this crate rather than a property of `windows`.
///
/// All three are unreachable through `identify_long`: a model row is a
/// log-softmax, so it is all-finite and its mass is positive.
///
/// # Examples
/// ```
/// use coremlit::audio::lid::{
/// LogProbabilities, NUM_LANGUAGES, ScorePooling, Span, WindowLogProbabilities,
/// aggregate_windows,
/// };
///
/// // Two equal-length windows: one sure of column 94, one sure of column 0.
/// // Each row is a real distribution: 99.9 % on one language, the remaining
/// // 0.1 % spread over the other 106.
/// let window = 160_000;
/// let row = |hot: usize| {
/// let rest = (0.001f64 / (NUM_LANGUAGES - 1) as f64).ln() as f32;
/// let mut values = vec![rest; NUM_LANGUAGES];
/// values[hot] = 0.999f64.ln() as f32;
/// LogProbabilities::try_from_slice(&values).expect("valid row")
/// };
/// let windows = vec![
/// WindowLogProbabilities::new(row(94), Span::new(0, window, window)),
/// WindowLogProbabilities::new(row(0), Span::new(window, window, window)),
/// ];
///
/// // A mixture splits the mass; a vote splits it too, but exactly in half and
/// // with every other language at log 0 probability.
/// let mixed = aggregate_windows(ScorePooling::MeanProbability, &windows)?;
/// assert!((mixed.as_slice()[94].exp() - 0.5).abs() < 1e-3);
/// let voted = aggregate_windows(ScorePooling::Vote, &windows)?;
/// assert_eq!(voted.as_slice()[94], 0.5f32.ln());
/// assert_eq!(voted.as_slice()[1], f32::NEG_INFINITY);
/// # Ok::<(), coremlit::audio::lid::Error>(())
/// ```
///
/// [`Span`]: crate::audio::lid::Span
/// [`Identifier::identify_long`]: crate::audio::lid::Identifier::identify_long
/// [`Identifier::log_probabilities_windows`]: crate::audio::lid::Identifier::log_probabilities_windows