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
//! The eight-bit products (GigaAM, Kandinsky ImageSR) as int8 × int8 on x86 with
//! AVX-512 VNNI.
//!
//! The weights stay the file's int8 codes, repacked once into blocks of 16
//! rows × 4 columns (`[block][group][16][4]` bytes), so that one `vpdpbusd`
//! adds four columns of sixteen rows against one input value broadcast to
//! every lane: no horizontal sums. Each input row (a frame) is quantized on
//! the fly to unsigned 8 bits with its own scale and zero point, after the
//! weight's column field is folded into it:
//!
//! `x'[c] = x[c]·col_field[c] ≈ s·(q[c] − z)`, `q ∈ [0, 255]`, the range
//! taking in zero so `z ∈ [0, 255]`; then
//! `y[r] = row_scale[r] · s · (Σ_c q[c]·w[r][c] − z·Σ_c w[r][c])`,
//! the sum exact in int32 (at most 4 096 columns of 255·127).
//!
//! `CMF_GIGAAM_INT8=0` keeps the float path.
#![cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]

use super::ops::{Shared, par};
use crate::pool::Pool;

/// Rows of one packed block (the lanes of a 512-bit int32 vector).
const BLOCK: usize = 16;
/// Input rows a tile keeps in registers against two blocks of rows.
const NR: usize = 12;
/// Input rows of one task (eight tiles).
const PANEL: usize = 96;
/// Rows of one task (four blocks).
const ROWS_TASK: usize = 64;

/// Is the int8 path on here (an x86 CPU with AVX-512 VNNI, not switched off)?
pub(crate) fn available() -> bool {
    use std::sync::OnceLock;
    static ON: OnceLock<bool> = OnceLock::new();
    *ON.get_or_init(|| {
        if std::env::var("CMF_GIGAAM_INT8").as_deref() == Ok("0") {
            return false;
        }
        #[cfg(target_arch = "x86_64")]
        {
            std::arch::is_x86_feature_detected!("avx512f")
                && std::arch::is_x86_feature_detected!("avx512bw")
                && std::arch::is_x86_feature_detected!("avx512vnni")
        }
        #[cfg(not(target_arch = "x86_64"))]
        {
            false
        }
    })
}

/// A weight repacked for the int8 product.
pub(crate) struct Packed {
    rows: usize,
    cols: usize,
    /// column groups of four (the columns padded with zero weights)
    groups: usize,
    /// `[block][group][16][4]`, rows padded with zero weights to whole blocks
    data: Vec<u8>,
    /// `Σ_c w[r][c]` a row (padded rows 0)
    wsum: Vec<i32>,
    /// the row scales, padded with zeros to whole blocks
    row_scale: Vec<f32>,
}

impl Packed {
    fn blocks(&self) -> usize {
        self.rows.div_ceil(BLOCK)
    }
}

/// Repack `codes` (`[rows, cols]` int8, row-major) with their row scales.
pub(crate) fn pack(codes: &[u8], row_scale: &[f32], rows: usize, cols: usize, pool: Option<&Pool>) -> Packed {
    assert!(codes.len() >= rows * cols && row_scale.len() >= rows);
    let groups = cols.div_ceil(4);
    let blocks = rows.div_ceil(BLOCK);
    let block_bytes = groups * BLOCK * 4;
    let mut data = vec![0u8; blocks * block_bytes];
    let mut wsum = vec![0i32; blocks * BLOCK];
    let (dp, sp) = (Shared(data.as_mut_ptr()), Shared(wsum.as_mut_ptr()));
    par(pool, blocks, 2, &|a, b| {
        for blk in a..b {
            // SAFETY: block `blk` of `data` and of `wsum` belongs to this range alone.
            let (dst, sums) = unsafe {
                (std::slice::from_raw_parts_mut(dp.ptr().add(blk * block_bytes), block_bytes), std::slice::from_raw_parts_mut(sp.ptr().add(blk * BLOCK), BLOCK))
            };
            for t in 0..BLOCK {
                let r = blk * BLOCK + t;
                if r >= rows {
                    break;
                }
                let row = &codes[r * cols..(r + 1) * cols];
                let mut s = 0i32;
                for (c, &v) in row.iter().enumerate() {
                    dst[((c / 4) * BLOCK + t) * 4 + c % 4] = v;
                    s += v as i8 as i32;
                }
                sums[t] = s;
            }
        }
    });
    let mut rs = row_scale[..rows].to_vec();
    rs.resize(blocks * BLOCK, 0.0);
    Packed { rows, cols, groups, data, wsum, row_scale: rs }
}

