ripvec-core 1.2.0

Semantic code + document search engine. Cacheless static-embedding + cross-encoder rerank by default; optional ModernBERT/BGE transformer engines with GPU backends. Tree-sitter chunking, hybrid BM25 + PageRank, composable ranking layers.
Documentation
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
//! MLX lazy-evaluation GPU driver for Apple Silicon.
//!
//! Implements the [`Driver`] trait using [`MlxTensor`] as the tensor type.
//! Every driver method builds a lazy computation graph — no GPU work happens
//! until [`to_host`](Driver::to_host) calls `eval()`. This preserves MLX's
//! graph fusion optimisations.
//!
//! # Design
//!
//! - **`type Tensor = MlxTensor`**: wraps `mlx_rs::Array` with `Send + Sync`.
//! - **`begin_batch` / `end_batch`**: no-ops. MLX is always lazy; the
//!   architecture calls `eval()` implicitly via `to_host`.
//! - **Reshapes are free**: MLX reshapes are metadata-only (no data movement).
//! - **`Array::clone()` is cheap**: reference-counted, no copy.

use std::collections::HashMap;

use hf_hub::api::sync::Api;
use mlx_rs::Array;
use mlx_rs::ops::indexing::TryIndexOp;

use super::{BatchInputs, Driver};
use crate::backend::Encoding;
use crate::backend::arch::classic_bert::{
    ClassicBertArch, ClassicBertLayerWeights, ClassicBertWeights,
};
use crate::backend::generic::GenericBackend;

/// Convert an MLX exception into our crate error type.
fn mlx_err(e: impl std::fmt::Display) -> crate::Error {
    crate::Error::Other(anyhow::anyhow!("MLX driver: {e}"))
}

// ---------------------------------------------------------------------------
// MlxDriver
// ---------------------------------------------------------------------------

/// Wrapper around `mlx_rs::Array` that is `Send + Sync`.
///
/// MLX arrays are reference-counted handles to lazy computation graph nodes.
/// The underlying Metal resources are managed by MLX's runtime, which is
/// thread-safe at the API level (one eval at a time). We enforce single-
/// threaded access through the `embed_distributed` architecture (GPU backends
/// are not cloned).
pub struct MlxTensor(pub Array);

// SAFETY: MLX arrays are reference-counted handles. The MLX runtime serialises
// GPU operations internally. Our pipeline ensures single-threaded forward-pass
// access (GPU backends are not cloned).
#[expect(unsafe_code, reason = "MLX runtime serialises GPU access")]
unsafe impl Send for MlxTensor {}
#[expect(unsafe_code, reason = "MLX runtime serialises GPU access")]
unsafe impl Sync for MlxTensor {}

impl Clone for MlxTensor {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

/// Stateless MLX compute driver.
///
/// MLX manages its own Metal device, command queues, and memory internally.
/// The driver is just a namespace for [`Driver`] trait methods — all state
/// lives in the lazy [`MlxTensor`] handles themselves.
pub struct MlxDriver;

impl MlxDriver {
    /// Create a new MLX driver.
    ///
    /// MLX initialises its Metal backend on first array operation, so this
    /// is essentially free.
    pub fn new() -> crate::Result<Self> {
        Ok(Self)
    }
}

// ---------------------------------------------------------------------------
// Driver trait implementation
// ---------------------------------------------------------------------------

impl Driver for MlxDriver {
    type Tensor = MlxTensor;

    fn name(&self) -> &'static str {
        "MLX"
    }

    // begin_batch / end_batch: no-ops. MLX is always lazy.

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn alloc_zeros(&self, n: usize) -> crate::Result<MlxTensor> {
        Array::zeros::<f32>(&[n as i32])
            .map_err(mlx_err)
            .map(MlxTensor)
    }

