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
//! Model validation, weight binding, and Metal engine initialization.

use super::*;

const MAX_PREFILL_CHUNK: usize = 4096;

pub(super) fn configured_prefill_chunk(value: Result<String, std::env::VarError>, context: usize) -> Result<usize, &'static str> {
    let chunk = match value {
        Err(std::env::VarError::NotPresent) => Some(MAX_PREFILL_CHUNK),
        Ok(value) => value.parse::<usize>().ok(),
        Err(std::env::VarError::NotUnicode(_)) => None,
    };
    chunk.filter(|&n| (32..=MAX_PREFILL_CHUNK).contains(&n) && n % 32 == 0)
        .map(|n| n.min(context))
        .ok_or("INK_CHUNK must be a multiple of 32 between 32 and 4096")
}

/// The context checks of `Engine::prepare_model`, made before the model file is opened: a positive multiple of 64
/// that lanes stored as `store` can address (`check_context_fits` with the model's `FULL_PASSES` full-attention slots).
pub(super) fn check_load_context(max_ctx: usize, store: LaneStore) -> io::Result<()> {
    if max_ctx == 0 || !max_ctx.is_multiple_of(64) {
        return Err(invalid_model("context size must be a positive multiple of 64"));
    }
    check_context_fits(max_ctx, crate::blocks::FULL_PASSES, store)
        .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
}

// ----------------------------------------------------------------------------- weights
#[derive(Clone, Copy, Default, Debug)]
pub struct QW { pub off: u64, pub row_bytes: u32, pub ty: u32, pub rows: u32, pub k: u32, pub expert_bytes: u64, pub gs: u64 }

fn qw(g: &Gguf, name: &str, shape: &[usize], types: &[u32]) -> io::Result<QW> {
    let t = g.tensor(name, shape, types)?;
    let rb = t.row_bytes;
    // All callers pass the target model's fixed geometry. The shaders use 32-bit strides.
    let expert_bytes = u32::try_from(rb * t.ne[1])
        .map_err(|_| invalid_model(format_args!("tensor {name} exceeds the GPU stride limit")))?;
    let gs = if t.ty == T_NV4 {
        let gname = name.replace(".weight", ".gscale");
        g.tensor(&gname, &[NEXP], &[T_F32])?.file_off as u64
    } else {
        0
    };
    Ok(QW {
        off: t.file_off as u64,
        row_bytes: rb as u32,
        ty: t.ty,
        rows: t.ne[1] as u32,
        k: t.ne[0] as u32,
        expert_bytes: u64::from(expert_bytes),
        gs,
    })
}

fn validate_vocab(g: &Gguf, unpadded: u64, padded: usize) -> io::Result<usize> {
    let token_count = match g.kv.get("tokenizer.ggml.tokens") {
        Some(Value::AS(tokens)) => tokens.len(),
        _ => return Err(invalid_model("missing GGUF tokenizer tokens")),
    };
    let type_count = match g.kv.get("tokenizer.ggml.token_type") {
        Some(Value::AI(types)) => types.len(),
        _ => return Err(invalid_model("missing GGUF tokenizer token types")),
    };
    let eos = g.uint("tokenizer.ggml.eos_token_id")?;
    check_vocab_lengths(unpadded, padded, token_count, type_count, eos)
}

pub(super) fn check_vocab_lengths(unpadded: u64, padded: usize, tokens: usize, types: usize, eos: u64) -> io::Result<usize> {
    if unpadded == 0 || unpadded > padded as u64 || unpadded != tokens as u64 || tokens != types {
        return Err(invalid_model(format_args!(
            "vocabulary length {unpadded} must fit {padded} rows and match the tokenizer's {tokens} tokens and {types} token types",
        )));
    }
    if eos >= unpadded {
        return Err(invalid_model(format_args!("EOS token ID {eos} is outside the vocabulary")));
    }
    Ok(tokens)
}

