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
//! Prompt-cache disk persistence, ported 1:1 from
//! [`mlx_lm.models.cache`](https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/cache.py)
//! `save_prompt_cache` / `load_prompt_cache` / `can_trim_prompt_cache` /
//! `trim_prompt_cache` (cache.py:43-113) and cross-checked against
//! mlx-swift-lm's `MLXLMCommon/KVCache.swift` `savePromptCache` /
//! `loadPromptCache` (the exact `tree_flatten` wire format).
//!
//! ## Cross-tool wire format
//!
//! A prompt cache written here uses the identical safetensors layout as
//! mlx-lm and mlx-swift-lm (`mx.save_safetensors(file, cache_data,
//! cache_metadata)`); the array map / side-table keying and the
//! reference-class-name labels are byte-for-byte what both tools produce
//! and consume — see the per-key spec below. **Compatibility scope (read
//! before relying on cross-tool load):**
//!
//! - **mlx-lm ⇄ mlxrs: full round-trip, all cache kinds.** Every cache's
//! `state`/`meta_state` is the verbatim 1:1 port of the *authoritative*
//! `mlx_lm.models.cache` (the spec this module is ported from), so a
//! cache saved by either loads in the other unchanged — **including**
//! `RotatingKVCache` (mlx-lm `meta_state` is the 4-tuple `(keep,
//! max_size, offset, _idx)`, cache.py:533; mlxrs emits exactly that).
//! - **mlx-swift-lm ⇄ mlxrs: the wire format + non-rotating kinds match;
//! `RotatingKVCache` `meta_state` does *not* (an upstream mlx-lm↔swift
//! divergence, faithfully inherited — *not* introduced here).**
//! mlx-swift-lm's `RotatingKVCache.metaState`
//! (`MLXLMCommon/KVCache.swift`) is a **5**-element tuple `(keep,
//! maxCacheSize, step, offset, idx)` and its loader hard-rejects any
//! count `!= 5`, whereas authoritative mlx-lm (and therefore mlxrs and
//! the merged `RotatingKvCache::meta_state`) is **4** elements (no
//! serialized `step` — it is a fixed class constant). So a *rotating*
//! prompt cache does **not** interoperate between mlx-swift-lm and
//! {mlx-lm, mlxrs} **in either direction** — and mlx-lm itself has the
//! same incompatibility with mlx-swift-lm. This port deliberately tracks
//! the authoritative mlx-lm shape (the cited spec; the merged
//! `RotatingKvCache::meta_state` is fixed at 4 fields, #32 — out of this
//! PR's scope to change, and changing it would *break* the mlx-lm
//! round-trip that is the spec). Non-rotating caches (`KVCache`/…) and
//! the array/side-table wire format remain fully mlx-swift-loadable.
//! Reconciling rotating-cache metadata across all three tools is an
//! upstream-coordination follow-up, not a defect in this port.
//!
//! Both tools use `mx.save_safetensors(file, cache_data, cache_metadata)`
//! where
//!
//! - `cache_data = tree_flatten([c.state for c in cache])` — a list of
//! per-cache array lists, so the safetensors **array map** is keyed
//! `"{i}.{j}"` (cache `i`, array `j`); mlx-lm cache.py:53-55, swift
//! `flattenedData["\(i).\(j)"]`.
//! - `cache_metadata = tree_flatten([cache_info, metadata,
//! cache_classes])` — flattened into the safetensors **string metadata
//! side-table** as (note `cache_info[i]` is **heterogeneous** —
//! `tree_flatten` keys it by its *type*):
//! - `"0.{i}.{j}"` → `cache_info[i][j]` when cache `i`'s `meta_state`
//! is a **non-empty list** (e.g. `RotatingKVCache`'s 4-tuple),
//! - `"0.{i}"` → `""` when cache `i`'s `meta_state` is **empty** —
//! because mlx-lm's `_BaseCache.meta_state` (the base of
//! `KVCache`/`ConcatenateKVCache`, which don't override it,
//! cache.py:138-139) is the empty *string* `""`, a `tree_flatten`
//! **scalar leaf** → key `"0.{i}"`, *not* an absent key. Emitting
//! this scalar (not nothing) is mandatory for mlx-lm cross-load: an
//! all-`KVCache` file with no `"0.*"` keys makes mlx-lm
//! `tree_unflatten` see `info == {}` and `zip` produce **zero
//! caches**. (mlx-swift's `unflattenMetadata` matches only `"0.i.j"`,
//! so it ignores the scalar and rebuilds the no-meta cache from an
//! empty metaState — correct for `KVCacheSimple`; the scalar is thus
//! mlx-lm-faithful and swift-harmless.) The loader here accepts
//! `"0.{i}"` (scalar empty), `"0.{i}.{j}"` (list), and an absent
//! index (swift's empty form) — all three ⇒ that cache's meta_state
//! is its respective shape.
//! - `"1.{key}"` → user `metadata[key]`,
//! - `"2.{i}"` → `cache_classes[i]` = `type(c).__name__` (cache.py
//! :56) — the **reference Python class name**, *not* the Rust struct
//! name, so the file round-trips through mlx-lm
//! `globals()[name].from_state` / swift `restoreCacheFromMetaState`
//! unchanged.
//!
//! (`mlx.utils.tree_flatten` uses dot notation: a list nests as `i.j`, a
//! dict as `key` — verified against `python/mlx/utils.py` `tree_flatten`
//! and the swift `unflattenArrays`/`unflattenMetadata` mirror.)
//!
//! ## Reference class name
//!
//! mlx-lm derives the kind via `type(c).__name__`; mlx-swift-lm via a
//! single `cacheClassName(_:)` `switch` over the concrete type. The
//! `KvCache` trait carries the equivalent
//! [`KvCache::reference_class_name`] method (defaulting to `"KVCache"`,
//! overridden by every concrete cache to its mlx-lm/mlx-swift name), so
//! [`reference_class_name`] is a thin dispatch over that trait method —
//! the emitted name (`"KVCache"` / `"RotatingKVCache"` / `"ChunkedKVCache"`
//! / `"QuantizedKVCache"` / `"CacheList"` / `"ArraysCache"` /
//! `"BatchKVCache"` / `"BatchRotatingKVCache"`) is precisely what mlx-lm /
//! mlx-swift expect and what [`from_state`] keys on. Adding a new cache
//! kind means overriding [`KvCache::reference_class_name`] on it (and the
//! corresponding [`from_state`] arm); no change here.
//!
//! ## Path-read DoS discipline
//!
//! `load_prompt_cache` reads an attacker-influenceable file, so it applies
//! the **same defense, with the same residual posture, as the merged
//! `lm::load` weight loader** (`load_weights` → `collect_sorted`'s
//! `fs::metadata` gate, then `crate::io::load_safetensors(path)` by path).
//! `crate::io`/mlx-c is path-only (`mlx_load_safetensors(const char*)`);
//! there is no fd/owned-bytes entry point, so this loader cannot consume
//! the bytes from the validated handle — closing that gap needs an mlx-c
//! API extension, a separate `mlxrs-sys` change out of this PR's scope (it
//! would also have to change the merged `lm::load` identically).
//!
//! Pre-`crate::io` gate: open the path **once** with `O_NONBLOCK |
//! O_CLOEXEC` (Unix) so a planted FIFO returns instead of hanging; fstat
//! the *opened* fd and reject a non-regular target (FIFO / device /
//! directory / symlink-to-special — these read as `len()==0` yet stream
//! unbounded data) and an oversized one (`metadata().len()` of the
//! proven-regular fd — an O(1) authoritative size; *not* `Read::take`,
//! which `lm::load` only needs because it streams the config body — here a
//! streaming probe would be a wasteful, itself-DoS-prone 2× read of a
//! multi-GB cache). Symlinks are intentionally followed (the post-open
//! `is_file()` fstat enforces the guarantee on the resolved target).
//!
//! **Residual TOCTOU (acknowledged, = merged `load_weights`):** the fd is
//! closed and `crate::io` re-`open`s `path`, so an adversary who can swap
//! `path` (or a symlink in it) *between* the fstat and that re-open could
//! still present a FIFO/device/oversized file to mlx-c. This window is
//! **identical** to the merged `lm::load` weight path and accepted on the
//! same basis (a trusted local cache directory; the gate is defense for
//! the non-racing common case, not a TOCTOU-free guarantee — the doc does
//! **not** claim one). The reconstructed-state rank gate below is the
//! independent backstop that turns a corrupt/foreign *payload* (incl. one
//! delivered via such a race) into a clean `Err` rather than a later
//! panic.
//!
//! The `tree_unflatten` step additionally rejects a *non-dense* flattened
//! list (the private `dense_len` gate) so a tiny hostile side-table cannot
//! drive an unbounded `Vec`, and every reconstructed cache's state arrays
//! are **rank-validated** (4-D `[B, n_kv_heads, S, head_dim]`) before
//! `load_prompt_cache` returns, so a wrong-rank array in a hostile file is
//! a recoverable error here, not a deferred `shape()[2]` panic on first
//! cache use. Every recoverable failure (missing / non-regular /
//! oversized / corrupt / non-dense / wrong-rank / unknown-kind) is a
//! typed [`Error`] variant — **never** a panic/`unwrap` on the load path.
use ;
use crate::;
use format_smolstr;
/// Upper bound on a prompt-cache file we will read, mirroring `lm::load`'s
/// `MAX_CONFIG_BYTES` rationale (a hostile file must not OOM the loader).
/// A prompt cache holds KV tensors so it is far larger than a config; this
/// 8 GiB ceiling is generous for real multi-GB caches yet still a hard cap
/// against an unbounded planted file. `crate::io`/mlx-c reads the file
/// itself; this bound is the pre-open gate (size + non-regular reject) the
/// `lm::load` discipline requires before any unbounded read.
pub const MAX_PROMPT_CACHE_BYTES: u64 = 8 << 30;
/// The **reference Python class name** for `cache` (mlx-lm
/// `type(c).__name__`, cache.py:56 / swift `cacheClassName`,
/// `KVCache.swift:1381-1392`).
///
/// Thin forward to [`KvCache::reference_class_name`] (the trait method
/// that lifts swift's `cacheClassName(_:)` switch onto the concrete cache
/// itself). The returned string is exactly the reference class name
/// [`from_state`] keys on and that mlx-lm / mlx-swift write, so the *kind
/// labeling and wire format* are cross-tool (subject to the rotating-cache
/// `meta_state` arity caveat in the module docs: full mlx-lm round-trip;
/// mlx-swift parity for the wire format + non-rotating kinds). Adding a
/// new cache kind means overriding [`KvCache::reference_class_name`] on
/// it (and the corresponding [`from_state`] arm); no change here.
/// Save a pre-computed prompt cache to a `.safetensors` file — port of
/// `mlx_lm.models.cache.save_prompt_cache` (cache.py:43-59), wire-format
/// cross-checked vs mlx-swift-lm `savePromptCache`.
///
/// Emits the exact cross-tool layout (see the module docs): arrays keyed
/// `"{i}.{j}"`, and a string side-table with `meta_state` under
/// `"0.{i}.{j}"`, user `metadata` under `"1.{key}"`, and the **reference
/// class name** under `"2.{i}"`. Writes each cache's `meta_state`
/// verbatim — i.e. the *authoritative mlx-lm* shape (cache.py:53-56), so
/// the file loads unchanged in mlx-lm and (for the wire format +
/// non-rotating kinds) mlx-swift; rotating-cache `meta_state` follows
/// mlx-lm's 4-field form, which upstream-diverges from mlx-swift's 5-field
/// — see the module-doc compatibility scope. The cache state arrays are
/// not materialized here (no implicit eval — `crate::io` writes them
/// lazily).
/// The materialized length of a flattened list given its observed max
/// index `max_idx` and the number of *present* (distinct) indices
/// `present`.
///
/// A list flattened by `tree_flatten` (this / mlx-lm / mlx-swift) is always
/// **dense** — indices `0..len`, so `max_idx + 1 == present`. Returning
/// that length is the only allocation; bounding it to `present` (≤ the
/// distinct-key count, which the [`MAX_PROMPT_CACHE_BYTES`] file cap already
/// bounds) is what prevents a tiny hostile side-table (e.g. one
/// `"2.4000000000"` key) from driving a multi-GB `vec!`. A non-dense list
/// (`max_idx + 1 != present`) only arises from a corrupt / adversarial
/// file, so it is a recoverable typed [`Error`] variant, never a silent huge
/// allocation or a panic.
/// Parse the `"{i}.{j}"` flattened array map into a **sparse** per-cache-
/// index map of ordered array lists — the inverse of mlx-lm's
/// `tree_flatten` / `tree_unflatten` for the array map (swift
/// `unflattenArrays`).
///
/// Returns a sparse `HashMap<cache_index, Vec<Array>>` rather than a dense
/// `Vec`: a cache whose `state` is `[]` (an empty/unused cache) emits **no**
/// `"{i}.{j}"` array keys at all, so the array map cannot itself tell you
/// how many caches there are — the authoritative count is the
/// `cache_classes` list (`= [type(c).__name__ for c in cache]`, always
/// length `len(cache)`). The caller indexes this sparse map by that count
/// (`remove(&i).unwrap_or_default()`), which is *more* robust than mlx-lm's
/// `zip(classes, arrays, info)` (silently truncates to `len(arrays)` →
/// drops trailing empty-state caches) and mlx-swift's strict
/// `cacheData.count == cacheClasses.count` guard (rejects an all-empty
/// cache list outright); both refs misbehave on all-empty state, this
/// reconstructs it faithfully from the class list.
///
/// A key whose `i`/`j` is not a base-10 `usize` is **ignored** (swift
/// parity — `unflattenArrays` silently skips non-`"i.j"` keys); a
/// `usize`-overflowing sub-index is a recoverable typed [`Error`] variant (a
/// hostile file must not drive an unbounded `Vec` resize).
/// Parse the flattened string side-table back into `(cache_info,
/// user_metadata, cache_classes)` — the inverse of mlx-lm's `tree_flatten`
/// of `[cache_info, metadata, cache_classes]` (swift `unflattenMetadata`).
///
/// `cache_info[i][j]` from `"0.{i}.{j}"`, user metadata from `"1.{key}"`
/// (the key is everything after the first `.`, so a metadata key may itself
/// contain dots — matches swift `components.dropFirst().joined(".")`),
/// `cache_classes[i]` from `"2.{i}"`. Unparseable indices are skipped
/// (swift parity); a `usize`-overflowing index is a recoverable typed
/// [`Error`] variant.
///
/// `cache_info` is returned as a **sparse** `HashMap<cache_index,
/// Vec<String>>` (like the array map): a cache with an empty `meta_state`
/// (e.g. a [`StandardKvCache`](super::StandardKvCache)) emits **no**
/// `"0.{i}.*"` keys, so the
/// per-cache dimension is genuinely sparse and the caller indexes it by the
/// authoritative `cache_classes` count. `cache_classes` is a dense `Vec`
/// (always exactly one `"2.{i}"` per cache).
///
/// **Unbounded-allocation defense.** mlx-lm's `tree_unflatten` of a list
/// assumes *dense* indices (`0..len`) — a real cache (this / mlx-lm /
/// mlx-swift) always is. A hostile file's tiny side-table could otherwise
/// carry one key like `"2.4000000000"` (~13 bytes, well under
/// [`MAX_PROMPT_CACHE_BYTES`]) and drive a multi-GB `vec![String::new();
/// 4e9]`. The only `Vec`s sized from a max index are the **inner**
/// `meta_state[j]` list and the **dense** `cache_classes` list; both go
/// through [`dense_len`], which rejects a non-dense list (corrupt /
/// adversarial only — never a faithful save) and bounds the length by the
/// present-key count (itself file-size bounded). The sparse `cache_info`
/// per-cache dimension allocates nothing per absent index.
/// Load a prompt cache from a `.safetensors` file — port of
/// `mlx_lm.models.cache.load_prompt_cache` (cache.py:62-85), wire-format
/// cross-checked vs mlx-swift-lm `loadPromptCache`.
///
/// Returns `(caches, user_metadata)`. Each slot is reconstructed via
/// [`from_state`] keyed on the on-disk **reference class name** (the same
/// names mlx-lm / mlx-swift write), so a cache produced by mlx-lm (any
/// kind) or by mlx-swift (the shared wire format + non-rotating kinds)
/// loads here — subject to the rotating-cache `meta_state` arity caveat in
/// the module docs (a Swift-shaped 5-field `RotatingKVCache` is rejected
/// by the merged 4-field `RotatingKvCache::set_meta_state` via
/// `from_state`, exactly as it would be by authoritative mlx-lm; this is
/// the inherited upstream divergence, surfaced as a clean typed
/// [`Error`] variant, never a panic). The hostile-file discipline — see
/// the module-level
/// "Path-read DoS discipline" for the full posture, **including the
/// acknowledged residual TOCTOU that equals the merged `lm::load` weight
/// path** — runs the non-regular/size gate **before** the path is handed
/// to `crate::io`, then rank-validates every reconstructed state array; a
/// missing / non-regular / oversized / corrupt / count-mismatch /
/// non-dense / wrong-rank / unknown-kind file is a recoverable typed
/// [`Error`] variant, never a panic. No implicit eval — the reconstructed
/// caches hold the loaded arrays lazily.
/// Whether every cache in the model state can be trimmed — port of
/// `mlx_lm.models.cache.can_trim_prompt_cache` (cache.py:88-92):
/// `all(c.is_trimmable() for c in cache)` (vacuously `true` for an empty
/// list, exactly as Python's `all([])`).
/// Trim every cache by `num_tokens`, returning the number trimmed — port of
/// `mlx_lm.models.cache.trim_prompt_cache` (cache.py:95-111).
///
/// mlx-lm: `if not can_trim_prompt_cache(cache) or len(cache) == 0: return
/// 0; return [c.trim(num_tokens) for c in cache][0]` — every cache is
/// trimmed (the list comprehension calls `trim` on each), but the returned
/// count is the **first** cache's. Faithful: not-trimmable / empty → 0
/// (nothing is trimmed); otherwise trim all, return `cache[0]`'s count
/// (each layer's KV is the same length, so all trims agree, matching
/// mlx-lm's `[...][0]`).