inky-engine 3.0.0

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
//! Runtime LoRA on the attention projections (`INK_LORA`, an internal experiment switch).
//!
//! A PEFT LoRA adapter for Inkling 2 Mini (for example harness-hub/Inkling-2-Mini-pi-adapted: rank 32, alpha 64,
//! on q / k / v / o of all 24 layers) is applied beside the quantized base weights instead of being merged into them:
//!
//! ```text
//!     y = W x + scale * B (A x),    scale = lora_alpha / r   (lora_alpha / sqrt(r) with use_rslora)
//! ```
//!
//! `W x` is the engine's unchanged GEMM on the GGUF's quantized weights. `A x` and `B (.)` run in fp32 from fp32
//! copies of the adapter (`k_lora_a`, `k_lora_b` in `lora.metal`), so the base quantization cannot round the update
//! away the way a merge into BF16 or Q8_0 does. Unset, nothing is loaded, no kernel is dispatched and every output is
//! the engine's own, bit for bit.
//!
//! `INK_LORA` names either the adapter directory (`adapter_config.json` + `adapter_model.safetensors`) or the
//! `.safetensors` file itself (its `adapter_config.json` beside it). The primary layout is the checkpoint's native
//! names, F32 (`...llm.layers.N.attn.{wq_du,wk_dv,wv_dv,wo_ud}.lora_{A,B}.weight`, the harness-hub adapter's `vllm/`
//! folder, which a directory's `vllm/` copy is taken from first, and how our own adapters are exported); PEFT's
//! transformers names (`...language_model.layers.N.self_attn.q_proj.linear.lora_A.weight`) load too. Every tensor of the file must map,
//! every (layer, projection) must be present once, and every shape must match the loaded GGUF.
//!
//! GGUF mapping (the GGUF stores each matrix as rows = outputs, row length = inputs, the same orientation as the
//! checkpoint's `[out, in]`):
//!
//! | projection | PEFT module          | official / vLLM | GGUF                 | A          | B          |
//! |------------|----------------------|-----------------|----------------------|------------|------------|
//! | q          | `self_attn.q_proj`   | `attn.wq_du`    | `blk.N.attn_q`       | [r, 2304]  | [3072, r]  |
//! | k          | `self_attn.k_proj`   | `attn.wk_dv`    | `blk.N.attn_k`       | [r, 2304]  | [1024, r]  |
//! | v          | `self_attn.v_proj`   | `attn.wv_dv`    | `blk.N.attn_v`       | [r, 2304]  | [1024, r]  |
//! | o          | `self_attn.o_proj`   | `attn.wo_ud`    | `blk.N.attn_output`  | [r, 3072]  | [2304, r]  |
//!
//! The looped layers (6..18, three passes) apply their layer's adapter on every pass, as the checkpoint's module does.
//!
//! Several adapters on one base (design; today `INK_LORA` loads one and every lane uses it): adapters live in a
//! [`Registry`] by [`AdapterId`] (0 = the base model, `i` = `adapters[i - 1]`), sharing one scratch; each `Lane`
//! carries the id its rows run with. A batch whose lanes all carry one id runs that adapter's two dispatches; mixed
//! batches are refused for now (`Engine::batch_adapter`). Per-row selection is the next step: the kernels take a
//! per-row adapter id (a `u16` table beside the row offsets, as the MoE gather does), `k_lora_a` reads its
//! threadgroup's row tile's adapter (tiles never straddle lanes: pad each span to `ROWS_PER_TG` rows, or split the
//! tile), and `k_lora_b` the same; rows on id 0 skip both. Requests would pick an adapter through the API as a model
//! alias (`"model": "inkling-pi"` -> id 1, the way vLLM's `--lora-modules name=path` serves them, which every
//! OpenAI / Anthropic client already sends) with an optional request field for tools that cannot change the model
//! name; the server resolves it at admission and sets the lane's id. Cache identity then has to carry the id:
//! prefix and spill keys must include the adapter's fingerprint (today the model fingerprint mixes in the default
//! adapter, which is exact while every lane shares it).

use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};

/// Largest rank the kernels take: one simdgroup lane per rank component.
pub const MAX_RANK: usize = 32;
/// Rows of one `k_lora_a` / `k_lora_b` threadgroup (`LORA_RT` in `lora.metal`).
pub const ROWS_PER_TG: usize = 8;
/// `k_lora_a`'s k-split: every matrix's `k` is cut into `8 * KSPLIT` slices (8 simdgroups of `KSPLIT` threadgroups),
/// whatever the batch, so a row's sums run in one fixed order at every width (batch invariance) and a decode-sized
/// batch still spreads over enough threadgroups. 2304 and 3072 both divide by 64.
pub const KSPLIT: usize = 8;
/// Projections in the order of [`Proj`].
pub const PROJS: [Proj; 4] = [Proj::Q, Proj::K, Proj::V, Proj::O];

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Proj {
    Q,
    K,
    V,
    O,
}

