cortiq-engine 0.9.26

Portable inference runtime for the CMF model format, with no ML framework underneath: runs on CPU, and on GPU (Vulkan / Metal / DX12) with the `gpu` feature; tokenizer, chat templates and dynamic per-skill weight overlay.
Documentation
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
//! Kandinsky ImageSR 2.0: one-step image super-resolution (×1, ×2, ×4), read
//! from a `kandinsky_sr` container (`cortiq upscale-pack`). This module is the
//! transformer's geometry and exact host path, the tiled pipeline and the
//! command's entry; the device programs are `gpu_cuda/ksr.rs`,
//! `gpu_wgpu/ksr.rs` and `gpu_metal/ksr.rs`.
//!
//! The model is a Kandinsky 5 DiT over FLUX.1 latents (16 channels, 8×): 2×2
//! patches, a 3-D RoPE with the time position 0, blocks of self-attention and
//! an erf-GELU feed-forward, both behind an affine-free LayerNorm modulated
//! by a per-timestep table. The release bakes its empty prompt: what was the
//! prompt's cross-attention is one bias vector a block and timestep. Heads
//! are 128 wide and need not fill the model's width (the pruned model keeps
//! 12 of 20 in a width of 2560).
//!
//! A picture's path, as the reference pipeline's:
//! 1. tiles of `1024 / f` pixels at a stride of three quarters, the last one
//!    flush with the edge; a smaller picture is padded with its edge pixels
//!    and cropped at the end;
//! 2. each tile enlarged bicubically (a = -0.75) to 1024², clamped, encoded:
//!    z = the posterior's mean × 0.3611 (no shift);
//! 3. one forward at t gives the velocity v, the corrected latent is z - t·v;
//! 4. decoded, and blended with Hanning windows that stay flat at the
//!    picture's edges. No noise anywhere: a run is deterministic.

use crate::dit::cmf_f32;
use crate::gigaam::int8;
use crate::pool::Pool;
use crate::attention::softmax_row;
use crate::s2v::{Lin, Rows, freqs, gelu, layer_norm_row, pool_rows, rms_row, silu};
use crate::vae::{VaeDecoder, VaeEncoder};
use crate::zimage::host_gemm;
use cortiq_core::CmfModel;
use std::sync::Arc;
use std::time::Instant;

pub const ARCH_NAME: &str = "kandinsky_sr";
pub const HEAD_DIM: usize = 128;
pub const ROPE_PAIRS: usize = HEAD_DIM / 2;
/// The side of a tile in output pixels, fixed by the release.
pub const TILE: usize = 1024;
/// The latent's scale; the pipeline subtracts no shift.
const VAE_SCALE: f32 = 0.3611;
const LN_EPS: f64 = 1e-5;
/// torch's `RMSNorm(eps=None)` in f32.
pub const RMS_EPS: f32 = f32::EPSILON;
/// Values of one block's modulation (`KsrDit::mods`).
pub const MODS: usize = 7;

/// The timestep of each creativity level 0..8 at ×1, ×2, ×4.
const CREATIVITY: [(usize, [f32; 9]); 3] = [
    (1, [0.005, 0.015, 0.025, 0.035, 0.05, 0.07, 0.086, 0.10, 0.118]),
    (2, [0.07, 0.086, 0.118, 0.134, 0.15, 0.18, 0.21, 0.27, 0.30]),
    (4, [0.17, 0.1885, 0.207, 0.2255, 0.244, 0.278, 0.312, 0.346, 0.38]),
];

/// Whether `m` is a Kandinsky ImageSR container.
pub fn is_ksr(m: &CmfModel) -> bool {
    m.header.arch.arch_name == ARCH_NAME
}

/// The timestep of a factor and creativity level.
pub fn resolve_t(factor: usize, creativity: usize) -> Result<f32, String> {
    let (_, ts) = CREATIVITY.iter().find(|(f, _)| *f == factor).ok_or_else(|| format!("scale {factor}: the model works at 1, 2 or 4"))?;
    ts.get(creativity).copied().ok_or_else(|| format!("creativity {creativity}: 0..8"))
}

struct Block {
    q: Lin,
    k: Lin,
    v: Lin,
    o: Lin,
    qn: Vec<f32>,
    kn: Vec<f32>,
    w1: Lin,
    w2: Lin,
    /// `[n_t][dim]`: the empty prompt's cross-attention output.
    xattn: Vec<f32>,
    /// `[n_t][6·dim]`: shift, scale, gate of the attention, then of the feed-forward.
    table: Vec<f32>,
}

/// A block's eight-bit projections repacked for the int8 product, in the
/// order q, k, v, attention output, w1, w2.
struct Int8Block(Vec<(int8::Packed, Vec<f32>)>);

