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
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
//! Local embedding-model **load factory** + a `model_type` →
//! constructor [`EmbeddingModelTypeRegistry`], ported from the local-path
//! slice of
//! [`mlx_embeddings.utils`](https://github.com/Blaizzy/mlx-embeddings/blob/main/mlx_embeddings/utils.py)
//! (`load` / `load_model` / `load_config` / `_get_model_arch`) and
//! `mlx-swift-lm`'s `MLXEmbedders` (`EmbedderModelFactory._load` /
//! `EmbedderTypeRegistry` / `EmbedderModelContext`).
//!
//! This is the embeddings twin of [`crate::lm::factory`] — it is **structurally
//! mirrored** on that module — and turns a local model directory into a
//! constructed [`EmbeddingModel`] + [`Tokenizer`] + (optional) pooling-config
//! bundle:
//!
//! - [`EmbeddingModelConfiguration`] — the model's *location* (mlx-swift-lm's
//! `ModelConfiguration`). An [`EmbeddingIdentifier::Id`] (an org/name string)
//! is treated as a **local path** — there is **no** Hugging Face Hub download
//! (the `snapshot_download` network slice of `mlx_embeddings.utils
//! .get_model_path` is deliberately out of scope). An optional
//! [`tokenizer_source`](EmbeddingModelConfiguration::tokenizer_source) lets
//! the tokenizer load from a different local directory; when `None` the model
//! directory is reused.
//! - [`EmbeddingModelTypeRegistry`] — `model_type: &str` → an
//! [`EmbeddingModelConstructor`] closure, mirroring mlx-swift-lm's
//! `EmbedderTypeRegistry`'s `ModelTypeRegistry<EmbeddingModel>` and replacing
//! `_get_model_arch`'s Python `importlib.import_module(
//! "mlx_embeddings.models.{model_type}")` dynamic dispatch with an explicit,
//! compile-time-safe registration table. Per-model architectures are **out of
//! scope** (the project's no-model-arch rule), so the registry is the
//! *extension point* future per-usecase model PRs register their constructor
//! into — this layer ships the seam, not the architectures.
//! - [`load()`] — the end-to-end entry: resolve the directory → parse the
//! `config.json` `model_type` → look it up in the registry (after
//! [`remap_model_type`], mirroring `_get_model_arch`) → load the weights + the
//! tokenizer + the optional `1_Pooling/config.json` → invoke the constructor →
//! return a [`LoadedEmbeddingContext`].
//!
//! ## Shared loaders reused (not re-implemented)
//!
//! The `embeddings` feature is deliberately `serde_json`-free (the
//! `1_Pooling/config.json` parse is a hand-rolled strict-JSON scanner) and does
//! **not** enable the `lm` feature, so [`crate::lm::load`]'s
//! `serde`-derived `Config` reader is unreachable here. "Reuse the shared
//! loaders" therefore means reusing the *lower*, ungated layers `lm::load`
//! itself builds on:
//!
//! - **weights** — [`crate::io::load_safetensors`], the exact lowest-level
//! loader `lm::load::load_weights` calls;
//! - **tokenizer** — [`Tokenizer::from_path`], the exact call
//! `lm::load::load_tokenizer` wraps (and which
//! [`crate::embeddings::encode()`] already uses);
//! - **pooling config** — the existing
//! [`pooling_from_st_config_path`](crate::embeddings::pooling_from_st_config_path)
//! (mlx-embeddings' `_read_pooling_config`).
//!
//! Only the `config.json` `model_type` read is module-local: it needs a single
//! string field, so a small dependency-free extractor reads it
//! with the same bounded-read discipline (`O_NONBLOCK | O_CLOEXEC` open,
//! post-open `is_file()` reject, `Read::take` cap) as
//! [`crate::embeddings::config`]'s pooling-config reader — the discipline
//! `lm::load`'s reader is itself modeled on.
//!
//! Conventions match the rest of `embeddings`: every fallible step returns
//! [`Result`], recoverable failures (missing/invalid config, no weights,
//! unknown `model_type`, tokenizer load, malformed pooling config) are
//! [`Error::Backend`] with a message naming the cause, borrows are preferred
//! over clones, and there is no implicit eval (the weight `Array`s are handed
//! to the constructor lazily).
use ;
use ;
use crateRankMismatchPayload;
use crate::;
/// Upper bound on a `config.json` we will read into memory, mirroring
/// [`crate::embeddings::config`]'s `MAX_ST_POOLING_CONFIG_BYTES` (and
/// `lm::load`'s `MAX_CONFIG_BYTES`). A real model's `config.json` is well under
/// 1 MiB; a hostile model directory cannot make us allocate unbounded memory by
/// planting a huge `config.json`.
const MAX_CONFIG_BYTES: u64 = 1 << 20;
/// Architecture-id remapping, mirroring `mlx_embeddings.utils.MODEL_REMAPPING`:
/// some checkpoints declare a `model_type` that is an alias for another
/// architecture's implementation. [`remap_model_type`] applies this (after the
/// `-`→`_` normalization) before an [`EmbeddingModelTypeRegistry`] lookup so a
/// registry only needs to register the *canonical* id.
///
/// `mlx_embeddings.utils.MODEL_REMAPPING` is currently the **empty dict**
/// `{}` — there are no embedding-model aliases upstream — so this table is
/// likewise empty. It is kept (rather than dropped) so the structure mirrors
/// [`crate::lm::factory`]'s `MODEL_REMAPPING` and a future upstream alias is a
/// one-line addition. Sorted by key for a deterministic, reviewable table.
const MODEL_REMAPPING: & = &;
/// Canonicalize a checkpoint's `model_type`, mirroring
/// `mlx_embeddings.utils._get_model_arch`'s
/// `model_type = config["model_type"].replace("-", "_")` **followed by**
/// `MODEL_REMAPPING.get(model_type, model_type)`.
///
/// Unlike [`crate::lm::factory::remap_model_type`] (whose
/// `mlx_lm` counterpart does *not* normalize separators), `mlx_embeddings`
/// replaces every `-` with `_` first — so `"xlm-roberta"` canonicalizes to
/// `"xlm_roberta"`. Because that step rewrites the string, this returns an
/// owned [`String`] rather than a borrow. An id with no `-` and no alias is
/// returned unchanged (as an owned copy).
/// Which local directory holds an embedding model (mlx-swift-lm's
/// `ModelConfiguration.Identifier`).
///
/// **No network**: an [`Id`](Self::Id) (an org/name string) is treated as a
/// *local path* — the already-local branch of
/// `mlx_embeddings.utils.get_model_path` (`Path(path_or_hf_repo)` when
/// `model_path.exists()`); the `snapshot_download` Hub fetch is out of scope.
/// So both variants resolve to a [`Path`] without any I/O beyond the later
/// directory read in [`load()`].
/// Where to load an embedding model and (optionally) its tokenizer from,
/// ported from the **local-path slice** of mlx-swift-lm's `ModelConfiguration`.
///
/// Behavioural metadata that mlx-swift-lm's `ModelConfiguration` carries
/// (`defaultPrompt` / `extraEOSTokens` / `toolCallFormat`) is intentionally
/// **not** modeled here: an embedding encoder does not generate (no eos /
/// chat / tool concerns). This type is purely the *source location* (model dir
/// + optional separate tokenizer dir).
/// A flat name → [`Array`] weight map (mlx-embeddings' `weights` dict /
/// `mx.load(...)` result, the [`crate::io::load_safetensors`] return type).
///
/// Keys carry mlx-embeddings' subfolder `<folder>.<key>` namespacing for shards
/// loaded from a nested component directory (see [`load()`]'s weight discovery);
/// a root-level shard's keys are verbatim. [`load()`] performs no further
/// `sanitize`/remap — architecture-specific key rewriting is the per-usecase
/// constructor's responsibility (exactly as [`crate::lm::load`] leaves it), but
/// the multi-component subfolder prefix is applied at load time to match
/// `mlx_embeddings.utils.load_model`.
pub type EmbeddingWeights = ;
/// Everything [`load()`] resolved from a model directory, handed to an
/// [`EmbeddingModelConstructor`] so it can assemble a concrete architecture
/// without re-reading the directory.
///
/// The embeddings twin of [`crate::lm::factory::LoadedModel`]. Borrowing — the
/// constructor gets `&LoadedEmbeddingModel`; it reads the
/// [`model_type()`](Self::model_type), the verbatim
/// [`config_json()`](Self::config_json) (the analogue of mlx-swift-lm passing the
/// raw `config.json` `Data` to each model's `Decodable` init), and takes the
/// weight [`Array`]s it needs out of [`weights_ref()`](Self::weights_ref) **by
/// reference** (no implicit eval; mlx `Array` is a cheap refcounted handle).
/// A registered embedding-model constructor: assemble an [`EmbeddingModel`]
/// from the already-resolved [`LoadedEmbeddingModel`] (model type + raw config
/// JSON + weights).
///
/// Mirrors mlx-swift-lm's `EmbedderTypeRegistry` creator `(Data) throws ->
/// EmbeddingModel` — but receives the *already-loaded* weights too (so a
/// per-usecase architecture never re-globs/re-reads the directory) and returns
/// a [`Result`] (Rust's `throws`). `Send + Sync` so a registry can be shared
/// across threads (e.g. a `static` shared registry, as mlx-swift-lm's
/// `EmbedderTypeRegistry.shared` is). The constructor itself does **no** I/O;
/// the directory was already read by [`load()`].
pub type EmbeddingModelConstructor =
;
/// A `model_type: String` → [`EmbeddingModelConstructor`] table, the load
/// factory's architecture **extension point**.
///
/// The embeddings twin of [`crate::lm::factory::ModelTypeRegistry`]. Mirrors
/// mlx-swift-lm's `EmbedderTypeRegistry`'s `ModelTypeRegistry<EmbeddingModel>`
/// (and replaces `mlx_embeddings.utils._get_model_arch`'s `importlib` dynamic
/// dispatch with an explicit registration table). Per-model architectures are
/// out of scope for this layer, so the registry starts [`empty`](Self::new);
/// future per-usecase model PRs call [`register`](Self::register) (or build one
/// with [`with`](Self::with)) to plug their architecture in. A `model_type` is
/// canonicalized via [`remap_model_type`] on both registration and lookup, so
/// callers register the *canonical* id and any alias / `-`-spelled variant
/// resolves to it.
/// The product of [`load()`]: a constructed [`EmbeddingModel`] plus the
/// [`Tokenizer`], the canonicalized `model_type`, and the optional
/// `1_Pooling/config.json` pooling configuration.
///
/// Mirrors [`crate::lm::factory::LoadedModelContext`] **and** mlx-swift-lm's
/// `EmbedderModelContext` — which, unlike the LM `ModelContext`, additionally
/// carries the `pooling` it resolved from `1_Pooling/config.json` (mlx-swift-lm
/// `loadPooling`). Here that is the optional [`StPoolingConfig`].
/// Load an embedding model + tokenizer from a local
/// [`EmbeddingModelConfiguration`], dispatching to `registry` on the
/// checkpoint's `model_type`.
///
/// The end-to-end port of `mlx_embeddings.utils.load` restricted to the
/// local-path, no-network surface (and mlx-swift-lm's
/// `EmbedderModelFactory._load`). The orchestration order is chosen so the
/// *cheap, recoverable* failures come first — nothing heavy (weights,
/// tokenizer) is touched until the checkpoint is known to be loadable:
///
/// 0. Reject an **empty** model-directory (or, if a separate
/// [`tokenizer_source`](EmbeddingModelConfiguration::tokenizer_source) is
/// set, tokenizer-directory) path **up front** — before any `config.json`,
/// pooling, or shard/glob resolution. An empty directory argument is a
/// caller bug: it is not normalized to `"."`, it is rejected with a
/// recoverable [`Error::Backend`]. The reason this cannot be left to the
/// later steps is shard discovery — `collect_glob_shards` builds its glob
/// pattern as `"<dir>/<suffix>"`, so an empty `<dir>` yields the *absolute*
/// pattern `"/**/model*.safetensors"`, which recursively scans the
/// filesystem root `/` and could merge unrelated `safetensors` from outside
/// the intended directory (a filesystem-escape + wrong-weight load). The
/// same up-front spirit as the non-UTF-8 model-dir-path rejection in
/// `collect_glob_shards`, hoisted ahead of *all* I/O.
/// 1. Resolve the model directory
/// ([`EmbeddingModelConfiguration::model_directory`] — local, no Hub
/// download) and read the `config.json` `model_type` **once** (bounded,
/// dependency-free), canonicalizing it with [`remap_model_type`].
/// 2. **Validate the `model_type` is registered** *before* loading anything
/// heavy: an unsupported checkpoint is a cheap, recoverable
/// [`Error::Backend`] here, with no weight/tokenizer I/O — mlx-embeddings'
/// `ValueError("Model type … not supported.")` / mlx-swift-lm's
/// `unsupportedModelType`.
/// 3. Read the optional `1_Pooling/config.json` via
/// [`pooling_from_st_config_path`](crate::embeddings::pooling_from_st_config_path)
/// (absent ⇒ `None`; a malformed *present* file ⇒ `Err`) — cheap,
/// recoverable metadata, validated **before** the heavy weight/tokenizer
/// loads so a broken pooling config fails fast.
/// 4. Select the tokenizer directory
/// ([`tokenizer_source`](EmbeddingModelConfiguration::tokenizer_source) if
/// set, else the model directory — mlx-swift-lm's `tokenizerDirectory`).
/// 5. Discover and merge the weights from the model directory (reusing
/// [`crate::io::load_safetensors`]), recursively including nested-component
/// shards with mlx-embeddings' `<folder>.` key prefix.
/// 6. Build the [`Tokenizer`] from the selected directory via
/// [`Tokenizer::from_path`].
/// 7. Construct the model via `registry` and return it with the tokenizer, the
/// canonical `model_type`, and the optional pooling config.
///
/// Per-model construction is the registry's job (this layer ships no
/// architectures). No implicit eval — the weights reach the constructor lazily.
/// Reject an **empty** directory path with a recoverable [`Error::Backend`].
///
/// `role` is the human label for the path being checked (`"model"` /
/// `"tokenizer"`), so the message names which directory the caller passed
/// empty. An empty [`Path`] is a caller bug — it is *not* silently normalized
/// to the current directory (`"."`); see [`load()`] step 0 for why an empty
/// model directory in particular is dangerous (the absolute `"/**/…"` shard
/// pattern → filesystem-root scan).
///
/// The check is `Path::as_os_str().is_empty()` — a byte/`OsStr`-level test, so
/// it is correct for a non-UTF-8 path too and never panics. A path that is
/// merely whitespace or `"."` is *not* empty and is left to the existing I/O
/// steps to resolve or reject; only the genuinely empty path is caught here.
/// Role of the directory checked by [`reject_empty_dir`]. Routing through
/// a closed enum keeps the [`EmptyInputPayload::context`] static so the
/// no-`format!` contract holds (no runtime-keyed label allocation).
/// Read `<dir>/1_Pooling/config.json` if present, mirroring
/// `mlx_embeddings.utils._read_pooling_config` (`return None` when the file is
/// absent) and mlx-swift-lm's `loadPooling`.
///
/// A **genuinely absent** `1_Pooling/config.json` (or no `1_Pooling` directory
/// at all) is the common case for a plain HF encoder checkpoint and yields
/// `Ok(None)`. A **present** entry is parsed via
/// [`pooling_from_st_config_path`](crate::embeddings::pooling_from_st_config_path)
/// (the existing bounded, hand-rolled strict-JSON reader); a malformed present
/// file therefore propagates as an [`Error::Backend`] rather than being
/// silently dropped — a planted broken pooling config is a recoverable error,
/// not a silently-wrong pooling strategy.
///
/// The presence probe is [`Path::symlink_metadata`] (an `lstat` — it does
/// **not** follow symlinks), *not* [`Path::exists`]: `exists()` collapses every
/// error — a broken symlink, a symlink loop, permission-denied, any metadata
/// failure — into `false`, so a *present-but-unresolvable* pooling config would
/// be silently treated as ABSENT and the loader would fall back to the wrong
/// pooling strategy/dimension with no diagnostic. With `symlink_metadata`:
///
/// - `Ok(_)` on the CHILD `1_Pooling/config.json` ⇒ an entry *is* present —
/// including a **broken symlink** at the child, which an `lstat` reports as
/// the link itself rather than erroring `NotFound`. The parse proceeds:
/// [`pooling_from_st_config_path`] opens (following symlinks) and a
/// broken/looping link, or a non-regular target, is rejected there as a
/// typed [`Error::FileIo`]. A "present but bad" config is thus an error,
/// never silently-absent.
/// - `Err(NotFound)` on the CHILD ⇒ the child path itself does not resolve;
/// this is **ambiguous** — the parent `1_Pooling` may be genuinely absent
/// (the common case ⇒ `Ok(None)`), OR it may be present-but-broken (a
/// dangling symlink whose target dir does not exist, in which case an
/// `lstat` on any child path returns `NotFound` even though `1_Pooling`
/// exists as a directory entry). A SECOND probe disambiguates by `lstat`ing
/// `1_Pooling` itself: if that returns `Ok` on a symlink whose followed
/// target does not exist (or fails to resolve), we fail closed with a typed
/// [`Error::FileIo`] rather than silently degrading.
/// - any other `Err` (permission-denied, …) on the CHILD ⇒ a
/// present-but-unresolvable config ⇒ an [`Error::FileIo`] naming the path,
/// never `Ok(None)`.
/// A discovered weight shard: its full path plus the **key prefix** to apply to
/// every tensor name it contributes (mlx-embeddings' subfolder rename), or
/// `None` for a root-level shard whose keys are merged verbatim.
/// Discover and merge an embedding model's weights from `dir`, mirroring the
/// weight-loading half of `mlx_embeddings.utils.load_model`.
///
/// Resolution order (a faithful port of `load_model`'s two `glob.glob` passes —
/// see [`collect_glob_shards`] for the [`glob`]-crate mechanics):
///
/// 1. **Sharded / single safetensors, RECURSIVELY:** every `model*.safetensors`
/// anywhere under `dir` —
/// `glob.glob(str(model_path / "**/model*.safetensors"), recursive=True)`
/// (mlx-embeddings `utils.py` line 159) — iterated in **sorted full-path
/// order** for a deterministic merge — [`crate::io::load_safetensors`] each
/// and `extend(...)` (later shard wins on a duplicate key, which a
/// well-formed shard set never produces). Covers both `model.safetensors`
/// and `model-00001-of-000NN.safetensors`, at the root and in nested
/// component folders (e.g. a ColVision-style `vision_model/model.safetensors`
/// + `text_model/model.safetensors`).
/// 2. **Back-compat `weight*.safetensors` (root only):** if there is no
/// `model*.safetensors` anywhere, mlx-embeddings `load_model` retries
/// `glob.glob(str(model_path / "weight*.safetensors"))` (`utils.py` line
/// 163) — the legacy layout, **not** recursive (no `**`) — and so does this
/// loader. The fallback fires only on a genuinely empty `model*.safetensors`
/// match: a `model*.safetensors` path `glob` *yields* but
/// [`crate::io::load_safetensors`] cannot load (a non-regular target — see
/// [`collect_glob_shards`]'s stat gate) makes step 1 **error**, so a corrupt
/// primary shard fails the load loudly rather than silently degrading to a
/// stale legacy snapshot.
///
/// **Nested-shard key prefixing (mlx-embeddings parity):** a shard found in a
/// *child* directory has every tensor key rewritten to `<folder>.<key>` before
/// merge, where `folder` is the shard's **immediate** parent-directory name —
/// exactly `load_model`'s
/// `folder_name = Path(wf).parent.name; new_key = f"{folder_name}.{key}"` (so a
/// deeper `a/b/model.safetensors` prefixes with `b`, not `a.b`). Root-level
/// shards (`Path(wf).parent == model_path`) keep their keys verbatim. The
/// prefix is computed from the **glob-returned** path's immediate parent (which,
/// for a symlinked component dir, is the *link* name — `glob` yields the path it
/// walked, not the symlink's canonical target). This is the one place the
/// embeddings factory diverges from [`crate::lm::load::load_weights`]'s flat,
/// verbatim merge: multi-component embedding models (vision + text) ship
/// per-component shard folders the loader must namespace, and the prefixing is
/// done **here** (per shard, then merge), leaving the shared
/// [`crate::io::load_safetensors`] and the lm loader untouched. GGUF is not a
/// `mlx_embeddings` weight path and is not handled.
///
/// No safetensors at all → [`Error::Backend`] (mlx-embeddings'
/// `FileNotFoundError("No safetensors found in {model_path}")`).
/// Run one `glob` pass under `dir` for the relative `pattern_suffix` (e.g.
/// `"**/model*.safetensors"` or `"weight*.safetensors"`), returning the matched
/// shards — each with its mlx-embeddings `<folder>.` key prefix already computed
/// — sorted by full path.
///
/// This is the faithful port of `mlx_embeddings.utils.load_model`'s
/// `glob.glob(str(model_path / "<suffix>"), recursive=True)`. Using the
/// maintained [`glob`] crate (`rust-lang/glob`) — rather than a hand-rolled
/// recursive directory walk — is what makes the Python-`glob` corner semantics
/// faithful by construction:
///
/// - **`**` recursion** is built into the pattern grammar: with the
/// `"**/model*.safetensors"` suffix `glob` matches `model*.safetensors` at the
/// model dir itself *and* in every subdirectory, exactly Python's
/// `recursive=True`. The legacy `"weight*.safetensors"` suffix has no `**`, so
/// it is root-only — matching `utils.py` line 163.
/// - **`include_hidden=False`** (Python `glob`'s default) excludes any path
/// whose name — at *any* component below the model dir — starts with `.`, so a
/// `.hidden/model.safetensors` directory shard and a root `.model.safetensors`
/// file shard are both excluded. The natural spelling would be
/// [`MatchOptions::require_literal_leading_dot`]` = true`, but `glob 0.3.3`
/// implements that hidden-filter by calling `file_name().to_str().unwrap()` on
/// **every** scanned directory child (`glob-0.3.3/src/lib.rs:953-955`) — a
/// single non-UTF-8 sibling name on a mounted NFS/exFAT/case-sensitive volume
/// would then *panic the process*. So the field is left `false` (which gates
/// off that `unwrap` path entirely) and the `.`-component exclusion is
/// re-implemented here ([`path_has_hidden_component`]) directly on the
/// returned `PathBuf`s' `OsStr` components — no UTF-8 unwrap, panic-free for
/// any filesystem.
/// - **`require_literal_separator` is forced `true`** by `glob_with` regardless
/// of the field, so a `*` never matches across a `/` — `model*.safetensors`
/// matches one path component, as in Python.
/// - **`case_sensitive` is `true`**: `model.safetensors` is matched, `MODEL.SAFETENSORS`
/// is not — Python `glob` is case-sensitive on a case-sensitive filesystem.
/// - **Directory symlinks are followed, and `scandir`/`OSError`s are
/// suppressed**, by the crate: a symlinked component directory is descended
/// (its shard discovered with the *link* name as the immediate-parent prefix),
/// a symlink **cycle** terminates (the crate does not recurse forever), and an
/// unreadable nested directory yields a per-entry [`glob::GlobError`] that is
/// **skipped** here (`continue`) so one bad subdirectory never aborts a load
/// whose real shards live elsewhere — matching Python `glob`, which swallows
/// the `scandir` `OSError`. (`**` recursion has no separate depth cap: the
/// crate bounds the walk itself, so the old hand-rolled `MAX_WEIGHT_DIR_DEPTH`
/// sanity ceiling is gone — there is no unbounded *our-code* recursion left to
/// guard.)
///
/// **Fail-loud on a `model*.safetensors`-named non-regular entry.** `glob`'s
/// match is **name-based** (like Python `glob`): a *directory*, a
/// symlink-to-directory, a FIFO/device, or a **dangling symlink** named
/// `model.safetensors` *is* yielded by the pattern. Each yielded path is
/// therefore `stat`-ed here (via [`std::fs::metadata`], which dereferences
/// symlinks) and a non-regular — or unresolvable — target is rejected with a
/// recoverable [`Error::Backend`] **naming the offending path**. This is the
/// explicit-stat form of the prior rounds' fail-loud contract: a broken
/// primary shard must fail the load, never silently vanish and let
/// [`load_weights`] degrade to a stale `weight*.safetensors` fallback. (HF Hub
/// snapshots store shards as symlinks into `blobs/<hash>`; a *valid* such
/// symlink resolves to a regular file and passes.)
///
/// **Non-UTF-8 paths — fully closed by a byte-level preflight.** Every path
/// component (the model dir, an intermediate directory, an immediate parent
/// folder, or the shard's own leaf file name) that is not valid UTF-8 is either
/// handled or produces a clean [`Error::Backend`] *before* a stale fallback can
/// fire:
///
/// - **Model dir path:** `glob_with` takes a `&str` pattern and internally
/// `unwrap()`s `Path::to_str()` on it, so a model directory whose own path is
/// not valid UTF-8 would *panic* inside the crate. It is rejected up front
/// here with a recoverable [`Error::Backend`].
/// - **Immediate parent folder:** the match is name-based, so a legitimately
/// -named (ASCII) `model*.safetensors` shard sitting in a *child directory
/// whose folder name is non-UTF-8* is yielded by the pattern, yet that
/// non-UTF-8 immediate-parent name cannot become the `String` key prefix —
/// that shard is rejected with a recoverable [`Error::Backend`] naming its
/// path (rather than silently mis-merging its keys as if it were a root
/// shard) by the prefix-derivation step below.
/// - **Shard leaf file name:** `glob 0.3.3` matches a non-recursive pattern
/// component via `file_name().and_then(|s| s.to_str())` and `continue`s on
/// `None` (`glob-0.3.3/src/lib.rs:463-467`, `// FIXME (#9639)`). So a
/// directory entry whose own leaf name is *not* valid UTF-8 — e.g. Unix bytes
/// `model\xff.safetensors` — is **never yielded** by `glob`, even though it
/// matches the `model*.safetensors` shard predicate. Left unchecked, such a
/// primary shard is silently dropped and [`load_weights`] degrades to a stale
/// `weight*.safetensors` fallback with no error. To close that hole,
/// [`collect_glob_shards`] runs a [`scan_non_utf8_shards`] **byte-level
/// preflight** alongside the `glob` pass: it inspects every entry's leaf name
/// at the `OsStr`/byte level (no `to_str`), and if any non-UTF-8 leaf matches
/// a shard pattern it returns an [`Error::Backend`] naming the path before
/// any weights are merged.
///
/// A non-UTF-8 *descendant* name that does **not** match a shard pattern is
/// simply skipped: with `require_literal_leading_dot: false` `glob` no longer
/// runs its `to_str().unwrap()` hidden-filter over directory children, so a
/// non-UTF-8 sibling on a mounted NFS/exFAT/case-sensitive volume no longer
/// panics the walk — it just does not match the ASCII pattern. The literal
/// `dir` portion of the pattern is [`glob::Pattern::escape`]d so a real
/// directory name containing a glob metacharacter (`*`, `?`, `[`, `]`) is
/// matched literally, not interpreted — only the `pattern_suffix` carries
/// pattern metacharacters.
///
/// A malformed *pattern* (a [`glob::PatternError`]) would be a bug in this
/// fixed, escaped pattern, not untrusted input, and maps to [`Error::Backend`].
/// `true` if `path` has a hidden (`.`-prefixed) component *strictly below* the
/// `root` model directory — the explicit, panic-free port of Python `glob`'s
/// `include_hidden=False` (and of `glob 0.3.3`'s `require_literal_leading_dot`,
/// which we cannot use directly: its implementation `unwrap()`s
/// `file_name().to_str()` on every scanned child and so panics on a non-UTF-8
/// sibling name — see [`collect_glob_shards`]).
///
/// Each component name is inspected as an [`OsStr`](std::ffi::OsStr) with **no
/// UTF-8 conversion**: on Unix via [`OsStrExt::as_bytes`] (testing the first
/// byte for `b'.'`), elsewhere via a lossy view. Either way this never panics on
/// a non-UTF-8 name — a non-UTF-8 component simply does not begin with an ASCII
/// `.` and so is not treated as hidden.
///
/// Only components *below* `root` are checked: the model directory the user
/// pointed at is theirs to name (it may itself sit under a `.`-prefixed path)
/// and matches Python `glob`, which only filters path segments it itself walked
/// *under* the glob root. The shard file name is included in the check — a
/// `.model.safetensors` is hidden — but `model*.safetensors` / `weight*.safetensors`
/// never begin with `.`, so a legitimate shard name is unaffected.
/// `true` if the OS string `name` begins with an ASCII `.`, inspected without a
/// UTF-8 unwrap so a non-UTF-8 file name can never panic the check.
/// The model directory `dir` re-expressed in the **exact path shape the
/// [`glob`] crate yields matched paths in**, so a glob result can be
/// [`strip_prefix`](Path::strip_prefix)ed against it.
///
/// `glob` does **not** preserve a leading current-directory (`.`) component:
/// walking the pattern `"./**/model*.safetensors"` it yields a root shard as
/// `model.safetensors` — *not* `./model.safetensors` — and a root shard under
/// `"./model/..."` as `model/model.safetensors`, *not* `./model/...`. (It also
/// drops any further interior `.` segment of the pattern's `dir` portion.) A
/// raw `dir` of `"."` / `"./sub"` therefore is **not** a prefix of what glob
/// returns, and the previous `path.parent() == dir` test in
/// [`collect_glob_shards`] mis-classified a valid root shard as nested.
///
/// This rebuilds `dir` keeping only the components glob keeps:
/// [`Component::Normal`](std::path::Component) names, a leading
/// [`RootDir`](std::path::Component)/[`Prefix`](std::path::Component) (so an
/// absolute `dir` stays absolute — glob yields absolute results verbatim), and
/// [`ParentDir`](std::path::Component) (`..`) segments, while **dropping every
/// [`CurDir`](std::path::Component) (`.`)** — exactly glob's own normalization.
/// `"."` and `"./"` collapse to the **empty** path, which `strip_prefix` treats
/// as the identity prefix (every relative glob result strips cleanly against
/// it). No `canonicalize`, no symlink resolution: the result is purely a
/// lexical re-spelling of `dir`, so a symlinked component directory still
/// contributes its on-disk *link* name to the key prefix — the documented
/// behavior. Operates on [`OsStr`](std::ffi::OsStr) components, so a non-UTF-8
/// directory name is carried through losslessly and never panics.
/// `true` if the OS string `name`'s **bytes** start with `prefix` and end with
/// `suffix` — the byte-level form of the `glob` shard predicate (`model*` /
/// `weight*` ... `*.safetensors`), evaluated with **no UTF-8 conversion** so a
/// non-UTF-8 leaf file name can be tested without a `to_str` (which `glob`'s
/// own matcher would drop on `None`).
///
/// On Unix the raw bytes are read via [`OsStrExt::as_bytes`]; elsewhere a lossy
/// view is used (non-Unix has no byte accessor, and a lossy view still cannot
/// panic — the ASCII `model`/`weight`/`.safetensors` literals survive any lossy
/// conversion intact, so a non-Unix host never mis-classifies a real shard).
/// Byte-level **preflight** for [`collect_glob_shards`]: detect any directory
/// entry whose **leaf file name is not valid UTF-8** yet matches a shard
/// pattern, and fail loudly with an [`Error::Backend`] naming it — *before* the
/// `glob` pass and the weight merge.
///
/// This is the structural backstop for `glob 0.3.3`'s non-recursive leaf match,
/// which reads `file_name().and_then(|s| s.to_str())` and silently `continue`s
/// on `None` (`glob-0.3.3/src/lib.rs:463-467`, `// FIXME (#9639)`). A non-UTF-8
/// -named `model*.safetensors` primary shard would therefore never be yielded
/// by `glob`, and [`load_weights`] would silently degrade to a stale
/// `weight*.safetensors` fallback. Detecting it here turns that silent
/// mis-load into a clean, recoverable error.
///
/// The scan **mirrors the two `glob` passes** [`collect_glob_shards`] runs,
/// dispatching on `pattern_suffix`:
///
/// - `"**/model*.safetensors"` → match a leaf whose bytes start with `b"model"`
/// and end with `b".safetensors"`, searched **recursively** (like the `**`
/// glob), descending every subdirectory.
/// - `"weight*.safetensors"` → match a leaf whose bytes start with `b"weight"`
/// and end with `b".safetensors"`, at the **root only** (the legacy fallback
/// glob has no `**`).
///
/// The SAME hidden-component exclusion the `glob` path applies
/// ([`path_has_hidden_component`] / [`starts_with_dot`]) is honoured: a
/// `.`-prefixed directory is *not* descended and a `.`-prefixed entry is *not*
/// flagged, so the preflight never errors on a path the `glob` pass would
/// itself skip (a non-UTF-8 leaf can never *itself* be hidden — it does not
/// begin with an ASCII `.` — but it may sit under a hidden ancestor). Recursion
/// uses [`std::fs::read_dir`] (no new crate dependency).
///
/// An **IO error is suppressed**, exactly as the `glob` pass suppresses a
/// `scandir` `OSError` (Python `glob` does likewise, and `collect_glob_shards`
/// `continue`s past a per-entry `GlobError`): a `read_dir` that fails — an
/// unreadable subdirectory, or even an unreadable model root — makes the
/// preflight skip that subtree rather than error. This keeps "one unreadable
/// nested directory must not abort a load whose real shards live elsewhere"
/// intact; and an unreadable directory's entries cannot be enumerated by `glob`
/// either, so there is no hidden non-UTF-8 shard to mis-load there. The
/// preflight changes behavior in exactly one way: a non-UTF-8 leaf that `glob`
/// *could* see (its parent is readable) but silently drops now errors.
///
/// The preflight only needs to **detect-and-error**: it does not replicate the
/// `glob` crate's sort order, symlink-cycle termination, or
/// regular-file/`stat` gate — those remain the `glob` pass's job for the
/// valid-UTF-8 shards it does yield. Entry **type is intentionally not
/// inspected**: a non-UTF-8 *directory* named `model\xff.safetensors` would
/// equally be yielded by `glob`'s name-based match (and rejected by the stat
/// gate); flagging any non-UTF-8 shard-named entry, file or not, keeps the
/// fail-loud contract complete.
///
/// **Known limitation (deliberate scope decision).** Recursion descends only
/// real directories (`file_type().is_dir()`, with a fallible `path().is_dir()`
/// fallback) — it does **not** follow directory *symlinks*, whereas the `glob`
/// pass does. So a non-UTF-8-named shard inside a *symlinked* component
/// directory is invisible to both the preflight (does not descend the symlink)
/// and `glob` (silently drops the non-UTF-8 leaf); a model directory stacking a
/// symlinked component dir + a non-UTF-8 shard name + a stale legacy
/// `weight*.safetensors` could then fall back to the legacy file instead of
/// erroring. This contrived layout is accepted as **out of scope** per E3's
/// "match the reference, trust the input" decision (see the project follow-ups
/// doc, `DEFERRED-3`); real Hugging Face model directories neither symlink
/// component directories nor use non-UTF-8 filenames.
/// Read `<dir>/config.json` **once**, returning the canonicalized
/// `model_type` (via [`remap_model_type`]) and the verbatim JSON body it was
/// extracted from.
///
/// Mirrors `mlx_embeddings.utils.load_config`'s `open(model_path /
/// "config.json")` followed by `_get_model_arch`'s `config["model_type"]`
/// lookup — but extracts only the single `model_type` field the load factory
/// dispatches on (the full typed config is the per-usecase architecture's
/// `Decodable` concern, fed the raw [`String`]).
///
/// The read is bounded against an untrusted model directory exactly as
/// [`crate::embeddings::config`]'s pooling-config read: open **once** (closing
/// the stat-then-read TOCTOU window), reject a non-regular file (FIFO / device
/// / directory / symlink-to-special) **before any read**, and cap the body at
/// [`MAX_CONFIG_BYTES`] via `Read::take`. On Unix the open carries
/// `O_NONBLOCK | O_CLOEXEC` so a planted FIFO returns immediately instead of
/// hanging the caller; symlinks are intentionally followed (HF Hub caches store
/// `config.json` as a symlink into `blobs/<hash>`) since the post-open
/// `is_file()` fstat enforces the guarantee on the *resolved* target. Every
/// failure path (absent, non-regular, oversized, unreadable, invalid JSON,
/// missing / non-string `model_type`) is a recoverable [`Error::Backend`].
/// Extract a single top-level string field `key` from a strict-JSON object
/// `src`, **dependency-free** (the `embeddings` feature carries no
/// `serde_json`).
///
/// Returns `Ok(Some(value))` when `key` is present with a JSON string value,
/// `Ok(None)` when `key` is absent, and `Err` when `src` is not a JSON object,
/// is structurally malformed, or `key` is present with a non-string value.
///
/// This is intentionally *not* the full [`crate::embeddings::config`]
/// strict-JSON scanner — that one is purpose-built for `1_Pooling/config.json`
/// (its `KNOWN_KEYS` schema and "pooling config" error text). The load factory
/// needs exactly one string field (`model_type`) from `config.json`, so this
/// is a minimal top-level-object walker: it parses each `"key": value` pair,
/// captures the matched string, and *skips* every other value (strings,
/// numbers, `true`/`false`/`null`, and — to find their end — nested
/// objects/arrays) with a depth cap so a hostile `config.json` cannot
/// stack-overflow the walker.
///
/// **Duplicate-key semantics match a real JSON parser:** if `key` appears more
/// than once at the top level, the **last** occurrence wins — exactly what
/// `serde_json` deserialization into a struct field and Python's `json.load`
/// (which keeps the last value for a duplicate key) both do. Each occurrence's
/// value is still required to be a JSON string (a non-string duplicate is
/// rejected), and every occurrence is fully parsed/validated.
///
/// The whole top-level object is validated to its closing `}` even after the
/// key is found, so a truncated / malformed `config.json` whose `model_type`
/// happens to be the first key (e.g. `{"model_type": "bert"` with no close) is
/// rejected rather than silently accepted — the file must be well-formed JSON.
/// Numbers are validated against the RFC 8259 grammar
/// (`-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?`), so a malformed number anywhere in
/// the object (`01`, `1.`, `1e`) rejects the whole config as invalid JSON
/// rather than being silently accepted.
/// After the top-level object's closing `}` is consumed, reject any trailing
/// non-whitespace bytes (a strict-JSON document is a single value) and return
/// the captured result.
/// Hard cap on nested object/array depth [`extract_string_field`]'s value-skip
/// will descend. A 1-MiB-capped `config.json` could otherwise pack hundreds of
/// thousands of `[`/`{` at one position; without this guard
/// [`JsonCursor::skip_value`]'s recursion would overflow the thread stack on
/// hostile model data (turning a malformed `config.json` into an abort instead
/// of a recoverable error). 128 levels covers every realistic HF
/// `config.json` — they are shallow — yet caps stack growth at a constant.
const MAX_JSON_DEPTH: usize = 128;
/// A byte cursor over a strict-JSON `config.json`, used by
/// [`extract_string_field`]. Deliberately tiny — it understands just enough
/// JSON to walk a flat top-level object and skip arbitrarily-typed values.