pub struct Layer {
    pub swa: bool,
    pub wq: QW, pub wgate: QW, pub wk: QW, pub wv: QW, pub wo: QW, pub wrel: QW, pub wsink: QW,
    pub kconvp: Option<QW>, pub vconvp: Option<QW>,
    pub attn_norm: i32, pub q_inp_norm: i32, pub k_inp_norm: i32, pub v_inp_norm: i32,
    pub attn_res_query: i32, pub n_attn_q: u32,
    pub ffn_res_query: u32, pub ffn_norm: u32,
    pub q_clip: u32, pub rel_clip: u32, pub rel_bias: u32, pub k_conv: u32, pub v_conv: u32,
    pub attn_post_conv: u32, pub ffn_post_conv: u32,
    pub router: u32, pub exp_bias: u32,
    pub gu: QW, pub dn: QW,
}

pub struct LoopW { pub msg_query: u32, pub down: [u32; 4], pub gain: [u32; 4], pub forget: [u32; 4] }

struct Pb { data: Vec<u8> }
impl Pb {
    fn align(&mut self) { while !self.data.len().is_multiple_of(256) { self.data.push(0); } }
    fn f32(&mut self, g: &Gguf, name: &str, shape: &[usize]) -> io::Result<u32> {
        let t = g.tensor(name, shape, &[T_F32])?;
        self.align();
        let off = self.data.len() as u32;
        self.data.extend_from_slice(g.bytes(t));
        Ok(off)
    }
    /// F32 -> BF16 (round to nearest even). Lossless for this model's bf16-origin matrices.
    fn bf16(&mut self, g: &Gguf, name: &str, shape: &[usize]) -> io::Result<u32> {
        let t = g.tensor(name, shape, &[T_F32])?;
        self.align();
        let off = self.data.len() as u32;
        for &c in g.bytes(t).as_chunks::<4>().0 {
            let u = u32::from_le_bytes(c);
            let r = u.wrapping_add(0x7FFF + ((u >> 16) & 1)) >> 16;
            self.data.extend_from_slice(&(r as u16).to_le_bytes());
        }
        Ok(off)
    }
}

/// CPU-validated GGUF model image ready to bind onto Metal after `enter_inky_mode()`.
pub struct PreparedModel {
    path: String,
    max_ctx: usize,
    t0: std::time::Instant,
    pub g: Gguf,
    pb: Pb,
    layers: Vec<Layer>,
    loops: Vec<LoopW>,
    tok_embd: QW,
    tok_norm: u32,
    output: QW,
    output_norm: u32,
    output_res_query: u32,
    pub(crate) n_vocab: usize,
    eps: f32,
    log_alpha: f32,
    log_floor: f32,
    situ_beta: f32,
    situ_lbeta: f32,
    wscale: f32,
    softcap: f32,
    slot_kind: Vec<(bool, usize)>,
}

impl PreparedModel {
    #[cfg(test)]
    pub fn into_engine(self, kv8: bool, chunk: usize) -> io::Result<Engine> {
        let mode = if kv8 { crate::blocks::KvMode::Kv8 } else { crate::blocks::KvMode::Fp16 };
        self.into_engine_mode(mode, chunk)
    }