impl Proj {
    pub fn index(self) -> usize {
        self as usize
    }
    /// The GGUF tensor this projection's update is added beside.
    pub fn gguf_name(self, layer: usize) -> String {
        let s = match self {
            Proj::Q => "attn_q",
            Proj::K => "attn_k",
            Proj::V => "attn_v",
            Proj::O => "attn_output",
        };
        format!("blk.{layer}.{s}.weight")
    }
    /// (inputs, outputs) of the base matrix for the model's dimensions.
    pub fn dims(self, e: usize, q_dim: usize, kv_dim: usize) -> (usize, usize) {
        match self {
            Proj::Q => (e, q_dim),
            Proj::K | Proj::V => (e, kv_dim),
            Proj::O => (q_dim, e),
        }
    }
}

/// `(layer, projection, is_b)` of an adapter tensor name, under either naming the adapter ships.
pub fn parse_tensor_name(name: &str) -> Option<(usize, Proj, bool)> {
    let (stem, is_b) = match name.strip_suffix(".lora_A.weight") {
        Some(s) => (s, false),
        None => (name.strip_suffix(".lora_B.weight")?, true),
    };
    // PEFT (transformers): base_model.model.model.language_model.layers.N.self_attn.q_proj.linear
    if let Some(rest) = stem.strip_prefix("base_model.model.model.language_model.layers.") {
        let (layer, tail) = rest.split_once('.')?;
        let proj = match tail {
            "self_attn.q_proj.linear" | "self_attn.q_proj" => Proj::Q,
            "self_attn.k_proj.linear" | "self_attn.k_proj" => Proj::K,
            "self_attn.v_proj.linear" | "self_attn.v_proj" => Proj::V,
            "self_attn.o_proj.linear" | "self_attn.o_proj" => Proj::O,
            _ => return None,
        };
        return Some((layer.parse().ok()?, proj, is_b));
    }
    // official checkpoint names (the adapter's vllm/ copy): base_model.model.model.llm.layers.N.attn.wq_du
    let rest = stem
        .strip_prefix("base_model.model.model.llm.layers.")
        .or_else(|| stem.strip_prefix("base_model.model.llm.layers."))?;
    let (layer, tail) = rest.split_once('.')?;
    let proj = match tail {
        "attn.wq_du" => Proj::Q,
        "attn.wk_dv" => Proj::K,
        "attn.wv_dv" => Proj::V,
        "attn.wo_ud" => Proj::O,
        _ => return None,
    };
    Some((layer.parse().ok()?, proj, is_b))
}

/// One projection's update: `a` is `[rank][k]` row-major, `b` is `[nout][rank]` row-major (the checkpoint's layouts).
#[derive(Clone, Debug, PartialEq)]
pub struct LoraMat {
    pub k: usize,
    pub nout: usize,
    pub a: Vec<f32>,
    pub b: Vec<f32>,
}

/// A parsed adapter: per layer, q / k / v / o.
#[derive(Clone, Debug)]
pub struct LoraAdapter {
    pub rank: usize,
    pub alpha: f64,
    pub scale: f32,
    pub layers: Vec<[LoraMat; 4]>,
    pub source: String,
}

fn bad(msg: impl std::fmt::Display) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, format!("INK_LORA: {msg}"))
}

/// The adapter's config and weights files for an `INK_LORA` value.
/// A directory's native-name copy (`vllm/`, the checkpoint's own module names: the primary layout, and the one our
/// adapters are exported in) wins over its PEFT-name root; the two hold the same numbers.
pub fn adapter_files(path: &Path) -> (PathBuf, PathBuf) {
    let native = path.join("vllm");
    if native.join("adapter_model.safetensors").is_file() && native.join("adapter_config.json").is_file() {
        (native.join("adapter_config.json"), native.join("adapter_model.safetensors"))
    } else if path.is_dir() {
        (path.join("adapter_config.json"), path.join("adapter_model.safetensors"))
    } else {
        let dir = path.parent().unwrap_or(Path::new("."));
        (dir.join("adapter_config.json"), path.to_path_buf())
    }
}