impl Int8Block {
    /// `None` where the CPU has no VNNI, under `CMF_KSR_INT8=0`, or when a
    /// projection is not a q8_2f tensor.
    fn of(model: &CmfModel, b: &Block, pool: Option<&Pool>) -> Option<Int8Block> {
        if !int8::available() || std::env::var("CMF_KSR_INT8").as_deref() == Ok("0") {
            return None;
        }
        let mut out = Vec::with_capacity(6);
        for l in [&b.q, &b.k, &b.v, &b.o, &b.w1, &b.w2] {
            let e = model.tensors.get(l.w.graph_w()?.1.idx)?;
            if e.dtype != cortiq_core::TensorDtype::Q8_2f {
                return None;
            }
            let (rows, cols) = (e.shape[0], e.shape[1]);
            let bytes = model.entry_bytes(e);
            let half = |at: usize, n: usize| -> Vec<f32> {
                bytes[at..at + 2 * n].chunks_exact(2).map(|p| cortiq_core::quant::f16_to_f32(u16::from_le_bytes([p[0], p[1]]))).collect()
            };
            let body = rows * cols;
            let (rs, field) = (half(body, rows), half(body + 2 * rows, cols));
            out.push((int8::pack(&bytes[..body], &rs, rows, cols, pool), field));
        }
        Some(Int8Block(out))
    }
}

/// `l` over `x` `[n][cols]` (with its bias): the int8 product, or the float one.
fn project(l: &Lin, packed: Option<&(int8::Packed, Vec<f32>)>, x: &[f32], n: usize, pool: Option<&Pool>, bias: bool) -> Vec<f32> {
    let rows = l.rows();
    let mut y = vec![0f32; n * rows];
    match packed {
        Some((p, field)) => int8::matmul(p, field, x, n, &mut y, pool),
        None => crate::s2v::host_lin(&l.w, x, n, &mut y, pool),
    }
    if let Some(b) = l.b.as_ref().filter(|_| bias) {
        let sr = Rows(y.as_mut_ptr());
        pool_rows(pool, n, &|lo, hi| {
            for r in lo..hi {
                // SAFETY: disjoint rows.
                for (d, &v) in unsafe { sr.at(r * rows, rows) }.iter_mut().zip(b) {
                    *d += v;
                }
            }
        });
    }
    y
}

pub struct KsrDit {
    pub model: Arc<CmfModel>,
    pool: Option<Arc<Pool>>,
    pub dim: usize,
    /// heads · 128
    pub inner: usize,
    pub ff: usize,
    axes: [usize; 3],
    pub baked: Vec<f32>,
    embed: Lin,
    out: Lin,
    out_shift: Vec<f32>,
    out_scale: Vec<f32>,
    blocks: Vec<Block>,
    /// The int8 products' weights, repacked at the first host forward.
    packed: std::sync::OnceLock<Vec<Option<Int8Block>>>,
}

/// The modulation of one timestep.
pub struct KsrMods {
    /// `[blocks][7·dim]`: 1 + scale, shift, gate and the constant
    /// (gate · the output bias + the cross-attention bias) of the attention,
    /// then 1 + scale, shift and gate of the feed-forward.
    pub blocks: Vec<f32>,
    /// `[2·dim]`: 1 + scale and shift of the output layer.
    pub fin: Vec<f32>,
}