/// The scale and zero point of one quantized input row: `x ≈ s·(q − z)`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct RowQ {
    pub s: f32,
    pub z: i32,
}

/// Scale and zero point for values in `[lo, hi]` (zero taken in).
pub(super) fn row_params(lo: f32, hi: f32) -> (RowQ, f32) {
    let (lo, hi) = (lo.min(0.0), hi.max(0.0));
    let range = hi - lo;
    if range <= 0.0 || !range.is_finite() {
        return (RowQ { s: 0.0, z: 0 }, 0.0);
    }
    let s = range / 255.0;
    let inv = 1.0 / s;
    let z = ((-lo * inv).round_ties_even() as i32).clamp(0, 255);
    (RowQ { s, z }, inv)
}

/// One input row's code: `clamp(round(v·inv) + z, 0, 255)`.
#[inline]
pub(super) fn code(v: f32, inv: f32, z: i32) -> u8 {
    (((v * inv).round_ties_even() as i32) + z).clamp(0, 255) as u8
}

/// `y[n, rows] = x[n, cols] · Wᵀ` with `w[r][c] = code·row_scale[r]·col_field[c]`
/// (an empty field is 1), `y` overwritten. Only where [`available`].
pub(crate) fn matmul(p: &Packed, col_field: &[f32], x: &[f32], n: usize, y: &mut [f32], pool: Option<&Pool>) {
    debug_assert_eq!(x.len(), n * p.cols);
    debug_assert_eq!(y.len(), n * p.rows);
    if n == 0 || p.rows == 0 {
        return;
    }
    #[cfg(target_arch = "x86_64")]
    {
        let stride = p.groups * 4;
        let mut q = vec![0u8; n * stride];
        let mut rq = vec![RowQ::default(); n];
        {
            let (qp, rp) = (Shared(q.as_mut_ptr()), Shared(rq.as_mut_ptr()));
            par(pool, n, 16, &|a, b| {
                for i in a..b {
                    // SAFETY: input row `i` of `q` and of `rq` belongs to this range alone.
                    unsafe {
                        let dst = std::slice::from_raw_parts_mut(qp.ptr().add(i * stride), stride);
                        *rp.ptr().add(i) = quantize_row(&x[i * p.cols..(i + 1) * p.cols], col_field, dst);
                    }
                }
            });
        }
        let row_tasks = p.rows.div_ceil(ROWS_TASK);
        let tasks = row_tasks * n.div_ceil(PANEL);
        let yp = Shared(y.as_mut_ptr());
        let (q, rq) = (&q[..], &rq[..]);
        par(pool, tasks, 1, &|a, b| {
            for task in a..b {
                let (rt, it) = (task % row_tasks, task / row_tasks);
                let (b0, b1) = (rt * ROWS_TASK / BLOCK, ((rt + 1) * ROWS_TASK / BLOCK).min(p.blocks()));
                let (i0, i1) = (it * PANEL, ((it + 1) * PANEL).min(n));
                // SAFETY: the features were detected by `available`; this task writes
                // rows i0..i1, columns of blocks b0..b1 of `y` and nothing else.
                unsafe { panel(p, q, stride, rq, b0, b1, i0, i1, yp) };
            }
        });
    }
    #[cfg(not(target_arch = "x86_64"))]
    {
        let _ = (col_field, x, y, pool);
        unreachable!("the int8 GigaAM product runs on x86 only");
    }
}