/// `(rank, alpha, scale)` from a PEFT `adapter_config.json`. Refuses what this runtime does not compute: DoRA, biases,
/// per-module rank or alpha patterns, a layer subset, a transposed layout, other PEFT methods.
pub fn parse_config(text: &str) -> io::Result<(usize, f64, f32)> {
    let v: serde_json::Value = serde_json::from_str(text).map_err(|e| bad(format!("adapter_config.json: {e}")))?;
    let peft = v.get("peft_type").and_then(|x| x.as_str()).unwrap_or("LORA");
    if peft != "LORA" {
        return Err(bad(format!("peft_type {peft}, expected LORA")));
    }
    let rank = v.get("r").and_then(|x| x.as_u64()).ok_or_else(|| bad("adapter_config.json has no integer r"))? as usize;
    let alpha =
        v.get("lora_alpha").and_then(|x| x.as_f64()).ok_or_else(|| bad("adapter_config.json has no lora_alpha"))?;
    if rank == 0 || rank > MAX_RANK {
        return Err(bad(format!("rank {rank}: the kernels take 1..={MAX_RANK}")));
    }
    if !(alpha.is_finite() && alpha > 0.0) {
        return Err(bad(format!("lora_alpha {alpha}")));
    }
    let flag = |k: &str| v.get(k).and_then(|x| x.as_bool()).unwrap_or(false);
    for k in ["use_dora", "fan_in_fan_out", "use_qalora", "lora_bias"] {
        if flag(k) {
            return Err(bad(format!("{k} is set; only plain LoRA is supported")));
        }
    }
    if let Some(b) = v.get("bias").and_then(|x| x.as_str()) {
        if b != "none" {
            return Err(bad(format!("bias {b}; only bias none is supported")));
        }
    }
    for k in ["rank_pattern", "alpha_pattern"] {
        if v.get(k).and_then(|x| x.as_object()).is_some_and(|m| !m.is_empty()) {
            return Err(bad(format!("{k} is not empty; one rank and alpha for every module is supported")));
        }
    }
    for k in ["layers_to_transform", "modules_to_save", "layer_replication", "trainable_token_indices"] {
        if v.get(k).is_some_and(|x| !x.is_null()) {
            return Err(bad(format!("{k} is set; not supported")));
        }
    }
    let scale = if flag("use_rslora") { alpha / (rank as f64).sqrt() } else { alpha / rank as f64 };
    Ok((rank, alpha, scale as f32))
}

/// One tensor of a safetensors file: dtype, shape, raw little-endian bytes.
pub type StTensor<'a> = (String, Vec<usize>, &'a [u8]);

/// The tensors of a safetensors file by name.
pub fn read_safetensors(bytes: &[u8]) -> io::Result<HashMap<String, StTensor<'_>>> {
    if bytes.len() < 8 {
        return Err(bad("safetensors file shorter than its header length"));
    }
    let n = u64::from_le_bytes(bytes[..8].try_into().unwrap());
    let body = usize::try_from(n)
        .ok()
        .and_then(|n| 8usize.checked_add(n))
        .filter(|&e| e <= bytes.len())
        .ok_or_else(|| bad("safetensors header runs past the file"))?;
    let hdr: serde_json::Map<String, serde_json::Value> =
        serde_json::from_slice(&bytes[8..body]).map_err(|e| bad(format!("safetensors header: {e}")))?;
    let data = &bytes[body..];
    let mut out = HashMap::new();
    for (name, t) in hdr {
        if name == "__metadata__" {
            continue;
        }
        let dtype =
            t.get("dtype").and_then(|x| x.as_str()).ok_or_else(|| bad(format!("{name}: no dtype")))?.to_string();
        let shape: Vec<usize> = t
            .get("shape")
            .and_then(|x| x.as_array())
            .ok_or_else(|| bad(format!("{name}: no shape")))?
            .iter()
            .map(|d| d.as_u64().map(|d| d as usize))
            .collect::<Option<_>>()
            .ok_or_else(|| bad(format!("{name}: bad shape")))?;
        let offs =
            t.get("data_offsets").and_then(|x| x.as_array()).ok_or_else(|| bad(format!("{name}: no data_offsets")))?;
        let (a, z) = match offs.as_slice() {
            [a, z] => (a.as_u64().unwrap_or(u64::MAX) as usize, z.as_u64().unwrap_or(u64::MAX) as usize),
            _ => return Err(bad(format!("{name}: bad data_offsets"))),
        };
        if a > z || z > data.len() {
            return Err(bad(format!("{name}: data_offsets [{a}, {z}) outside the file")));
        }
        out.insert(name, (dtype, shape, &data[a..z]));
    }
    Ok(out)
}

fn to_f32(name: &str, dtype: &str, raw: &[u8], n: usize) -> io::Result<Vec<f32>> {
    let width = match dtype {
        "F32" => 4,
        "BF16" | "F16" => 2,
        _ => return Err(bad(format!("{name}: dtype {dtype}; F32, BF16 or F16 expected"))),
    };
    if raw.len() != n * width {
        return Err(bad(format!("{name}: {} bytes for {n} {dtype} values", raw.len())));
    }
    let v: Vec<f32> = match dtype {
        "F32" => raw.as_chunks::<4>().0.iter().map(|&c| f32::from_le_bytes(c)).collect(),
        "BF16" => {
            raw.as_chunks::<2>().0.iter().map(|&c| f32::from_bits((u16::from_le_bytes(c) as u32) << 16)).collect()
        }
        _ => raw.as_chunks::<2>().0.iter().map(|&c| crate::blocks::f16_bits_to_f32(u16::from_le_bytes(c))).collect(),
    };
    if let Some(i) = v.iter().position(|x| !x.is_finite()) {
        return Err(bad(format!("{name}: non-finite value at {i}")));
    }
    Ok(v)
}