    pub fn into_engine_mode(mut self, mode: crate::blocks::KvMode, chunk: usize) -> io::Result<Engine> {
        let kv8 = mode == crate::blocks::KvMode::Kv8;
        let kv4 = mode == crate::blocks::KvMode::Kv4;
        let exact = !kv8 && !kv4 && EXACT.load(std::sync::atomic::Ordering::Relaxed);
        let (chip, mem) = crate::tuning::this_machine();
        let tuning = crate::tuning::select(&chip, mem);
        let use_mpp = Engine::effective_use_mpp_for_tuning(
            DISABLE_MPP.load(std::sync::atomic::Ordering::Relaxed),
            tuning.use_mpp,
        );
        self.pb.data.extend(std::iter::repeat_n(0u8, 128 * NREL * 4)); // k_attn_h reads up to 95 rows past a relative-bias table
        let k_dc_rot_off = if kv4 {
            let align = (256 - (self.pb.data.len() % 256)) % 256;
            self.pb.data.extend(std::iter::repeat_n(0u8, align));
            let off = u32::try_from(self.pb.data.len()).expect("PB k_dc_rot_off fits u32");
            self.pb.data.extend(std::iter::repeat_n(0u8, N_SLOT * NKV * HD * 2));
            off
        } else {
            0
        };
        let on = |name: &str| super::dev_switch(std::env::var(name).ok().as_deref());
        let (tc_exp2, tc_lazy) = (on("INK_TC_EXP2"), on("INK_TC_LAZY_RESCALE"));
        if !kv8 && (tc_exp2 || tc_lazy) {
            eprintln!("[inky] tensor-core prefill softmax reordering refused: KV8 only (--kv8); this cache keeps the exact order");
        }
        let kv_header = if kv4 {
            format!("#define KV4 1\n#define KV4_DC_OFF {k_dc_rot_off}u\n")
        } else if kv8 {
            let softmax = super::tc_softmax_defines(kv8, tc_exp2, tc_lazy);
            if !softmax.is_empty() {
                eprintln!("[inky] tensor-core prefill softmax reordered: {}", softmax.trim_end().replace('\n', ", "));
            }
            format!("#define KV8 1\n{softmax}")
        } else {
            String::new()
        };
        let src = format!(
            "{}{}{}\n{}\n{}\n{}",
            kv_header,
            if !use_mpp { "#define NO_MPP 1\n" } else { "" },
            include_str!("../kernels.metal"),
            include_str!("../prefill.metal"),
            include_str!("../bench_kernels.metal"),
            include_str!("../lora.metal")
        );
        let kvb = mode.kvb_tag() as usize;
        let kv_row_bytes = mode.row_bytes() as usize;
        let gpu = Gpu::new_with_lang(&src, if use_mpp { KERNELS } else { KERNELS_NON_MPP }, use_mpp);
        if self.g.map_len() > gpu.dev.maxBufferLength() {
            return Err(invalid_model("GGUF exceeds the Metal buffer size limit"));
        }
        let w = gpu.buffer_nocopy(self.g.ptr(), self.g.map_len());
        let pbuf = gpu.buffer_with(&self.pb.data);
        let lora = {
            use crate::lora::Proj;
            let layers = &self.layers;
            crate::lora::Registry::from_env(
                &gpu,
                layers.len(),
                |l, p| {
                    let w = match p {
                        Proj::Q => &layers[l].wq,
                        Proj::K => &layers[l].wk,
                        Proj::V => &layers[l].wv,
                        Proj::O => &layers[l].wo,
                    };
                    (w.k as usize, w.rows as usize)
                },
                64,
            )?
        };

        let max_split = super::split_scratch_slots(self.max_ctx);
        let ar = Arena::new(max_split, N_VOCAB_PAD);
        // the batch arena is allocated when a prefill needs it and released when generation starts
        let act = gpu.buffer(ar.total as usize * 4);
        let ctr = gpu.buffer(4096 * 4);
        eprintln!(
            "[inky] loaded {} ({:.1} GiB mapped, {:.1} MiB params) in {:.2?}",
            self.path.rsplit('/').next().unwrap_or(&self.path),
            self.g.file_len() as f64 / (1u64 << 30) as f64,
            self.pb.data.len() as f64 / (1 << 20) as f64,
            self.t0.elapsed()
        );
        // KV_CAP0 positions is one block. Further slots come from `BlockPool::grow`.
        // Default (`--sparse-topk` unset) allocates 0 sketch bytes and 0 sketch `MTLBuffer`.
        let init_sparse_topk = match SPARSE_TOPK.load(std::sync::atomic::Ordering::Relaxed) {
            0 => None,
            k => Some(k),
        };
        let block_pool = std::cell::RefCell::new(crate::blocks::BlockPools::gpu_mode_with_sketches(
            &gpu.dev,
            1,
            1,
            mode,
            init_sparse_topk.is_some(),
        ));
        let blocked_slab = Rc::new(RefCell::new(BlockedSlab::new(self.max_ctx.div_ceil(crate::blocks::BLOCK))));
        let mut eng = Engine {
            eps: self.eps, log_alpha: self.log_alpha, log_floor: self.log_floor,
            situ_beta: self.situ_beta, situ_lbeta: self.situ_lbeta, wscale: self.wscale, softcap: self.softcap,
            g: self.g, gpu, w, pb: pbuf, act: std::cell::RefCell::new(act),
            slot_kind: self.slot_kind, qcap: RefCell::new(None), ctr, layers: self.layers, loops: self.loops,
            tok_embd: self.tok_embd, tok_norm: self.tok_norm, output: self.output,
            output_norm: self.output_norm, output_res_query: self.output_res_query,
            ar, abase: Cell::new(0), dstart: Cell::new(0), kv8, kv4, exact, kvb, kv_row_bytes, k_dc_rot_off,
            ba: Default::default(), chunk,
            use_mpp,
            kv_window_pct: tuning.kv_window_pct,
            decode_splits: tuning.decode_splits,
            tensor: use_mpp,
            hgemm: Engine::resolve_effective_hgemm(use_mpp, std::env::var_os("INK_NO_HGEMM").is_some(), true),
            lora,
            sep_comb: std::env::var("INK_FUSE_COMB").is_err(),
            sep_topk: std::env::var("INK_SEP_TOPK").is_ok(),
            tail: std::cell::Cell::new(std::env::var("INK_NO_TAIL").is_err()),
            skip: Default::default(), stop: std::cell::Cell::new(usize::MAX), done: std::cell::Cell::new(0),
            last_out: Default::default(), last_mid: Default::default(),
            max_ctx: self.max_ctx, n_vocab: self.n_vocab,
            verify_keep: RefCell::new(None), verify_record: Cell::new(false),
            pinned_nonterminal_steps: RefCell::new(Vec::new()),
            #[cfg(test)]
            test_drop_witness: RefCell::new(None),
            block_pool,
            blocked_slab,
            loopcd_omega: Cell::new(0.0),
            never_tok: Cell::new(u32::MAX),
            early_cbs: RefCell::new(Vec::new()),
            guided_logit_rows: Cell::new(0),
            lg_weak: RefCell::new(None),
            no_grp_dec: Cell::new(std::env::var("INK_NO_GRP_DEC").is_ok_and(|v| !v.is_empty() && v != "0")),
            no_grp_moe: Cell::new(std::env::var("INK_NO_GRP_MOE").is_ok_and(|v| !v.is_empty() && v != "0")),
            no_gemm_dec: Cell::new(std::env::var("INK_NO_GEMM_DEC").is_ok_and(|v| !v.is_empty() && v != "0")),
            full_attn_budget: Cell::new(match FULL_ATTN_BUDGET.load(std::sync::atomic::Ordering::Relaxed) {
                0 => None,
                b => Some(b),
            }),
            sparse_topk: Cell::new(init_sparse_topk),
            sparse_anchors: Cell::new(SPARSE_ANCHORS.load(std::sync::atomic::Ordering::Relaxed)),
            sparse_min_ctx: Cell::new(SPARSE_MIN_CTX.load(std::sync::atomic::Ordering::Relaxed)),
            force_sparse_4k_scorer: Cell::new(false),
            force_sparse_wide_scorer: Cell::new(false),
            sparse_buf: RefCell::new(None),
            last_sparse_meta: Cell::new((0, 0, 0)),
            last_sparse_task_blks: RefCell::new(Vec::new()),
            l2_sparse_task_seq: Cell::new(0),
            l2_sparse_task_users: RefCell::new(Default::default()),
            l2_sparse_task_off: Cell::new(0),
            pending_sketch_batches: RefCell::new(std::collections::VecDeque::new()),
            l2_catchup_dispatches: Cell::new(0),
            sparse_prefill: sparse_prefill::SparsePrefillState::from_env(),
            verify_sparse: RefCell::new(None),
            verify_sparse_bufs: RefCell::new(Vec::new()),
            #[cfg(test)]
            test_logit_target: Cell::new(None),
            #[cfg(test)]
            test_pin_full_after_prefill: Cell::new(false),
            #[cfg(test)]
            test_pinned_full_slot: Cell::new(None),
            #[cfg(test)]
            test_verify_dispatches: Cell::new(0),
            #[cfg(test)]
            test_decode_dispatches: Cell::new(0),
        };
        eng.ensure_batch(64);
        let layout_ok = !eng.hgemm || eng.layout_ok();
        eng.release_batch();
        let eff_hgemm = Engine::resolve_effective_hgemm(eng.use_mpp, !eng.hgemm, layout_ok);
        if eng.hgemm && !eff_hgemm {
            eprintln!("[inky] unexpected tensor accumulator layout on this GPU/OS: using the slower prefill path");
        }
        eng.hgemm = eff_hgemm;
        if eng.hgemm {
            // build the prefill MoE kernels of this model's expert formats now, not in the first prefill
            for l in &eng.layers {
                for cls in 0..NTC {
                    eng.gpu.pso(moe_sg_kernel(cls, l.gu.ty, true));
                    eng.gpu.pso(moe_sg_kernel(cls, l.dn.ty, false));
                }
            }
        }
        if std::env::var("INK_NO_WARM").is_err() { eng.warm(); }
        if eng.kv4 { eng.calibrate_kv4_dc_mean()?; }
        Ok(eng)
    }
}