impl KsrDit {
    pub fn from_cmf(model: &Arc<CmfModel>, pool: Option<Arc<Pool>>) -> Result<Self, String> {
        let raw = model.tensor_bytes("dit.config_json").map_err(|e| e.to_string())?;
        let cfg: serde_json::Value = serde_json::from_slice(raw).map_err(|e| format!("dit.config_json: {e}"))?;
        let u = |k: &str| cfg[k].as_u64().map(|v| v as usize).ok_or_else(|| format!("dit.config_json: no {k}"));
        let floats = |k: &str| -> Result<Vec<f32>, String> {
            Ok(cfg[k].as_array().ok_or_else(|| format!("dit.config_json: no {k}"))?.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect())
        };
        let dim = u("model_dim")?;
        let baked = floats("baked_timesteps")?;
        let axes: Vec<usize> = floats("axes_dims")?.into_iter().map(|v| v as usize).collect();
        if axes.len() != 3
            || axes.iter().sum::<usize>() != HEAD_DIM
            || cfg["patch_size"] != serde_json::json!([1, 2, 2])
            || cfg["baked_visual_modulation"] != serde_json::json!(true)
            || u("in_visual_dim")? != 16
            || u("out_visual_dim")? != 16
        {
            return Err("an ImageSR transformer of an unsupported geometry (the release with baked modulation is)".into());
        }
        let n_t = baked.len();
        let mut blocks = Vec::with_capacity(u("num_visual_blocks")?);
        for b in 0..u("num_visual_blocks")? {
            let p = format!("dit.visual_transformer_blocks.{b}");
            let a = format!("{p}.self_attention");
            let blk = Block {
                q: Lin::load(model, &format!("{a}.to_query"))?,
                k: Lin::load(model, &format!("{a}.to_key"))?,
                v: Lin::load(model, &format!("{a}.to_value"))?,
                o: Lin::load(model, &format!("{a}.out_layer"))?,
                qn: cmf_f32(model, &format!("{a}.query_norm.weight"))?,
                kn: cmf_f32(model, &format!("{a}.key_norm.weight"))?,
                w1: Lin::load(model, &format!("{p}.feed_forward.in_layer"))?,
                w2: Lin::load(model, &format!("{p}.feed_forward.out_layer"))?,
                xattn: cmf_f32(model, &format!("{p}.xattn_bias_table"))?,
                table: cmf_f32(model, &format!("{p}.visual_modulation_table"))?,
            };
            if blk.xattn.len() != n_t * dim || blk.table.len() != n_t * 6 * dim || blk.qn.len() != HEAD_DIM || blk.kn.len() != HEAD_DIM {
                return Err(format!("block {b}: a table of the wrong size"));
            }
            blocks.push(blk);
        }
        let first = blocks.first().ok_or("a transformer without blocks")?;
        let (inner, ff) = (first.q.rows(), first.w1.rows());
        if inner % HEAD_DIM != 0 || blocks.iter().any(|b| b.q.rows() != inner || b.w1.rows() != ff || b.w2.rows() != dim) {
            return Err("blocks of different widths".into());
        }
        // the output layer's modulation: one linear over SiLU(the timestep's embedding)
        let te: Vec<f32> = cmf_f32(model, "dit.time_embed_table")?.into_iter().map(silu).collect();
        let m = Lin::load(model, "dit.out_layer.modulation.out_layer")?.apply(&te, n_t, pool.as_deref());
        let (mut out_shift, mut out_scale) = (Vec::new(), Vec::new());
        for r in m.chunks(2 * dim) {
            out_shift.extend_from_slice(&r[..dim]);
            out_scale.extend_from_slice(&r[dim..]);
        }
        Ok(KsrDit {
            embed: Lin::load(model, "dit.visual_embeddings.in_layer")?,
            out: Lin::load(model, "dit.out_layer.out_layer")?,
            model: model.clone(),
            pool,
            dim,
            inner,
            ff,
            axes: [axes[0], axes[1], axes[2]],
            baked,
            out_shift,
            out_scale,
            blocks,
            packed: std::sync::OnceLock::new(),
        })
    }

    pub fn t_index(&self, t: f32) -> Result<usize, String> {
        self.baked.iter().position(|b| (b - t).abs() <= 1e-6).ok_or_else(|| format!("t = {t} is not one of this model's timesteps"))
    }

    /// The modulation at baked timestep `ti`.
    pub fn mods(&self, ti: usize) -> KsrMods {
        let d = self.dim;
        let mut blocks = Vec::with_capacity(self.blocks.len() * MODS * d);
        for b in &self.blocks {
            let t = &b.table[ti * 6 * d..(ti + 1) * 6 * d];
            let x = &b.xattn[ti * d..(ti + 1) * d];
            let (sh, sc, g) = (&t[..d], &t[d..2 * d], &t[2 * d..3 * d]);
            blocks.extend(sc.iter().map(|v| 1.0 + v));
            blocks.extend_from_slice(sh);
            blocks.extend_from_slice(g);
            match &b.o.b {
                Some(ob) => blocks.extend((0..d).map(|i| g[i] * ob[i] + x[i])),
                None => blocks.extend_from_slice(x),
            }
            blocks.extend(t[4 * d..5 * d].iter().map(|v| 1.0 + v));
            blocks.extend_from_slice(&t[3 * d..4 * d]);
            blocks.extend_from_slice(&t[5 * d..6 * d]);
        }
        let mut fin: Vec<f32> = self.out_scale[ti * d..(ti + 1) * d].iter().map(|v| 1.0 + v).collect();
        fin.extend_from_slice(&self.out_shift[ti * d..(ti + 1) * d]);
        KsrMods { blocks, fin }
    }

    /// cos and sin `[h2·w2][64]` of the rotation of one frame.
    pub fn rope(&self, h2: usize, w2: usize) -> (Vec<f32>, Vec<f32>) {
        let lad = self.axes.map(|a| freqs(a / 2));
        let (mut cos, mut sin) = (Vec::with_capacity(h2 * w2 * ROPE_PAIRS), Vec::with_capacity(h2 * w2 * ROPE_PAIRS));
        for r in 0..h2 {
            for c in 0..w2 {
                for (pos, l) in [0, r, c].into_iter().zip(&lad) {
                    for f in l {
                        let a = pos as f32 * f;
                        cos.push(a.cos());
                        sin.push(a.sin());
                    }
                }
            }
        }
        (cos, sin)
    }