impl LoraAdapter {
    /// Parse an adapter for a model of `n_layers` layers, hidden size `e`, `q_dim` query and `kv_dim` key/value
    /// outputs. Every tensor must map and every (layer, projection) must be present with the shapes the model has.
    pub fn parse(
        config: &str,
        weights: &[u8],
        n_layers: usize,
        e: usize,
        q_dim: usize,
        kv_dim: usize,
        source: &str,
    ) -> io::Result<LoraAdapter> {
        let (rank, alpha, scale) = parse_config(config)?;
        let tensors = read_safetensors(weights)?;
        let mut slots: Vec<[Option<LoraMat>; 4]> = (0..n_layers).map(|_| [None, None, None, None]).collect();
        let mut names: Vec<&String> = tensors.keys().collect();
        names.sort();
        let mut seen: HashMap<(usize, Proj, bool), &str> = HashMap::new();
        for name in names {
            let (layer, proj, is_b) = parse_tensor_name(name)
                .ok_or_else(|| bad(format!("tensor {name} is not a q/k/v/o attention LoRA matrix of this model")))?;
            if layer >= n_layers {
                return Err(bad(format!("{name}: layer {layer} of a {n_layers}-layer model")));
            }
            if let Some(prev) = seen.insert((layer, proj, is_b), name) {
                return Err(bad(format!("{name} and {prev} are the same matrix")));
            }
            let (k, nout) = proj.dims(e, q_dim, kv_dim);
            let want = if is_b { vec![nout, rank] } else { vec![rank, k] };
            let (dtype, shape, raw) = &tensors[name];
            if *shape != want {
                return Err(bad(format!(
                    "{name}: shape {shape:?}, the model's {} needs {want:?}",
                    proj.gguf_name(layer)
                )));
            }
            let vals = to_f32(name, dtype, raw, want[0] * want[1])?;
            let slot = &mut slots[layer][proj.index()];
            let m = slot.get_or_insert_with(|| LoraMat { k, nout, a: Vec::new(), b: Vec::new() });
            if is_b {
                m.b = vals;
            } else {
                m.a = vals;
            }
        }
        let mut layers = Vec::with_capacity(n_layers);
        for (l, s) in slots.into_iter().enumerate() {
            let mut out = Vec::with_capacity(4);
            for (p, m) in PROJS.iter().zip(s) {
                let m = m.ok_or_else(|| bad(format!("no update for {}", p.gguf_name(l))))?;
                if m.a.is_empty() || m.b.is_empty() {
                    return Err(bad(format!("{}: lora_A or lora_B is missing", p.gguf_name(l))));
                }
                out.push(m);
            }
            layers.push(out.try_into().unwrap());
        }
        Ok(LoraAdapter { rank, alpha, scale, layers, source: source.to_string() })
    }

    pub fn load(path: &Path, n_layers: usize, e: usize, q_dim: usize, kv_dim: usize) -> io::Result<LoraAdapter> {
        let (cfg, st) = adapter_files(path);
        let config = std::fs::read_to_string(&cfg).map_err(|e| bad(format!("{}: {e}", cfg.display())))?;
        let weights = std::fs::read(&st).map_err(|e| bad(format!("{}: {e}", st.display())))?;
        Self::parse(&config, &weights, n_layers, e, q_dim, kv_dim, &st.display().to_string())
    }

    /// The kernels' fp32 image and each matrix's place in it: per (layer, projection) `A^T` as `[k][MAX_RANK]` and
    /// `B` as `[nout][MAX_RANK]`, ranks past `rank` zero, every matrix 16-byte aligned.
    pub fn pack(&self) -> (Vec<f32>, Vec<[LoraSlot; 4]>) {
        let r = self.rank;
        let mut img: Vec<f32> = Vec::new();
        let mut slots = Vec::with_capacity(self.layers.len());
        for l in &self.layers {
            let mut ls = [LoraSlot::default(); 4];
            for (p, m) in l.iter().enumerate() {
                let at_off = img.len();
                img.resize(at_off + m.k * MAX_RANK, 0.0);
                for i in 0..r {
                    for c in 0..m.k {
                        img[at_off + c * MAX_RANK + i] = m.a[i * m.k + c];
                    }
                }
                let b_off = img.len();
                img.resize(b_off + m.nout * MAX_RANK, 0.0);
                for o in 0..m.nout {
                    img[b_off + o * MAX_RANK..][..r].copy_from_slice(&m.b[o * r..][..r]);
                }
                ls[p] = LoraSlot { at_off: at_off as u32, b_off: b_off as u32, k: m.k as u32, nout: m.nout as u32 };
            }
            slots.push(ls);
        }
        (img, slots)
    }

    /// A 64-bit identity of the update (scale and every weight), mixed into the model fingerprint so no cache made
    /// without the adapter (or with another) is reused with it.
    pub fn fingerprint(&self) -> u64 {
        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
        let mut eat = |w: u32| {
            h ^= w as u64;
            h = h.wrapping_mul(0x0000_0100_0000_01b3);
        };
        eat(self.rank as u32);
        eat(self.scale.to_bits());
        for l in &self.layers {
            for m in l {
                m.a.iter().chain(&m.b).for_each(|x| eat(x.to_bits()));
            }
        }
        h
    }
}