impl Engine {
    pub fn prefill_chunk_for(max_ctx: usize) -> Result<usize, String> {
        configured_prefill_chunk(std::env::var("INK_CHUNK"), max_ctx).map_err(str::to_owned)
    }

    /// Validate the GGUF at `path` for a context of `max_ctx` positions whose lanes are stored as `store`.
    /// `LaneStore::Contiguous` admits at most `MAX_CONTIGUOUS_CONTEXT`; `LaneStore::Pooled` admits up to
    /// `MAX_POOLED_CONTEXT`, and above `MAX_CONTIGUOUS_CONTEXT` the engine refuses `Lane::new`.
    pub fn prepare_model(path: &str, max_ctx: usize, store: LaneStore) -> io::Result<PreparedModel> {
        check_load_context(max_ctx, store)?;
        let t0 = std::time::Instant::now();
        let g = Gguf::open(path)?;
        if !matches!(g.kv.get("general.architecture"), Some(Value::S(s)) if s == "inkling2_loop") {
            return Err(invalid_model("expected inkling2_loop architecture"));
        }
        let a = |k: &str| format!("inkling2_loop.{k}");
        for (name, expected) in [
            ("embedding_length", E), ("block_count", N_PHYS), ("expert_count", NEXP),
            ("expert_used_count", TOPK), ("loop.start", LOOP_START), ("loop.end", LOOP_END),
            ("loop.count", N_PASS), ("attn_res.block_size", BLOCK), ("attention.sliding_window", EXT),
            ("attention.relative_extent", EXT), ("vocab_size", N_VOCAB_PAD),
        ] {
            let value = g.uint(&a(name))?;
            if value != expected as u64 {
                return Err(invalid_model(format_args!("{} is {value}, expected {expected}", a(name))));
            }
        }
        let swa_pat = match g.kv.get(&a("attention.sliding_window_pattern")) {
            Some(Value::AB(v)) if v.len() == N_PHYS
                && v.iter().copied().eq((0..N_PHYS).map(|i| !(i + 1).is_multiple_of(BLOCK))) => v,
            _ => return Err(invalid_model("unexpected sliding-window attention pattern")),
        };

        let n_vocab = validate_vocab(&g, g.uint(&a("vocab_size_unpadded"))?, N_VOCAB_PAD)?;
        let _ = crate::tokenizer::Tokenizer::try_load(&g)?;
        let embed_shape = [E, N_VOCAB_PAD];
        let tok_embd = qw(&g, "token_embd.weight", &embed_shape, &[T_Q4_K, T_Q8_0])?;
        let output = qw(&g, "output.weight", &embed_shape, &[T_Q6_K, T_Q8_0, T_Q4_K, T_Q3_K, T_Q2_K])?;

        let eps = g.f(&a("attention.layer_norm_rms_epsilon"))?;
        let log_alpha = g.f(&a("attention.log_scale_alpha"))?;
        let log_floor = g.f(&a("attention.log_scale_floor"))?;
        let situ_beta = g.f(&a("activation.situ_beta"))?;
        let situ_lbeta = g.f(&a("activation.situ_linear_beta"))?;
        let wscale = g.f(&a("expert_weights_scale"))?;
        let softcap = g.f(&a("final_logit_softcapping"))?;

        let mut pb = Pb { data: Vec::new() };
        let mut layers = Vec::new();
        for (i, &swa) in swa_pat.iter().enumerate() {
            let n = |s: &str| format!("blk.{i}.{s}");
            let (attn_norm, q_inp_norm, k_inp_norm, v_inp_norm, attn_res_query, n_attn_q, kconvp, vconvp) =
                if swa {
                    let query = n("attn_res_query.weight");
                    let res_query = match g.opt(&query) {
                        Some(t) => {
                            let shape: &[usize] = if t.ne.len() == 2 { &[E, 1] } else { &[E] };
                            pb.f32(&g, &query, shape)? as i32
                        }
                        None => -1,
                    };
                    (pb.f32(&g, &n("attn_norm.weight"), &[E])? as i32, -1, -1, -1, res_query, 1, None, None)
                } else {
                    (
                        -1,
                        pb.f32(&g, &n("attn_q_inp_norm.weight"), &[E])? as i32,
                        pb.f32(&g, &n("attn_k_inp_norm.weight"), &[E])? as i32,
                        pb.f32(&g, &n("attn_v_inp_norm.weight"), &[E])? as i32,
                        pb.f32(&g, &n("attn_res_query.weight"), &[E, 3])? as i32,
                        3,
                        Some(qw(&g, &n("attn_k_conv_proj.weight"), &[E, NKV * CONV_TAPS], &[T_Q4_K, T_Q6_K, T_Q8_0, T_Q3_K, T_Q2_K])?),
                        Some(qw(&g, &n("attn_v_conv_proj.weight"), &[E, NKV * CONV_TAPS], &[T_Q4_K, T_Q6_K, T_Q8_0, T_Q3_K, T_Q2_K])?),
                    )
                };
            layers.push(Layer {
                swa,
                wq: qw(&g, &n("attn_q.weight"), &[E, NH * HD], &[T_Q4_K, T_Q8_0, T_Q3_K, T_Q2_K])?,
                wgate: qw(&g, &n("attn_gate.weight"), &[E, NH * HD], &[T_Q4_K, T_Q8_0, T_Q3_K, T_Q2_K])?,
                wk: qw(&g, &n("attn_k.weight"), &[E, NKV * HD], &[T_Q4_K, T_Q8_0, T_Q3_K, T_Q2_K])?,
                wv: qw(&g, &n("attn_v.weight"), &[E, NKV * HD], &[T_Q4_K, T_Q6_K, T_Q8_0, T_Q3_K, T_Q2_K])?,
                wo: qw(&g, &n("attn_output.weight"), &[NH * HD, E], &[T_Q4_K, T_Q8_0, T_Q3_K, T_Q2_K])?,
                wrel: qw(&g, &n("attn_rel.weight"), &[E, NH * NREL], &[T_Q4_K, T_Q8_0, T_Q3_K, T_Q2_K])?,
                wsink: qw(&g, &n("attn_sink_proj.weight"), &[E, NH], &[T_Q4_K, T_Q8_0, T_Q3_K, T_Q2_K])?,
                kconvp, vconvp,
                attn_norm, q_inp_norm, k_inp_norm, v_inp_norm, attn_res_query, n_attn_q,
                ffn_res_query: pb.f32(&g, &n("ffn_res_query.weight"), &[E])?,
                ffn_norm: pb.f32(&g, &n("ffn_norm.weight"), &[E])?,
                q_clip: pb.f32(&g, &n("attn_q_clip.weight"), &[HD, NH])?,
                rel_clip: pb.f32(&g, &n("attn_rel_clip.weight"), &[NREL, NH])?,
                rel_bias: pb.f32(&g, &n("attn_rel_bias.weight"), &[NREL, EXT])?,
                k_conv: pb.f32(&g, &n("attn_k_conv.weight"), &[CONV_TAPS, NKV * HD])?,
                v_conv: pb.f32(&g, &n("attn_v_conv.weight"), &[CONV_TAPS, NKV * HD])?,
                attn_post_conv: pb.f32(&g, &n("attn_post_conv.weight"), &[CONV_TAPS, E])?,
                ffn_post_conv: pb.f32(&g, &n("ffn_post_conv.weight"), &[CONV_TAPS, E])?,
                router: pb.bf16(&g, &n("ffn_gate_inp.weight"), &[E, NEXP])?,
                exp_bias: pb.f32(&g, &n("exp_probs_b.bias"), &[NEXP])?,
                gu: qw(&g, &n("ffn_gate_up_exps.weight"), &[E, 2 * FF, NEXP], &[T_Q4_K, T_Q8_0, T_NV4, T_MX8, T_Q3_K, T_Q2_K, T_Q3_0])?,
                dn: qw(&g, &n("ffn_down_exps.weight"), &[FF, E, NEXP], &[T_Q8_0, T_Q5_0, T_NV4, T_MX8, T_Q3_0])?,
            });
        }
        let mut loops = Vec::new();
        for i in LOOP_START..LOOP_END {
            let n = |s: &str| format!("blk.{i}.{s}");
            let mut lw = LoopW {
                msg_query: pb.f32(&g, &n("loop_msg_query.weight"), &[E, 4])?,
                down: [0; 4], gain: [0; 4], forget: [0; 4],
            };
            for (c, name) in ["q", "k", "v", "ffn"].into_iter().enumerate() {
                lw.down[c] = pb.bf16(&g, &n(&format!("loop_{name}_ctrl_down.weight")), &[2 * E, CTRL_RANK])?;
                lw.gain[c] = pb.bf16(&g, &n(&format!("loop_{name}_ctrl_gain.weight")), &[CTRL_RANK, E])?;
                lw.forget[c] = pb.bf16(&g, &n(&format!("loop_{name}_ctrl_forget.weight")), &[CTRL_RANK, E])?;
            }
            loops.push(lw);
        }
        let tok_norm = pb.f32(&g, "token_embd_norm.weight", &[E])?;
        let output_norm = pb.f32(&g, "output_norm.weight", &[E])?;
        let output_res_query = pb.f32(&g, "output_res_query.weight", &[E])?;

        let mut slot_kind = Vec::new();
        let (mut n_swa, mut n_full) = (0usize, 0usize);
        for s in 0..N_SLOT {
            let phys = if s < N_PHYS { s } else { LOOP_START + (s - N_PHYS) % (LOOP_END - LOOP_START) };
            if layers[phys].swa { slot_kind.push((true, n_swa)); n_swa += 1; } else { slot_kind.push((false, n_full)); n_full += 1; }
        }
        if n_full != crate::blocks::FULL_PASSES {
            return Err(invalid_model(format_args!(
                "{n_full} full-attention slots, expected {}",
                crate::blocks::FULL_PASSES
            )));
        }
        Ok(PreparedModel {
            path: path.to_owned(), max_ctx, t0, g, pb, layers, loops, tok_embd, tok_norm, output, output_norm,
            output_res_query, n_vocab, eps, log_alpha, log_floor, situ_beta, situ_lbeta, wscale, softcap, slot_kind,
        })
    }
}