    /// What a device program is prepared from; `None` when a weight is not a
    /// container tensor of a codec the devices expand.
    pub fn prepare_args<'a>(&'a self, n: usize, mods: &'a KsrMods, rope: &'a (Vec<f32>, Vec<f32>)) -> Option<crate::gpu::KsrPrepareArgs<'a>> {
        let idx = |l: &Lin| l.w.graph_w().map(|(_, g)| g.idx);
        let blocks = self
            .blocks
            .iter()
            .map(|b| {
                Some(crate::gpu::KsrBlockRef {
                    w: [idx(&b.q)?, idx(&b.k)?, idx(&b.v)?, idx(&b.o)?, idx(&b.w1)?, idx(&b.w2)?],
                    b: [b.q.b.as_deref()?, b.k.b.as_deref()?, b.v.b.as_deref()?],
                    qn: &b.qn,
                    kn: &b.kn,
                })
            })
            .collect::<Option<Vec<_>>>()?;
        let dense = |l: &'a Lin| -> Option<(&'a [f32], &'a [f32])> {
            match &l.w {
                crate::dit::Proj::F32 { w, .. } => Some((w.as_slice(), l.b.as_deref()?)),
                _ => None,
            }
        };
        Some(crate::gpu::KsrPrepareArgs {
            model: &self.model,
            n,
            dim: self.dim,
            inner: self.inner,
            ff: self.ff,
            blocks,
            mods: &mods.blocks,
            fin: &mods.fin,
            rope: (&rope.0, &rope.1),
            embed: dense(&self.embed)?,
            out: dense(&self.out)?,
        })
    }

    /// The host forward: patch tokens `[n][64]` in, `[n][64]` out.
    pub fn forward_tokens(&self, tok: &[f32], mods: &KsrMods, rope: &(Vec<f32>, Vec<f32>)) -> Vec<f32> {
        let pool = self.pool.as_deref();
        let (d, inner, nh) = (self.dim, self.inner, self.inner / HEAD_DIM);
        let n = tok.len() / 64;
        let mut x = self.embed.apply(tok, n, pool);
        // dst = LN(x) · sc + sh
        let norm = |x: &[f32], sc: &[f32], sh: &[f32]| -> Vec<f32> {
            let mut y = vec![0f32; n * d];
            let sr = Rows(y.as_mut_ptr());
            pool_rows(pool, n, &|lo, hi| {
                for r in lo..hi {
                    // SAFETY: disjoint rows.
                    let row = unsafe { sr.at(r * d, d) };
                    layer_norm_row(&x[r * d..(r + 1) * d], LN_EPS, row);
                    for ((v, &s), &a) in row.iter_mut().zip(sc).zip(sh) {
                        *v = *v * s + a;
                    }
                }
            });
            y
        };
        let add = |x: &mut [f32], y: &[f32], g: &[f32], c: &[f32]| {
            let sr = Rows(x.as_mut_ptr());
            pool_rows(pool, n, &|lo, hi| {
                for r in lo..hi {
                    // SAFETY: disjoint rows.
                    let row = unsafe { sr.at(r * d, d) };
                    for (i, v) in row.iter_mut().enumerate() {
                        *v += g[i] * y[r * d + i] + c[i];
                    }
                }
            });
        };
        let zeros = vec![0f32; d];
        let packed = self.packed.get_or_init(|| self.blocks.iter().map(|b| Int8Block::of(&self.model, b, pool)).collect());
        let scale = 1.0 / (HEAD_DIM as f32).sqrt();
        for (b, blk) in self.blocks.iter().enumerate() {
            let m = |k: usize| &mods.blocks[(b * MODS + k) * d..(b * MODS + k + 1) * d];
            let p8 = |i: usize| packed[b].as_ref().map(|p| &p.0[i]);
            let h = norm(&x, m(0), m(1));
            let mut q = project(&blk.q, p8(0), &h, n, pool, true);
            let mut k = project(&blk.k, p8(1), &h, n, pool, true);
            let v = project(&blk.v, p8(2), &h, n, pool, true);
            for (buf, w) in [(&mut q, &blk.qn), (&mut k, &blk.kn)] {
                let sr = Rows(buf.as_mut_ptr());
                pool_rows(pool, n, &|lo, hi| {
                    for r in lo..hi {
                        for hh in 0..nh {
                            // SAFETY: disjoint rows.
                            let row = unsafe { sr.at((r * nh + hh) * HEAD_DIM, HEAD_DIM) };
                            rms_row(row, w, RMS_EPS as f64);
                            for j in 0..ROPE_PAIRS {
                                let (c, s) = (rope.0[r * ROPE_PAIRS + j], rope.1[r * ROPE_PAIRS + j]);
                                let (a, bb) = (row[2 * j], row[2 * j + 1]);
                                row[2 * j] = a * c - bb * s;
                                row[2 * j + 1] = a * s + bb * c;
                            }
                        }
                    }
                });
            }
            let mut att = vec![0f32; n * inner];
            let (mut qh, mut kh, mut vt) = (vec![0f32; n * HEAD_DIM], vec![0f32; n * HEAD_DIM], vec![0f32; HEAD_DIM * n]);
            let (mut sc, mut oh) = (vec![0f32; n * n], vec![0f32; n * HEAD_DIM]);
            for hh in 0..nh {
                for r in 0..n {
                    let base = (r * nh + hh) * HEAD_DIM;
                    for i in 0..HEAD_DIM {
                        qh[r * HEAD_DIM + i] = q[base + i] * scale;
                        vt[i * n + r] = v[base + i];
                    }
                    kh[r * HEAD_DIM..(r + 1) * HEAD_DIM].copy_from_slice(&k[base..base + HEAD_DIM]);
                }
                host_gemm::gemm_nt(&qh, &kh, &mut sc, n, HEAD_DIM, n, pool);
                let sp = Rows(sc.as_mut_ptr());
                pool_rows(pool, n, &|lo, hi| {
                    for r in lo..hi {
                        // SAFETY: disjoint rows.
                        let row = unsafe { sp.at(r * n, n) };
                        softmax_row(row);
                        // a weight below 1e-30 is zero: denormals are slow on x86
                        for v in row.iter_mut() {
                            *v = if *v < 1e-30 { 0.0 } else { *v };
                        }
                    }
                });
                host_gemm::gemm_nt(&sc, &vt, &mut oh, n, n, HEAD_DIM, pool);
                for r in 0..n {
                    let base = (r * nh + hh) * HEAD_DIM;
                    att[base..base + HEAD_DIM].copy_from_slice(&oh[r * HEAD_DIM..(r + 1) * HEAD_DIM]);
                }
            }
            // the output bias is part of the constant
            let y = project(&blk.o, p8(3), &att, n, pool, false);
            add(&mut x, &y, m(2), m(3));
            let h = norm(&x, m(4), m(5));
            let mut mid = project(&blk.w1, p8(4), &h, n, pool, true);
            let sr = Rows(mid.as_mut_ptr());
            pool_rows(pool, n, &|lo, hi| {
                for r in lo..hi {
                    // SAFETY: disjoint rows.
                    for v in unsafe { sr.at(r * self.ff, self.ff) } {
                        *v = gelu(*v);
                    }
                }
            });
            let y = project(&blk.w2, p8(5), &mid, n, pool, true);
            add(&mut x, &y, m(6), &zeros);
        }
        let h = norm(&x, &mods.fin[..d], &mods.fin[d..]);
        self.out.apply(&h, n, pool)
    }
}