/// Quantize one input row (the column field folded in) into `dst`
/// (`groups·4` bytes, the padding left at zero).
#[cfg(target_arch = "x86_64")]
fn quantize_row(x: &[f32], col_field: &[f32], dst: &mut [u8]) -> RowQ {
    // SAFETY: `matmul` runs only where `available` found AVX-512.
    unsafe { quantize_row_avx512(x, col_field, dst) }
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw")]
unsafe fn quantize_row_avx512(x: &[f32], col_field: &[f32], dst: &mut [u8]) -> RowQ {
    use core::arch::x86_64::*;
    let cols = x.len();
    let field = !col_field.is_empty();
    debug_assert!(!field || col_field.len() == cols);
    let c16 = cols / 16 * 16;
    // SAFETY: every load and store is inside `x`, `col_field` and `dst` (c + 16 ≤ c16 ≤ cols ≤ dst.len()).
    unsafe {
        let value = |c: usize| -> __m512 {
            let v = _mm512_loadu_ps(x.as_ptr().add(c));
            if field { _mm512_mul_ps(v, _mm512_loadu_ps(col_field.as_ptr().add(c))) } else { v }
        };
        let (mut lo, mut hi) = (_mm512_setzero_ps(), _mm512_setzero_ps());
        let mut c = 0;
        while c < c16 {
            let v = value(c);
            lo = _mm512_min_ps(lo, v);
            hi = _mm512_max_ps(hi, v);
            c += 16;
        }
        let mut l = [0f32; 16];
        let mut h = [0f32; 16];
        _mm512_storeu_ps(l.as_mut_ptr(), lo);
        _mm512_storeu_ps(h.as_mut_ptr(), hi);
        let (mut lo_s, mut hi_s) = (l.iter().copied().fold(0f32, f32::min), h.iter().copied().fold(0f32, f32::max));
        let scalar = |c: usize| if field { x[c] * col_field[c] } else { x[c] };
        for c in c16..cols {
            lo_s = lo_s.min(scalar(c));
            hi_s = hi_s.max(scalar(c));
        }
        let (rq, inv) = row_params(lo_s, hi_s);
        let (vinv, vz, zero, top) = (_mm512_set1_ps(inv), _mm512_set1_epi32(rq.z), _mm512_setzero_si512(), _mm512_set1_epi32(255));
        let mut c = 0;
        while c < c16 {
            // the default rounding mode: to nearest, ties to even, as `code`
            let r = _mm512_add_epi32(_mm512_cvtps_epi32(_mm512_mul_ps(value(c), vinv)), vz);
            let r = _mm512_min_epi32(_mm512_max_epi32(r, zero), top);
            _mm_storeu_si128(dst.as_mut_ptr().add(c) as *mut __m128i, _mm512_cvtepi32_epi8(r));
            c += 16;
        }
        for c in c16..cols {
            dst[c] = code(scalar(c), inv, rq.z);
        }
        rq
    }
}

/// The tiles of one task: blocks `b0..b1` of rows against input rows `i0..i1`.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw,avx512vnni")]
#[allow(clippy::too_many_arguments)]
unsafe fn panel(p: &Packed, q: &[u8], stride: usize, rq: &[RowQ], b0: usize, b1: usize, i0: usize, i1: usize, y: Shared<f32>) {
    let mut b = b0;
    while b < b1 {
        let mb = if b + 2 <= b1 { 2 } else { 1 };
        let mut i = i0;
        while i < i1 {
            let nb = (i1 - i).min(NR);
            // SAFETY: as `panel`: rows i..i + nb and blocks b..b + mb are in range.
            unsafe { tile_dispatch(p, q, stride, rq, b, mb, i, nb, y) };
            i += nb;
        }
        b += mb;
    }
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw,avx512vnni")]
#[allow(clippy::too_many_arguments)]
unsafe fn tile_dispatch(p: &Packed, q: &[u8], stride: usize, rq: &[RowQ], b: usize, mb: usize, i: usize, nb: usize, y: Shared<f32>) {
    macro_rules! go {
        ($mb:literal; $($n:literal)*) => {
            match nb {
                $($n => unsafe { tile::<$mb, $n>(p, q, stride, rq, b, i, y) },)*
                _ => unreachable!(),
            }
        };
    }
    if mb == 2 {
        go!(2; 1 2 3 4 5 6 7 8 9 10 11 12)
    } else {
        go!(1; 1 2 3 4 5 6 7 8 9 10 11 12)
    }
}

/// `MB` blocks of 16 rows (from block `b`) against `N` input rows (from
/// row `i`): `MB·N` int32 accumulators in registers, one `vpdpbusd` per
/// (block, input row, group of four columns).
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw,avx512vnni")]
#[inline]
unsafe fn tile<const MB: usize, const N: usize>(p: &Packed, q: &[u8], stride: usize, rq: &[RowQ], b: usize, i: usize, y: Shared<f32>) {
    use core::arch::x86_64::*;
    let block_bytes = p.groups * BLOCK * 4;
    // SAFETY: blocks b..b + MB are inside `p.data`, input rows i..i + N inside `q` and `rq`,
    // and the stores go to rows i..i + N, columns of rows b·16.. < p.rows (the last block masked).
    unsafe {
        let w = p.data.as_ptr().add(b * block_bytes);
        let xq = q.as_ptr().add(i * stride);
        let mut acc = [[_mm512_setzero_si512(); N]; MB];
        for g in 0..p.groups {
            let mut wv = [_mm512_setzero_si512(); MB];
            for (k, v) in wv.iter_mut().enumerate() {
                *v = _mm512_loadu_si512(w.add(k * block_bytes + g * 64) as *const _);
            }
            for j in 0..N {
                let xb = _mm512_set1_epi32(std::ptr::read_unaligned(xq.add(j * stride + g * 4) as *const i32));
                for k in 0..MB {
                    acc[k][j] = _mm512_dpbusd_epi32(acc[k][j], xb, wv[k]);
                }
            }
        }
        for (k, row) in acc.iter().enumerate() {
            let r0 = (b + k) * BLOCK;
            let valid = (p.rows - r0).min(BLOCK);
            let mask: __mmask16 = if valid == BLOCK { 0xffff } else { (1u16 << valid) - 1 };
            let wsum = _mm512_loadu_si512(p.wsum.as_ptr().add(r0) as *const _);
            let scale = _mm512_loadu_ps(p.row_scale.as_ptr().add(r0));
            for (j, a) in row.iter().enumerate() {
                let RowQ { s, z } = rq[i + j];
                let corr = _mm512_sub_epi32(*a, _mm512_mullo_epi32(_mm512_set1_epi32(z), wsum));
                let v = _mm512_mul_ps(_mm512_cvtepi32_ps(corr), _mm512_mul_ps(_mm512_set1_ps(s), scale));
                _mm512_mask_storeu_ps(y.0.add((i + j) * p.rows + r0), mask, v);
            }
        }
    }
}

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

    struct Rng(u64);
    impl Rng {
        fn f(&mut self) -> f32 {
            self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
            ((self.0 >> 40) as f32 / (1u64 << 24) as f32) - 0.5
        }
    }

    /// The product as the kernel defines it, in plain scalar code.
    fn emulate(codes: &[u8], row_scale: &[f32], col_field: &[f32], x: &[f32], n: usize, rows: usize, cols: usize) -> Vec<f32> {
        let mut y = vec![0f32; n * rows];
        for i in 0..n {
            let xs: Vec<f32> = (0..cols).map(|c| if col_field.is_empty() { x[i * cols + c] } else { x[i * cols + c] * col_field[c] }).collect();
            let lo = xs.iter().copied().fold(0f32, f32::min);
            let hi = xs.iter().copied().fold(0f32, f32::max);
            let (rq, inv) = row_params(lo, hi);
            let q: Vec<i32> = xs.iter().map(|&v| code(v, inv, rq.z) as i32).collect();
            for r in 0..rows {
                let w = &codes[r * cols..(r + 1) * cols];
                let dot: i32 = w.iter().zip(&q).map(|(&a, &b)| a as i8 as i32 * b).sum();
                let ws: i32 = w.iter().map(|&a| a as i8 as i32).sum();
                y[i * rows + r] = ((dot - rq.z * ws) as f32) * (rq.s * row_scale[r]);
            }
        }
        y
    }

    #[test]
    fn row_params_take_zero_in() {
        let (rq, inv) = row_params(-1.0, 3.0);
        assert_eq!(rq.z, 64);
        assert!((rq.s - 4.0 / 255.0).abs() < 1e-7);
        assert_eq!(code(-1.0, inv, rq.z), 0);
        assert_eq!(code(3.0, inv, rq.z), 255);
        assert_eq!(code(0.0, inv, rq.z), 64);
        // all positive: zero is the bottom of the range
        let (rq, _) = row_params(2.0, 5.0);
        assert_eq!(rq.z, 0);
        // an all-zero row has no scale
        assert_eq!(row_params(0.0, 0.0).0, RowQ { s: 0.0, z: 0 });
    }

    #[test]
    fn the_kernel_is_the_scalar_definition_and_close_to_the_float_product() {
        if !available() {
            eprintln!("no AVX-512 VNNI here: the int8 kernel is not exercised");
            return;
        }
        let pool = Pool::new(3);
        let mut rng = Rng(7);
        // rows with and without a partial last block; columns with and without a partial group
        for &(rows, cols) in &[(16usize, 64usize), (40, 30), (96, 768), (33, 7), (768, 384)] {
            let codes: Vec<u8> = (0..rows * cols).map(|_| (rng.f() * 254.0) as i8 as u8).collect();
            let row_scale: Vec<f32> = (0..rows).map(|_| 0.01 + rng.f().abs() * 0.02).collect();
            let col_field: Vec<f32> = (0..cols).map(|_| 0.5 + rng.f().abs() * 2.0).collect();
            let p = pack(&codes, &row_scale, rows, cols, Some(&pool));
            for &n in &[1usize, 5, 12, 13, 50, 100, 197] {
                for field in [&col_field[..], &[][..]] {
                    let x: Vec<f32> = (0..n * cols).map(|_| rng.f() * 3.0 + 0.4).collect();
                    let mut y = vec![f32::NAN; n * rows];
                    matmul(&p, field, &x, n, &mut y, Some(&pool));
                    let want = emulate(&codes, &row_scale, field, &x, n, rows, cols);
                    assert_eq!(y, want, "{rows}x{cols} n={n}");
                    // against the float product: the error of eight-bit inputs, relative to the row's norm
                    for i in 0..n.min(4) {
                        for r in 0..rows.min(8) {
                            let (mut exact, mut norm) = (0f64, 0f64);
                            for c in 0..cols {
                                let xv = x[i * cols + c] as f64 * field.get(c).copied().unwrap_or(1.0) as f64;
                                let wv = codes[r * cols + c] as i8 as f64 * row_scale[r] as f64;
                                exact += xv * wv;
                                norm += (xv * wv).abs();
                            }
                            assert!((y[i * rows + r] as f64 - exact).abs() <= 0.01 * norm + 1e-6, "{rows}x{cols} n={n} ({i}, {r})");
                        }
                    }
                }
            }
        }
        // a zero row and a row of one sign
        let (rows, cols) = (16usize, 32usize);
        let codes: Vec<u8> = (0..rows * cols).map(|k| (k % 251) as u8).collect();
        let rs = vec![0.5f32; rows];
        let p = pack(&codes, &rs, rows, cols, None);
        let mut x = vec![0f32; 2 * cols];
        x[cols..].iter_mut().enumerate().for_each(|(c, v)| *v = 1.0 + c as f32);
        let mut y = vec![f32::NAN; 2 * rows];
        matmul(&p, &[], &x, 2, &mut y, None);
        assert!(y[..rows].iter().all(|v| *v == 0.0));
        assert_eq!(y, emulate(&codes, &rs, &[], &x, 2, rows, cols));
    }
}