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
//! Vision-feature cache for multi-turn multimodal conversations.
//!
//! Ported 1:1 from `mlx-vlm/mlx_vlm/vision_cache.py::VisionFeatureCache`
//! (the only reference — mlx-vlm has no Swift counterpart for this type;
//! confirmed by a repo-wide search of `mlx-swift-lm`). The cache stores
//! the output of `vision_tower` + `embed_vision` (image features already
//! projected into the language model's embedding space, ready for the
//! image-into-text splice), keyed by image identity, so a VLM discussing
//! the **same image across multiple turns/prompts** re-uses the cached
//! embeddings instead of re-running the (expensive) vision encoder.
//!
//! ## Reference structure (`feedback_mirror_reference_structure`)
//!
//! `vision_cache.py` is one class, [`VisionFeatureCache`], built on a
//! Python `OrderedDict` with:
//! - **LRU eviction** — oldest entry dropped once `max_size` is exceeded
//! (`OrderedDict.popitem(last=False)` after `move_to_end`);
//! - a `_make_key` helper deriving a `str` key from the image source —
//! three branches: a `str` path/URL used directly, a `list` joined with
//! `"|"`, and a PIL image content-hashed (`sha256(tobytes())[:16]`);
//! - `get` / `put` / `clear` / `__len__` / `__contains__`.
//!
//! mlxrs mirrors that shape faithfully: one [`VisionFeatureCache`] type,
//! the same `max_size`-bounded LRU, the same five operations ([`get`] /
//! [`put`] / [`clear`] / [`len`] / [`contains`]), and a key-derivation
//! family ([`Key`]) covering the same three source kinds.
//!
//! [`get`]: VisionFeatureCache::get
//! [`put`]: VisionFeatureCache::put
//! [`clear`]: VisionFeatureCache::clear
//! [`len`]: VisionFeatureCache::len
//! [`contains`]: VisionFeatureCache::contains
//!
//! ## Deviations from the Python reference (and why)
//!
//! - **Stored value is an owned [`Array`]**, duplicated on `put`/`get` via
//! the refcount-sharing [`Array::try_clone`] — `mlxrs::Array` is
//! deliberately `!Clone` (a panicking `Clone` would hide the rare FFI
//! allocation failure), so the fallible `try_clone` is the only handle
//! dup. A `try_clone` is **cheap** (a refcount bump + a small handle
//! alloc, no feature-data copy), so caching shares the buffer exactly
//! like Python's reference-semantics `mx.array`.
//! - **Keys are [`Key`], a normalized-string wrapper.** Python's
//! `_make_key` normalizes every source to a `str`; [`Key`] does the same
//! with three constructors mirroring the three Python branches —
//! [`Key::from_source`] (the `str` branch — path/URL), [`Key::from_sources`]
//! (the `list` branch — a multi-image source), and [`Key::from_bytes`]
//! (the PIL branch — a content hash). Each constructor prefixes a distinct
//! variant tag (`s:` / `l:` / `b:`), and the list variant length-prefixes
//! its components. This is a deliberate deviation — the reference's encoding
//! *aliases* distinct image identities (a `'|'`-joined list collides with a
//! literal `'|'`-bearing path; a `pil:`-hashed key collides with a literal
//! `pil:…` path), which would silently feed one image's cached embeddings to
//! a different image. The variant tag makes **cross-variant** collision
//! impossible by construction, and the length-prefix makes the
//! [`from_sources`](Key::from_sources) list encoding **injective** (see
//! [`Key`]'s "Internal representation" note). The per-variant key contract
//! is:
//! - [`from_source`](Key::from_source) / [`from_sources`](Key::from_sources)
//! carry the **full source string(s)** verbatim (tagged, and the list
//! length-prefixed), so they are **injective** — distinct sources always
//! produce distinct keys, so a cache hit can never return a different
//! image's features.
//! - [`from_bytes`](Key::from_bytes) **digests** arbitrary image bytes to a
//! fixed-width value, so it is a digest, *not* an injection — it is
//! **collision-resistant**, not collision-free. A digest maps an unbounded
//! byte space onto fixed-width output, so a collision is possible in
//! principle; the 128-bit width (below) makes it astronomically unlikely
//! (see that constructor's note).
//!
//! [`Key`] holds the encoded string as an [`Arc<str>`](std::sync::Arc) (an
//! implementation detail — every public constructor / accessor has the same
//! signature and semantics it would with a `String` field); the cache stores
//! `Arc<str>` clones in both its containers, so the recency queue and the
//! entry map share one heap-allocated string and [`put`] never heap-copies a
//! key (see [`Key`]'s "Internal representation" note and
//! [`VisionFeatureCache`]'s "Key storage" note). `Arc` (not `Rc`) keeps the
//! public [`Key`] type `Send + Sync` — see [`Key`]'s "Internal
//! representation" note. Because mlxrs has no PIL type and adds no crypto
//! dependency, [`Key::from_bytes`] does not use the reference's `sha256`; it
//! builds a **128-bit** digest from two domain-separated
//! [`DefaultHasher`](std::hash::DefaultHasher) (SipHash) passes. 128 bits
//! lifts the birthday bound to ≈2⁶⁴ distinct images before a collision is
//! *expected* — practically unreachable for a cache — so a collision is
//! negligible without pulling any new crate (a content hash here is a cache
//! key, never a security boundary; cryptographic strength is not required,
//! only practical collision-resistance).
//! - **Bounded memory** — the reference is already bounded (`max_size`,
//! default 20); mlxrs keeps that exact cap and default. The constructor
//! rejects `max_size == 0` ([`Error::InvariantViolation`]) rather than
//! silently building a cache that can hold nothing (Python would not
//! raise but every `put` would immediately self-evict — a faithful but
//! useless state; mlxrs surfaces the misuse).
//!
//! ## No implicit eval
//!
//! The cache never evaluates an `Array`. `put` stores whatever lazy or
//! materialized handle the caller passes (the reference relies on the
//! caller having `mx.eval`'d the features first — see
//! `generate.py:1055`); `get` hands back a `try_clone` of that same
//! handle. Evaluation stays the caller's explicit step.
use ;
use crate::;
/// The default `max_size` — matches `VisionFeatureCache(max_size=20)` in
/// `mlx-vlm/mlx_vlm/vision_cache.py:31`.
pub const DEFAULT_MAX_SIZE: usize = 20;
/// A normalized cache key derived from an image source.
///
/// Mirrors `VisionFeatureCache._make_key` (`vision_cache.py:35-50`), which
/// reduces every image source to a `str`. The three constructors map 1:1
/// to the reference's three branches:
///
/// | Python branch | constructor | encoded form | contract |
/// |---|---|---|---|
/// | `isinstance(image_source, str)` — path / URL | [`Key::from_source`] | `s:<source>` | injective |
/// | `isinstance(image_source, list)` — multi-image | [`Key::from_sources`] | `l:` + length-prefixed components | injective |
/// | PIL image — `sha256(tobytes())[:16]` | [`Key::from_bytes`] | `b:<128-bit hexdigest>` | collision-resistant |
///
/// Two `Key`s are equal iff their encoded strings are equal. **List order
/// is significant** (matching the reference) — `["a", "b"]` and `["b", "a"]`
/// are different keys.
///
/// # Per-variant key contract
///
/// The three constructors do **not** share one guarantee — the "contract"
/// column above is exact:
///
/// - [`from_source`](Self::from_source) and [`from_sources`](Self::from_sources)
/// are **injective**: they carry the full source string(s) verbatim (tagged,
/// and the list length-prefixed), so distinct image identities *always*
/// produce distinct keys. A cache hit on one of these keys can never return
/// a different image's features.
/// - [`from_bytes`](Self::from_bytes) is **collision-resistant**, not
/// injective: it *digests* arbitrary image bytes onto a fixed-width 128-bit
/// value, so by the pigeonhole principle two different byte slices *can* in
/// principle map to the same key. The 128-bit digest makes that
/// astronomically unlikely (birthday bound ≈2⁶⁴ images), so for any
/// practical workload a `from_bytes` collision never occurs — but the
/// guarantee is collision-*resistance*, not the injectivity the
/// string-carrying variants give.
///
/// The **variant tag** (`s:` / `l:` / `b:`) is a separate, unconditional
/// guarantee that holds for *all three*: two keys from *different*
/// constructors can never be equal, so `from_bytes`'s digest can never alias a
/// literal path/list source (and vice versa) regardless of the digest's value.
///
/// # Internal representation — unambiguous encoding
///
/// The key is **not** the reference's bare normalized string. The reference
/// derives a `str` that *aliases* distinct image identities, and a cache
/// hit on an aliased key returns the wrong stored features — silently
/// feeding one image's embeddings to a different image/prompt. Two concrete
/// aliasing bugs in the reference's scheme, and how mlxrs's encoding closes
/// each:
///
/// - **Cross-variant aliasing.** The reference joins a list with `'|'` and
/// hashes PIL bytes with a `pil:` prefix, but a single-source `str` is
/// used verbatim — so a literal path `"a|b"` collides with the list
/// `["a", "b"]`, and a literal path `"pil:deadbeef"` collides with a
/// `from_bytes` digest. mlxrs prefixes each constructor with a **distinct
/// variant tag**: `s:` for [`from_source`](Self::from_source), `l:` for
/// [`from_sources`](Self::from_sources), `b:` for [`from_bytes`](Self::from_bytes).
/// The tag is the first two bytes of every key, so two keys from
/// *different* constructors can never be equal — regardless of what the
/// user's source string contains. A source string of literally `"l:x"`
/// encodes to `s:l:x` (an `s:` key); it cannot equal any `l:` key,
/// because the tag is prepended to — never spoofable from within — the
/// user's bytes.
/// - **Within-list aliasing.** A bare `'|'`-join is not injective: a list
/// *component* may itself contain `'|'`, so `["a|b"]` and `["a", "b"]`
/// both join to `"a|b"`. [`from_sources`](Self::from_sources) instead
/// **length-prefixes** every component — `<byte-len>:<component>` — so the
/// decode boundaries are unambiguous whatever characters a component
/// holds: `["a|b"]` encodes `l:3:a|b`, `["a", "b"]` encodes `l:1:a1:b`,
/// and the two differ. The list encoding is injective.
///
/// Together the variant tag (kills cross-variant aliasing) and the
/// length-prefixed list components (kill within-list aliasing) make the two
/// **string-carrying** variants — [`from_source`](Self::from_source) and
/// [`from_sources`](Self::from_sources) — **injective**: distinct path/URL/list
/// identities always produce distinct keys, so a cache hit on those can never
/// return a different image's features. The third variant,
/// [`from_bytes`](Self::from_bytes), is a fixed-width *digest* of the raw
/// bytes, so it is **collision-resistant** rather than injective (a digest
/// cannot be injective over an unbounded byte space — see the "Per-variant key
/// contract" section above and that constructor's note); its variant tag still
/// unconditionally prevents cross-variant aliasing with the two injective
/// variants. The encoded form is an internal cache key —
/// [`as_str`](Self::as_str) exposes it for tests/introspection, but no caller
/// parses it back into a source.
///
/// The encoded string is held as an [`Arc<str>`](Arc), not a `String`.
/// This is an implementation detail — every public method
/// ([`from_source`](Self::from_source), [`from_sources`](Self::from_sources),
/// [`from_bytes`](Self::from_bytes), [`as_str`](Self::as_str), and the
/// `From<&str>` conversion) has the exact same signature and behavior it
/// would with a `String` field. The `Arc` backing buys three things:
///
/// - **`Clone` is a refcount bump** — infallible, no heap allocation, no
/// string copy. [`VisionFeatureCache`] stores a key in *two* containers
/// (the entry map and the recency queue); with an `Arc<str>` the second
/// container gets an [`Arc::clone`], so a [`put`](VisionFeatureCache::put)
/// never heap-copies a key and the post-eviction key handoff cannot
/// fail. (With a `String` field that second copy was a fallible-by-abort
/// heap allocation occurring *after* eviction — a transactional hazard.)
/// The bump is a single atomic increment — negligible for this cache's
/// use, and the same allocation-free handoff a non-atomic `Rc` gave.
/// - **`Hash`/`Eq` are unchanged** — `Arc<str>` hashes and compares by the
/// pointed-to `str` *content* (it derefs / `Borrow`s `str`), so the
/// derived `Hash`/`PartialEq`/`Eq` here are byte-for-byte the same
/// relation as a `String`-backed `Key`: two `Key`s are equal iff their
/// strings are equal, full stop.
/// - **`Send + Sync` are preserved** — `Arc<str>` is `Send + Sync` (a
/// non-atomic `Rc<str>` is neither), so the public `Key` keeps the
/// `Send`/`Sync` auto-traits a `String`-backed `Key` had. Downstream code
/// may precompute, queue, or move `Key`s across thread/task boundaries.
/// (This is `Key` alone — [`VisionFeatureCache`] stores [`Array`], which
/// is intentionally `!Send`/`!Sync`; only the *key* is thread-portable.)
;
// Compile-time guard: the public `Key` must stay `Send + Sync`. The prior
// `Rc<str>` backing silently dropped both auto-traits; `Arc<str>` restores
// them. A regression back to `Rc` (or any other `!Send`/`!Sync` field)
// fails this assertion at compile time. `VisionFeatureCache` itself is
// deliberately NOT asserted here — it stores `Array`, which is intentionally
// `!Send`/`!Sync` (one cache belongs to one inference thread); only the
// thread-portable `Key` carries the contract.
const _: fn = ;
/// An LRU cache of vision-encoder output features, keyed by image
/// identity.
///
/// Port of `mlx-vlm`'s `VisionFeatureCache` (`vision_cache.py:15-79`). A
/// VLM that discusses the same image across several turns calls [`get`]
/// before encoding; on a hit it skips the vision tower entirely and
/// re-uses the cached features, on a miss it encodes once and [`put`]s
/// the result. Eviction is purely LRU once [`max_size`](Self::max_size)
/// is exceeded.
///
/// [`get`]: Self::get
/// [`put`]: Self::put
///
/// # Memory
///
/// Bounded by construction: at most `max_size` feature [`Array`]s are
/// retained (default [`DEFAULT_MAX_SIZE`]). Each stored value is a
/// refcount-sharing [`Array::try_clone`] of the caller's handle — the
/// feature *buffer* is shared, not copied, so the cache's marginal cost
/// per entry is one small mlx-c handle. [`clear`](Self::clear) drops every
/// entry (the reference's model-unload hook); on `Drop` the whole map is
/// freed.
///
/// # Key storage
///
/// A key's normalized string is stored exactly **once** per entry as an
/// [`Arc<str>`](Arc): the entry-map key and the recency-queue entry are two
/// [`Arc::clone`]s of that one allocation. `Arc::clone` is an infallible
/// refcount bump (a single atomic increment) — **no heap allocation, no
/// string copy** — so every key-side operation on the [`put`] path
/// (inserting into both containers) and on the recency-update path (a
/// [`get`] hit relocates the key within the recency queue) is
/// allocation-free. The string a [`Key`] carries is consumed into the
/// `Arc<str>` once, on the inserting `put`; after that no `put` or `get`
/// ever heap-allocates a key. This is what makes a full-cache `put`
/// (evict + insert) and a `get` hit's recency bump strictly
/// allocation-free on the key side, and what makes the post-eviction key
/// handoff infallible (a refcount bump cannot fail), so a failed `put` can
/// never leave the cache half-mutated.
///
/// # Concurrency
///
/// Neither `Send` nor `Sync` — it stores [`Array`], which is intentionally
/// `!Send` + `!Sync`. One cache belongs to one inference thread, the same
/// single-thread contract the rest of `mlxrs` is built on. Note this is the
/// *cache* type only: its [`Key`] type *is* `Send + Sync` (it is backed by
/// an `Arc<str>`), so keys may be precomputed or moved across threads even
/// though the cache they index must not.
/// Allocation-discipline tests that need to inspect the cache's **private**
/// containers (`entries` / `recency`) — capacity stability and `Arc<str>`
/// key sharing. They live in an inline `#[cfg(test)]` module (not the
/// integration suite in `tests/vlm_feature_cache.rs`) precisely because the
/// guarantees under test are structural and only observable through the
/// private fields. The functional behavior tests (put/get/LRU/overwrite/
/// the lazy-capacity tests) stay in the integration suite.