/// `[16][lh][lw]` into patch tokens `[lh/2·lw/2][64]` (row, column, channel).
pub fn patchify(z: &[f32], lh: usize, lw: usize) -> Vec<f32> {
    let (h2, w2) = (lh / 2, lw / 2);
    let mut t = vec![0f32; h2 * w2 * 64];
    for (i, tk) in t.chunks_mut(64).enumerate() {
        let (r, c) = (i / w2, i % w2);
        for (j, v) in tk.iter_mut().enumerate() {
            let (p, ch) = (j / 16, j % 16);
            *v = z[ch * lh * lw + (2 * r + p / 2) * lw + 2 * c + p % 2];
        }
    }
    t
}

/// The output tokens `[n][64]` (channel, row, column) as `[16][lh][lw]`.
pub fn unpatchify(y: &[f32], lh: usize, lw: usize) -> Vec<f32> {
    let w2 = lw / 2;
    let mut z = vec![0f32; 16 * lh * lw];
    for (i, tk) in y.chunks(64).enumerate() {
        let (r, c) = (i / w2, i % w2);
        for (j, v) in tk.iter().enumerate() {
            let (ch, p) = (j / 4, j % 4);
            z[ch * lh * lw + (2 * r + p / 2) * lw + 2 * c + p % 2] = *v;
        }
    }
    z
}

/// Where a side of `len` pixels is cut into tiles.
pub fn tile_positions(len: usize, tile: usize, stride: usize) -> Vec<usize> {
    if len <= tile {
        return vec![0];
    }
    let mut v: Vec<usize> = (0..len - tile).step_by(stride).collect();
    if v[v.len() - 1] + tile < len {
        v.push(len - tile);
    }
    v
}