impl Engine {
    /// Load for a caller that builds contiguous lanes (`Lane::new`, `--kv-disk`): `max_ctx` is at most
    /// `MAX_CONTIGUOUS_CONTEXT`. Exits the process with a message on any load error.
    pub fn load(path: &str, max_ctx: usize) -> Engine {
        Self::load_store(path, max_ctx, LaneStore::Contiguous)
    }
    /// Load for a caller whose lanes above `MAX_CONTIGUOUS_CONTEXT` are all `Lane::new_blocked`: `max_ctx` is at
    /// most `MAX_POOLED_CONTEXT`. Exits the process with a message on any load error.
    pub fn load_pooled(path: &str, max_ctx: usize) -> Engine {
        Self::load_store(path, max_ctx, LaneStore::Pooled)
    }
    fn load_store(path: &str, max_ctx: usize, store: LaneStore) -> Engine {
        let chunk = configured_prefill_chunk(std::env::var("INK_CHUNK"), max_ctx).unwrap_or_else(|err| {
            eprintln!("[inky] {err}");
            std::process::exit(2);
        });
        let kv8 = KV8.load(std::sync::atomic::Ordering::Relaxed);
        let kv4 = KV4.load(std::sync::atomic::Ordering::Relaxed);
        let mode = crate::blocks::KvMode::from_flags(kv8, kv4).unwrap_or_else(|_| {
            eprintln!("[inky] --kv4 cannot be combined with --kv8");
            std::process::exit(2);
        });
        Self::prepare_model(path, max_ctx, store)
            .and_then(|prepared| prepared.into_engine_mode(mode, chunk))
            .unwrap_or_else(|err| {
                eprintln!("[inky] could not load {path}: {err}");
                std::process::exit(1);
            })
    }
    /// Load a contiguous-lane engine with explicit [`crate::blocks::KvMode`] (`Fp16`, `Kv8`, or `Kv4`).
    #[cfg(test)]
    pub fn load_with_mode(path: &str, max_ctx: usize, mode: crate::blocks::KvMode, chunk: usize) -> io::Result<Engine> {
        Self::prepare_model(path, max_ctx, LaneStore::Contiguous)?.into_engine_mode(mode, chunk)
    }
}