/// Adapter id of a lane or a request: 0 is the base model (no adapter), `i > 0` is `Registry::adapters[i - 1]`.
pub type AdapterId = u16;
/// The base model, no adapter.
pub const NO_ADAPTER: AdapterId = 0;

/// One adapter on the GPU: its packed fp32 image (buffer 15 of `k_lora_a` / `k_lora_b`).
pub struct LoraGpu {
    pub w: crate::metal::Buf,
    pub scale: f32,
    pub slots: Vec<[LoraSlot; 4]>,
    pub fingerprint: u64,
    /// What a schema v2 record names this adapter by (`adapter_id`, [`record_id`]); set by whoever knows its path.
    pub record_id: std::sync::Arc<str>,
}

impl LoraGpu {
    pub fn new(gpu: &crate::metal::Gpu, ad: &LoraAdapter) -> LoraGpu {
        let (img, slots) = ad.pack();
        let bytes: Vec<u8> = img.iter().flat_map(|x| x.to_le_bytes()).collect();
        let fingerprint = ad.fingerprint();
        LoraGpu { w: gpu.buffer_with(&bytes), scale: ad.scale, slots, fingerprint, record_id: record_id("", fingerprint).into() }
    }
}

/// The adapter directory's basename for an `INK_LORA` value: the directory itself, or a weights file's parent.
pub fn adapter_dir_name(path: &Path) -> String {
    let dir = if path.is_dir() { path } else { path.parent().unwrap_or(Path::new("")) };
    dir.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned())
}

/// A loaded adapter's id in a schema v2 record (`adapter_id`, docs/RECORD-FORMAT.md): its directory's basename, `@`,
/// and its [`LoraAdapter::fingerprint`] (the identity the caches key on) as 16 lowercase hex digits. The fingerprint
/// alone identifies the weights; the name is for people. The base model has none (`null`).
pub fn record_id(dir_name: &str, fingerprint: u64) -> String {
    format!("{dir_name}@{fingerprint:016x}")
}

/// Every adapter loaded on one base model, by [`AdapterId`], and the rank-space scratch they share (buffer 16),
/// grown with the batch arena (`Engine::ensure_batch`, when nothing is in flight). Today `INK_LORA` loads at most
/// one adapter (id 1) and every lane takes it; the ids are there so lanes (requests) can pick different adapters.
pub struct Registry {
    pub adapters: Vec<LoraGpu>,
    pub scratch: std::cell::RefCell<Option<crate::metal::Buf>>,
    /// floats the scratch holds
    pub scratch_cap: std::cell::Cell<usize>,
    /// the adapter a new lane starts with
    pub default_id: AdapterId,
}

impl Default for Registry {
    fn default() -> Registry {
        Registry {
            adapters: Vec::new(),
            scratch: Default::default(),
            scratch_cap: Default::default(),
            default_id: NO_ADAPTER,
        }
    }
}

impl Registry {
    pub fn is_empty(&self) -> bool {
        self.adapters.is_empty()
    }
    /// The adapter of `id`; `None` for the base model. An id past the registry is a caller bug.
    pub fn get(&self, id: AdapterId) -> Option<&LoraGpu> {
        match id {
            NO_ADAPTER => None,
            i => Some(self.adapters.get(i as usize - 1).unwrap_or_else(|| panic!("no LoRA adapter {i} loaded"))),
        }
    }
    /// Register an adapter; returns its id.
    pub fn add(&mut self, gpu: &crate::metal::Gpu, g: LoraGpu, rows: usize) -> AdapterId {
        self.adapters.push(g);
        self.reserve_rows(gpu, rows);
        AdapterId::try_from(self.adapters.len()).expect("adapter ids fit u16")
    }
    /// Grow the shared scratch for batches of `rows` rows. Nothing may be in flight on the GPU (command buffers do not
    /// retain it). Nothing without an adapter.
    pub fn reserve_rows(&self, gpu: &crate::metal::Gpu, rows: usize) {
        let need = scratch_floats(rows);
        if !self.is_empty() && need > self.scratch_cap.get() {
            *self.scratch.borrow_mut() = Some(gpu.buffer(need * 4));
            self.scratch_cap.set(need);
        }
    }
    /// A 64-bit identity of the default adapter (0 without one), mixed into the model fingerprint.
    pub fn default_fingerprint(&self) -> u64 {
        self.get(self.default_id).map_or(0, |a| a.fingerprint)
    }
    /// The record's `adapter_id` for a lane on `id`: `None` for the base model, else the adapter's [`record_id`].
    pub fn record_id(&self, id: AdapterId) -> Option<std::sync::Arc<str>> {
        self.get(id).map(|a| a.record_id.clone())
    }

