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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
//! CoreML wrapper over a fixed-window CTC acoustic encoder: `waveform [1, W]`
//! f32 in, `emissions [1, T, V]` f32 out. The encoder is an
//! [`Aligner`](crate::audio::align::Aligner)'s, and only an aligner's: see
//! "The encoder is the aligner's" below. The staged
//! `base960h_aligner.mlmodelc` (design spec §3 Candidate A) is `W = 960_000`
//! (60 s @ 16 kHz), `T = 2999`, `V = 29`, 20 ms/frame (stride 320 samples @
//! 16 kHz) — ground truth pinned by
//! `tests/model_io.rs::base960h_aligner_io_matches_spec`.
//!
//! `W`, `T` and `V` are READ at load (`Encoder::window_samples`,
//! `Encoder::frames`, `Encoder::vocab_size`), never pinned: a model
//! converted at another window, or one that spells another alphabet, is as
//! correct through this door as the staged one. What no declaration says is
//! the model's [`AcousticContract`], which the caller states and this door
//! checks: `T` must be the frames the contract's front-end geometry makes of
//! `W`, else [`AlignerError::FrameCountMismatch`] at load. Pairing `V` with a
//! vocabulary is [`crate::audio::align::aligner::Aligner`]'s, which refuses a
//! table of another size at load.
//!
//! # The encoder is the aligner's
//!
//! An encoder runs one model under one [`AcousticContract`], and asry's seam
//! has to tokenize with the same contract's blank, stride and tokenization:
//! its `prepare` pads and silence-masks a chunk for THAT seam, and its `finish`
//! reads the emissions' columns by THAT seam's blank. Nothing in asry's
//! `PreparedChunk` names the contract it belongs to, and its `encode_with` runs
//! whichever encoder it is handed, so a prepared chunk of one seam encoded by
//! another model's encoder would compose without an error and align against
//! the wrong columns.
//!
//! So the composition is not public. `Encoder` and `EncoderInput` are this
//! crate's, and the one road from audio to words is
//! [`Aligner::align_chunk`](crate::audio::align::Aligner::align_chunk), whose
//! aligner owns the seam, the encoder and the contract they were both built
//! from. No public value can cross from one aligner to another:
//!
//! ```compile_fail,E0603
//! use coremlit::audio::align::encode::Encoder;
//! ```
//!
//! ```compile_fail,E0603
//! use coremlit::audio::align::encode::EncoderInput;
//! ```
//!
//! # Fixed-window bridging
//!
//! `Encoder::emissions` hides the model's fixed window (60 s on the staged
//! model) behind a variable-length `&[f32]` contract, mirroring asry's own
//! encoder call shape (`(1, T) -> (1, T', V)`, `asry/src/runner/aligner/algorithm/
//! encode.rs`) as closely as a fixed-window CoreML graph allows:
//!
//! - **Longer than the window** (`Encoder::window_samples`): rejected with
//! [`AlignError::InputTooLong`] rather than silently truncated, before any
//! prediction. The caller is responsible for chunking audio to at most the
//! window before calling — see "60 s clamp vs asry's `MAX_CHUNK_SIZE`" below
//! for why the staged model's ceiling is far tighter than asry's own
//! per-chunk cap.
//! - **Shorter**: zero-padded up to exactly the window, never rejected —
//! unlike `dia-coreml`'s `SegmentModel::infer`, which
//! rejects rather than pads short input
//! (`crates/dia-coreml/src/segment/mod.rs`'s "dia contract match"
//! section). wav2vec2 is not causal, so whether padding perturbs
//! in-range emissions was an open empirical question — the B5 word-timing
//! parity gate (`tests/parity_words.rs`) has since MEASURED it: fed a full
//! window the encoder is frame-exact against asry's ONNX reference, and
//! zero-padding a short clip leaves the median boundary frame-identical
//! (p90 40.1 ms on the 11 s `jfk.wav`). See the crate root's "How far you
//! can trust the timings" table for both clips.
//! - **`emissions` frames past the real (non-padded) audio**: truncated
//! away, to the frames the contract's geometry makes of the real audio —
//! see `Encoder::emissions`'s doc for the exact formula and why it must be
//! clamped to the model's actual frame count.
//!
//! # 60 s clamp vs asry's `MAX_CHUNK_SIZE`
//!
//! asry's own chunk-size ceiling is `pub const MAX_CHUNK_SIZE: Duration =
//! Duration::from_secs(600);` (`asry/src/core/transcriber.rs:137`) — 10
//! minutes. The staged model's window, [`ENCODER_WINDOW_SAMPLES`], is 60 s,
//! ten times tighter. This is a deliberate, DOCUMENTED divergence, not a
//! parity target: asry's 600 s cap bounds per-chunk RAM for its own
//! (non-fixed-window) ONNX wav2vec2 path, which allocates proportionally to
//! whatever length it is given. `base960h_aligner.mlmodelc` allocates a
//! *fixed* 960,000-sample input / `[1, 2999, 29]` output tensor pair
//! regardless of how much of it is real audio, so there is no equivalent "let
//! it grow" option on this side — the model's own fixed graph is the ceiling,
//! not a tunable, and a model converted at another window has that window as
//! its ceiling. A caller must chunk audio to at most the encoder's window
//! (`Encoder::window_samples`) before calling `Encoder::emissions`; that
//! chunking responsibility is explicitly out of scope here (design spec §7's
//! data flow already assumes per-chunk audio, not a whole-file stream).
//!
//! # The log-prob door: `EncoderOutput::LogProbs`, not `Logits`
//!
//! `Encoder::emissions` hands the raw `emissions` tensor to asry as an
//! [`EncoderOutput::LogProbs`] — the log-prob door — with **no softmax or
//! log-softmax applied**, and asry's `PreparedChunk::encode_with` makes the
//! chunk's emissions of it. The model's own graph already
//! ends in one (`Models/alignkit/base960h_aligner.mlmodelc/model.mil`, final
//! ops — this is graph truth, not an inference from measured values):
//!
//! ```text
//! linear_73_cast_fp16 = linear(...) // CTC head → logits
//! var_849_softmax_cast_fp16 = softmax(axis = -1, x = linear_73_cast_fp16)
//! var_849_cast_fp16 = log(epsilon = 0x1p-149, x = var_849_softmax_cast_fp16)
//! emissions = cast(dtype = fp32, x = var_849_cast_fp16)
//! ```
//!
//! The reason to prefer this door is NOT that re-applying a log-softmax
//! would corrupt the values. It would not: **log-softmax is exactly
//! idempotent.** For `y = log_softmax(x)`, `lse(y) = ln Σ exp(x_j − lse(x)) =
//! ln 1 = 0`, so `log_softmax(y) = y`. Routing genuine log-probs through
//! [`EncoderOutput::Logits`] (asry's raw-logit door, which applies its
//! `log_softmax_with_finite_guard`) would be a numerical no-op.
//!
//! The real reason is that this door **refuses to paper over a model-artifact
//! swap**. [`EncoderOutput::Logits`] would have asry apply its own
//! `log_softmax_with_finite_guard` and **re-normalize whatever it is handed** —
//! genuine log-probs (a no-op, per above) *or* raw logits — into a plausible
//! log-prob domain, then align on the result forever.
//! [`EncoderOutput::LogProbs`] hands asry the tensor **as-is**, so a future
//! model revision that ships a raw-logit CTC head — entirely plausible, since
//! that is the *standard* wav2vec2 export, and asry's own ONNX model does
//! exactly that (`asry/src/runner/aligner/algorithm/encode.rs` takes the logit
//! door) — is caught rather than absorbed.
//!
//! Caught by what, exactly, is the subtle part, and the earlier revisions of
//! this doc got it wrong. asry's own `O(T·V)` scan of a `LogProbs` tensor
//! (every element finite ∧ `<= 0`) is **necessary but not sufficient**: it
//! rejects a raw-logit
//! head only when some logit is *positive*. Logits are defined only up to an
//! additive per-frame constant, so a raw-logit row shifted wholly into, say,
//! `[-20, -10]` — or the degenerate all-zeros row, `exp(0) = 1` on every class —
//! is finite and `<= 0` on every cell and sails straight through that scan while
//! being nothing like a probability distribution. What actually pins the tensor
//! to the log-probability domain is the **per-frame logsumexp guard**
//! (`check_log_prob_normalization`, [`log_prob_sum_tolerance`]): a genuine CTC
//! log-prob row satisfies `logsumexp(row) = ln Σ exp(log p_j) = ln Σ p_j =
//! ln 1 = 0` by construction, while an un-normalized row is off by whole units
//! (the all-zeros row by `ln 29 ≈ 3.37`, a `[-20, -10]` shifted row by `>= 6.6`).
//! That guard and the `<= 0` scan are together what make "these really are
//! log-probs" a *checked* contract rather than a hope — for any artifact loaded
//! through the public API, not merely the one reviewed here. See "The
//! normalization guard" below. The staged artifact's contract adds a third,
//! its sentinel band (below).
//!
//! For the same reason the raw tensor is passed through **unclamped**. The
//! graph's `softmax` output is in `[0, 1]` by construction, so its `log` is
//! `<= 0` *guaranteed by the graph* (measured max is exactly `0.0` on every
//! compute placement). An unbounded `.min(0.0)` would be actively dangerous —
//! it is exactly what would mask a raw-logit head's *positive maxima* from the
//! `<= 0` scan above (the logsumexp guard would still catch a shifted-negative
//! head, but suppressing any model-swap signal is the wrong direction). If a
//! clamp is ever needed here, it must be **bounded** to a pinned slack, never
//! open-ended.
//!
//! # The sentinel band: one artifact's measurement, in its contract
//!
//! asry's scan of an [`EncoderOutput::LogProbs`] tensor bounds the emissions
//! from **above**
//! (`<= 0`) and rules out non-finite values. It does not bound them from
//! **below**, and it cannot: `-45440` is finite and negative, so the staged
//! model's ANE-corrupted matrix — every softmax output under the fp16 floor
//! underflowed to `0`, every `log(0)` saturated to that sentinel
//! ([`DEFAULT_ENCODER_COMPUTE`]) — sails straight through it and aligns to
//! plausible, silently wrong timings.
//!
//! That gap was reachable from this crate's own public API
//! ([`crate::audio::align::AlignerOptions::with_compute`]),
//! and it was the *measured* defect, not the hypothetical one the paragraph
//! above guards against. So when the model's contract carries a
//! [`SentinelBand`], `Encoder::emissions` scans for it: any cell in the band
//! is [`AlignError::CorruptEmissions`], a typed error that NAMES the compute
//! placement the encoder was loaded with. Loud, and self-diagnosing.
//!
//! Only [`AcousticContract::BASE960H`] carries a band. No law bounds a
//! log-probability from below, so no finite threshold tells a sentinel from a
//! valid value for every model: `[0, -40000]` is a normalized row of some
//! model, and it lies inside the staged model's band. A band is therefore a
//! measurement of one artifact, and a contract made with
//! [`AcousticContract::new`] has none.
//!
//! # The normalization guard: per-frame logsumexp
//!
//! A sentinel band and asry's `<= 0` scan bound each *cell*;
//! neither checks that a frame's `V` log-probs describe a *distribution*.
//! `check_log_prob_normalization` does, and it is what makes the "The log-prob
//! door" section's model-swap claim actually true. For every truncated frame it
//! recomputes `logsumexp` over the vocab axis (in `f64`, so the bound reflects
//! the model's own fp16 deviation, not this crate's summation error) and rejects
//! the matrix with [`AlignError::UnnormalizedEmissions`] — naming the worst frame
//! and its `logsumexp` — the moment any frame's `|logsumexp|` exceeds
//! [`log_prob_sum_tolerance`] of the head's width. A genuine CTC log-prob frame
//! sums to 1 in probability space, so its `logsumexp` is `0`; a raw-logit frame
//! (even one shifted wholly `<= 0`), or an all-zeros frame, is off by whole
//! units. This is
//! the check that closes the bypass the `<= 0` scan leaves open, for *any*
//! artifact a caller loads through the public API — not only the reviewed one,
//! whose normalization `tests/model_io.rs::emissions_are_log_probs_not_raw_logits`
//! also pins. The identity is CTC's (a frame of log-probabilities sums to one);
//! the allowance is fp16 arithmetic's, scaled by the head's width
//! ([`log_prob_sum_tolerance`]), so it holds for a head of any width.
//!
//! Cost: one `f64` exp/sum/log over `[<= 2999, 29]` per window on the staged
//! model — ~87k operations against a 0.74 s CoreML predict. Not measurable
//! ([`log_prob_sum_tolerance`]'s "Cost").
use ;
use ;
use crate::;
use ;
use crate;
/// The staged `base960h_aligner.mlmodelc`'s input window: 960,000 samples,
/// 60 s @ 16 kHz. Pinned by `tests/model_io.rs::base960h_aligner_io_matches_spec`
/// (`waveform [1, 960_000]`). See the module doc's "Fixed-window bridging" and
/// "60 s clamp vs asry's `MAX_CHUNK_SIZE`" sections.
///
/// A fact of that artifact, not of this door: an aligner's encoder reads its
/// model's own window at load
/// ([`Aligner::window_samples`](crate::audio::align::Aligner::window_samples)),
/// and this constant is what the staged model declares there.
pub const ENCODER_WINDOW_SAMPLES: usize = 960_000;
/// wav2vec2's frame stride: 20 ms @ 16 kHz, [`AcousticGeometry::WAV2VEC2`]'s
/// stride and so the staged model's, and asry's own `hop_samples` default
/// (`asry/src/runner/aligner/aligner.rs`'s `Aligner::from_paths` doc:
/// "`hop_samples` defaults to 320").
///
/// A fact of that geometry, not of this door: an aligner's encoder truncates by
/// the stride of its model's [`AcousticContract`], and the aligner hands the
/// seam that same stride. This constant is what [`AcousticContract::BASE960H`]
/// states.
pub const HOP_SAMPLES: usize = 320;
/// The one output frame count `base960h_aligner.mlmodelc` declares for its
/// [`ENCODER_WINDOW_SAMPLES`] window: **2999**, the wav2vec2 feature
/// extractor's output length for one full window, `floor((960_000 - 400) /
/// 320) + 1`. The load no longer requires it (a model's frame count is read
/// and checked against its contract's geometry), but the staged artifact's
/// tests and the compile-time tie below do.
const EXPECTED_OUTPUT_FRAMES: usize = 2_999;
/// Ties the staged artifact's three numbers to [`AcousticContract::BASE960H`]
/// at **compile time**: its geometry must make [`EXPECTED_OUTPUT_FRAMES`] of
/// [`ENCODER_WINDOW_SAMPLES`], and its stride must be [`HOP_SAMPLES`] — the
/// check `Encoder::load` runs at load, here run on the constants, so
/// re-spelling any of them without the others is a BUILD failure, not a model
/// that fails to load.
const _: = ;
/// The feature names this door sends and reads: the staged
/// `base960h_aligner.mlmodelc`'s (pinned by
/// `tests/model_io.rs::base960h_aligner_io_matches_spec`). They are the door's
/// interface, checked at load rather than trusted: a model under other names
/// is refused there ([`AlignerError::ContractMismatch`] for a missing
/// `waveform` or `emissions`, [`AlignerError::UnsatisfiableInput`] for a
/// required input the door never sends).
/// The default compute placement of an aligner's encoder
/// ([`AlignerOptions::compute`](crate::audio::align::AlignerOptions::compute)).
///
/// **`CpuOnly` is a correctness requirement of this model, not a performance
/// preference.** Do NOT "optimise" it back to `ComputeUnits::All`: on the ANE
/// this model produces a corrupted emission matrix.
///
/// # Why
///
/// `base960h_aligner.mlmodelc` does not end in a fused, numerically-stable
/// `log_softmax`. Its graph decomposes the CTC tail into an fp16 `softmax`
/// followed by a separate fp16 `log`
/// (`Models/alignkit/base960h_aligner.mlmodelc/model.mil`, final ops):
///
/// ```text
/// var_849_softmax_cast_fp16 = softmax(axis = -1, x = linear_73_cast_fp16)
/// var_849_cast_fp16 = log(epsilon = 0x1p-149, x = var_849_softmax_cast_fp16)
/// ```
///
/// That `log`'s anti-`log(0)` guard is `epsilon = 0x1p-149` (2⁻¹⁴⁹) — far
/// below fp16's smallest subnormal (2⁻²⁴ ≈ `5.96e-8`) — so inside an fp16
/// `log` it rounds to zero and the guard is **inert**. On the ANE any softmax
/// output beneath the fp16 floor therefore underflows to 0, and `log(0)`
/// saturates to ≈ `-45440`: a sentinel standing where an ordinary log-prob
/// (`-19.0` … `-21.75`) belongs.
///
/// Measured on `jfk.wav` (549 frames × 29 = 15,921 cells). `load` is a cold
/// first load — the ANE compilation is cached afterwards, so a warm `All`
/// load is fast and hides nothing:
///
/// | compute | load (cold) | predict | `min(emissions)` | sentinel cells |
/// |---|---|---|---|---|
/// | `CpuOnly` | 0.68 s | **0.74 s** | **-30.81** | **0** |
/// | `All` | 308 s | 2.15 s | `-45440` | 2,667 (16.7%) |
/// | `CpuAndNeuralEngine` | 508 s | 2.32 s | `-45440` | 2,667 (16.7%) |
/// | `CpuAndGpu` | 0.37 s | 3.55 s | -30.02 | 0 |
///
/// The corruption is bit-identical run to run — systematic, not
/// nondeterminism — and it reaches the output: on the `All` path 8 of the 22
/// jfk words shift in time (`ask` starts 881.6 ms early — 7533.7 ms against the
/// correct 8415.3 ms) and all 22 differ in timing and/or score. Those
/// word-shift figures are a pre-truncation-fix measurement, whose exact ms
/// shifted with the fix; unlike the post-fix 549-frame table above they show
/// only the ANE corruption's *direction* and *magnitude*, not timings against
/// the current frame geometry. There is no trade-off to weigh, because the ANE
/// placement is ~450× slower to load, ~3× slower to predict, **and** wrong;
/// `CpuOnly` additionally has the best predict time of any numerically-correct
/// placement.
///
/// Running this model on the ANE would require **re-converting the artifact**
/// with a fused (or fp32) `log_softmax` tail. That is a model fix, not a code
/// fix — nothing in this crate can recover the underflowed cells.
///
/// Pinned by `tests::emissions_have_no_fp16_log_zero_sentinel`, which builds
/// its encoder from this constant (never a hardcoded placement) and fails on
/// `All`.
///
/// This is the *default*, not a lock:
/// [`AlignerOptions::with_compute`](crate::audio::align::AlignerOptions::with_compute)
/// still accepts any placement. What stops an ANE override from silently
/// corrupting a caller's timings is the staged contract's
/// [`SentinelBand::Fp16Saturation`] — a value-domain guard in the encoder, not
/// a ban on the placement.
///
/// For a model loaded with its own contract `CpuOnly` is a default, not an
/// assumption about the model: every graph runs on the CPU, and whether another
/// placement computes a given graph correctly is that model's to show (the
/// staged one's ANE placements do not).
pub const DEFAULT_ENCODER_COMPUTE: ComputeUnits = CpuOnly;
/// fp16's unit roundoff, `2^-11`: the largest relative error of one rounding to
/// the nearest fp16. fp16 is the least precise float format CoreML computes a
/// softmax in.
const FP16_UNIT_ROUNDOFF: f64 = 1.0 / 2048.0;
/// Largest per-frame `|logsumexp|` an aligner's encoder accepts from a head of
/// `vocab_size` classes as normalized log-probabilities:
/// **`2·(V + 1)·2^-11`**, `0.0293` at the staged model's 29 classes. A frame
/// whose `logsumexp` over the vocab axis exceeds it in magnitude is not a
/// probability distribution — a genuine CTC log-prob frame satisfies
/// `logsumexp = ln Σ exp(log p_j) = ln Σ p_j = ln 1 = 0` by construction — and
/// the encoder rejects the whole matrix with
/// [`AlignError::UnnormalizedEmissions`] rather than align on it.
///
/// # Why a normalization check, on top of the `<= 0` scan
///
/// It is the half of the log-prob contract asry's `finite ∧ <= 0` scan of an
/// [`EncoderOutput::LogProbs`] tensor cannot cover — the model-swap guard the
/// module doc's
/// "The log-prob door" advertises but that scan alone does not deliver. That
/// scan rejects a raw-logit CTC head only when some logit is *positive*; logits
/// are defined only up to an additive per-frame constant, so a raw-logit frame
/// shifted wholly into `[-20, -10]` — or the degenerate all-zeros frame,
/// `exp(0) = 1` on every class — is finite and `<= 0` on every cell yet carries
/// no distribution. The `logsumexp` identity is the property that tells the two
/// apart. See the module doc's "The normalization guard: per-frame logsumexp".
///
/// # Why this allowance, for every width
///
/// The identity is a law of CTC log-probabilities; the allowance is a law of the
/// arithmetic that computes them. A log-softmax computed in fp16 normalizes a
/// frame only to within its roundings, each at most fp16's unit roundoff
/// `u = 2^-11` relative: summing `V` positive terms rounds up to `V − 1`
/// times, and the exponential, the division and the logarithm add a few more,
/// the last weighted by the frame's entropy (at most `ln V`). So a genuine frame's `|logsumexp|`
/// stays within about `(V + 2 + 2 ln V)·u`, which `2·(V + 1)·u` covers at every
/// width (`V ≥ 2 ln V` for every `V`). A precision finer than fp16 (the CPU's
/// fp32, `u = 2^-24`) stays far inside it.
///
/// It grows with the head because the rounding does: a fixed allowance measured
/// on one 29-class head would refuse the genuine emissions of an fp16 head of a
/// few hundred classes or more, the size of a character-level vocabulary for a
/// script with many characters. What it must refuse stays whole units away for
/// the heads a CTC aligner uses: an all-zeros frame of `V` classes is off by
/// `ln V` (3.37 at 29 classes, 8.5 at 5,000), and a raw-logit head, whose
/// logits are never normalized, is off by whole units on most frames. Past
/// about 9,000 classes the allowance passes `ln V`, so for a head that wide the
/// degenerate all-zeros frame is no longer caught, and the guard rests on a
/// raw-logit head's typical frames alone.
///
/// Measured on the staged model (f64 accumulation, the real runtime path), both
/// gate clips and both numerically-clean gate placements:
///
/// | placement | clip | worst `|logsumexp|` |
/// |---|---|---|
/// | `CpuOnly` (the default) | `ted_60.wav` (full 960 k window) | **5.2485e-3** |
/// | `CpuOnly` | `jfk.wav` | 4.7453e-3 |
/// | `CpuAndGpu` | `ted_60.wav` | 2.578e-7 |
/// | `CpuAndGpu` | `jfk.wav` | 2.406e-7 |
///
/// Its 29-class allowance, `0.0293`, sits 5.6× above the worst of them and more
/// than two orders of magnitude below the smallest deviation it must reject
/// there: an all-zeros frame's `ln 29 ≈ 3.367` (115×) and a `[-20, -10]` shifted
/// raw-logit frame's `|logsumexp| >= 6.6` (>225×). Nothing the model produces
/// lands between `5.2e-3` and `3.37`.
///
/// It is deliberately *looser* than `tests/model_io.rs`'s `1e-2` logsumexp
/// tolerance. That is a **tripwire** on the one reviewed artifact — tight, to
/// catch drift in a known quantity; this is a **fence** for any artifact a caller
/// loads through the public API — lenient enough not to false-reject an
/// unknown-but-legitimate one, still two orders below any un-normalized tensor.
///
/// # Cost
///
/// One `f64` exp/sum/log pass over `<= 2,999 × 29 = 86,971` cells on the staged
/// model, against a **0.74 s** CoreML predict. Not measurable.
///
/// Pinned by `tests::check_log_prob_normalization_*` (hermetic: a `[-20, -10]`
/// shifted-logit matrix and an all-zeros frame rejected, real log-probs accepted,
/// the allowance's growth with the width) and
/// `tests::emissions_pass_the_normalization_guard_on_real_speech` (the live
/// model, both clips, both numerically-clean placements).
pub const
/// [`log_prob_sum_tolerance`]'s separation property on the staged model's 29
/// classes, asserted at **compile time**: it must sit strictly above the worst
/// legitimate per-frame `|logsumexp|` that model produces (`5.2485e-3`,
/// `CpuOnly` `ted_60`) and at least an order of magnitude below the smallest
/// un-normalized deviation the guard must reject there (an all-zeros frame's
/// `ln 29 ≈ 3.367`). Re-deriving the allowance into either danger zone is then a
/// BUILD failure, not a test failure — below the jitter it false-rejects real
/// audio, and up toward `ln 29` it stops separating a shifted raw-logit head from
/// a real log-prob one, the exact bypass this guard exists to close.
const _: = ;
/// The smallest `|logsumexp|` of a frame the normalization check must refuse:
/// **`ln 2`**, a frame whose probabilities sum to 2 or more, or to 1/2 or less.
/// Such a frame is no distribution by any reading; a raw-logit frame is
/// typically off by whole units.
pub const UNNORMALIZED_LOGSUMEXP: f64 = LN_2;
/// The widest CTC head, **353** classes, whose log-probabilities the
/// normalization check can tell from an unnormalized frame's: the widest `V`
/// for which twice [`log_prob_sum_tolerance`] of `V`, the most fp16 rounding
/// can move a genuine frame, stays within [`UNNORMALIZED_LOGSUMEXP`].
///
/// Past it the allowance a genuine frame needs reaches within a factor of two
/// of a frame off by `ln 2`, and at 5,000 classes it admits a frame of `-4` in
/// every column (a probability mass of about 92). So a contract stating
/// [`OutputKind::LogProbabilities`] for a wider head is refused at load
/// ([`AlignerError::UnprovableNormalization`]); such a head is stated as
/// [`OutputKind::Logits`], which asry normalizes, and normalizing a log-softmax
/// output again changes nothing.
pub const MAX_LOG_PROB_WIDTH: usize =
as usize - 1;
/// [`MAX_LOG_PROB_WIDTH`] is exactly the widest separated head, asserted at
/// **compile time**: twice its allowance is within [`UNNORMALIZED_LOGSUMEXP`],
/// one class more is not.
const _: = ;
/// The load-time check of the contract's output kind against the head's
/// width: a head stated as [`OutputKind::LogProbabilities`] must be one the
/// normalization check can separate ([`MAX_LOG_PROB_WIDTH`]).
///
/// # Errors
/// [`AlignerError::UnprovableNormalization`], naming the width and the widest.
/// The load contract this door states for a model whose receptive field is
/// `receptive_field`: `waveform` `[1, W]` f32 in, with `W` at least that
/// receptive field, the length asry pads a short chunk to, `emissions`
/// `[1, T, V]` f32 out, no state, every axis one fixed size.
///
/// Data rather than a sequence of checks, and the ONLY check
/// [`Encoder::load`] makes of the graph itself beyond calling [`Model::load`]. The six free functions this replaced — a presence
/// resolver, a shape-and-dtype check and an `expected …` renderer per feature —
/// were each a call the constructor could forget to make, and deleting any of
/// them failed no runnable test, because `Models/alignkit/` holds exactly one
/// artifact and every gate that loads it is `#[ignore]`d. A [`Checked`] field
/// turns that mutation into a compile error.
///
/// **"Fixed in every dimension" is a check rather than a sentence.** A contract
/// whose every axis is [`Dim::Exactly`] or [`Dim::AnyFixed`] requires both
/// features to be [`crate::ShapeConstraint::Fixed`], so a `RangeDims` export
/// declaring fixed-looking numbers — which [`crate::FeatureInfo::shape`] reports
/// identically — is refused. Measured on the staged `base960h_aligner.mlmodelc`:
/// `waveform` `[1, 960000]` Float32 with spans `1+1, 960000+1`, `emissions`
/// `[1, 2999, 29]` Float32 with spans `1+1, 2999+1, 29+1`, both `Fixed`,
/// `states` empty.
///
/// The window `W` is [`Dim::AtLeast`] the contract's receptive field, which
/// asry's seam is stated and pads a short chunk to: every chunk that reaches the
/// encoder is at least that long, so a smaller window would refuse every one of
/// them. The frame count `T` and
/// the head width `V` are [`Dim::AnyFixed`]. All three are READ back after the
/// check ([`Declared`]). Every step of
/// this door sizes itself by what it read: the zero-padding to `W`, the copy of
/// `[1, T, V]`, the truncation, the per-frame normalization and the hand-off. What
/// the numbers must AGREE with is checked by the door that can see the other
/// side of each pairing, the way [`Dim::AnyFixed`] asks:
///
/// - `T` against `W`: the frames the model's [`AcousticContract`] geometry
/// makes of `W` must be `T` ([`check_frame_count`], at load). One `T` fits
/// several geometries, so the geometry is the caller's statement and this is
/// the check the declaration allows.
/// - `V` against the vocabulary the seam tokenizes with: a pairing only the
/// aligner can see. [`crate::audio::align::aligner::Aligner`] refuses a table
/// of another size at load, and asry re-checks the emissions' width against
/// its tokenizer on every chunk.
/// What a checked model declares: its input window, its frames per window and
/// its CTC head width.
/// Reads [`Declared`] off the checked `description`.
///
/// Read AFTER the check (see [`Dim::AnyFixed`]): [`align_contract`] names
/// `waveform` at rank 2 and `emissions` at rank 3, every read axis one
/// non-zero fixed size, so a description that passed it has each axis and none
/// is zero.
/// The load-time pairing of the contract's geometry with what the model
/// declares: the geometry must make exactly the declared `frames` of the
/// declared `window`.
///
/// The declaration fixes the two ends and not the front end between them, and
/// several geometries fit one pair: a 400-sample and a 640-sample receptive
/// field both make 2999 frames of a 960,000-sample window at a 320-sample
/// stride. So this cannot tell such geometries apart. What it does is refuse
/// every geometry that does NOT fit, which would truncate every chunk to the
/// wrong number of frames.
///
/// # Errors
/// [`AlignerError::FrameCountMismatch`], carrying the geometry and both counts.
/// Map a [`ContractViolation`] into this module's error vocabulary.
///
/// The two "unsatisfiable" clauses keep their own variants — they are about
/// what the door cannot SUPPLY, not about a feature's declared shape — and the
/// per-feature clauses all land in [`AlignerError::ContractMismatch`], which
/// already carries a feature name and a rendered expected/actual pair. An
/// output the model declares OPTIONAL is one of those: it is a fact about the
/// named feature's declaration, so "expected a required output, got optional"
/// is the shape that pair was made for.
///
/// `ContractViolation::rendered` performs that reduction, so a clause added to
/// the checker later lands in the `Feature` arm rather than breaking this
/// function and its five siblings at once.
/// Copies a prediction's `emissions` tensor out as `frames × vocab_size`
/// row-major cells — only once the tensor is shown to BE
/// `[1, frames, vocab_size]`, the shape the load contract declared and every
/// later read of the buffer assumes.
///
/// The load contract established what the graph DECLARES; this is the tensor a
/// prediction RETURNED. `MultiArray::copy_into` validates only the element
/// count, and a tensor with that count and other axes (`[1, V, frames]`, or
/// `[frames, V, 1]`) would be copied without complaint and then read as frames
/// of `V` classes that are nothing of the kind. So the shape check and the copy
/// are one function, the only one [`Encoder::emissions_raw`] reads the tensor
/// through: there is no copy without the check.
///
/// # Errors
/// [`AlignError::OutputShape`], carrying both shapes, before any cell is
/// copied; [`AlignError::Tensor`] if the copy itself fails.
/// Rejects an emission matrix holding a cell in `band`, the values the model's
/// contract says it emits IN PLACE OF a log-probability (a saturated fp16
/// `log(0)`, for the staged model). With no band — every contract but the
/// staged artifact's — there is nothing to refuse: no finite value is outside
/// the log-probability domain for every model. Hermetic (no loaded model), and
/// a PREDICT-time guard: the load contract established what the graph
/// declares, which says nothing about the numbers a prediction comes back with.
///
/// `compute` is carried into the error so the failure NAMES the placement that
/// produced it — the diagnosis, not just the symptom.
///
/// Deliberately only the band: the upper bound (`<= 0`) and finiteness are
/// asry's scan of the [`EncoderOutput::LogProbs`] that
/// [`ValueDomainChecked::into_output`] makes of the very tensor this guard just
/// cleared, run when `PreparedChunk::encode_with` receives it from the encoder.
/// A `NaN` therefore passes *here*
/// (`NaN <= x` is false) and is caught *there*; neither scan is redundant with
/// the other.
/// Rejects an emission matrix whose frames are not **normalized**
/// log-probabilities: a genuine CTC log-prob frame satisfies
/// `logsumexp(frame) = ln Σ exp(log p_j) = ln Σ p_j = ln 1 = 0` by construction,
/// so a frame whose `|logsumexp|` over the vocab axis exceeds the allowance
/// [`log_prob_sum_tolerance`] gives its width carries raw logits — or another
/// un-normalized distribution — not log-probabilities. Reports the single worst
/// frame (largest `|logsumexp|`) in [`AlignError::UnnormalizedEmissions`], with
/// `compute` for the placement, so the failure is self-diagnosing. Hermetic (no
/// loaded model), like [`check_sentinel_band`].
///
/// This is the half of the contract asry's `finite ∧ <= 0` scan of an
/// [`EncoderOutput::LogProbs`] tensor cannot cover: a raw-logit frame shifted
/// wholly into
/// `[-20, -10]`, or the all-zeros frame, is finite and `<= 0` on every cell yet
/// is no distribution at all — the model-swap the module doc's "The log-prob
/// door" warns of. See the module doc's "The normalization guard".
///
/// `logsumexp` is accumulated in `f64` so the bound reflects the MODEL's
/// deviation rather than this scan's own summation error, matching how the
/// staged model's jitter was measured. A frame with a non-finite maximum
/// (all `-inf`, or a `+inf`/`NaN` cell) is skipped here and left to asry's
/// finite scan of the [`EncoderOutput::LogProbs`] this guard's tensor becomes
/// ([`ValueDomainChecked::into_output`]) —
/// exactly the division of labour [`check_sentinel_band`] keeps with `NaN`;
/// recomputing `logsumexp` over it would only manufacture a `NaN` bound. An empty
/// matrix (`real_samples == 0` → zero frames) has no frame to check and is
/// accepted.
///
/// A frame is `vocab_size` cells: the model's CTC head width, read at load
/// ([`Encoder::vocab_size`]), which also sizes the allowance.
/// The value-domain guard sequence run over a raw log-prob tensor before it is
/// handed on: [`check_sentinel_band`] then [`check_log_prob_normalization`], in
/// that order, over the same buffer. It takes the buffer **by value and hands it
/// back on success**, so the minter cannot check one buffer and seal another:
/// [`RawEmissions::check_value_domain`] moves its tensor through here and can seal
/// only what this returns. Clearing `&[]` (or any second buffer) and then handing
/// on the real tensor no longer type-checks — there is no borrowed slice to swap for
/// an empty one, and after the move no second handle to the original.
///
/// On the production door this is the exact pair [`RawEmissions::check_value_domain`]
/// runs to mint a [`ValueDomainChecked`] — the capability [`Encoder::emissions`]
/// must hold before [`ValueDomainChecked::into_output`] will hand the tensor to
/// asry as an [`EncoderOutput::LogProbs`]. The guard is therefore not merely
/// called *near* the hand-off; the hand-off is unreachable without it, so
/// swapping in the weaker
/// [`check_sentinel_band`] alone at the call site stops type-checking (a bare
/// `()` mints no token). This mirrors the [`EncoderInput`] capability one screen
/// down: just as that type makes a buffer paired with the wrong real-sample count
/// unrepresentable, this token makes "hand on a tensor the guard never cleared"
/// unrepresentable.
///
/// The hermetic suite drives this sequence through the minter itself
/// (`tests::raw_emissions_check_value_domain_binds_the_guard_and_the_minted_buffer`),
/// not through this helper in isolation: the normalization half has no real-model
/// fixture — no loadable model emits un-normalized raw logits — so binding that
/// predicate to the door means handing the door's own minter a hand-built
/// shifted-raw-logit tensor and asserting both the rejection and, on the accepted
/// frame, that the sealed buffer is the one the guard validated. The band half is
/// additionally exercised at the full public door by the model-gated
/// `tests::emissions_reject_an_ane_corrupted_matrix`.
///
/// Band before normalization, so the staged model's ANE-corrupted matrix is
/// reported as [`AlignError::CorruptEmissions`] rather than merely
/// un-normalized.
///
/// # Errors
/// [`AlignError::CorruptEmissions`] from [`check_sentinel_band`] (a cell in the
/// contract's band); [`AlignError::UnnormalizedEmissions`] from
/// [`check_log_prob_normalization`] (a frame's `|logsumexp|` past
/// [`log_prob_sum_tolerance`] of its width).
/// A capability proof that a specific raw log-prob tensor cleared the FULL
/// value-domain guard — [`check_sentinel_band`] THEN
/// [`check_log_prob_normalization`] — and which OWNS that exact tensor.
/// Non-`Copy`, module-private, minted only by [`RawEmissions::check_value_domain`]
/// on success and consumed only by [`Self::into_output`].
///
/// This is the [`EncoderInput`] capability pattern (same file, same intent)
/// applied to the value-domain guard rather than to input geometry. `EncoderInput`
/// makes a buffer paired with the wrong real-sample count unrepresentable; this
/// token makes "hand on a tensor the guard never cleared" unrepresentable. The
/// mechanism is the same — carry the checked thing INSIDE the capability so it
/// cannot be swapped after the fact:
///
/// - Calling only [`check_sentinel_band`], or skipping the guard, yields `()`
/// and no token, so [`Self::into_output`] — the sole production route from a
/// raw log-probability tensor to the [`EncoderOutput`] asry makes emissions
/// of — has nothing to consume and [`Encoder::emissions`] no longer compiles.
/// - Clearing `&[]` (or any other buffer) and then handing on the real tensor does
/// not type-check: [`check_emission_value_domain`] takes the buffer by value and
/// returns THAT buffer, and [`RawEmissions::check_value_domain`] seals only what
/// it returns — there is no borrowed slice to validate and discard, and after the
/// move no second handle to the original. The token owns the very bytes the guard
/// validated, so the only tensor `into_output` can hand on is the one that
/// passed.
/// A provenance-bound encoder input: the buffer [`Encoder::emissions`] runs the
/// model on, bound at construction to the count of REAL (pre-pad) audio samples
/// that determines the truncated frame count `T`.
///
/// # Why this type exists — the recurring bug class, closed at the type level
///
/// [`Encoder::emissions`] needs two lengths that are NOT the same number: the
/// buffer it feeds the fixed-window CoreML graph (asry's silence-masked,
/// receptive-field-padded `encoder_input`, or a standalone caller's raw
/// samples), and the count of real audio the chunk represents — which drives
/// `truncated_frame_count`, and through it every word's timing. When those
/// arrived as two independent arguments (`encoder_input: &[f32]` and a free
/// `real_samples: usize`) nothing tied them together:
///
/// - A 176,000-sample buffer with `real_samples = 175_360` (two hops short)
/// silently produced 547 frames where 549 belong, moving the tail by two
/// frames with **no error** — asry 0.2's `chunk_extent ± 2·hop` stride check
/// was too loose to catch a two-hop lie, and a per-chunk frame-count band
/// cannot be what keeps the two lengths together.
/// - Naturally passing `encoder_input.len()` as the real count on a padded chunk
/// (200 real samples zero-padded to 400) recorded the padded extent as real.
/// With the corrected conv-geometry truncation that *particular* slip is now
/// benign for a sub-receptive-field chunk — 200 real samples and their
/// 400-sample pad both yield the single receptive-field frame — but the
/// binding still has to hold for the general case above, where a real count
/// short of a full-window slice genuinely moves the count.
///
/// This type makes that mismatch **unrepresentable**. `real_samples` is never a
/// free integer supplied alongside the buffer; it is always a slice length,
/// captured at construction from the audio itself:
///
/// - [`from_samples`](Self::from_samples) — the standalone / raw door. The
/// buffer IS the real audio, so both lengths are one slice's `.len()` and
/// cannot disagree.
/// - [`from_prepared`](Self::from_prepared) — the composition door. Reads BOTH
/// the padded buffer and the true pre-pad real length off one
/// [`PreparedChunk`] — the capability token
/// only asry's `prepare` can mint — so the two are drawn from the same
/// authoritative object and cannot be paired wrong. It is the door
/// [`Aligner::align_chunk`](crate::audio::align::aligner::Aligner::align_chunk) takes AND the
/// one an external `prepare` → `Encoder` → `finish` composer takes.
///
/// There is deliberately **no** public `(buffer, count)` constructor: a free
/// `real_samples: usize` supplied alongside a buffer is exactly the forgeable
/// pair this type exists to delete. `from_prepared` is safe to expose precisely
/// because it takes neither a loose integer nor a loose buffer — it reads both
/// off the unforgeable [`PreparedChunk`], whose
/// [`real_samples`](asry::emissions::PreparedChunk::real_samples) is asry's own
/// pre-pad `samples.len()`, not a number the caller gets to choose.
///
/// The window ceiling is not this type's to check: the window is the model's,
/// read at load ([`Encoder::window_samples`]), so [`Encoder::emissions`] refuses
/// a buffer longer than its own window, before any prediction runs.
pub
/// Refuses an encoder buffer longer than the model's `window`, before any
/// prediction: the graph takes exactly `window` samples, and truncating the
/// buffer to fit would silently drop audio the caller meant to align.
///
/// # Errors
/// [`AlignError::InputTooLong`], carrying both lengths.
/// CoreML wrapper over a fixed-window CTC acoustic encoder: one
/// [`Self::window_samples`]-sample window in, per-frame CTC log-probabilities
/// out — see the module doc for the padding/truncation contract that bridges
/// the fixed window to asry's variable-length encoder shape.
pub
/// The **raw** truncated per-frame CTC output from [`Encoder::emissions_raw`]:
/// `frames × vocab_size` row-major, exactly the tensor [`Encoder::emissions`]
/// hands asry as an [`EncoderOutput`].
///
/// Crate-private, like the method that produces it: the currency asry aligns
/// is its [`Emissions`](asry::emissions::Emissions), made from an
/// [`EncoderOutput`] through a prepared chunk's `encode_with`, which
/// intentionally exposes no per-cell reads (its opaque design deletes the
/// row-major aliasing footgun asry documents). This is a plain internal
/// carrier, not an API — it holds no invariant beyond
/// `data.len() == frames * vocab_size`, and in particular it is NOT a
/// validated log-prob tensor (that is asry's `Emissions`, made only through
/// `encode_with`, after this crate's guards).
pub
/// The `(frames, vocab)` shape of `output`, whichever door it goes out through.
pub
/// See [`Encoder::emissions`]'s "Truncation formula" doc section.