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
//! ColVision base processor seam — ports
//! [`mlx_embeddings/colvision_processor.py`](https://github.com/Blaizzy/mlx-embeddings/blob/main/mlx_embeddings/colvision_processor.py)
//! `BaseColVisionProcessor` (lines 9-110), which itself is a port of
//! illuin-tech / colpali-engine's `BaseVisualRetrieverProcessor`
//! (`colpali_engine/utils/processing_utils.py`).
//!
//! ## What this module ships
//!
//! Mirroring the python reference's structure faithfully:
//!
//! - [`BaseColVisionProcessor`] — a **trait** mirroring the python
//! abstract base class (python lines 9-41). It declares the three
//! abstract methods every concrete processor (ColIdefics3 / ColQwen2_5 /
//! …) implements:
//! * [`process_images`](BaseColVisionProcessor::process_images) —
//! python `process_images` (lines 18-23): turn a batch of images
//! into the model-specific multimodal `BatchFeature` / `BatchEncoding`
//! (image arrays + token ids + masks). Per the
//! no-model-arch rule this trait declares the *shape* of the
//! contract only; the dictionary-of-tensors return type is
//! represented as a [`ProcessorBatch`] map keyed by the python
//! field name. Concrete implementations live with each model arch.
//! * [`process_queries`](BaseColVisionProcessor::process_queries) —
//! python `process_queries` (lines 25-32): tokenize a batch of
//! string queries (with the model-specific prefix / suffix /
//! augmentation tokens) into a [`ProcessorBatch`].
//! * [`score`](BaseColVisionProcessor::score) — python `score`
//! (lines 34-41): the scoring entry every concrete subclass
//! overrides (colidefics3.py:325 delegates to `score_multi_vector`
//! for late-interaction / MaxSim).
//!
//! - [`score_single_vector`] — module-level free function mirroring
//! python `@staticmethod BaseColVisionProcessor.score_single_vector`
//! (lines 43-63). Dot-product score between single-vector queries `qs`
//! and passages `ps`. Cast to `f32`.
//!
//! - [`score_multi_vector`] — module-level free function mirroring
//! python `@staticmethod BaseColVisionProcessor.score_multi_vector`
//! (lines 65-110). Late-interaction / MaxSim (ColBERT-like) score
//! between multi-vector queries and passages, batched on `batch_size`.
//! Cast to `f32`.
//!
//! Python `@staticmethod` ports as a module-level free function: the
//! method is callable without an instance in the reference (it is invoked
//! both as `BaseColVisionProcessor.score_single_vector(...)` and
//! `self.score_multi_vector(...)`), and Rust trait dispatch adds nothing.
//! This follows Rust-idiomatic ergonomics over verbatim mirroring of
//! OO sugar that has no Rust analog.
//!
//! ## What this module deliberately does NOT ship (no per-model
//! arch porting)
//!
//! Concrete model-specific processors (the python
//! `colidefics3.Processor` / `colqwen2_5.Processor` subclasses, which
//! also inherit from the HF `transformers` `*Processor` mixin and own
//! the image preprocessor + tokenizer state) are **out of scope**.
//! Those are model architectures and ship per-usecase. This module ships
//! the cross-architecture seam those subclasses register into — exactly
//! the python `colvision_processor.py` boundary.
//!
//! ## [`ProcessorBatch`] — the cross-architecture return type
//!
//! The python `process_images` / `process_queries` return either
//! `BatchFeature` or `BatchEncoding` — both are HF dict-of-tensors
//! containers (the model-specific `Processor` runs the HF processor +
//! calls `mx.array` on every numpy value, e.g. `colidefics3.py` lines
//! 287-296 and 315-322). The cross-architecture shape is a string-keyed
//! map of [`Array`] values; [`ProcessorBatch`] is a [`std::collections::HashMap`]
//! `String → Array` (the field names are model-specific:
//! `input_ids`, `attention_mask`, `pixel_values`, …). No new dep.
//!
//! ## Errors
//!
//! Recoverable failures (empty `qs`/`ps`, ragged shapes the python
//! reference rejects, shape mismatches MLX would have silently
//! broadcasted, allocation pressure on the inner batch-loop) return
//! [`Result`] with an [`Error`] message naming the cause. Python
//! `ValueError("No queries provided")` / `"No passages provided"`
//! (lines 51-54 and 75-78) map to [`Error::EmptyInput`] with the
//! python message text preserved for parity.
use HashMap;
use crate::;
/// Which side of a `(queries, passages)` pair the colvision scoring code
/// is inspecting. Routes the per-side context labels through a closed
/// enum so the typed-error payloads can carry static `&'static str`
/// contexts (no `format!` for the side tag).
/// A `String → Array` dictionary mirroring the python `BatchFeature` /
/// `BatchEncoding` return shape that `process_images` and
/// `process_queries` produce.
///
/// Concrete fields are model-specific (e.g. `input_ids`,
/// `attention_mask`, `pixel_values`, `pixel_attention_mask`) — the
/// cross-architecture seam only fixes the **type** of the bundle, not
/// the schema, exactly like the python `BatchFeature` / `BatchEncoding`
/// dict.
pub type ProcessorBatch = ;
/// The cross-architecture ColVision processor seam, mirroring
/// [`mlx_embeddings/colvision_processor.py`](https://github.com/Blaizzy/mlx-embeddings/blob/main/mlx_embeddings/colvision_processor.py)
/// `BaseColVisionProcessor` (lines 9-41).
///
/// Concrete model-specific processors (`ColIdefics3` /
/// `ColQwen2_5` / …) own the image preprocessor + tokenizer + chat
/// template and implement this trait. The trait itself only fixes the
/// three abstract method shapes; no state lives on the seam. Per the
/// no-model-arch rule the per-model
/// implementations are out of scope for this module.
///
/// Each implementation is expected to be `!Send`-tolerant: [`Array`] is
/// `!Send`, so a `BaseColVisionProcessor` impl that holds [`Array`]
/// fields will inherit that (intentional).
/// Dot-product score between single-vector queries `qs` and passages
/// `ps`. Mirrors python `BaseColVisionProcessor.score_single_vector`
/// (lines 43-63) — `mx.einsum("bd,cd->bc", qs_stacked, ps_stacked)` is
/// equivalent to `qs_stacked @ ps_stacked.T`, computed here as
/// [`matmul`] after [`transpose_axes`] (no `einsum` FFI binding is
/// wrapped in mlxrs and a 2-D matmul + transpose is the canonical
/// equivalent — mlx itself rewrites the same einsum to a matmul
/// internally).
///
/// Each input is a single-vector embedding `(d,)`; they are
/// [`stack`]ed into a `(b, d)` query batch and a `(c, d)` passage
/// batch. The result is the `(b, c)` similarity matrix, cast to
/// [`Dtype::F32`] (python `scores.astype(mx.float32)`).
///
/// ## Errors
/// - `qs.is_empty()` → [`Error::EmptyInput`] with the python message
/// `"No queries provided"` (line 52).
/// - `ps.is_empty()` → [`Error::EmptyInput`] with the python message
/// `"No passages provided"` (line 54).
/// - Any input with `shape[0] == 0` (zero-element vector / zero-token
/// embedding) → [`Error::OutOfRange`] whose message contains
/// `"zero tokens"`. A zero-element single vector would dot-product
/// with every passage to `0.0` regardless of content, silently
/// collapsing the ranking signal; the equivalent precondition that
/// the internal `pad_to_max` helper enforces for the multi-vector
/// path is enforced here directly (this function does not go through
/// `pad_to_max`).
/// - Underlying [`stack`] / [`matmul`] errors propagate (e.g. inputs
/// with mismatched `d`).
/// MaxSim / late-interaction (ColBERT-like) score between multi-vector
/// queries `qs` and passages `ps`. Mirrors python
/// `BaseColVisionProcessor.score_multi_vector` (lines 65-110).
///
/// Each query is an `(n_i, d)` multi-vector embedding, each passage an
/// `(s_j, d)`. Within each `(batch_size, batch_size)` tile the function
/// zero-pads ragged token-axis lengths to the tile max (the python
/// `pad_to_max` inner helper, lines 80-91), then for each query-passage tile computes the
/// `(n, s)` similarity matrix, takes the max over the passage tokens
/// (`axis=3`), and sums over the query tokens (`axis=2`) — the MaxSim
/// reduction. Tiles are [`concatenate`]d along the passage axis (within
/// a query tile) and then along the query axis. Result is `(B, C)`
/// where `B = qs.len()` and `C = ps.len()`, cast to [`Dtype::F32`]
/// (python `scores.astype(mx.float32)`).
///
/// `batch_size` mirrors the python keyword (`batch_size: int = 128`).
///
/// `einsum("bnd,csd->bcns", qs_batch, ps_batch)` is implemented via
/// rank-4 [`matmul`] after expanding `qs_batch (b,n,d)` to `(b,1,n,d)`,
/// expanding `ps_batch.transpose(0,2,1) (c,d,s)` to `(1,c,d,s)`, and
/// matmuling — mlx's `matmul` batches the leading dims, so the result
/// is exactly `(b,c,n,s)` (the einsum semantic). No `mlx_einsum` FFI
/// wrapper is needed.
///
/// ## Deliberate divergence from the python reference: padded-passage masking
///
/// The python reference at
/// [`mlx_embeddings/colvision_processor.py`](https://github.com/Blaizzy/mlx-embeddings/blob/main/mlx_embeddings/colvision_processor.py)
/// lines 80-102 zero-pads ragged passages with **zero vectors** and
/// then includes those padded columns in `mx.max(sim, axis=3)`. For
/// signed embeddings (e.g. anything with negative similarity components
/// — common with non-normalized or non-ReLU'd encoders) this is a
/// **correctness bug**: a real similarity of `-1.0` between query and
/// a passage token loses to the padded `0.0` dot product, so MaxSim
/// reports `0` instead of `-1` whenever the passage was tile-padded.
/// Worst-case, a passage's score depends on its `batch_size` tile
/// neighbours: passage `p0 = [[-1, 0]]` returns `-1.0` alone but `0.0`
/// when tiled with a length-2 passage. This violates the contract
/// (MaxSim should be batch-size-agnostic) and corrupts ranking.
///
/// The mlxrs port fixes this by masking the padded positions to
/// `f32::NEG_INFINITY` (cast via [`astype`] to the input dtype to
/// preserve f16/bf16) **before** the [`max_axes`] reduction. Padded
/// positions can never win the max, so the per-tile result equals the
/// untiled result for every passage, restoring batch-size invariance.
///
/// Dtype choice: `f32::NEG_INFINITY` (via the existing `scalar_like`
/// pattern shared with [`crate::embeddings::pooling::max_pooling`])
/// rather than `T::MIN` finite — mlx's [`max_axes`] handles `-inf`
/// cleanly (no NaN propagation: the input similarities are finite, so
/// `max(finite, -inf) = finite` always). The all-padded edge case
/// cannot arise here because the internal `pad_to_max` helper only ever
/// pads *up to* the tile max length, so every column at index
/// `< max_len` exists for at least one passage in the tile. (A `-inf`
/// result would only escape
/// the max if a real similarity happened to be `-inf`, which finite
/// f32/f16/bf16 dot products of finite embeddings cannot produce.)
///
/// ### Precondition (enforced): no zero-token queries or passages
///
/// The "padded positions can never win the max" invariant above
/// depends on every input having **at least one** real token (i.e.
/// `shape[0] >= 1`). A zero-token passage `(0, d)` would record `0`
/// in the internal `pad_to_max` helper's `original_lengths`; the
/// per-passage mask row would then be all-`false`, [`select`] would
/// replace every position with `-inf`, and `max(axis=3)` on an
/// all-`-inf` row returns `-inf`, which `sum(axis=2)` would propagate
/// as a non-finite ranking score. To preserve the invariant, the
/// internal `pad_to_max` helper explicitly rejects any array with
/// `shape[0] == 0` with an [`Error::OutOfRange`] whose message
/// contains `"zero tokens"`. Both the query and passage paths of
/// `score_multi_vector` inherit this precondition through their
/// `pad_to_max` calls. Callers must filter out empty-tokenization
/// inputs before invoking the scorer.
///
/// An upstream issue should be filed against
/// <https://github.com/Blaizzy/mlx-embeddings> referencing this PR.
///
/// ## Errors
/// - `qs.is_empty()` → [`Error::EmptyInput`] with the python message
/// `"No queries provided"` (line 76).
/// - `ps.is_empty()` → [`Error::EmptyInput`] with the python message
/// `"No passages provided"` (line 78).
/// - `batch_size == 0` → [`Error::InvariantViolation`] (the python
/// `range(0, len(qs), batch_size)` would `ValueError` on
/// `batch_size == 0`; surface the equivalent recoverable error
/// instead of looping forever).
/// - Any query or passage with `shape[0] == 0` → [`Error::OutOfRange`]
/// whose message identifies the offending input by path tag and
/// *global* index (e.g. `"score_multi_vector: passages[3] has zero
/// tokens (shape[0] == 0); ..."`) and contains the substring
/// `"zero tokens"`. The check runs up front, before any tiling, so
/// the index is the caller's index into `qs` / `ps` — not a
/// tile-local index. See the "Precondition (enforced)" subsection of
/// the divergence note above. (The internal `pad_to_max` helper
/// also rejects `shape[0] == 0` as defense-in-depth, but its message
/// is never observed by `score_multi_vector` callers because the
/// pre-validation fires first.)
/// - Per-tile shape errors (mismatched `d`, non-rank-2 inputs) propagate
/// from [`stack`] / [`matmul`].
/// Zero-pad a slice of `(n_i, d)` multi-vector arrays to the slice's
/// max `n` and [`stack`] them into a `(len, max_n, d)` batch. Mirrors
/// the python inner helper `pad_to_max` (lines 80-91):
///
/// ```python
/// def pad_to_max(arrays):
/// max_len = max(a.shape[0] for a in arrays)
/// emb_dim = arrays[0].shape[1]
/// padded = []
/// for a in arrays:
/// pad_width = max_len - a.shape[0]
/// if pad_width > 0:
/// pad = mx.zeros((pad_width, emb_dim), dtype=a.dtype)
/// padded.append(mx.concatenate([a, pad], axis=0))
/// else:
/// padded.append(a)
/// return mx.stack(padded)
/// ```
///
/// Padding is done with [`Array::zeros`] of the *input dtype*
/// ([`Dtype`] preserved from the input, mirroring python's
/// `dtype=a.dtype`) so a half-precision query batch stays half — no
/// silent f32 promotion (the dtype-fidelity discipline this module shares with the rest of
/// `embeddings`).
///
/// Empty `arrays` is rejected by the callers
/// ([`score_multi_vector`]'s outer guards), so this helper documents
/// `!arrays.is_empty()` as a precondition; calling with an empty slice
/// returns [`Error::EmptyInput`] (defensive — would otherwise panic
/// on `arrays[0].shape()`).
///
/// Any **individual** array with `shape[0] == 0` is also rejected with
/// an [`Error::OutOfRange`] whose message contains `"zero tokens"`.
/// A zero-token sequence would record `0` in `original_lengths`, and
/// the [`score_multi_vector`] masking loop would then build an
/// all-`false` row for that passage — every position in `sim` for that
/// passage would be replaced with `-inf` by [`select`], `max(axis=3)`
/// would return `-inf`, and `sum(axis=2)` would propagate a non-finite
/// ranking score. Enforcing the precondition here (rather than in the
/// caller) means both the query and passage paths of
/// [`score_multi_vector`] inherit the guard for free. See the
/// "Precondition (enforced)" subsection of the divergence note on
/// [`score_multi_vector`].
///
/// ## Return shape (diverges from python)
///
/// Returns `(padded, original_lengths)`:
/// - `padded` — the stacked `(len, max_n, d)` batch (the python return).
/// - `original_lengths` — a `Vec<usize>` of length `arrays.len()` where
/// `original_lengths[i] == arrays[i].shape()[0]` (before padding).
/// Required by [`score_multi_vector`] to mask the zero-padded
/// passage columns to `-inf` before the MaxSim `max(axis=3)`. See
/// the divergence note on [`score_multi_vector`].
pub