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
//! Local model **load factory** + a [`model_type`](crate::lm::load::Config)
//! → constructor [`ModelTypeRegistry`], ported from the local-path slice of
//! [`mlx_lm.utils`](https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/utils.py)
//! (`load` / `load_model` / `load_config` / `_get_classes`) and
//! `mlx-swift-lm`'s `MLXLMCommon` (`ModelFactory` / `ModelConfiguration` /
//! `ModelTypeRegistry` / `BaseConfiguration`).
//!
//! This layer sits **on top of** [`crate::lm::load`] (which already ports the
//! arch-agnostic `config.json` parse + weight discovery + tokenizer build) and
//! adds the three pieces that turn a directory into a constructed model:
//!
//! - [`ModelConfiguration`] — the model's *location* (mlx-swift-lm's
//! `ModelConfiguration.Identifier`). An [`Identifier::Id`] (an
//! org/name string) is treated as a **local path** (there is **no**
//! Hugging Face Hub download — the network slice of `_download` /
//! `snapshot_download` is deliberately out of scope), exactly the
//! `path_or_hf_repo` already-local branch of `mlx_lm.utils._download`. An
//! optional [`ModelConfiguration::tokenizer_source`] lets the tokenizer load
//! from a different local directory (mlx-swift-lm's `tokenizerSource`); when
//! `None` the model directory is reused.
//! - [`ModelTypeRegistry`] — `model_type: &str` → a [`ModelConstructor`]
//! closure, mirroring mlx-swift-lm's
//! `ModelTypeRegistry<T>.creators: [String: (Data) throws -> T]` and
//! replacing `_get_classes`' Python `importlib.import_module(
//! "mlx_lm.models.{model_type}")` dynamic dispatch with an explicit,
//! compile-time-safe registration table. Per-model architectures are **out
//! of scope** (the project's no-model-arch rule), so the registry is the
//! *extension point* future per-usecase model PRs register their constructor
//! into — this PR ships the seam, not the architectures.
//! - [`load()`] — the end-to-end entry: resolve the directory → parse the
//! `config.json` `model_type` + load the weights + build the tokenizer
//! (all via [`crate::lm::load::load`]) → look the `model_type` up in the
//! registry (after [`remap_model_type`], mirroring `MODEL_REMAPPING`) →
//! invoke the constructor → return the `(Box<dyn Model>, Tokenizer)` pair.
//!
//! On top of that load surface sits [`ModelContext`] — a thin **owning
//! bundle** of the loaded `(model, tokenizer, config)` with ergonomic
//! convenience methods (`encode` / `decode` / `apply_chat_template` /
//! `generate` / `stream_generate`, each a thin forward to the tokenizer or
//! [`crate::lm::generate`]). It is the single-thread reduction of
//! mlx-swift-lm's `ModelContext` / `ModelContainer` — the actor concurrency of
//! the Swift `ModelContainer` is dropped because mlxrs's
//! [`Array`](crate::array::Array) is `!Send`/`!Sync` (see the
//! [`ModelContext`] type docs).
//!
//! Conventions match the rest of `lm`: every fallible step returns
//! [`Result`], recoverable failures (missing/invalid config, no weights,
//! unknown `model_type`, tokenizer load) are [`Error::Backend`] with a
//! message naming the cause, borrows are preferred over clones, and there is
//! no implicit eval (the weight `Array`s are handed to the constructor lazily,
//! exactly as [`crate::lm::load::load`] returns them).
use ;
use crateRankMismatchPayload;
use crate::;
/// Architecture-id remapping, mirroring `mlx_lm.utils.MODEL_REMAPPING`:
/// some checkpoints declare a `model_type` that is an alias for another
/// architecture's implementation (e.g. `"mistral"` is served by the `"llama"`
/// model). [`remap_model_type`] applies this before a [`ModelTypeRegistry`]
/// lookup so a registry only needs to register the *canonical* id.
///
/// Kept verbatim from `mlx_lm.utils` (the authoritative spec) so a checkpoint
/// that loads in mlx-lm dispatches to the same constructor here. Sorted by key
/// for a deterministic, reviewable table.
const MODEL_REMAPPING: & = &;
/// Canonicalize a checkpoint's `model_type` via the `MODEL_REMAPPING` table,
/// mirroring `mlx_lm.utils._get_classes`'s
/// `model_type = MODEL_REMAPPING.get(model_type, model_type)`. An id with no
/// alias is returned unchanged.
/// Everything [`crate::lm::load::load`] resolved from a model directory,
/// handed to a [`ModelConstructor`] so it can assemble (and, if
/// [`Config::quantization`] is set, quantize) a concrete architecture without
/// re-reading the directory.
///
/// Borrowing — the constructor gets `&LoadedModel`; it reads the typed
/// [`Config`] (and, for keys outside that typed subset, the verbatim
/// [`config_json`](Self::config_json) text — the analogue of mlx-swift-lm
/// passing the raw `config.json` `Data` to each model's `Codable` init) and
/// takes the weight [`Array`](crate::array::Array)s it needs out of
/// [`weights`](Self::weights) **by reference** (no implicit eval; mlx `Array`
/// is a cheap refcounted handle, so an arch clones only the handles it keeps).
/// A registered model constructor: assemble a [`Model`] from the
/// already-resolved [`LoadedModel`] (parsed config + raw config JSON +
/// weights).
///
/// Mirrors mlx-swift-lm's `ModelTypeRegistry` creator
/// `(Data) throws -> T` — but receives the *already-loaded* weights too (so a
/// per-usecase architecture never re-globs/re-reads the directory) and returns
/// a [`Result`] (Rust's `throws`). `Send + Sync` so a registry can be shared
/// across threads (e.g. a `static` shared registry, as mlx-swift-lm's
/// `LLMTypeRegistry.shared` is). The constructor itself does **no** I/O; the
/// directory was already read by [`load()`].
pub type ModelConstructor =
;
/// A `model_type: String` → [`ModelConstructor`] table, the load factory's
/// architecture **extension point**.
///
/// Mirrors mlx-swift-lm's `ModelTypeRegistry<T>` (and replaces
/// `mlx_lm.utils._get_classes`' `importlib` dynamic dispatch with an explicit
/// registration table). Per-model architectures are out of scope for this PR,
/// so the registry starts [`empty`](Self::new); future per-usecase model PRs
/// call [`register`](Self::register) (or build one with
/// [`with`](Self::with)) to plug their architecture in. A `model_type` is
/// canonicalized via [`remap_model_type`] on both registration and lookup, so
/// callers register the *canonical* id and any alias resolves to it.
/// Which local directory holds a model (mlx-swift-lm's
/// `ModelConfiguration.Identifier`).
///
/// **No network**: an [`Id`](Self::Id) (an org/name string) is treated as a
/// *local path* — the already-local branch of `mlx_lm.utils._download`
/// (`Path(path_or_hf_repo)` when `model_path.exists()`); the
/// `snapshot_download` Hub fetch is out of scope. So both variants resolve to
/// a [`Path`] without any I/O beyond the later directory read in [`load()`].
/// Where to load a model and (optionally) its tokenizer from, ported from the
/// **local-path slice** of mlx-swift-lm's `ModelConfiguration`.
///
/// Behavioural metadata that mlx-swift-lm's `ModelConfiguration` carries
/// (`defaultPrompt` / `extraEOSTokens` / `toolCallFormat`) is intentionally
/// **not** modeled here: the eos set is already resolved from
/// `config.json` + `generation_config.json` by [`crate::lm::load::load`]
/// (and lives on the [`Tokenizer`]), and prompt/tool-format are
/// chat-pipeline concerns layered above this loader. This type is purely the
/// *source location* (model dir + optional separate tokenizer dir).
/// The product of [`load()`]: a constructed [`Model`] plus the
/// [`Tokenizer`] and the parsed [`Config`], the analogue of mlx-swift-lm's
/// `ModelContext` (restricted to the text-LM essentials — no
/// `UserInputProcessor`, which is a chat-pipeline concern above this loader).
/// Load a model + tokenizer from a local [`ModelConfiguration`], dispatching
/// to `registry` on the checkpoint's `model_type`.
///
/// The end-to-end port of `mlx_lm.utils.load` restricted to the local-path,
/// no-network surface (and mlx-swift-lm's `GenericModelFactory._load`). The
/// orchestration order is chosen so the *cheap, recoverable* failures come
/// first — nothing heavy (weights, tokenizer) is touched until the checkpoint
/// is known to be loadable:
///
/// 1. Resolve the model directory ([`ModelConfiguration::model_directory`] —
/// local, no Hub download) and read `config.json` **once** via
/// [`crate::lm::load::load_config`], yielding both the typed [`Config`]
/// (with the `generation_config.json` eos override applied) and the
/// verbatim JSON body — the *same bytes* the typed config was parsed from,
/// so the constructor's typed [`Config`] and raw
/// [`config_json`](LoadedModel::config_json) can never diverge across two
/// opens.
/// 2. **Validate the `model_type` is registered** (after [`remap_model_type`])
/// *before* loading anything heavy: an unsupported checkpoint is a cheap,
/// recoverable [`Error::Backend`] here, with no weight/tokenizer I/O —
/// mlx-lm's `ValueError("Model type … not supported.")` /
/// mlx-swift-lm's `unsupportedModelType`.
/// 3. Select the tokenizer directory FIRST
/// ([`tokenizer_source`](ModelConfiguration::tokenizer_source) if set, else
/// the model directory — mlx-swift-lm's `tokenizerDirectory`).
/// 4. Discover and merge the weights from the model directory via
/// [`crate::lm::load::load_weights`].
/// 5. Build the [`Tokenizer`] EXACTLY ONCE from the selected directory (with
/// the eos set resolved on the [`Config`] from step 1).
/// 6. Construct the model via `registry` on the [`LoadedModel`] (parsed config
/// + raw JSON + weights) and return it with the tokenizer and config.
///
/// Per-model construction is the registry's job (this PR ships no
/// architectures). No implicit eval — the weights reach the constructor lazily.
/// An owning bundle of a loaded `(model, tokenizer, config)` with ergonomic
/// convenience entry points — the single-thread reduction of mlx-swift-lm's
/// `ModelContext` / `ModelContainer`.
///
/// # Relationship to [`LoadedModelContext`]
///
/// [`load()`] returns a [`LoadedModelContext`] — the loader's plain *product*
/// struct (public fields, no behavior). [`ModelContext`] is the **owning
/// context** layered on top: it takes the same three values by value and adds
/// the convenience surface (`encode` / `decode` / `apply_chat_template` /
/// `generate` / `stream_generate`) so a caller need not thread `&model`,
/// `&tokenizer` and a hand-built `CacheConfig` through every `lm::generate`
/// call. Build one straight from a load with [`From<LoadedModelContext>`]
/// (`load(..)?.into()`) or the [`ModelContext::load`] one-call convenience.
///
/// # Actor → single-thread divergence (intentional)
///
/// mlx-swift-lm's `ModelContainer` is a Swift **`actor`** — it exists to share
/// one model safely across threads, serializing access to the non-`Sendable`
/// `MLXArray`s inside. mlxrs's [`Array`](crate::array::Array) is deliberately
/// `!Send`/`!Sync` (single-thread, matching MLX's own threading model), so a
/// faithful actor port is **inapplicable**: there is no cross-thread sharing
/// to serialize. [`ModelContext`] therefore ports the *logic* of
/// `ModelContext` / `ModelContainer` — the `(model, tokenizer, config)`
/// ownership plus the convenience entry points — as a plain single-thread
/// owning struct, dropping only the actor concurrency machinery (the
/// `SerialAccessContainer`, the `perform` closure isolation, the `Sendable` /
/// `sending` annotations). This mirrors how the project already handles the
/// other Swift `actor` types it ports.
///
/// # API conventions
///
/// Matches the rest of `lm`: every fallible call returns [`Result`]; accessors
/// ([`model`](Self::model) / [`tokenizer`](Self::tokenizer) /
/// [`config`](Self::config)) borrow and never eval (no implicit eval — the
/// owned [`Array`](crate::array::Array) weights are touched only by an explicit
/// `generate` forward pass). The convenience methods are **thin forwards** —
/// `encode` / `decode` / `apply_chat_template` defer to the [`Tokenizer`],
/// `generate` / `stream_generate` defer to [`crate::lm::generate`] — they
/// re-implement nothing.
///
/// The generation methods take `&self`, not `&mut self`: a [`ModelContext`]
/// owns **no** KV cache (model weights are immutable after load — see the
/// [`Model`] trait — and [`crate::lm::generate`] takes `&M`). Each `generate`
/// / `stream_generate` call builds a *fresh* per-call cache (sized from
/// [`Config::num_hidden_layers`] / [`Config::sliding_window`] via
/// [`crate::lm::cache::make_prompt_cache`]) that the call consumes, so the
/// context is never mutated. A persistent multi-turn cache is a chat-session
/// concern layered above this bundle (mlx-swift-lm's `ChatSession`), not part
/// of the `ModelContext` reduction.