/// A side's Hanning window: flat over the halves that touch the picture's edge.
pub fn window(n: usize, first: bool, last: bool) -> Vec<f32> {
    (0..n)
        .map(|i| {
            if (first && i < n / 2) || (last && i >= n / 2) {
                1.0
            } else {
                0.5 - 0.5 * ((2.0 * std::f32::consts::PI) * i as f32 / n as f32).cos()
            }
        })
        .collect()
}

/// torch's bicubic coefficients (a = -0.75) at the fraction `t`.
fn cubic(t: f32) -> [f32; 4] {
    const A: f32 = -0.75;
    let near = |x: f32| ((A + 2.0) * x - (A + 3.0)) * x * x + 1.0;
    let far = |x: f32| ((A * x - 5.0 * A) * x + 8.0 * A) * x - 4.0 * A;
    [far(t + 1.0), near(t), near(1.0 - t), far(2.0 - t)]
}

/// A crop `[3][s][s]` enlarged to `[3][s·f][s·f]` (torch's bicubic,
/// `align_corners=False`), clamped to 0..1, the cores over the rows.
pub fn bicubic(x: &[f32], s: usize, f: usize) -> Vec<f32> {
    let n = s * f;
    let taps: Vec<([usize; 4], [f32; 4])> = (0..n)
        .map(|i| {
            let p = (i as f32 + 0.5) / f as f32 - 0.5;
            let fl = p.floor();
            (std::array::from_fn(|k| (fl as isize - 1 + k as isize).clamp(0, s as isize - 1) as usize), cubic(p - fl))
        })
        .collect();
    let mut out = vec![0f32; 3 * n * n];
    let threads = std::thread::available_parallelism().map_or(4, |t| t.get());
    let per = (3 * n).div_ceil(threads).max(1);
    std::thread::scope(|sc| {
        for (t, part) in out.chunks_mut(per * n).enumerate() {
            let taps = &taps;
            sc.spawn(move || {
                let mut line = vec![0f32; s];
                for (j, row) in part.chunks_mut(n).enumerate() {
                    let (ch, y) = ((t * per + j) / n, (t * per + j) % n);
                    let (ys, yw) = &taps[y];
                    for (c, l) in line.iter_mut().enumerate() {
                        *l = (0..4).map(|k| yw[k] * x[(ch * s + ys[k]) * s + c]).sum();
                    }
                    for (v, (xs, xw)) in row.iter_mut().zip(taps) {
                        *v = (0..4).map(|k| xw[k] * line[xs[k]]).sum::<f32>().clamp(0.0, 1.0);
                    }
                }
            });
        }
    });
    out
}

#[derive(Clone, Copy, Debug)]
pub struct UpscaleParams {
    /// 1, 2 or 4
    pub scale: usize,
    /// 0..8, how much the model redraws
    pub creativity: usize,
    /// what neighbouring tiles share, 0..1
    pub overlap: f32,
}

impl Default for UpscaleParams {
    fn default() -> Self {
        UpscaleParams { scale: 2, creativity: 4, overlap: 0.25 }
    }
}

/// Seconds of a run by stage.
#[derive(Clone, Copy, Debug, Default)]
pub struct UpscaleTimes {
    pub tiles: usize,
    pub resize: f64,
    pub encode: f64,
    pub step: f64,
    pub decode: f64,
    pub blend: f64,
    pub total: f64,
}

/// A loaded model.
pub struct Upscaler {
    dit: KsrDit,
    enc: VaeEncoder,
    dec: VaeDecoder,
    rope: (Vec<f32>, Vec<f32>),
    /// the device program of one timestep
    dev: Option<(usize, Option<Box<dyn crate::gpu::KsrStepper>>)>,
}

/// The side of a tile's latent.
pub const LATENT: usize = TILE / 8;
const TOKENS: usize = (LATENT / 2) * (LATENT / 2);

impl Upscaler {
    pub fn from_cmf(model: &Arc<CmfModel>, pool: Option<Arc<Pool>>) -> Result<Self, String> {
        if !is_ksr(model) {
            return Err("not a Kandinsky ImageSR container".into());
        }
        let dit = KsrDit::from_cmf(model, pool)?;
        let enc = VaeEncoder::from_cmf(model)?;
        let mut dec = VaeDecoder::from_cmf(model)?;
        dec.scaling_factor = VAE_SCALE;
        dec.shift_factor = 0.0;
        dec.keep = true;
        let rope = dit.rope(LATENT / 2, LATENT / 2);
        Ok(Upscaler { dit, enc, dec, rope, dev: None })
    }

    /// z `[16][128][128]` of a tile's picture `[3][1024][1024]` in 0..1.
    pub fn encode(&self, px: &[f32]) -> Vec<f32> {
        let x: Vec<f32> = px.iter().map(|v| v * 2.0 - 1.0).collect();
        let mut z = self.enc.encode_fast(&x, TILE, TILE);
        for v in &mut z {
            *v *= VAE_SCALE;
        }
        z
    }