    /// The registry `INK_LORA` asks for, on a model whose layer `l` has projections of `(inputs, outputs)`
    /// `dims(l, proj)`: its adapter as id 1 and every lane's default, or an empty registry when it is unset or empty.
    pub fn from_env(
        gpu: &crate::metal::Gpu,
        n_layers: usize,
        dims: impl Fn(usize, Proj) -> (usize, usize),
        rows: usize,
    ) -> io::Result<Registry> {
        let mut reg = Registry::default();
        let Some(path) = std::env::var_os("INK_LORA").filter(|p| !p.is_empty()) else { return Ok(reg) };
        let (e, q_dim) = dims(0, Proj::Q);
        let (_, kv_dim) = dims(0, Proj::K);
        let ad = LoraAdapter::load(Path::new(&path), n_layers, e, q_dim, kv_dim)?;
        for (l, ms) in ad.layers.iter().enumerate() {
            for (p, m) in PROJS.iter().zip(ms) {
                let (k, nout) = dims(l, *p);
                if (m.k, m.nout) != (k, nout) {
                    return Err(bad(format!(
                        "{}: the GGUF has {k} inputs x {nout} outputs, the adapter {} x {}",
                        p.gguf_name(l),
                        m.k,
                        m.nout
                    )));
                }
            }
        }
        let mut g = LoraGpu::new(gpu, &ad);
        g.record_id = record_id(&adapter_dir_name(Path::new(&path)), g.fingerprint).into();
        gpu.pso("k_lora_a");
        gpu.pso("k_lora_b");
        eprintln!(
            "[inky] INK_LORA: adapter 1 = {} (rank {}, alpha {}, scale {}, {} matrices, {:.1} MiB fp32) on q/k/v/o of {} layers, every lane",
            ad.source,
            ad.rank,
            ad.alpha,
            ad.scale,
            4 * ad.layers.len() * 2,
            (g.slots.iter().flatten().map(|s| (s.k + s.nout) as usize).sum::<usize>() * MAX_RANK * 4) as f64
                / (1 << 20) as f64,
            ad.layers.len()
        );
        reg.default_id = reg.add(gpu, g, rows);
        Ok(reg)
    }
}

/// Where one matrix pair lives in the packed image (offsets in floats).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LoraSlot {
    pub at_off: u32,
    pub b_off: u32,
    pub k: u32,
    pub nout: u32,
}

#[cfg(test)]
/// CPU reference of one projection's update on `rows` rows of `x` (`[rows][k]`): `scale * B (A x)` in f64.
pub fn reference_delta(m: &LoraMat, rank: usize, scale: f64, x: &[f32], rows: usize) -> Vec<f64> {
    let mut out = vec![0.0f64; rows * m.nout];
    let mut u = vec![0.0f64; rank];
    for r in 0..rows {
        let xr = &x[r * m.k..][..m.k];
        for (i, ui) in u.iter_mut().enumerate() {
            *ui = m.a[i * m.k..][..m.k].iter().zip(xr).map(|(&a, &x)| a as f64 * x as f64).sum();
        }
        for o in 0..m.nout {
            out[r * m.nout + o] =
                scale * m.b[o * rank..][..rank].iter().zip(&u).map(|(&b, &u)| b as f64 * u).sum::<f64>();
        }
    }
    out
}

/// Floats of rank-space scratch for `rows` rows: the partial sums of up to four jobs.
pub fn scratch_floats(rows: usize) -> usize {
    rows.max(1).div_ceil(ROWS_PER_TG) * ROWS_PER_TG * 4 * MAX_RANK * KSPLIT
}

#[cfg(test)]
mod tests {
    use super::*;