    fn clone_tensor(&self, tensor: &MlxTensor, _n: usize) -> crate::Result<MlxTensor> {
        // MLX arrays are reference-counted; clone just bumps the refcount.
        Ok(tensor.clone())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        clippy::cast_precision_loss,
        reason = "token IDs, masks, and type IDs from tokenizer are always small non-negative values"
    )]
    fn prepare_batch(
        &self,
        encodings: &[Encoding],
        max_seq: usize,
    ) -> crate::Result<BatchInputs<MlxTensor>> {
        let batch = encodings.len();
        let total = batch * max_seq;

        let mut input_ids = vec![0_i32; total];
        let mut attn_mask_int = vec![0_i32; total];
        let mut token_type_ids = vec![0_i32; total];
        let mut position_ids = vec![0_i32; total];
        let mut float_mask = vec![0.0_f32; total];
        let mut pooling_mask = vec![0.0_f32; total];

        for (b, enc) in encodings.iter().enumerate() {
            let offset = b * max_seq;
            let seq_len = enc.input_ids.len();
            for (i, (&id, (&mask, &typ))) in enc
                .input_ids
                .iter()
                .zip(enc.attention_mask.iter().zip(enc.token_type_ids.iter()))
                .enumerate()
            {
                input_ids[offset + i] = id as i32;
                attn_mask_int[offset + i] = mask as i32;
                token_type_ids[offset + i] = typ as i32;
                position_ids[offset + i] = i as i32;
                // Real token: 0.0 (pass-through); pad: -1e9 (kill softmax)
                float_mask[offset + i] = if mask == 1 { 0.0 } else { -1e9 };
                pooling_mask[offset + i] = mask as f32;
            }
            // Pad positions beyond seq_len stay 0 (default).
            // Float mask for pad positions is already -1e9 (default 0.0 for
            // unset means pad, but we explicitly set real tokens above).
            // Fix: pad positions default to 0.0 float_mask, need -1e9.
            for i in seq_len..max_seq {
                float_mask[offset + i] = -1e9;
            }
        }

        let seq_lengths: Vec<usize> = encodings.iter().map(|e| e.input_ids.len()).collect();
        let total_tokens: usize = seq_lengths.iter().sum();
        let total_i32 = total as i32;
        Ok(BatchInputs {
            input_ids: MlxTensor(Array::from_slice(&input_ids, &[total_i32])),
            attention_mask: MlxTensor(Array::from_slice(&attn_mask_int, &[total_i32])),
            token_type_ids: MlxTensor(Array::from_slice(&token_type_ids, &[total_i32])),
            position_ids: MlxTensor(Array::from_slice(&position_ids, &[total_i32])),
            float_mask: MlxTensor(Array::from_slice(&float_mask, &[total_i32])),
            pooling_mask: MlxTensor(Array::from_slice(&pooling_mask, &[total_i32])),
            batch,
            max_seq,
            total_tokens,
            seq_lengths,
            cu_seqlens: None, // Padded mode
        })
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "token IDs, masks, and type IDs from tokenizer are always small non-negative values"
    )]
    fn prepare_batch_unpadded(
        &self,
        encodings: &[Encoding],
    ) -> crate::Result<BatchInputs<MlxTensor>> {
        let batch = encodings.len();
        let seq_lengths: Vec<usize> = encodings.iter().map(|e| e.input_ids.len()).collect();
        let total_tokens: usize = seq_lengths.iter().sum();
        let max_seq = seq_lengths
            .iter()
            .copied()
            .max()
            .unwrap_or(0)
            .next_multiple_of(8);

        let mut cu_seqlens = Vec::with_capacity(batch + 1);
        cu_seqlens.push(0);
        let mut cumsum = 0;
        for &len in &seq_lengths {
            cumsum += len;
            cu_seqlens.push(cumsum);
        }

        let mut input_ids = Vec::with_capacity(total_tokens);
        let mut token_type_ids = Vec::with_capacity(total_tokens);
        let mut position_ids = Vec::with_capacity(total_tokens);

        for enc in encodings {
            for (i, &id) in enc.input_ids.iter().enumerate() {
                input_ids.push(id as i32);
                token_type_ids.push(enc.token_type_ids[i] as i32);
                position_ids.push(i as i32);
            }
        }

        let padded_total = batch * max_seq;
        let mut attn_mask_int = vec![0_i32; padded_total];
        let mut float_mask = vec![-1e9_f32; padded_total];
        let mut pooling_mask = vec![0.0_f32; padded_total];

        for (b, &len) in seq_lengths.iter().enumerate() {
            let offset = b * max_seq;
            for i in 0..len {
                attn_mask_int[offset + i] = 1;
                float_mask[offset + i] = 0.0;
                pooling_mask[offset + i] = 1.0;
            }
        }

        Ok(BatchInputs {
            input_ids: MlxTensor(Array::from_slice(&input_ids, &[total_tokens as i32])),
            attention_mask: MlxTensor(Array::from_slice(&attn_mask_int, &[padded_total as i32])),
            token_type_ids: MlxTensor(Array::from_slice(&token_type_ids, &[total_tokens as i32])),
            position_ids: MlxTensor(Array::from_slice(&position_ids, &[total_tokens as i32])),
            float_mask: MlxTensor(Array::from_slice(&float_mask, &[padded_total as i32])),
            pooling_mask: MlxTensor(Array::from_slice(&pooling_mask, &[padded_total as i32])),
            batch,
            max_seq,
            total_tokens,
            seq_lengths,
            cu_seqlens: Some(cu_seqlens),
        })
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn pad_to_batch(
        &self,
        flat: &MlxTensor,
        padded: &mut MlxTensor,
        seq_lengths: &[usize],
        max_seq: usize,
        dim: usize,
    ) -> crate::Result<()> {
        // Perform on CPU — pad/unpad is a small, infrequent operation.
        // The large GEMMs remain fully lazy in MLX.
        let batch = seq_lengths.len();
        let total_out = batch * max_seq * dim;
        let mut out = vec![0.0_f32; total_out];

        // Eval flat to read data — synchronisation point.
        flat.0.eval().map_err(mlx_err)?;
        let flat_data: &[f32] = flat.0.as_slice();

        let mut offset = 0;
        for (b, &len) in seq_lengths.iter().enumerate() {
            for t in 0..len {
                let src = (offset + t) * dim;
                let dst = (b * max_seq + t) * dim;
                out[dst..dst + dim].copy_from_slice(&flat_data[src..src + dim]);
            }
            offset += len;
        }
        *padded = MlxTensor(Array::from_slice(&out, &[total_out as i32]));
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn unpad_from_batch(
        &self,
        padded: &MlxTensor,
        flat: &mut MlxTensor,
        seq_lengths: &[usize],
        max_seq: usize,
        dim: usize,
    ) -> crate::Result<()> {
        // Perform on CPU — pad/unpad is a small, infrequent operation.
        let _batch = seq_lengths.len();
        let total_tokens: usize = seq_lengths.iter().sum();
        let mut out = vec![0.0_f32; total_tokens * dim];

        // Eval padded to read data — synchronisation point.
        padded.0.eval().map_err(mlx_err)?;
        let padded_data: &[f32] = padded.0.as_slice();

        let mut offset = 0;
        for (b, &len) in seq_lengths.iter().enumerate() {
            for t in 0..len {
                let src = (b * max_seq + t) * dim;
                let dst = (offset + t) * dim;
                out[dst..dst + dim].copy_from_slice(&padded_data[src..src + dim]);
            }
            offset += len;
        }
        *flat = MlxTensor(Array::from_slice(&out, &[(total_tokens * dim) as i32]));
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn embedding_lookup(
        &self,
        word_ids: &MlxTensor,
        embedding_table: &MlxTensor,
        seq_len: usize,
        hidden: usize,
    ) -> crate::Result<MlxTensor> {
        let ids = mlx_rs::ops::reshape(&word_ids.0, &[seq_len as i32]).map_err(mlx_err)?;
        let table =
            mlx_rs::ops::reshape(&embedding_table.0, &[-1, hidden as i32]).map_err(mlx_err)?;
        let emb = table.try_index(&ids).map_err(mlx_err)?;
        // Flatten back to 1D: [seq_len * hidden]
        let flat = mlx_rs::ops::reshape(&emb, &[(seq_len * hidden) as i32]).map_err(mlx_err)?;
        Ok(MlxTensor(flat))
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn add_embeddings(
        &self,
        hidden: &mut MlxTensor,
        table: &MlxTensor,
        ids: &MlxTensor,
        seq_len: usize,
        hidden_dim: usize,
    ) -> crate::Result<()> {
        let ids_2d = mlx_rs::ops::reshape(&ids.0, &[seq_len as i32]).map_err(mlx_err)?;
        let table_2d = mlx_rs::ops::reshape(&table.0, &[-1, hidden_dim as i32]).map_err(mlx_err)?;
        let emb = table_2d.try_index(&ids_2d).map_err(mlx_err)?;
        let emb_flat =
            mlx_rs::ops::reshape(&emb, &[(seq_len * hidden_dim) as i32]).map_err(mlx_err)?;
        let h =
            mlx_rs::ops::reshape(&hidden.0, &[(seq_len * hidden_dim) as i32]).map_err(mlx_err)?;
        hidden.0 = mlx_rs::ops::add(&h, &emb_flat).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn layer_norm(
        &self,
        output: &mut MlxTensor,
        input: &MlxTensor,
        weight: &MlxTensor,
        bias: &MlxTensor,
        rows: usize,
        cols: usize,
        eps: f32,
    ) -> crate::Result<()> {
        let x = mlx_rs::ops::reshape(&input.0, &[rows as i32, cols as i32]).map_err(mlx_err)?;
        let w = mlx_rs::ops::reshape(&weight.0, &[cols as i32]).map_err(mlx_err)?;
        let b = mlx_rs::ops::reshape(&bias.0, &[cols as i32]).map_err(mlx_err)?;

        // Use mlx_rs::fast::layer_norm which is optimised
        let normed = mlx_rs::fast::layer_norm(&x, Some(&w), Some(&b), eps).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::reshape(&normed, &[(rows * cols) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::many_single_char_names,
        reason = "matches Driver trait signature (m, n, k)"
    )]
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn gemm(
        &self,
        a: &MlxTensor,
        b: &MlxTensor,
        output: &mut MlxTensor,
        m: usize,
        n: usize,
        k: usize,
        transpose_b: bool,
    ) -> crate::Result<()> {
        let a_2d = mlx_rs::ops::reshape(&a.0, &[m as i32, k as i32]).map_err(mlx_err)?;
        let b_2d = if transpose_b {
            // B is [n, k], need [k, n] for matmul
            let b_shaped = mlx_rs::ops::reshape(&b.0, &[n as i32, k as i32]).map_err(mlx_err)?;
            b_shaped.t()
        } else {
            mlx_rs::ops::reshape(&b.0, &[k as i32, n as i32]).map_err(mlx_err)?
        };
        let result = mlx_rs::ops::matmul(&a_2d, &b_2d).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::reshape(&result, &[(m * n) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::many_single_char_names,
        reason = "matches Driver trait signature (m, n, k)"
    )]
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn gemm_batched(
        &self,
        a: &MlxTensor,
        b: &MlxTensor,
        output: &mut MlxTensor,
        m: usize,
        n: usize,
        k: usize,
        transpose_b: bool,
        _stride_a: usize,
        _stride_b: usize,
        _stride_c: usize,
        batch_count: usize,
    ) -> crate::Result<()> {
        let bc = batch_count as i32;
        let a_3d = mlx_rs::ops::reshape(&a.0, &[bc, m as i32, k as i32]).map_err(mlx_err)?;
        let b_3d = if transpose_b {
            // B is [batch, n, k] stored flat, need [batch, k, n] for matmul
            let b_shaped =
                mlx_rs::ops::reshape(&b.0, &[bc, n as i32, k as i32]).map_err(mlx_err)?;
            mlx_rs::ops::transpose_axes(&b_shaped, &[0, 2, 1]).map_err(mlx_err)?
        } else {
            mlx_rs::ops::reshape(&b.0, &[bc, k as i32, n as i32]).map_err(mlx_err)?
        };
        let result = mlx_rs::ops::matmul(&a_3d, &b_3d).map_err(mlx_err)?;
        output.0 =
            mlx_rs::ops::reshape(&result, &[(batch_count * m * n) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn fused_scale_mask_softmax(
        &self,
        scores: &mut MlxTensor,
        mask: &MlxTensor,
        batch: usize,
        num_heads: usize,
        seq_len: usize,
        scale: f32,
    ) -> crate::Result<()> {
        let total_heads = (batch * num_heads) as i32;
        let s = seq_len as i32;

        // scores: [batch*num_heads, seq, seq], mask: [batch*seq] (flat)
        let sc = mlx_rs::ops::reshape(&scores.0, &[total_heads, s, s]).map_err(mlx_err)?;

        // Scale
        let scale_arr = Array::from_f32(scale);
        let scaled = mlx_rs::ops::multiply(&sc, &scale_arr).map_err(mlx_err)?;

        // Reshape mask to [batch, 1, 1, seq] for broadcasting over heads and query positions
        let mask_2d = mlx_rs::ops::reshape(&mask.0, &[batch as i32, s]).map_err(mlx_err)?;
        let mask_4d = mlx_rs::ops::reshape(&mask_2d, &[batch as i32, 1, 1, s]).map_err(mlx_err)?;

        // Reshape scores to [batch, num_heads, seq, seq] for broadcast with mask
        let scaled_4d = mlx_rs::ops::reshape(&scaled, &[batch as i32, num_heads as i32, s, s])
            .map_err(mlx_err)?;

        let masked = mlx_rs::ops::add(&scaled_4d, &mask_4d).map_err(mlx_err)?;

        // Softmax along last axis
        let softmaxed = mlx_rs::ops::softmax_axis(&masked, -1, None).map_err(mlx_err)?;

        // Flatten back
        let total = batch * num_heads * seq_len * seq_len;
        scores.0 = mlx_rs::ops::reshape(&softmaxed, &[total as i32]).map_err(mlx_err)?;
        Ok(())
    }

    fn fused_scale_mask_softmax_windowed(
        &self,
        scores: &mut MlxTensor,
        mask: &MlxTensor,
        batch: usize,
        num_heads: usize,
        seq_len: usize,
        scale: f32,
        window_size: usize,
    ) -> crate::Result<()> {
        // For now, delegate to non-windowed version.
        // Windowed attention is only used by ModernBERT; ClassicBert doesn't need it.
        // TODO: implement sliding window mask when adding ModernBERT MlxDriver support.
        let _ = window_size;
        self.fused_scale_mask_softmax(scores, mask, batch, num_heads, seq_len, scale)
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn build_attn_mask(
        &self,
        output: &mut MlxTensor,
        int_mask: &MlxTensor,
        n: usize,
    ) -> crate::Result<()> {
        // Convert int mask (0/1) to float mask (0.0 / -1e9)
        let mask_f32 = int_mask
            .0
            .as_dtype(mlx_rs::Dtype::Float32)
            .map_err(mlx_err)?;
        let ones = Array::ones::<f32>(&[n as i32]).map_err(mlx_err)?;
        let inverted = mlx_rs::ops::subtract(&ones, &mask_f32).map_err(mlx_err)?;
        let neg = Array::from_f32(-1e9_f32);
        output.0 = mlx_rs::ops::multiply(&inverted, &neg).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn qkv_split(
        &self,
        q: &mut MlxTensor,
        k: &mut MlxTensor,
        v: &mut MlxTensor,
        qkv: &MlxTensor,
        batch: usize,
        seq: usize,
        _hidden: usize,
        num_heads: usize,
        head_dim: usize,
    ) -> crate::Result<()> {
        let total_tokens = batch * seq;

        // qkv is flat [total_tokens * 3 * hidden]. Reshape to [total_tokens, 3, num_heads, head_dim].
        let qkv_4d = mlx_rs::ops::reshape(
            &qkv.0,
            &[total_tokens as i32, 3, num_heads as i32, head_dim as i32],
        )
        .map_err(mlx_err)?;

        // Extract Q, K, V along axis 1
        let q_3d = qkv_4d.try_index((.., 0, .., ..)).map_err(mlx_err)?;
        let k_3d = qkv_4d.try_index((.., 1, .., ..)).map_err(mlx_err)?;
        let v_3d = qkv_4d.try_index((.., 2, .., ..)).map_err(mlx_err)?;

        // Reshape from [total_tokens, num_heads, head_dim] to
        // [batch, seq, num_heads, head_dim] -> transpose to [batch, num_heads, seq, head_dim]
        // -> reshape to [batch*num_heads, seq, head_dim] -> flatten to 1D
        let reshape_head = |x: Array| -> crate::Result<Array> {
            let x = mlx_rs::ops::reshape(
                &x,
                &[batch as i32, seq as i32, num_heads as i32, head_dim as i32],
            )
            .map_err(mlx_err)?;
            let x = mlx_rs::ops::transpose_axes(&x, &[0, 2, 1, 3]).map_err(mlx_err)?;
            let x = mlx_rs::ops::reshape(
                &x,
                &[(batch * num_heads) as i32, seq as i32, head_dim as i32],
            )
            .map_err(mlx_err)?;
            mlx_rs::ops::reshape(&x, &[(batch * num_heads * seq * head_dim) as i32])
                .map_err(mlx_err)
        };

        q.0 = reshape_head(q_3d)?;
        k.0 = reshape_head(k_3d)?;
        v.0 = reshape_head(v_3d)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn attn_reshape(
        &self,
        output: &mut MlxTensor,
        input: &MlxTensor,
        batch: usize,
        seq: usize,
        num_heads: usize,
        head_dim: usize,
    ) -> crate::Result<()> {
        let hidden = num_heads * head_dim;
        // input: flat [batch * num_heads * seq * head_dim]
        // -> [batch, num_heads, seq, head_dim]
        // -> transpose [batch, seq, num_heads, head_dim]
        // -> reshape [batch*seq, hidden]
        // -> flatten [batch*seq*hidden]
        let x = mlx_rs::ops::reshape(
            &input.0,
            &[batch as i32, num_heads as i32, seq as i32, head_dim as i32],
        )
        .map_err(mlx_err)?;
        let x = mlx_rs::ops::transpose_axes(&x, &[0, 2, 1, 3]).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::reshape(&x, &[(batch * seq * hidden) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    fn apply_rope(
        &self,
        _qk: &mut MlxTensor,
        _cos: &MlxTensor,
        _sin: &MlxTensor,
        _num_rows: usize,
        _seq_len: usize,
        _head_dim: usize,
        _num_heads: usize,
    ) -> crate::Result<()> {
        // RoPE is used by ModernBERT, not ClassicBert. Implement when adding ModernBERT MLX support.
        Err(crate::Error::Other(anyhow::anyhow!(
            "MLX driver: apply_rope not yet implemented (ModernBERT support pending)"
        )))
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn split_gate_value(
        &self,
        first: &mut MlxTensor,
        second: &mut MlxTensor,
        input: &MlxTensor,
        rows: usize,
        cols: usize,
    ) -> crate::Result<()> {
        // input is flat [rows * 2 * cols]. Reshape to [rows, 2*cols], split at cols.
        let x =
            mlx_rs::ops::reshape(&input.0, &[rows as i32, (2 * cols) as i32]).map_err(mlx_err)?;
        let first_half = x.try_index((.., ..cols as i32)).map_err(mlx_err)?;
        let second_half = x.try_index((.., cols as i32..)).map_err(mlx_err)?;
        first.0 = mlx_rs::ops::reshape(&first_half, &[(rows * cols) as i32]).map_err(mlx_err)?;
        second.0 = mlx_rs::ops::reshape(&second_half, &[(rows * cols) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn gelu(&self, x: &mut MlxTensor, n: usize) -> crate::Result<()> {
        let reshaped = mlx_rs::ops::reshape(&x.0, &[n as i32]).map_err(mlx_err)?;
        let activated = mlx_rs::nn::gelu(&reshaped).map_err(mlx_err)?;
        x.0 = activated;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn swiglu(
        &self,
        value: &MlxTensor,
        gate: &MlxTensor,
        output: &mut MlxTensor,
        n: usize,
    ) -> crate::Result<()> {
        let v = mlx_rs::ops::reshape(&value.0, &[n as i32]).map_err(mlx_err)?;
        let g = mlx_rs::ops::reshape(&gate.0, &[n as i32]).map_err(mlx_err)?;
        let gate_activated = mlx_rs::nn::silu(&g).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::multiply(&v, &gate_activated).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn geglu(
        &self,
        value: &MlxTensor,
        gate: &MlxTensor,
        output: &mut MlxTensor,
        n: usize,
    ) -> crate::Result<()> {
        let v = mlx_rs::ops::reshape(&value.0, &[n as i32]).map_err(mlx_err)?;
        let g = mlx_rs::ops::reshape(&gate.0, &[n as i32]).map_err(mlx_err)?;
        let gelu_v = mlx_rs::nn::gelu(&v).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::multiply(&gelu_v, &g).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn fused_bias_gelu(
        &self,
        x: &mut MlxTensor,
        bias: &MlxTensor,
        rows: usize,
        cols: usize,
    ) -> crate::Result<()> {
        let x_2d = mlx_rs::ops::reshape(&x.0, &[rows as i32, cols as i32]).map_err(mlx_err)?;
        let b = mlx_rs::ops::reshape(&bias.0, &[1, cols as i32]).map_err(mlx_err)?;
        let biased = mlx_rs::ops::add(&x_2d, &b).map_err(mlx_err)?;
        let activated = mlx_rs::nn::gelu(&biased).map_err(mlx_err)?;
        x.0 = mlx_rs::ops::reshape(&activated, &[(rows * cols) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn fused_bias_residual(
        &self,
        output: &mut MlxTensor,
        input: &MlxTensor,
        bias: &MlxTensor,
        residual: &MlxTensor,
        n: usize,
        cols: usize,
    ) -> crate::Result<()> {
        let rows = n / cols;
        let inp = mlx_rs::ops::reshape(&input.0, &[rows as i32, cols as i32]).map_err(mlx_err)?;
        let b = mlx_rs::ops::reshape(&bias.0, &[1, cols as i32]).map_err(mlx_err)?;
        let res =
            mlx_rs::ops::reshape(&residual.0, &[rows as i32, cols as i32]).map_err(mlx_err)?;
        let biased = mlx_rs::ops::add(&inp, &b).map_err(mlx_err)?;
        let sum = mlx_rs::ops::add(&biased, &res).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::reshape(&sum, &[n as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn fused_residual_layernorm(
        &self,
        output: &mut MlxTensor,
        hidden: &MlxTensor,
        residual: &MlxTensor,
        weight: &MlxTensor,
        bias: &MlxTensor,
        rows: usize,
        cols: usize,
        eps: f32,
    ) -> crate::Result<()> {
        let h = mlx_rs::ops::reshape(&hidden.0, &[rows as i32, cols as i32]).map_err(mlx_err)?;
        let r = mlx_rs::ops::reshape(&residual.0, &[rows as i32, cols as i32]).map_err(mlx_err)?;
        let sum = mlx_rs::ops::add(&h, &r).map_err(mlx_err)?;
        let w = mlx_rs::ops::reshape(&weight.0, &[cols as i32]).map_err(mlx_err)?;
        let b = mlx_rs::ops::reshape(&bias.0, &[cols as i32]).map_err(mlx_err)?;
        let normed = mlx_rs::fast::layer_norm(&sum, Some(&w), Some(&b), eps).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::reshape(&normed, &[(rows * cols) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn residual_add(
        &self,
        output: &mut MlxTensor,
        hidden: &MlxTensor,
        residual: &MlxTensor,
        n: usize,
    ) -> crate::Result<()> {
        let h = mlx_rs::ops::reshape(&hidden.0, &[n as i32]).map_err(mlx_err)?;
        let r = mlx_rs::ops::reshape(&residual.0, &[n as i32]).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::add(&h, &r).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn add_bias(
        &self,
        x: &mut MlxTensor,
        bias: &MlxTensor,
        rows: usize,
        cols: usize,
    ) -> crate::Result<()> {
        let x_2d = mlx_rs::ops::reshape(&x.0, &[rows as i32, cols as i32]).map_err(mlx_err)?;
        let b = mlx_rs::ops::reshape(&bias.0, &[1, cols as i32]).map_err(mlx_err)?;
        let result = mlx_rs::ops::add(&x_2d, &b).map_err(mlx_err)?;
        x.0 = mlx_rs::ops::reshape(&result, &[(rows * cols) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn cls_pool(
        &self,
        output: &mut MlxTensor,
        hidden: &MlxTensor,
        batch: usize,
        seq: usize,
        hidden_dim: usize,
    ) -> crate::Result<()> {
        // hidden: flat [batch * seq * hidden_dim]
        // -> [batch, seq, hidden_dim] -> take [:, 0, :] -> flatten [batch * hidden_dim]
        let h = mlx_rs::ops::reshape(&hidden.0, &[batch as i32, seq as i32, hidden_dim as i32])
            .map_err(mlx_err)?;
        let cls = h.try_index((.., 0, ..)).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::reshape(&cls, &[(batch * hidden_dim) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn mean_pool(
        &self,
        output: &mut MlxTensor,
        hidden: &MlxTensor,
        mask: &MlxTensor,
        batch: usize,
        seq: usize,
        hidden_dim: usize,
    ) -> crate::Result<()> {
        // hidden: [batch*seq*hidden_dim] -> [batch, seq, hidden_dim]
        // mask: [batch*seq] -> [batch, seq, 1] for broadcasting
        let h = mlx_rs::ops::reshape(&hidden.0, &[batch as i32, seq as i32, hidden_dim as i32])
            .map_err(mlx_err)?;
        let m = mlx_rs::ops::reshape(&mask.0, &[batch as i32, seq as i32, 1]).map_err(mlx_err)?;

        // Masked sum: sum(hidden * mask, axis=1)
        let masked = mlx_rs::ops::multiply(&h, &m).map_err(mlx_err)?;
        let sum = masked.sum_axis(1, false).map_err(mlx_err)?; // [batch, hidden_dim]

        // Count: sum(mask, axis=1), clamp to avoid div-by-zero
        let count = m.sum_axis(1, false).map_err(mlx_err)?; // [batch, 1]
        let eps = Array::from_f32(1e-9_f32);
        let count = mlx_rs::ops::maximum(&count, &eps).map_err(mlx_err)?;

        let mean = mlx_rs::ops::divide(&sum, &count).map_err(mlx_err)?;
        output.0 = mlx_rs::ops::reshape(&mean, &[(batch * hidden_dim) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn l2_normalize(&self, data: &mut MlxTensor, rows: usize, cols: usize) -> crate::Result<()> {
        let x = mlx_rs::ops::reshape(&data.0, &[rows as i32, cols as i32]).map_err(mlx_err)?;
        let sq = x.square().map_err(mlx_err)?;
        let norms = sq
            .sum_axis(-1, true)
            .map_err(mlx_err)?
            .sqrt()
            .map_err(mlx_err)?;
        let eps = Array::from_f32(1e-12_f32);
        let norms = mlx_rs::ops::maximum(&norms, &eps).map_err(mlx_err)?;
        let normalized = mlx_rs::ops::divide(&x, &norms).map_err(mlx_err)?;
        data.0 = mlx_rs::ops::reshape(&normalized, &[(rows * cols) as i32]).map_err(mlx_err)?;
        Ok(())
    }

    fn banded_qk(
        &self,
        _q: &MlxTensor,
        _k: &MlxTensor,
        _scores: &mut MlxTensor,
        _bh: usize,
        _seq: usize,
        _hd: usize,
        _w: usize,
        _sqk: usize,
        _ss: usize,
    ) -> crate::Result<()> {
        Err(crate::Error::Other(anyhow::anyhow!(
            "banded_qk not implemented for MLX"
        )))
    }

    fn banded_sv(
        &self,
        _s: &MlxTensor,
        _v: &MlxTensor,
        _o: &mut MlxTensor,
        _bh: usize,
        _seq: usize,
        _hd: usize,
        _w: usize,
        _ss: usize,
        _sv: usize,
        _so: usize,
    ) -> crate::Result<()> {
        Err(crate::Error::Other(anyhow::anyhow!(
            "banded_sv not implemented for MLX"
        )))
    }

    fn banded_softmax(
        &self,
        _s: &mut MlxTensor,
        _rows: usize,
        _w: usize,
        _scale: f32,
    ) -> crate::Result<()> {
        Err(crate::Error::Other(anyhow::anyhow!(
            "banded_softmax not implemented for MLX"
        )))
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "mlx-rs requires i32 for shape params; ML tensor dims fit in i32"
    )]
    fn to_host(
        &self,
        tensor: &MlxTensor,
        batch: usize,
        dim: usize,
    ) -> crate::Result<Vec<Vec<f32>>> {
        let t = mlx_rs::ops::reshape(&tensor.0, &[batch as i32, dim as i32]).map_err(mlx_err)?;
        let t = t.as_dtype(mlx_rs::Dtype::Float32).map_err(mlx_err)?;
        // ALL computation happens here — eval triggers the entire lazy graph.
        t.eval().map_err(mlx_err)?;
        let flat: &[f32] = t.as_slice();
        let mut results = Vec::with_capacity(batch);
        for b in 0..batch {
            results.push(flat[b * dim..(b + 1) * dim].to_vec());
        }
        Ok(results)
    }
}

// ---------------------------------------------------------------------------
// ClassicBert weight loading
// ---------------------------------------------------------------------------

/// Configuration parsed from a ClassicBert `config.json`.
pub struct ClassicBertConfig {
    /// Hidden dimension (e.g. 384 for BGE-small).
    pub hidden_size: usize,
    /// Number of transformer layers.
    pub num_hidden_layers: usize,
    /// Number of attention heads.
    pub num_attention_heads: usize,
    /// FFN intermediate dimension.
    pub intermediate_size: usize,
    /// Maximum position embedding length.
    pub max_position_embeddings: usize,
    /// Layer normalization epsilon.
    pub layer_norm_eps: f32,
}

impl ClassicBertConfig {
    /// Parse from a `config.json` serde value.
    ///
    /// # Errors
    ///
    /// Returns an error if required keys are missing.
    #[expect(
        clippy::cast_possible_truncation,
        reason = "HuggingFace config ints always fit in usize"
    )]
    pub fn from_json(v: &serde_json::Value) -> crate::Result<Self> {
        let get = |key: &str| -> crate::Result<usize> {
            v.get(key)
                .and_then(serde_json::Value::as_u64)
                .map(|n| n as usize)
                .ok_or_else(|| crate::Error::Other(anyhow::anyhow!("missing config key: {key}")))
        };
        let get_f64 = |key: &str| -> crate::Result<f64> {
            v.get(key)
                .and_then(serde_json::Value::as_f64)
                .ok_or_else(|| crate::Error::Other(anyhow::anyhow!("missing config key: {key}")))
        };

        #[expect(
            clippy::cast_possible_truncation,
            reason = "layer_norm_eps is always a small float"
        )]
        let layer_norm_eps =
            get_f64("layer_norm_eps").or_else(|_| get_f64("layer_norm_epsilon"))? as f32;

        Ok(Self {
            hidden_size: get("hidden_size")?,
            num_hidden_layers: get("num_hidden_layers")?,
            num_attention_heads: get("num_attention_heads")?,
            intermediate_size: get("intermediate_size")?,
            max_position_embeddings: get("max_position_embeddings").unwrap_or(512),
            layer_norm_eps,
        })
    }
}

/// Remove a weight from the map by name, returning an error if missing.
fn take_weight(weights: &mut HashMap<String, Array>, name: &str) -> crate::Result<Array> {
    weights
        .remove(name)
        .ok_or_else(|| crate::Error::Other(anyhow::anyhow!("missing weight: {name}")))
}

/// Load a `ClassicBert` model (e.g. BGE-small) for the MLX driver.
///
/// Downloads model files via `hf-hub`, loads safetensors weights into MLX
/// arrays wrapped as [`MlxTensor`], fuses Q/K/V per layer, and returns an
/// [`EmbedBackend`] backed by [`GenericBackend`]. Because [`MlxTensor`]
/// implements `Send + Sync`, no extra mutex is required.
///
/// # Errors
///
/// Returns an error if the model cannot be downloaded, config cannot be
/// parsed, or weight loading fails.
#[expect(
    clippy::too_many_lines,
    reason = "weight loading is inherently verbose per-field"
)]
pub fn load_classic_mlx(model_repo: &str) -> crate::Result<Box<dyn crate::backend::EmbedBackend>> {
    let api = Api::new().map_err(|e| crate::Error::Download(e.to_string()))?;
    let repo = api.model(model_repo.to_string());

    let config_path = repo
        .get("config.json")
        .map_err(|e| crate::Error::Download(e.to_string()))?;
    let weights_path = repo
        .get("model.safetensors")
        .map_err(|e| crate::Error::Download(e.to_string()))?;

    // Parse config
    let config_str = std::fs::read_to_string(&config_path).map_err(|e| crate::Error::Io {
        path: config_path.display().to_string(),
        source: e,
    })?;
    let config_json: serde_json::Value = serde_json::from_str(&config_str)
        .map_err(|e| crate::Error::Other(anyhow::anyhow!("config parse error: {e}")))?;
    let config = ClassicBertConfig::from_json(&config_json)?;

    // Load weights into MLX arrays
    let mut weights = Array::load_safetensors(&weights_path).map_err(mlx_err)?;

    // Helper: flatten an Array to 1D and wrap in MlxTensor.
    let flatten = |a: Array| -> crate::Result<MlxTensor> {
        let n: i32 = a.shape().iter().product();
        mlx_rs::ops::reshape(&a, &[n])
            .map_err(mlx_err)
            .map(MlxTensor)
    };

    // Build per-layer weights, fusing Q/K/V
    let mut layers = Vec::with_capacity(config.num_hidden_layers);
    for i in 0..config.num_hidden_layers {
        let prefix = format!("encoder.layer.{i}");

        // Fuse Q/K/V weights into single [3*hidden, hidden] matrix
        let q_w = take_weight(
            &mut weights,
            &format!("{prefix}.attention.self.query.weight"),
        )?;
        let k_w = take_weight(&mut weights, &format!("{prefix}.attention.self.key.weight"))?;
        let v_w = take_weight(
            &mut weights,
            &format!("{prefix}.attention.self.value.weight"),
        )?;
        let qkv_weight = mlx_rs::ops::concatenate_axis(&[&q_w, &k_w, &v_w], 0).map_err(mlx_err)?;

        // Fuse Q/K/V biases
        let q_b = take_weight(&mut weights, &format!("{prefix}.attention.self.query.bias"))?;
        let k_b = take_weight(&mut weights, &format!("{prefix}.attention.self.key.bias"))?;
        let v_b = take_weight(&mut weights, &format!("{prefix}.attention.self.value.bias"))?;
        let qkv_bias = mlx_rs::ops::concatenate_axis(&[&q_b, &k_b, &v_b], 0).map_err(mlx_err)?;

        layers.push(ClassicBertLayerWeights {
            qkv_weight: flatten(qkv_weight)?,
            qkv_bias: flatten(qkv_bias)?,
            output_weight: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.attention.output.dense.weight"),
            )?)?,
            output_bias: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.attention.output.dense.bias"),
            )?)?,
            output_ln_weight: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.attention.output.LayerNorm.weight"),
            )?)?,
            output_ln_bias: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.attention.output.LayerNorm.bias"),
            )?)?,
            ffn_inter_weight: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.intermediate.dense.weight"),
            )?)?,
            ffn_inter_bias: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.intermediate.dense.bias"),
            )?)?,
            ffn_out_weight: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.output.dense.weight"),
            )?)?,
            ffn_out_bias: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.output.dense.bias"),
            )?)?,
            ffn_ln_weight: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.output.LayerNorm.weight"),
            )?)?,
            ffn_ln_bias: flatten(take_weight(
                &mut weights,
                &format!("{prefix}.output.LayerNorm.bias"),
            )?)?,
        });
    }

    let hidden = config.hidden_size;
    let num_heads = config.num_attention_heads;
    let head_dim = hidden / num_heads;
    let max_tokens = config.max_position_embeddings;

    let arch = ClassicBertArch {
        weights: ClassicBertWeights {
            word_embeddings: flatten(take_weight(
                &mut weights,
                "embeddings.word_embeddings.weight",
            )?)?,
            position_embeddings: flatten(take_weight(
                &mut weights,
                "embeddings.position_embeddings.weight",
            )?)?,
            token_type_embeddings: flatten(take_weight(
                &mut weights,
                "embeddings.token_type_embeddings.weight",
            )?)?,
            emb_ln_weight: flatten(take_weight(&mut weights, "embeddings.LayerNorm.weight")?)?,
            emb_ln_bias: flatten(take_weight(&mut weights, "embeddings.LayerNorm.bias")?)?,
            layers,
            num_heads,
            head_dim,
            hidden_dim: hidden,
            intermediate_dim: config.intermediate_size,
            layer_norm_eps: config.layer_norm_eps,
        },
    };

    let driver = MlxDriver::new()?;

    // MLX copies weights into its own arrays, but GenericBackend needs an mmap
    // to satisfy the lifetime invariant. Create a dummy mmap from the safetensors
    // file (it's already cached by hf-hub).
    let file = std::fs::File::open(&weights_path).map_err(|e| crate::Error::Io {
        path: weights_path.display().to_string(),
        source: e,
    })?;
    #[expect(unsafe_code, reason = "mmap of read-only cached file is safe")]
    let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(|e| crate::Error::Io {
        path: weights_path.display().to_string(),
        source: e,
    })?;

    tracing::info!(
        model_repo,
        hidden,
        layers = config.num_hidden_layers,
        heads = num_heads,
        intermediate = config.intermediate_size,
        max_tokens,
        "ClassicBert loaded on MLX (driver/arch)"
    );

    Ok(Box::new(GenericBackend::new(
        driver, arch, max_tokens, true, mmap,
    )))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::{EmbedBackend, Encoding};

    const BGE_SMALL: &str = "BAAI/bge-small-en-v1.5";

    /// Verify that the MlxDriver can be constructed.
    #[test]
    #[ignore = "requires MLX/Metal runtime"]
    fn mlx_driver_creates() {
        let driver = MlxDriver::new().unwrap();
        let zeros = driver.alloc_zeros(16).unwrap();
        zeros.0.eval().map_err(mlx_err).unwrap();
        assert_eq!(zeros.0.as_slice::<f32>().len(), 16);
    }

    #[test]
    fn mlx_prepare_batch_unpadded_keeps_token_tensors_flat() {
        let driver = MlxDriver::new().unwrap();
        let enc1 = Encoding {
            input_ids: vec![101, 7592, 102],
            attention_mask: vec![1, 1, 1],
            token_type_ids: vec![0, 0, 0],
        };
        let enc2 = Encoding {
            input_ids: vec![101, 2023, 2003, 1037, 3231, 102],
            attention_mask: vec![1, 1, 1, 1, 1, 1],
            token_type_ids: vec![0, 0, 0, 0, 0, 0],
        };

        let batch = driver.prepare_batch_unpadded(&[enc1, enc2]).unwrap();
        batch.input_ids.0.eval().map_err(mlx_err).unwrap();
        batch.position_ids.0.eval().map_err(mlx_err).unwrap();
        batch.float_mask.0.eval().map_err(mlx_err).unwrap();

        assert_eq!(batch.total_tokens, 9);
        assert_eq!(batch.max_seq, 8);
        assert_eq!(batch.seq_lengths, vec![3, 6]);
        assert_eq!(batch.input_ids.0.as_slice::<i32>().len(), 9);
        assert_eq!(
            batch.position_ids.0.as_slice::<i32>(),
            &[0, 1, 2, 0, 1, 2, 3, 4, 5]
        );
        assert_eq!(batch.float_mask.0.as_slice::<f32>().len(), 16);
    }

    #[test]
    fn mlx_layer_norm_accepts_flat_affine_params() {
        let driver = MlxDriver::new().unwrap();
        let input = MlxTensor(Array::from_slice(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[6]));
        let weight = MlxTensor(Array::from_slice(&[1.0_f32, 1.0, 1.0], &[3]));
        let bias = MlxTensor(Array::from_slice(&[0.0_f32, 0.0, 0.0], &[3]));
        let mut output = driver.alloc_zeros(6).unwrap();

        driver
            .layer_norm(&mut output, &input, &weight, &bias, 2, 3, 1e-5)
            .unwrap();
        output.0.eval().map_err(mlx_err).unwrap();

        assert_eq!(output.0.as_slice::<f32>().len(), 6);
    }

    /// Load ClassicBert via driver/arch and embed a short sequence.
    /// Verifies the full pipeline produces a 384-dim unit vector.
    #[test]
    #[ignore = "requires model download"]
    fn mlx_driver_arch_bge_small() {
        let backend = load_classic_mlx(BGE_SMALL).unwrap();
        let enc = Encoding {
            input_ids: vec![101, 2023, 2003, 1037, 3231, 102],
            attention_mask: vec![1, 1, 1, 1, 1, 1],
            token_type_ids: vec![0, 0, 0, 0, 0, 0],
        };
        let results = backend.embed_batch(&[enc]).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].len(), 384);

        let norm: f32 = results[0].iter().map(|x| x * x).sum::<f32>().sqrt();
        eprintln!("L2 norm = {norm:.6}");
        assert!(
            (norm - 1.0).abs() < 1e-4,
            "L2 norm should be ~1.0, got {norm}"
        );
    }

    /// Compare MLX driver/arch output against the monolithic MLX backend.
    #[test]
    #[ignore = "requires model download"]
    fn mlx_driver_matches_monolithic() {
        let driver_backend = load_classic_mlx(BGE_SMALL).unwrap();
        let mono_backend =
            crate::backend::mlx::MlxBackend::load(BGE_SMALL, &crate::backend::DeviceHint::Auto)
                .unwrap();

        let enc = Encoding {
            input_ids: vec![101, 2023, 2003, 1037, 3231, 102],
            attention_mask: vec![1, 1, 1, 1, 1, 1],
            token_type_ids: vec![0, 0, 0, 0, 0, 0],
        };

        let driver_result = driver_backend
            .embed_batch(std::slice::from_ref(&enc))
            .unwrap();
        let mono_result = mono_backend
            .embed_batch(std::slice::from_ref(&enc))
            .unwrap();

        let cosine: f32 = driver_result[0]
            .iter()
            .zip(&mono_result[0])
            .map(|(a, b)| a * b)
            .sum();
        eprintln!("cosine(MLX driver/arch, MLX monolithic) = {cosine:.6}");
        assert!(
            cosine > 0.99,
            "driver/arch and monolithic should produce near-identical embeddings, got cosine={cosine:.6}"
        );
    }

    /// Multi-sequence batch test — verifies batching and padding work.
    #[test]
    #[ignore = "requires model download"]
    fn mlx_driver_batch() {
        let backend = load_classic_mlx(BGE_SMALL).unwrap();
        let enc1 = Encoding {
            input_ids: vec![101, 7592, 102],
            attention_mask: vec![1, 1, 1],
            token_type_ids: vec![0, 0, 0],
        };
        let enc2 = Encoding {
            input_ids: vec![101, 2023, 2003, 1037, 3231, 102],
            attention_mask: vec![1, 1, 1, 1, 1, 1],
            token_type_ids: vec![0, 0, 0, 0, 0, 0],
        };
        let results = backend.embed_batch(&[enc1, enc2]).unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].len(), 384);
        assert_eq!(results[1].len(), 384);

        // Both should be unit vectors
        for (i, r) in results.iter().enumerate() {
            let norm: f32 = r.iter().map(|x| x * x).sum::<f32>().sqrt();
            assert!(
                (norm - 1.0).abs() < 1e-4,
                "batch element {i}: L2 norm should be ~1.0, got {norm}"
            );
        }
    }
}