    /// The velocity of a tile's latent at timestep `t`: the device program,
    /// or the host forward.
    pub fn velocity(&mut self, z: &[f32], t: f32) -> Result<Vec<f32>, String> {
        let ti = self.dit.t_index(t)?;
        let tok = patchify(z, LATENT, LATENT);
        if self.dev.as_ref().is_none_or(|(i, _)| *i != ti) {
            self.dev = None;
            let mods = self.dit.mods(ti);
            let dev = if crate::gpu::enabled_here() {
                self.dit.prepare_args(TOKENS, &mods, &self.rope).and_then(|a| crate::gpu::ksr_prepare(&a))
            } else {
                None
            };
            self.dev = Some((ti, dev));
        }
        if let Some((_, Some(dev))) = &mut self.dev {
            match dev.step(&tok) {
                Ok(y) => return Ok(unpatchify(&y, LATENT, LATENT)),
                Err(e) => eprintln!("upscale: the device forward failed ({e}); this tile runs on the CPU"),
            }
        }
        Ok(unpatchify(&self.dit.forward_tokens(&tok, &self.dit.mods(ti), &self.rope), LATENT, LATENT))
    }

    /// A corrected latent as a tile's picture `[3][1024][1024]` in 0..1.
    pub fn decode(&self, z: &[f32]) -> Vec<f32> {
        let mut px = self.dec.decode_fast(z, LATENT, LATENT);
        for v in &mut px {
            *v = (v.clamp(-1.0, 1.0) + 1.0) / 2.0;
        }
        px
    }

    /// An RGB picture `[h][w][3]` into `[h·f][w·f][3]`. `on_tile(done, all)`
    /// runs after each tile.
    pub fn run(&mut self, img: &[u8], h: usize, w: usize, p: &UpscaleParams, on_tile: &mut dyn FnMut(usize, usize)) -> Result<(Vec<u8>, UpscaleTimes), String> {
        if img.len() != h * w * 3 || h == 0 || w == 0 {
            return Err("a picture of the wrong size".into());
        }
        if !(0.0..1.0).contains(&p.overlap) {
            return Err(format!("overlap {}: 0 up to 1", p.overlap));
        }
        let t = resolve_t(p.scale, p.creativity)?;
        self.dit.t_index(t)?;
        let t_all = Instant::now();
        let f = p.scale;
        let lq = TILE / f;
        let stride = ((lq as f32 * (1.0 - p.overlap)) as usize).max(1);
        let (ph, pw) = (h.max(lq), w.max(lq));
        let (tops, lefts) = (tile_positions(ph, lq, stride), tile_positions(pw, lq, stride));
        let mut tm = UpscaleTimes { tiles: tops.len() * lefts.len(), ..Default::default() };
        let mut out = vec![0u8; h * f * w * f * 3];
        let wo = pw * f;
        // The rows still open: a tile row's height at the output's width.
        let mut band = vec![0f32; TILE * wo * 3];
        let mut wy_sum = vec![0f32; ph * f];
        let mut wx_sum = vec![0f32; wo];
        for (r, &y) in tops.iter().enumerate() {
            for (s, v) in wy_sum[y * f..y * f + TILE].iter_mut().zip(window(TILE, r == 0, r + 1 == tops.len())) {
                *s += v;
            }
        }
        for (c, &x) in lefts.iter().enumerate() {
            for (s, v) in wx_sum[x * f..x * f + TILE].iter_mut().zip(window(TILE, c == 0, c + 1 == lefts.len())) {
                *s += v;
            }
        }
        let mut done = 0;
        for (r, &top) in tops.iter().enumerate() {
            let wy = window(TILE, r == 0, r + 1 == tops.len());
            for (c, &left) in lefts.iter().enumerate() {
                let t0 = Instant::now();
                let mut crop = vec![0f32; 3 * lq * lq];
                for (ch, plane) in crop.chunks_mut(lq * lq).enumerate() {
                    for (yy, row) in plane.chunks_mut(lq).enumerate() {
                        let sy = (top + yy).min(h - 1);
                        for (xx, v) in row.iter_mut().enumerate() {
                            *v = img[(sy * w + (left + xx).min(w - 1)) * 3 + ch] as f32 / 255.0;
                        }
                    }
                }
                let up = bicubic(&crop, lq, f);
                tm.resize += t0.elapsed().as_secs_f64();
                let t0 = Instant::now();
                let mut z = self.encode(&up);
                tm.encode += t0.elapsed().as_secs_f64();
                let t0 = Instant::now();
                let v = self.velocity(&z, t)?;
                tm.step += t0.elapsed().as_secs_f64();
                for (a, b) in z.iter_mut().zip(&v) {
                    *a -= t * b;
                }
                let t0 = Instant::now();
                let px = self.decode(&z);
                tm.decode += t0.elapsed().as_secs_f64();
                let t0 = Instant::now();
                let wx = window(TILE, c == 0, c + 1 == lefts.len());
                let (x0, n) = (left * f, TILE);
                for_rows(&mut band, wo * 3, |yy, row| {
                    for (xx, o) in row[x0 * 3..(x0 + n) * 3].chunks_mut(3).enumerate() {
                        let k = wy[yy] * wx[xx];
                        for (ch, o) in o.iter_mut().enumerate() {
                            *o += px[(ch * n + yy) * n + xx] * k;
                        }
                    }
                });
                tm.blend += t0.elapsed().as_secs_f64();
                done += 1;
                on_tile(done, tm.tiles);
            }
            // the rows no later tile touches are final
            let t0 = Instant::now();
            let y0 = top * f;
            let y1 = tops.get(r + 1).map_or(y0 + TILE, |n| n * f);
            let (hh, ww) = (h * f, w * f);
            let last = y1.min(hh);
            if last > y0 {
                let (band, wy_sum, wx_sum) = (&band, &wy_sum, &wx_sum);
                for_rows(&mut out[y0 * ww * 3..last * ww * 3], ww * 3, |yy, row| {
                    let src = &band[yy * wo * 3..];
                    for (xx, o) in row.chunks_mut(3).enumerate() {
                        let k = (wy_sum[y0 + yy] * wx_sum[xx]).max(1e-6);
                        for (ch, o) in o.iter_mut().enumerate() {
                            *o = ((src[xx * 3 + ch] / k).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
                        }
                    }
                });
            }
            let shift = y1 - y0;
            band.copy_within(shift * wo * 3.., 0);
            band[(TILE - shift) * wo * 3..].fill(0.0);
            tm.blend += t0.elapsed().as_secs_f64();
        }
        tm.total = t_all.elapsed().as_secs_f64();
        Ok((out, tm))
    }
}

impl Drop for Upscaler {
    fn drop(&mut self) {
        self.dev = None;
        crate::gpu::ksr_release();
    }
}

/// `f(row index, row)` over rows of `width` values, the cores over the rows.
fn for_rows<T: Send, F: Fn(usize, &mut [T]) + Sync>(v: &mut [T], width: usize, f: F) {
    let rows = v.len() / width;
    let threads = std::thread::available_parallelism().map_or(4, |t| t.get());
    let per = rows.div_ceil(threads).max(1);
    std::thread::scope(|s| {
        for (t, part) in v.chunks_mut(per * width).enumerate() {
            let f = &f;
            s.spawn(move || {
                for (j, row) in part.chunks_mut(width).enumerate() {
                    f(t * per + j, row);
                }
            });
        }
    });
}

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

