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
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
//! Native CoreML **granite** text embeddings — a general sentence-embedding
//! surface whose first model is IBM's
//! `granite-embedding-97m-multilingual-r2` (a ModernBERT encoder with CLS
//! pooling projecting to a 384-dim space).
//!
//! A `&str` in, a unit-norm 384-dim [`Embedding`] out ([`TextEmbedder::embed`]):
//! the artifact's granite tokenizer around the fp16 CoreML ModernBERT graph, with
//! L2 normalization applied in Rust.
//!
//! Design spec: `docs/superpowers/specs/2026-07-18-embedkit-design.md`
//! (Amendment 3: granite confirmed, `coremlit::embeddings::granite`, prompt-free,
//! committed-golden oracle).
//!
//! macOS only (built on [`crate`]).
//!
//! # Prompt-free (raw strings)
//!
//! granite-embedding r2 retrieval is **prompt-free**: its
//! `config_sentence_transformers.json` query/document prompts are empty. Feed
//! **raw strings** — no task prefixes. (This is the model's documented retrieval
//! contract; it differs from instruction-tuned embedders.)
//!
//! # Model artifacts
//!
//! The CoreML graph is distributed on the Hugging Face Hub at
//! [`FinDIT-Studio/embedkit-coreml`](https://huggingface.co/FinDIT-Studio/embedkit-coreml),
//! revision `a61241cb`, converted from
//! [`ibm-granite/granite-embedding-97m-multilingual-r2`](https://huggingface.co/ibm-granite/granite-embedding-97m-multilingual-r2)
//! (**Apache-2.0**; see the crate `NOTICE`). It is a gitignored dev-time
//! download under `Models/embedkit-granite/`; its per-file SHA-256 and I/O
//! contract are pinned by `tests/granite/model_io.rs`.
//!
//! # Rust front-end around an fp16 CoreML graph
//!
//! The graph emits the **pre-normalization** CLS embedding (`hidden_states[:,
//! 0]` after the final LayerNorm); this module applies the final L2
//! normalization in Rust (keeping the fp16 rsqrt-guard class out of the graph,
//! the workspace convention). The graph takes tokenized `input_ids` /
//! `attention_mask` (`[1, 512]` int32), produced from the granite
//! `tokenizer.json` that ships in the artifact directory (see
//! [`TOKENIZER_FILE_NAME`]).
//!
//! # Committed-golden oracle (no ort)
//!
//! Parity is scored against **committed transformers-fp32 fixtures**
//! (`tests/granite/fixtures/goldens/corpus.json`), never a live ONNX crate — the
//! embedkit "no ort anywhere, not even dev" rule. The hermetic
//! `tests/granite/tokenizer_identity.rs` proves the artifact tokenizer is
//! byte-correct (token-ids match the goldens exactly, no model load needed);
//! `tests/granite/parity_embed.rs` scores the CoreML embeddings against the
//! fp32 goldens by cosine (model-gated).
//!
//! # Compute placement (measured, never marketed)
//!
//! Placement is characterized, not asserted (`tests/granite/placement.rs`).
//! Unlike CLAP's audio tower, the granite ModernBERT graph **does** compile for
//! the ANE: T1's ANECCompile accepted it and the `CPU_AND_NE` compile plan
//! reported 482/493 ops (97.8%) preferring the ANE — a planner/compile-eligibility
//! report, not measured runtime residency. fp16 under `CpuAndNeuralEngine` scored
//! worst cosine 0.99996 vs the fp32 reference build. [`crate::ComputeUnits::All`]
//! (the default) lets CoreML schedule it — on T1's Mac the planner chose the GPU
//! for this small graph; `CpuAndNeuralEngine` targets the ANE. The module
//! characterizes the placement rather than claiming it.
pub use Embedding;
pub use ;
/// windit's window geometry, re-exported as one of the two windit types in
/// granite's public surface: the per-chunk token budget, overlap, tail policy,
/// and window cap. Carried by [`LongTextOptions`] (alongside granite's own
/// `max_input_bytes` bound), the options [`TextEmbedder::embed_long_with`]
/// accepts.
pub use WindowOptions;
/// The tail policy carried by [`WindowOptions`], re-exported so a caller can
/// name it — set it, read it back, round-trip a persisted geometry — without a
/// direct `windit` dependency of their own.
///
/// From windit's crate root, which is where 0.4 lifted it precisely because it
/// was otherwise unnameable through a re-exporting consumer.
///
/// On granite's own path it moves a boundary and never drops text: see
/// [`LongTextOptions::tail_policy`] for what each variant does — the same
/// geometry, and the same tail behavior, governs both `embed_long` and
/// `embed_windows`.
pub use TailPolicy;
use ;
use crate::;
use ;
use crate;
/// File name of the granite `tokenizer.json` sidecar inside the model artifact
/// directory — the file [`TextEmbedder::load`] / [`TextEmbedder::from_file`]
/// read from the directory *containing* the `.mlmodelc`.
///
/// The tokenizer is the one from the source model repo
/// [`ibm-granite/granite-embedding-97m-multilingual-r2`](https://huggingface.co/ibm-granite/granite-embedding-97m-multilingual-r2),
/// revision `835ad14087e140460703cf0fae09f97d469d65c2` (SHA-256
/// `4f2842d568e2724370aec203652a42ac783c7937f8347a1a2cc7506d71f1582f`) — the
/// exact tokenizer that produced the committed token-id goldens. It is
/// distributed with the CoreML graph at
/// [`FinDIT-Studio/embedkit-coreml`](https://huggingface.co/FinDIT-Studio/embedkit-coreml)
/// rather than compiled into this crate, and the bytes read from disk are held
/// to the same fail-closed identity pin a caller-supplied tokenizer is
/// ([`TextEmbedder::from_memory`]).
pub const TOKENIZER_FILE_NAME: &str = "tokenizer.json";
/// Declared feature names on the granite `.mlmodelc` (pinned by
/// `tests/granite/model_io.rs`).
/// The Granite tokenizer/model contract, verified against the artifact tokenizer and
/// the committed goldens: the total vocabulary INCLUDING added tokens, the
/// highest id the model's embedding table can gather, the special tokens
/// [`TextEmbedder::token_ids`] brackets every sequence with, and one pinned
/// sentinel encoding. [`validate_tokenizer_contract`] checks every constructor's
/// tokenizer against these, fail-closed.
/// Fixed token-sequence length the ModernBERT graph was converted at (the
/// export sequence length, `[1, 512]`). Shorter inputs are right-padded to this
/// length with the mask zeroed on the pad positions; longer inputs are truncated
/// at this length. RoPE makes any fixed length sound, and CLS pooling reads
/// position 0 (never a pad), so the pad token value never reaches the output.
pub const MAX_TOKENS: usize = 512;
/// Special tokens the pinned tokenizer's post-processor adds to EVERY sequence:
/// `2`, the `<|startoftext|> A <|return|>` single-sequence template of the
/// artifact `tokenizer.json` ([`TOKENIZER_FILE_NAME`]).
///
/// Every encoding on this door's paths runs `encode(s, add_special_tokens =
/// true)` — [`TextEmbedder::token_ids`], the chunker's measurement, and the
/// sentinel gate alike — so this overhead is charged against [`MAX_TOKENS`]
/// unconditionally, leaving [`CONTENT_TOKENS_PER_WINDOW`] for the caller's own
/// text.
///
/// Not a knob: the tokenizer is pinned by SHA-256, so this is a fact about the
/// one artifact this door accepts, re-measured from it rather than asserted —
/// `special_token_overhead_matches_the_pinned_template` (model-gated) reads it
/// three independent ways: the post-processor's own `added_tokens(false)`, the
/// length of `encode("", true)`, and the difference an `add_special_tokens`
/// makes to one encoding.
pub const SPECIAL_TOKENS_PER_WINDOW: usize = 2;
/// Raw-content token budget of one window: [`MAX_TOKENS`] −
/// [`SPECIAL_TOKENS_PER_WINDOW`] = `510`.
///
/// The most tokens of the CALLER'S OWN text that fit one prediction — and the
/// tokenizer's own effective text window, since this module configures
/// truncation at [`MAX_TOKENS`] and `tokenizers` truncates at `max_length −
/// post_processor.added_tokens(false)`.
///
/// [`LongTextOptions::window_options`] is stated in TOTAL tokens, not in these:
/// `WindowOptions::window()` is compared against a measure that counts the
/// specials too (chunk measurement and per-chunk embedding run the same
/// `encode(s, true)`), so a `window()` of `w` admits
/// `w − `[`SPECIAL_TOKENS_PER_WINDOW`] content tokens and the default
/// `window() == MAX_TOKENS` admits exactly this many. Set `window()` as a total;
/// read the content budget off this constant.
pub const CONTENT_TOKENS_PER_WINDOW: usize = MAX_TOKENS - SPECIAL_TOKENS_PER_WINDOW;
/// Default [`TextEmbedderOptions::compute`]: [`ComputeUnits::All`]. The granite
/// ModernBERT graph is ANE-capable (T1's `CPU_AND_NE` compile plan: 97.8% of ops
/// ANE-preferred); `All` lets CoreML schedule it — T1 saw the planner pick the
/// GPU on Macs for this small graph; `CpuAndNeuralEngine` targets the ANE.
/// Placement is characterized, not asserted (`tests/granite/placement.rs`).
pub const DEFAULT_COMPUTE: ComputeUnits = All;
/// Construction options for [`TextEmbedder`] (rust-options-pattern): a single
/// `compute` knob with one source of truth shared by `const new`/`Default`.
/// Options for [`TextEmbedder::embed_long_with`] and
/// [`TextEmbedder::embed_windows_with`] (rust-options-pattern) — both share this
/// one type: windit's chunk geometry ([`WindowOptions`]) plus granite's
/// pre-tokenization input bound.
///
/// The geometry is reachable whole ([`Self::window_options`]) and, for the tail
/// policy, one field at a time ([`Self::tail_policy`]). Neither requires naming
/// `windit`: [`WindowOptions`] and [`TailPolicy`] are both re-exported by this
/// module.
///
/// # Wire form
///
/// Serializable under the `serde` feature, which is what coremlit's `serde`
/// turning on `windit?/serde` buys — this type composes windit's
/// [`WindowOptions`], so it could not be derived while that crate carried no
/// impls. The geometry is windit's own document, nested under
/// `window_options`:
///
/// ```json
/// {"window_options":{"window":512,"hop":512,"tail":{"kind":"keep_with_coverage"},
/// "max_windows":null},"max_input_bytes":null}
/// ```
///
/// Both fields carry defaults, so a partial config fills the rest from
/// [`Self::new`] — `{}` deserializes to exactly it, the same convention
/// [`TextEmbedderOptions`] and the doors' `WindowPlan`s follow.
///
/// UNKNOWN KEYS ARE REFUSED, at this level and (windit's own rule) inside
/// `window_options`. Defaulted fields and a tolerated stray key compose into a
/// silent hole: `{"max_input_byte":4096}` — the plural dropped — would
/// otherwise deserialize to `max_input_bytes: None`, and
/// [`TextEmbedder::embed_long_with`] (or, sharing this same options type,
/// [`TextEmbedder::embed_windows_with`]) would then run with NO size gate on
/// its input, which is the one bound a caller sets for untrusted text. The
/// misspelling is a hard error naming the key instead.
///
/// That refusal makes this type UNFLATTENABLE: serde's `deny_unknown_fields`
/// and `flatten` do not compose (a flattened field sees the outer struct's
/// other keys and rejects them), so a config type composing these options must
/// NEST them under a key of its own — `long_text = { … }` — not
/// `#[serde(flatten)]` them into itself.
///
/// # Binary formats
///
/// The document above is a human-readable one; this type ALSO round-trips
/// through a non-self-describing format (postcard and friends), under every
/// tail policy. That is windit's contract, not coremlit's — the nested geometry
/// is windit's own type — and it holds only from windit 0.5: 0.4 tagged
/// `TailPolicy` adjacently through the derive, which writes the tag as a struct
/// FIELD and reads it back through `deserialize_identifier`, so a format
/// carrying no field names refused EVERY variant and a `LongTextOptions`
/// serialized to bytes it could not read back. windit 0.5 asks for the adjacent
/// shape itself (a `deserialize_struct` visitor serving both `visit_map` and
/// `visit_seq`), which leaves the document above byte-identical while making the
/// compact form readable. `long_text_options_round_trip_through_postcard` pins
/// it here, variant by variant.
/// The [`LongTextOptions::window_options`] serde default: the same full-window
/// geometry [`LongTextOptions::new`] builds, so an omitted key and an omitted
/// options value agree.
/// **This spelling is persisted by downstream derivation fingerprints — change
/// it only with a major bump.**
///
/// `key=value` pairs in declaration order, joined by `,`: [`Self::window_options`]
/// nests [`WindowOptions`]'s own `Display` in parentheses — composed verbatim,
/// not re-derived, so windit 0.5.1 is the one place that nested spelling can
/// change and a drift there fails the same pinning test this one does — and
/// [`Self::max_input_bytes`] prints its `usize` when set or `none` when absent,
/// the same identity fold windit's own `max_windows` uses: `Option` folds to
/// `none`, never to a gap.
///
/// For example, `LongTextOptions::new()` prints
/// `window_options=(window=512,hop=512,tail=keep_with_coverage,max_windows=none),max_input_bytes=none`.
/// One planned window of a long text and the embedding of exactly that window —
/// the element type of [`TextEmbedder::embed_windows`].
///
/// It carries what a consumer needs to score windows independently and attach
/// its own provenance to a hit, without re-deriving the geometry:
///
/// * [`ordinal`](Self::ordinal) — position in planning order, `0..n`. The
/// OCCURRENCE IDENTITY: two windows whose text is byte-identical (a repeated
/// paragraph) embed to the same vector, so nothing else distinguishes them.
/// * [`byte_start`](Self::byte_start) / [`byte_end`](Self::byte_end) — the
/// window's half-open range in UTF-8 bytes of the `text` that was passed in,
/// `char`-aligned, exactly the chunk the planner cut. Slice the caller's own
/// string with it ([`byte_range`](Self::byte_range)).
/// * [`token_span`](Self::token_span) — the window's placement in TOKENS:
/// `start()` is the running sum of the preceding windows' token counts (a
/// position in the concatenated window token stream, not an index into `text`
/// — under a non-zero overlap the repeated tokens are counted twice, which is
/// the double weighting the overlap expresses), `len()` is this window's own
/// token count including the [`SPECIAL_TOKENS_PER_WINDOW`] specials
/// ([`token_count`](Self::token_count)), and `window()` is [`MAX_TOKENS`]. Its
/// `coverage()` is the weight [`TextEmbedder::embed_long`] aggregates with.
/// * [`embedding`](Self::embedding) — the unit-norm 384-d [`Embedding`] of that
/// window's bytes alone, from one CoreML prediction.
///
/// This is not windit's `Windowed` (aliased there as `WindowEmbedding`, hence
/// the name collision): that is a value plus a `Span`, and this adds the anchor
/// into the caller's own text and the occurrence identity.
/// [`TextEmbedder::embed_long`] builds windit's pairing from the embedding and
/// the token span, and never sees the other two.
///
/// # No `PartialEq`
///
/// Deliberately, and for [`Embedding`]'s own reason: an ML model's f32 outputs
/// are not bit-stable across runs, threads, or OSes, so `==` on a value carrying
/// one is a trap. Compare the geometry field by field, and the vectors with
/// [`Embedding::is_close`] / [`Embedding::is_close_cosine`]:
///
/// ```compile_fail,E0369
/// # fn f(a: &coremlit::embeddings::granite::WindowEmbedding,
/// # b: &coremlit::embeddings::granite::WindowEmbedding) -> bool {
/// a == b
/// # }
/// ```
///
/// For the same reason this type carries no `serde` impls: neither [`Embedding`]
/// nor windit's `Span` has any, and a persisted window vector is a
/// storage-format decision (fp16? quantized? which index?) that belongs to the
/// consumer, not to this door.
/// granite text embedder: a `&str` in, a unit-norm 384-d [`Embedding`] out.
///
/// Tokenizes with the granite tokenizer (truncation `LongestFirst` at
/// [`MAX_TOKENS`] and the tokenizer's own padding disabled, matching the goldens'
/// convention so token ids are identical), right-pads to the fixed `[1, 512]`
/// window with an attention mask, runs the fp16 CoreML ModernBERT graph, and
/// L2-normalizes the pre-normalization CLS projection.
/// Overrides the loaded tokenizer's truncation and padding policy to this
/// module's fixed-window contract, so the contract holds for ANY tokenizer
/// (artifact-read or caller-supplied) regardless of what it carried:
///
/// * **Truncation** `LongestFirst` at [`MAX_TOKENS`], stride 0, right direction —
/// the convention the committed goldens were tokenized under (fixed 512, right
/// truncation), so this module's token ids match them exactly. The export
/// sequence length is a hard model constraint, not a knob.
/// * **Padding disabled** (`with_padding(None)`) — this module does its own
/// fixed-window right-padding in [`build_window`] and masks the pad positions.
/// Leaving an inherited padding policy in place would let pad ids reach
/// [`TextEmbedder::token_ids`] marked as real tokens (corrupt mask), push the
/// CLS token off position 0 under left-padding (wrong CLS pooling), or overflow
/// the window under fixed-padding beyond 512.
///
/// The tokenizer is a caller input on the `from_files` path, so this is also
/// where its special-token overhead is checked against the window (see
/// [`SpecialTokenOverhead`]) — before [`validate_tokenizer_contract`]'s sentinel
/// encode, because the overhead breaks the CONFIGURATION, not the encoding.
///
/// # Errors
/// [`Error::SpecialTokenOverhead`] if the tokenizer's post-processor adds at
/// least [`MAX_TOKENS`] special tokens, leaving no room for text;
/// [`Error::TokenizerConfig`] if the tokenizer rejects the truncation policy.
/// Validates a tokenizer against the Granite model contract, fail-closed: a
/// parseable-but-foreign tokenizer would otherwise produce finite, unit-norm,
/// semantically meaningless embeddings, or emit ids past the model's embedding
/// table that gather to zeros and surface only as a misleading
/// [`Error::EmbeddingZero`]. Run by every constructor on the CONFIGURED tokenizer
/// (after [`configure_tokenizer`]), so the sentinel check proves the exact
/// production [`TextEmbedder::token_ids`] behavior.
///
/// Checks, first failure wins: the three special-token ids, the total vocabulary
/// size, the maximum token id (the out-of-vocabulary gate), then the pinned
/// sentinel encoding. `validate_tokenizer_identity` has already refused anything
/// that is not the pinned artifact, byte for byte, so these behavioral checks now
/// re-derive from those bytes what the pin already guarantees: they are the
/// backstop that would still hold if the pin ever stopped covering a path, and
/// the gate the hermetic `configured_tokenizer_from_bytes` seam runs against.
///
/// # Errors
/// [`Error::TokenizerContractMismatch`] naming the first failed check;
/// [`Error::Tokenize`] if the sentinel encode itself fails.
/// Lowercase-hex SHA-256 of `bytes` — the tokenizer-identity digest. Mirrors the
/// dev-time provenance folds (`granite/tests.rs`, `tests/granite/common`).
/// Read from the model artifact's own [`TOKENIZER_FILE_NAME`] sidecar
/// ([`TextEmbedder::load`] / [`TextEmbedder::from_file`]): the lowercase-hex
/// SHA-256 of the file's RAW bytes, plus the path they came from — a wrong or
/// truncated staged artifact must say WHICH file failed.
///
/// Payload of [`TokenizerProvenance::Artifact`].
/// Where a constructor's tokenizer bytes came from — carried so the
/// byte-identity backstop ([`validate_tokenizer_identity`]) can name the source
/// in its diagnostic. Both variants are checked against the same pin: nothing is
/// compiled in any more, so no tokenizer is identity-by-construction.
/// The artifact-root path [`TextEmbedder::load`] reads its tokenizer from: the
/// directory CONTAINING `model_path`, joined with [`TOKENIZER_FILE_NAME`].
///
/// The published bundle lays the artifact out with `tokenizer.json` beside the
/// `.mlmodelc` (its `CHECKSUMS.sha256` lists `./granite_97m_512.mlmodelc/...`
/// with the siblings at `./`). A `model_path` with no parent component yields
/// the bare file name, i.e. the current directory — the same place `.mlmodelc`
/// itself would resolve from.
/// Byte-identity backstop for EVERY tokenizer this module loads, fail-closed.
/// granite is a FIXED model, so exactly one tokenizer artifact is correct — the
/// pinned `tokenizer.json`, SHA-256 [`contract::TOKENIZER_SHA256_HEX`]. The
/// behavioral contract ([`validate_tokenizer_contract`]) runs FIRST (named,
/// actionable diagnostics for accidentally foreign tokenizers); this then catches
/// what no behavioral spot-check can — corruption or version skew outside the
/// sentinel's coverage (swapped vocab entries, divergent merges, normalizer
/// drift) that would silently produce wrong embeddings. A re-serialized but
/// behaviorally identical tokenizer is rejected BY DESIGN: supply the pinned
/// artifact bytes instead.
///
/// The artifact sidecar goes through the same gate as caller-supplied bytes:
/// once the tokenizer is a file on disk rather than compiled-in, "identity by
/// construction" no longer holds, and an unverified sidecar would be strictly
/// weaker than the embedded bytes it replaced.
///
/// # Why this runs before `Tokenizer::from_bytes`
///
/// Every constructor judges its RAW bytes here FIRST, so foreign bytes are never
/// handed to the tokenizers parser at all. That ordering is what closes the
/// dependency's own hazard: a `TemplateProcessing` that the tokenizers builder
/// would reject still DESERIALIZES (the crate's deserializer skips its builder's
/// `validate`), and applying it panics — indexing a `special_tokens` map that
/// does not carry the id, or `encodings[1]` for a single sequence. Because this
/// door pins one exact artifact, refusing before the parse costs nothing and
/// leaves no reachable path to that panic. The doors that accept an UNPINNED
/// tokenizer cannot rely on ordering and check the template's structure
/// explicitly instead (`embeddings::tokenizer_guard`).
///
/// The cost is a diagnostic one, and it is deliberate: an accidentally foreign
/// tokenizer is now named by its digest rather than by the first behavioral
/// difference [`validate_tokenizer_contract`] would have found. The remedy is the
/// same either way — supply the pinned artifact bytes.
///
/// # Errors
/// [`Error::TokenizerContractMismatch`] with `check = "tokenizer identity
/// (sha-256)"` (caller-supplied) or `"artifact tokenizer identity (sha-256)"`
/// (the sidecar) if the digest differs from the pin.
/// Builds the fixed `[1, `[`MAX_TOKENS`]`]` `input_ids` / `attention_mask` window
/// from the real token `ids`: the real tokens occupy the prefix (mask `1`) and
/// the remainder is right-padded with `pad_id` (mask `0`). CLS therefore stays at
/// position 0 and no pad position is ever attended.
///
/// [`configure_tokenizer`] forces truncation at [`MAX_TOKENS`] and disables the
/// tokenizer's own padding, so `ids` is already real and within the window; this
/// still returns a typed [`Error`] rather than panicking should that contract
/// ever be violated (an over-long or out-of-range id must not become an
/// out-of-bounds write or a wrapping cast). The id conversion in particular is a
/// backstop rather than a live guard: [`validate_tokenizer_contract`] refuses any
/// vocabulary whose maximum id exceeds [`contract::MAX_TOKEN_ID`] (179_999), far
/// inside `i32::MAX`, so no tokenizer that reaches here can produce one.
///
/// # Errors
/// [`Error::TokenCount`] if `ids` exceeds [`MAX_TOKENS`]; [`Error::TokenIdRange`]
/// if a token id does not fit the model's `int32` `input_ids` tensor.
/// Rejects an oversized or mis-budgeted [`TextEmbedder::embed_long_with`] call
/// before any tokenizer or chunker work. Checked in order: the input byte limit
/// ([`Error::InputTooLarge`]), then the per-chunk budget
/// ([`Error::WindowOverBudget`]) — an over-budget window would let
/// [`TextEmbedder::token_ids`] silently truncate every chunk. Reads only
/// `text.len()` and the options — O(1), no tokenizer access — so the reject
/// path's cost is independent of the input size by construction. Factored out so
/// the check is hermetically testable. `window == 0` and `overlap >= window` are
/// left to windit's own validation (surfacing as [`Error::Windowing`]).
///
/// # Errors
/// [`Error::InputTooLarge`] if `text` exceeds
/// [`LongTextOptions::max_input_bytes`]; [`Error::WindowOverBudget`] if the
/// window exceeds [`MAX_TOKENS`].
/// The pure text-splitting stage of [`TextEmbedder::embed_long`]: token-budgeted,
/// boundary-aware byte ranges over `text`, measured with `measure_tok` (the
/// truncation-disabled tokenizer). Model-free, so the chunk geometry is
/// hermetically testable.
///
/// The chunks jointly cover `text`: windit's `ContentAware` extracts tokenized
/// content only, leaving separator bytes (paragraph breaks, whitespace-only
/// interiors, and word-fallback inter-word punctuation) uncovered at chunk
/// boundaries, so [`attach_gaps`] reattaches every such gap — re-measuring the
/// repaired substring against the window — before the chunks are returned. With
/// `overlap == 0` the chunks partition `text` (the first starts at byte 0, each
/// begins where the previous ends, the last ends at `text.len()`); a non-zero
/// overlap covers `text` while preserving its repeats. A
/// [`TailPolicy::DropBelowMin`] tail is a THIRD source of uncovered bytes, from
/// windit 0.5 (see [`LongTextOptions::tail_policy`]): the repair covers it like
/// any other gap, so the policy shifts the last boundary and never drops text.
/// Nonempty text always yields at least one chunk: text that chunks to nothing
/// — no tokenizable content at all (whitespace-only), or a lone chunk the tail
/// policy dropped — becomes a single whole-input chunk, the cost of the
/// whole-input `embed` fallback it is embedded by. Only `""` yields no
/// chunks.
///
/// Measurement and per-chunk embedding run the SAME tokenization
/// (`encode(s, add_special_tokens = true)`) on the SAME substring, so a chunk
/// measured at `<= window <= MAX_TOKENS` re-tokenizes to exactly the counted ids
/// and [`build_window`] never truncates or rejects it. Every chunk returned has
/// an untruncated measure `<= MAX_TOKENS`, with a single exception: windit's
/// lone oversized `char` (one `char` encodes to at most a handful of ids, far
/// below [`MAX_TOKENS`], so it can exceed a small `window` but never the model
/// window). Both contentless escapes — a pure-separator gap [`attach_gaps`]
/// would emit as its own chunk, and the whole-input fallback chunk for text with
/// no tokenizable content — are now MEASURED and refused past [`MAX_TOKENS`]
/// with [`Error::ContentlessInputOverBudget`] rather than silently truncated by
/// the embed path. The production tokenizer's truncation therefore never engages
/// on the `embed_long` path.
///
/// # Errors
/// [`Error::Windowing`] carrying whatever windit's `ContentAware::chunk` rejects
/// (a zero window, an overlap at or above the window, or a `max_windows`
/// overrun), or `TooManyWindows` raised here when gap reattachment or the
/// whole-input fallback chunk grows the final list past `opts.max_windows()`
/// — the cap binds the FINAL chunk count, exactly the per-chunk predictions
/// [`TextEmbedder::embed_long_with`] dispatches, `got` reporting that full
/// count (windit's own raise aborts at `max + 1`; this one reports the whole
/// overrun); [`Error::ContentlessInputOverBudget`] if a contentless run that
/// must be embedded whole (the whole input, or a pure-separator gap
/// [`attach_gaps`] emits) measures past [`MAX_TOKENS`] — measured at synthesis,
/// BEFORE the `max_windows` re-check; [`Error::Tokenize`] if the measuring
/// tokenizer fails to encode such a run.
/// Reattaches the byte gaps windit leaves between chunks, so [`chunk_long`]'s
/// output covers every byte of `text`. windit's `ContentAware` extracts
/// tokenized content only: paragraph separators (`\n\n` runs), whitespace-only
/// paragraph interiors, and — under its oversized-sentence word fallback — the
/// whitespace and punctuation between words are excluded, so a gap opens wherever
/// such bytes fall on a chunk boundary (including a leading gap before the first
/// chunk and a trailing gap after the last). A tail windit discarded under
/// [`TailPolicy::DropBelowMin`] is a trailing gap of the same kind, and is
/// reattached the same way — always as its own chunk, since the discarded tail
/// is by construction content its predecessor had no room for, so step 1 below
/// cannot take it.
///
/// A single left-to-right sweep closes every positive gap by re-measuring the
/// exact candidate substring against `window` (BPE is not additive — the repaired
/// range is re-measured, never assumed to gain a fixed token count), trying in
/// order:
///
/// 1. append the gap to the left neighbor if the extended range still fits —
/// left-first because terminal punctuation and paragraph breaks belong to the
/// preceding content, and it keeps every chunk starting where content starts;
/// 2. otherwise prepend it to the right neighbor if that range fits;
/// 3. otherwise emit the gap as its own chunk (pure separator bytes), reachable
/// only when both neighbors are already packed to exactly `window`.
///
/// With `overlap == 0` the result partitions `text`: the first chunk starts at
/// byte 0, each starts where the previous ends, the last ends at `text.len()`,
/// and the chunks concatenate back to `text`. With `overlap > 0` the pre-existing
/// overlaps are negative gaps, left untouched, so coverage is completed without
/// disturbing the repeats. The sweep never fuses two input chunks — each maps to
/// exactly one output chunk — so the output count is the input count plus one
/// per own-chunk emitted; [`chunk_long`] re-enforces `max_windows` on that
/// final count.
///
/// Every accepted attachment re-measures within `window`. A pure-separator
/// own-chunk (emitted when neither neighbor can absorb the gap) may still exceed
/// `window` up to [`MAX_TOKENS`] — the same tolerance as windit's lone
/// oversized-`char` escape — but its run is MEASURED, and a gap measuring past
/// [`MAX_TOKENS`] is refused with [`Error::ContentlessInputOverBudget`] rather
/// than left for the embed path to silently truncate. Every constructed boundary
/// is a windit cut or `0`/`text.len()`, all on `char` boundaries, so `Chunk::new`
/// never straddles a `char` and `as_str` never returns `None`.
///
/// # Errors
/// [`Error::ContentlessInputOverBudget`] if a pure-separator gap emitted as its
/// own chunk measures more than [`MAX_TOKENS`] tokens; [`Error::Tokenize`] if
/// the measuring tokenizer fails to encode a candidate substring (surfaced here,
/// one call earlier than the per-chunk `token_ids` would).
/// Builds the pure-separator own-chunk spanning the `start..end` byte range,
/// measuring its run first: a gap measuring past [`MAX_TOKENS`] would be silently
/// right-truncated by the embed path (dropping its suffix tokens), so it is
/// refused with [`Error::ContentlessInputOverBudget`] instead. The `(window,
/// MAX_TOKENS]` tolerance is kept — the same shape as windit's lone oversized
/// `char`.
///
/// # Errors
/// [`Error::ContentlessInputOverBudget`] if the run exceeds [`MAX_TOKENS`];
/// [`Error::Tokenize`] if the measuring tokenizer fails to encode it.
/// Test-only seam: the module's actual tokenizer configuration, without loading
/// a CoreML model — so `tests` can exercise the real tokenization path
/// hermetically (the tokenizer-identity gate).
pub
/// Test-only seam: the module's MEASURING tokenizer — the production
/// configuration ([`configured_tokenizer_from_bytes`]) with truncation then
/// DISABLED — without loading a CoreML model, so `tests` can exercise the real
/// `chunk_long` measurement path (and pin the truncation hazard) hermetically.
pub
/// Human-readable `shape dtype` rendering for [`Error::ContractMismatch`].