    const CFG: &str = r#"{"peft_type":"LORA","r":4,"lora_alpha":8,"bias":"none","use_dora":false,"use_rslora":false,
        "fan_in_fan_out":false,"rank_pattern":{},"alpha_pattern":{},"layers_to_transform":null,"modules_to_save":null,
        "target_modules":".*self_attn\\.(q_proj|k_proj|v_proj|o_proj)\\.linear"}"#;

    /// A safetensors image of `tensors` (name, shape, f32 values).
    pub(crate) fn safetensors_f32(tensors: &[(String, Vec<usize>, Vec<f32>)]) -> Vec<u8> {
        let mut hdr = serde_json::Map::new();
        let mut data = Vec::new();
        for (name, shape, vals) in tensors {
            let a = data.len();
            vals.iter().for_each(|v| data.extend_from_slice(&v.to_le_bytes()));
            hdr.insert(
                name.clone(),
                serde_json::json!({"dtype": "F32", "shape": shape, "data_offsets": [a, data.len()]}),
            );
        }
        hdr.insert("__metadata__".into(), serde_json::json!({"format": "pt"}));
        let mut h = serde_json::to_vec(&hdr).unwrap();
        while !h.len().is_multiple_of(8) {
            h.push(b' ');
        }
        let mut out = (h.len() as u64).to_le_bytes().to_vec();
        out.extend_from_slice(&h);
        out.extend_from_slice(&data);
        out
    }

    fn peft_name(layer: usize, p: Proj, b: bool) -> String {
        let m = ["q", "k", "v", "o"][p.index()];
        format!(
            "base_model.model.model.language_model.layers.{layer}.self_attn.{m}_proj.linear.lora_{}.weight",
            if b { "B" } else { "A" }
        )
    }

    fn vllm_name(layer: usize, p: Proj, b: bool) -> String {
        let m = ["wq_du", "wk_dv", "wv_dv", "wo_ud"][p.index()];
        format!("base_model.model.model.llm.layers.{layer}.attn.{m}.lora_{}.weight", if b { "B" } else { "A" })
    }

    /// A small model: 2 layers, e = 16, q = 24, kv = 8, rank 4; values tagged by position.
    fn tiny(name: fn(usize, Proj, bool) -> String) -> Vec<(String, Vec<usize>, Vec<f32>)> {
        let mut t = Vec::new();
        for l in 0..2 {
            for p in PROJS {
                let (k, nout) = p.dims(16, 24, 8);
                let tag = (l * 4 + p.index()) as f32;
                t.push((name(l, p, false), vec![4, k], (0..4 * k).map(|i| tag + i as f32 * 1e-3).collect()));
                t.push((name(l, p, true), vec![nout, 4], (0..nout * 4).map(|i| -tag - i as f32 * 1e-3).collect()));
            }
        }
        t
    }

    #[test]
    fn both_namings_map_to_the_same_gguf_tensors() {
        for p in PROJS {
            for b in [false, true] {
                assert_eq!(parse_tensor_name(&peft_name(7, p, b)), Some((7, p, b)));
                assert_eq!(parse_tensor_name(&vllm_name(7, p, b)), Some((7, p, b)));
            }
        }
        assert_eq!(Proj::O.gguf_name(3), "blk.3.attn_output.weight");
        // the real adapter's names
        assert_eq!(
            parse_tensor_name("base_model.model.model.language_model.layers.23.self_attn.o_proj.linear.lora_B.weight"),
            Some((23, Proj::O, true))
        );
        assert_eq!(
            parse_tensor_name("base_model.model.model.llm.layers.0.attn.wk_dv.lora_A.weight"),
            Some((0, Proj::K, false))
        );
        // not attention q/k/v/o: refused, never silently skipped
        assert_eq!(parse_tensor_name("base_model.model.model.llm.layers.0.attn.gate_attn.lora_A.weight"), None);
        assert_eq!(parse_tensor_name("base_model.model.model.language_model.layers.0.mlp.experts.lora_A.weight"), None);
        assert_eq!(parse_tensor_name("base_model.model.model.llm.layers.x.attn.wq_du.lora_A.weight"), None);
    }

    #[test]
    fn config_scale_and_refusals() {
        assert_eq!(parse_config(CFG).unwrap(), (4, 8.0, 2.0));
        // the harness-hub adapter: r 32, alpha 64
        assert_eq!(parse_config(r#"{"peft_type":"LORA","r":32,"lora_alpha":64}"#).unwrap(), (32, 64.0, 2.0));
        assert_eq!(parse_config(r#"{"r":16,"lora_alpha":16,"use_rslora":true}"#).unwrap().2, 4.0);
        for bad_cfg in [
            r#"{"r":32,"lora_alpha":64,"use_dora":true}"#,
            r#"{"r":32,"lora_alpha":64,"bias":"all"}"#,
            r#"{"r":64,"lora_alpha":64}"#,
            r#"{"r":0,"lora_alpha":64}"#,
            r#"{"r":32,"lora_alpha":64,"rank_pattern":{"q_proj":8}}"#,
            r#"{"r":32,"lora_alpha":64,"layers_to_transform":[0,1]}"#,
            r#"{"r":32,"lora_alpha":64,"peft_type":"IA3"}"#,
            r#"{"r":32}"#,
        ] {
            assert!(parse_config(bad_cfg).is_err(), "{bad_cfg} must be refused");
        }
    }

    #[test]
    fn parse_takes_both_namings_and_packs_transposed_a() {
        let a = LoraAdapter::parse(CFG, &safetensors_f32(&tiny(peft_name)), 2, 16, 24, 8, "t").unwrap();
        let b = LoraAdapter::parse(CFG, &safetensors_f32(&tiny(vllm_name)), 2, 16, 24, 8, "t").unwrap();
        assert_eq!(a.layers, b.layers);
        assert_eq!(a.fingerprint(), b.fingerprint());
        assert_eq!((a.rank, a.scale), (4, 2.0));
        let (img, slots) = a.pack();
        for (l, ls) in a.layers.iter().zip(&slots) {
            for (m, s) in l.iter().zip(ls) {
                assert_eq!((s.at_off % 4, s.b_off % 4), (0, 0), "16-byte aligned");
                assert_eq!((s.k as usize, s.nout as usize), (m.k, m.nout));
                for i in 0..MAX_RANK {
                    for c in 0..m.k {
                        let want = if i < 4 { m.a[i * m.k + c] } else { 0.0 };
                        assert_eq!(img[s.at_off as usize + c * MAX_RANK + i], want);
                    }
                }
                for o in 0..m.nout {
                    for i in 0..MAX_RANK {
                        let want = if i < 4 { m.b[o * 4 + i] } else { 0.0 };
                        assert_eq!(img[s.b_off as usize + o * MAX_RANK + i], want);
                    }
                }
            }
        }
        // another adapter, another fingerprint
        let mut t = tiny(peft_name);
        t[0].2[0] += 1.0;
        assert_ne!(
            LoraAdapter::parse(CFG, &safetensors_f32(&t), 2, 16, 24, 8, "t").unwrap().fingerprint(),
            a.fingerprint()
        );
    }

    #[test]
    fn record_id_is_the_dir_name_and_the_cache_fingerprint() {
        let a = LoraAdapter::parse(CFG, &safetensors_f32(&tiny(peft_name)), 2, 16, 24, 8, "t").unwrap();
        let id = record_id("inkling-pi", a.fingerprint());
        assert_eq!(id, format!("inkling-pi@{:016x}", a.fingerprint()));
        assert_eq!(record_id("x", 0xab), "x@00000000000000ab", "fixed width, lowercase");
        // a weights file names its directory; a directory names itself
        assert_eq!(adapter_dir_name(Path::new("/no/such/inkling-pi/adapter_model.safetensors")), "inkling-pi");
        let dir = std::env::temp_dir().join(format!("inky-lora-name-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        assert_eq!(adapter_dir_name(&dir), dir.file_name().unwrap().to_str().unwrap());
        let _ = std::fs::remove_dir(&dir);
    }

    #[test]
    fn parse_refuses_incomplete_misshapen_or_foreign_adapters() {
        let ok = tiny(peft_name);
        let parse =
            |t: &[(String, Vec<usize>, Vec<f32>)]| LoraAdapter::parse(CFG, &safetensors_f32(t), 2, 16, 24, 8, "t");
        assert!(parse(&ok).is_ok());
        // a missing matrix
        let missing: Vec<_> = ok.iter().filter(|t| t.0 != peft_name(1, Proj::V, true)).cloned().collect();
        assert!(parse(&missing).unwrap_err().to_string().contains("blk.1.attn_v"));
        // a transposed B
        let mut wrong = ok.clone();
        let i = wrong.iter().position(|t| t.0 == peft_name(0, Proj::Q, true)).unwrap();
        wrong[i].1 = vec![4, 24];
        assert!(parse(&wrong).unwrap_err().to_string().contains("shape"));
        // a layer the model doesn't have
        let mut extra = ok.clone();
        extra.push((peft_name(2, Proj::Q, false), vec![4, 16], vec![0.0; 64]));
        assert!(parse(&extra).is_err());
        // a module this runtime doesn't apply (an expert, the gate): refused, not skipped
        let mut foreign = ok.clone();
        foreign.push((
            "base_model.model.model.llm.layers.0.attn.gate_attn.lora_A.weight".into(),
            vec![4, 16],
            vec![0.0; 64],
        ));
        assert!(parse(&foreign).unwrap_err().to_string().contains("gate_attn"));
        // the same matrix under both namings
        let mut twice = ok.clone();
        twice.push((vllm_name(0, Proj::K, false), vec![4, 16], vec![0.0; 64]));
        assert!(parse(&twice).unwrap_err().to_string().contains("same matrix"));
        // a non-finite weight
        let mut nan = ok;
        nan[3].2[1] = f32::NAN;
        assert!(parse(&nan).unwrap_err().to_string().contains("non-finite"));
    }

    #[test]
    fn a_directory_prefers_its_native_name_copy() {
        let d = std::env::temp_dir().join(format!("inky-lora-files-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(d.join("vllm")).unwrap();
        for f in ["adapter_config.json", "adapter_model.safetensors"] {
            std::fs::write(d.join(f), b"").unwrap();
        }
        assert_eq!(adapter_files(&d).1, d.join("adapter_model.safetensors"), "no native copy: the root");
        for f in ["adapter_config.json", "adapter_model.safetensors"] {
            std::fs::write(d.join("vllm").join(f), b"").unwrap();
        }
        assert_eq!(adapter_files(&d), (d.join("vllm/adapter_config.json"), d.join("vllm/adapter_model.safetensors")));
        // a file names itself, its config beside it
        let f = d.join("adapter_model.safetensors");
        assert_eq!(adapter_files(&f), (d.join("adapter_config.json"), f.clone()));
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[test]
    fn scratch_holds_four_jobs_of_partials() {
        for rows in [1usize, 7, 8, 9, 63, 64, 65, 200, 4096] {
            assert!(4 * rows.div_ceil(ROWS_PER_TG) * ROWS_PER_TG * MAX_RANK * KSPLIT <= scratch_floats(rows));
        }
        const { assert!(2304 % (8 * KSPLIT) == 0 && 3072 % (8 * KSPLIT) == 0) };
    }
}