    #[test]
    fn tiles_cover_the_side_and_end_flush() {
        assert_eq!(tile_positions(200, 256, 192), vec![0]);
        assert_eq!(tile_positions(512, 256, 192), vec![0, 192, 256]);
        assert_eq!(tile_positions(576, 256, 192), vec![0, 192, 320]);
        assert_eq!(tile_positions(448, 256, 192), vec![0, 192]);
    }

    #[test]
    fn a_window_is_flat_at_the_edges_and_bicubic_keeps_a_constant() {
        let w = window(1024, true, false);
        assert!(w[..512].iter().all(|v| *v == 1.0) && w[1023] < 1e-4);
        let x = vec![0.25f32; 3 * 16 * 16];
        assert!(bicubic(&x, 16, 4).iter().all(|v| (v - 0.25).abs() < 1e-6));
    }

    #[test]
    fn patches_keep_the_reference_orders() {
        let z: Vec<f32> = (0..16 * 4 * 4).map(|v| v as f32).collect();
        let t = patchify(&z, 4, 4);
        // token 1 (row 0, column 1), patch position (1, 0), channel 3
        assert_eq!(t[64 + 2 * 16 + 3], z[3 * 16 + 4 + 2]);
        // the output's order is (channel, row, column)
        let y: Vec<f32> = (0..4 * 64).map(|v| v as f32).collect();
        let u = unpatchify(&y, 4, 4);
        assert_eq!(u[3 * 16 + 4 + 2], y[64 + 3 * 4 + 2]);
    }

    #[test]
    fn the_timestep_follows_scale_and_creativity() {
        assert_eq!(resolve_t(4, 4).unwrap(), 0.244);
        assert_eq!(resolve_t(1, 0).unwrap(), 0.005);
        assert!(resolve_t(3, 4).is_err() && resolve_t(2, 9).is_err());
    }
}