gresil 0.1.0-alpha.9

Spiking neural networks in no_std Rust, i16 fixed point, for microcontrollers
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
// SPDX-FileCopyrightText: 2026 philo-the-dendron
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Unstable: behind `unstable-bridge`.
//! Stage 3 of the ternary bridge: the **shared kernel** (see
//! `docs/VISION.md`).
//!
//! One `no_std`, zero-alloc, integer-only ternary matmul primitive that an
//! SNN layer and a dense LLM-style layer both call — the mechanical proof
//! that the union composes. This is the BitNet-matmul analog: packed
//! ternary weights `{−1, 0, +1}` × Q15 activations, i32 accumulation.
//!
//! # Two formats, two roles (the Stage-3 decision)
//!
//! - **Wire format** = `BitNet` `i2_s` ([`crate::bridge`], transposed 4-lane
//!   packing) — what crosses systems.
//! - **Compute format** = this module's **sequential** packing — element
//!   `i` at byte `i/4`, shift `2·(i%4)`, LSB-first lanes, codes
//!   `{0,1,2} = {−1,0,+1}`. Sequential indexing is what a hot matmul loop
//!   wants (no lane transpose math per element).
//!
//! [`crate::bridge::repack_i2s_to_kernel`] is the seam: weights arrive as
//! `i2_s` bytes, repack once, compute in the native layout.
//!
//! # Numeric contract
//!
//! Activations are Q15 i16 (`−32768..=32767`, produced by
//! [`absmax_normalize_q15`] — the integer analog of `BitNet`'s per-token
//! absmax activation quantization). Accumulation is i32 with the documented
//! bound `|acc| ≤ n × 32,768` (an [`i16::MIN`] activation), which fits `i32`
//! for `n ≤ 65,535`; [`ternary_matvec`] refuses a wider row. No float, no
//! heap: every function is buffer-based.

#![allow(clippy::module_name_repetitions)]
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss
)]

use crate::bridge::BridgeError;
use crate::trit::Trit;

/// Sequential packing: 4 trits per byte.
const TRITS_PER_BYTE: usize = 4;

/// Q15 full scale (1.0 in the activation fixed-point).
const Q15_MAX: i16 = i16::MAX;

/// Pack a ternary slice into the kernel's sequential compute layout.
///
/// Element `i` → byte `i/4`, shift `2·(i%4)`; codes `{0,1,2}` =
/// `{−1,0,+1}` (the shared code table). Requires `trits.len() % 4 == 0` and
/// `out.len() >= trits.len()/4`. Returns bytes written.
///
/// # Errors
///
/// [`BridgeError::BadLength`] on a non-multiple-of-4 slice;
/// [`BridgeError::TooShort`] on an undersized `out`.
pub fn pack_trits(trits: &[Trit], out: &mut [u8]) -> Result<usize, BridgeError> {
    let n = trits.len();
    if !n.is_multiple_of(TRITS_PER_BYTE) {
        return Err(BridgeError::BadLength);
    }
    if out.len() < n / TRITS_PER_BYTE {
        return Err(BridgeError::TooShort);
    }
    out[..n / TRITS_PER_BYTE].fill(0);
    for (i, t) in trits.iter().enumerate() {
        let code = match t {
            Trit::MinusOne => 0,
            Trit::Zero => 1,
            Trit::One => 2,
        };
        out[i / TRITS_PER_BYTE] |= code << (2 * (i % TRITS_PER_BYTE));
    }
    Ok(n / TRITS_PER_BYTE)
}

/// Unpack element `i` from sequential kernel packing.
///
/// # Errors
///
/// [`BridgeError::UnsupportedCode`] on code 3 (corrupt data).
///
/// # Panics
///
/// Panics if `i >= packed.len() × 4` (slice indexing).
pub fn unpack_trit(packed: &[u8], i: usize) -> Result<Trit, BridgeError> {
    let code = (packed[i / TRITS_PER_BYTE] >> (2 * (i % TRITS_PER_BYTE))) & 0x03;
    match code {
        0 => Ok(Trit::MinusOne),
        1 => Ok(Trit::Zero),
        2 => Ok(Trit::One),
        _ => Err(BridgeError::UnsupportedCode),
    }
}

/// Normalize a vector into Q15 by its absmax — the integer analog of
/// `BitNet`'s per-token activation quantization.
///
/// `out[i] = round(value[i] / absmax × 32767)` in pure integer math
/// (round-half-away-from-zero). Returns the absmax itself (as `u16` —
/// the scale the caller needs to un-normalize downstream; note
/// `absmax` is 32768 when the input contains [`i16::MIN`], which does
/// NOT fit i16: the old `i16` return wrapped to −32768 there). An
/// all-zero vector normalizes to zeros and returns 0.
///
/// Writes `out[..values.len()]`; a longer `out` keeps its tail.
///
/// # Errors
///
/// [`BridgeError::TooShort`] if `out` is shorter than `values`.
pub fn absmax_normalize_q15(values: &[i16], out: &mut [i16]) -> Result<u16, BridgeError> {
    if out.len() < values.len() {
        return Err(BridgeError::TooShort);
    }
    let absmax = values.iter().map(|v| v.unsigned_abs()).max().unwrap_or(0);
    if absmax == 0 {
        out[..values.len()].fill(0);
        return Ok(0);
    }
    for (v, slot) in values.iter().zip(out.iter_mut()) {
        // |v| ≤ absmax → |num| ≤ 32767 × absmax ≤ 32767×32768 < 2^31: exact.
        let num = i32::from(*v) * i32::from(Q15_MAX);
        let den = i32::from(absmax);
        let half = den / 2; // den > 0
        let q = if num >= 0 {
            (num + half) / den
        } else {
            -((-num + half) / den)
        };
        *slot = q.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16;
    }
    Ok(absmax)
}

/// The shared ternary matvec: `out[j] = Σᵢ w[j·n+i] · a[i]`.
///
/// `packed_weights` holds `rows` consecutive rows of sequentially-packed
/// ternary weights (each row `n = activations.len()` trits, `n/4` bytes —
/// pack with [`pack_trits`] or arrive via
/// [`crate::bridge::repack_i2s_to_kernel`]); `activations` are Q15 i16;
/// `out` receives `rows` i32 accumulators.
///
/// Accumulation bound: `|out[j]| ≤ n × 32,768` (an [`i16::MIN`] activation),
/// which fits `i32` for `n ≤ 65,535`; a wider row is refused.
///
/// # Errors
///
/// [`BridgeError::BadLength`] if `n % 4 != 0`; [`BridgeError::RowTooWide`]
/// if `n > 65_535`; [`BridgeError::TooShort`] if
/// `packed_weights.len() < rows·n/4` or `out.len() < rows`;
/// [`BridgeError::UnsupportedCode`] on any code-3 lane. On `Err`, `out`
/// may already hold partial row results — do not use them.
pub fn ternary_matvec(
    packed_weights: &[u8],
    activations: &[i16],
    rows: usize,
    out: &mut [i32],
) -> Result<(), BridgeError> {
    let n = activations.len();
    if !n.is_multiple_of(TRITS_PER_BYTE) {
        return Err(BridgeError::BadLength);
    }
    if n > 65_535 {
        return Err(BridgeError::RowTooWide);
    }
    let row_bytes = n / TRITS_PER_BYTE;
    if packed_weights.len() < rows * row_bytes || out.len() < rows {
        return Err(BridgeError::TooShort);
    }
    for (j, acc) in out.iter_mut().enumerate().take(rows) {
        let row = &packed_weights[j * row_bytes..(j + 1) * row_bytes];
        let mut sum: i32 = 0;
        for (i, &a) in activations.iter().enumerate() {
            let code = (row[i / TRITS_PER_BYTE] >> (2 * (i % TRITS_PER_BYTE))) & 0x03;
            let w = match code {
                0 => -1_i32,
                1 => 0,
                2 => 1,
                _ => return Err(BridgeError::UnsupportedCode),
            };
            sum += w * i32::from(a);
        }
        *acc = sum;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    #![allow(clippy::shadow_unrelated)]
    use super::*;
    use proptest::prelude::*;

    // ----- Packing -----

    #[test]
    fn pack_known_vector() {
        // [+1, −1, 0, 0] → codes 2,0,1,1 → byte 2 | 0<<2 | 1<<4 | 1<<6 = 0x52.
        let trits = [Trit::One, Trit::MinusOne, Trit::Zero, Trit::Zero];
        let mut out = [0_u8; 1];
        assert_eq!(pack_trits(&trits, &mut out), Ok(1));
        assert_eq!(out[0], 0x52);
        // Unpack round-trip.
        for (i, &t) in trits.iter().enumerate() {
            assert_eq!(unpack_trit(&out, i), Ok(t));
        }
    }

    #[test]
    fn pack_rejects_bad_input() {
        let mut out = [0_u8; 1];
        assert_eq!(
            pack_trits(&[Trit::One; 3], &mut out),
            Err(BridgeError::BadLength)
        );
        assert_eq!(
            pack_trits(&[Trit::One; 8], &mut out),
            Err(BridgeError::TooShort)
        );
    }

    // ----- absmax Q15 -----

    #[test]
    fn absmax_known_vector() {
        let vals = [10_i16, 5, 0, -10];
        let mut out = [0_i16; 4];
        let scale = absmax_normalize_q15(&vals, &mut out).unwrap();
        assert_eq!(scale, 10);
        assert_eq!(out, [32_767, 16_384, 0, -32_767]); // 16383.5 rounds away → 16384
    }

    #[test]
    fn absmax_i16_min_returns_32768_not_wrapped() {
        // 2026-08-15 review: the old i16 return wrapped 32768 → −32768,
        // flipping every downstream un-normalization sign. Derived
        // expectations (not hand-waved): absmax = 32768 (from i16::MIN);
        // i16::MIN → −32768·32767/32768 = −32767 exactly; i16::MAX →
        // 32767·32767/32768 = 32766.00003 → 32766.
        let vals = [i16::MIN, 0, i16::MAX];
        let mut out = [0_i16; 3];
        let scale = absmax_normalize_q15(&vals, &mut out).unwrap();
        assert_eq!(scale, 32_768); // u16 — does not wrap
        assert_eq!(out, [-32_767, 0, 32_766]);
    }

    #[test]
    fn absmax_zero_vector_is_zeros() {
        let mut out = [7_i16; 3];
        assert_eq!(absmax_normalize_q15(&[0, 0, 0], &mut out), Ok(0));
        assert_eq!(out, [0, 0, 0]);
    }

    #[test]
    fn absmax_refuses_a_short_out() {
        let mut out = [7_i16; 3];
        assert_eq!(
            absmax_normalize_q15(&[1, 2, 3, 4], &mut out),
            Err(BridgeError::TooShort)
        );
        assert_eq!(out, [7, 7, 7]);
    }

    #[test]
    fn absmax_writes_the_prefix_of_a_longer_out() {
        let mut out = [7_i16; 4];
        assert_eq!(absmax_normalize_q15(&[10, -5], &mut out), Ok(10));
        assert_eq!(out, [32_767, -16_384, 7, 7]);
        let mut out = [7_i16; 4];
        assert_eq!(absmax_normalize_q15(&[0, 0], &mut out), Ok(0));
        assert_eq!(out, [0, 0, 7, 7]);
    }

    // ----- Matvec -----

    #[test]
    fn matvec_known_vector() {
        // W = [[+1, 0, −1, 0], [−1, −1, −1, −1]], a = [1000, 5000, 200, 7].
        let row0 = [Trit::One, Trit::Zero, Trit::MinusOne, Trit::Zero];
        let row1 = [Trit::MinusOne; 4];
        let mut packed = [0_u8; 2];
        pack_trits(&row0, &mut packed[..1]).expect("pack");
        pack_trits(&row1, &mut packed[1..]).expect("pack");
        let a = [1000_i16, 5000, 200, 7];
        let mut out = [0_i32; 2];
        ternary_matvec(&packed, &a, 2, &mut out).expect("matvec");
        assert_eq!(out, [1000 - 200, -(1000 + 5000 + 200 + 7)]);
    }

    #[test]
    fn matvec_rejects_bad_input() {
        let mut out = [0_i32; 1];
        let mut packed = [0_u8; 1];
        // n % 4 != 0.
        assert_eq!(
            ternary_matvec(&packed, &[1_i16, 2, 3], 1, &mut out),
            Err(BridgeError::BadLength)
        );
        // packed too short for rows=2.
        assert_eq!(
            ternary_matvec(&packed, &[1_i16, 2, 3, 4], 2, &mut out),
            Err(BridgeError::TooShort)
        );
        // out too short for rows=2.
        pack_trits(&[Trit::One; 4], &mut packed).expect("pack");
        assert_eq!(
            ternary_matvec(&packed, &[1_i16, 2, 3, 4], 2, &mut out),
            Err(BridgeError::TooShort)
        );
    }

    #[test]
    fn matvec_refuses_a_row_wider_than_65_535() {
        // Code 0 is −1, so every lane adds −1 × i16::MIN = +32,768: 65,532
        // lanes sum to 2,147,352,576, inside i32; 65,536 would reach 2^31.
        let packed = vec![0x00_u8; 65_536 / 4];
        let mut out = [0_i32; 1];
        assert_eq!(
            ternary_matvec(&packed, &vec![i16::MIN; 65_536], 1, &mut out),
            Err(BridgeError::RowTooWide)
        );
        assert_eq!(
            ternary_matvec(&packed, &vec![i16::MIN; 65_532], 1, &mut out),
            Ok(())
        );
        assert_eq!(out, [2_147_352_576]);
    }

    // ----- Properties: matvec vs an unpacked scalar reference -----

    proptest! {
        /// For any packed weights and activations, ternary_matvec equals a
        /// naive Trit×i16 scalar reference — exact integer equality.
        #[test]
        fn prop_matvec_matches_scalar_reference(
            n4 in 1_usize..=16,        // row width in bytes (4·n4 trits)
            rows in 1_usize..=6,
            seed in any::<u64>(),
        ) {
            let n = n4 * 4;
            // xorshift64 trit generator.
            let mut x = seed | 1;
            let mut next_trit = || {
                x ^= x << 13; x ^= x >> 7; x ^= x << 17;
                match x % 3 { 0 => Trit::MinusOne, 1 => Trit::Zero, _ => Trit::One }
            };
            let trits: Vec<Vec<Trit>> =
                (0..rows).map(|_| (0..n).map(|_| next_trit()).collect()).collect();
            let acts: Vec<i16> = (0..n).map(|_| next_trit() as i16 * 10_000).collect();

            let mut packed = vec![0_u8; rows * n4];
            for (r, row) in trits.iter().enumerate() {
                pack_trits(row, &mut packed[r * n4..(r + 1) * n4]).unwrap();
            }
            let mut out = vec![0_i32; rows];
            ternary_matvec(&packed, &acts, rows, &mut out).unwrap();

            for (r, row) in trits.iter().enumerate() {
                let reference: i32 = row
                    .iter()
                    .zip(&acts)
                    .map(|(&t, &a)| i32::from(t.to_weight(1)) * i32::from(a))
                    .sum();
                prop_assert_eq!(out[r], reference, "row {}", r);
            }
        }

        /// absmax output: sign-preserving, |out| ≤ 32767, and the max
        /// magnitude element attains ±32767 exactly.
        #[test]
        fn prop_absmax_bounds_and_attainment(
            vals in prop::collection::vec(-3000i16..=3000, 1..=40),
        ) {
            let mut out = vec![0_i16; vals.len()];
            let scale = absmax_normalize_q15(&vals, &mut out).unwrap();
            let max_abs = vals.iter().map(|v| v.unsigned_abs()).max().unwrap();
            prop_assert_eq!(scale, max_abs);
            for (v, &o) in vals.iter().zip(out.iter()) {
                // Q15 by construction: the output can never be i16::MIN
                // (|out| ≤ 32767 — the clamp is unreachable for in-range math).
                prop_assert!(o != i16::MIN, "{o} escaped Q15");
                if *v == 0 { prop_assert_eq!(o, 0); }
                if *v > 0 { prop_assert!(o >= 0); }
                if *v < 0 { prop_assert!(o <= 0); }
            }
            if max_abs > 0 {
                prop_assert!(out.iter().any(|&o| o.abs() == 32_767));
            }
        }

        /// pack → unpack round-trips every element.
        #[test]
        fn prop_pack_unpack_round_trip(
            n4 in 1_usize..=32,
            seed in any::<u64>(),
        ) {
            let n = n4 * 4;
            let mut x = seed | 1;
            let trits: Vec<Trit> = (0..n).map(|_| {
                x ^= x << 13; x ^= x >> 7; x ^= x << 17;
                match x % 3 { 0 => Trit::MinusOne, 1 => Trit::Zero, _ => Trit::One }
            }).collect();
            let mut packed = vec![0_u8; n4];
            pack_trits(&trits, &mut packed).unwrap();
            for (i, &t) in trits.iter().enumerate() {
                prop_assert_eq!(unpack_trit(&packed, i), Ok(t));
            }
        }
    }

    // ----- ISA round 70: tests for the kernel.rs survivors of a mutation
    // pass at 645afa8. Tests only: no behavior moves, no verdict of the
    // closed chapter is read. Each run green at 645afa8 and red under the
    // survivors it answers. -----

    /// `pack_trits` writes the packing whatever `out` held: from a buffer
    /// of all ones it gives what it gives from a zeroed one.
    #[test]
    fn pack_overwrites_what_out_held() {
        let trits = [Trit::One, Trit::MinusOne, Trit::Zero, Trit::Zero];
        let mut zeroed = [0_u8; 1];
        let mut stale = [0xFF_u8; 1];
        assert_eq!(pack_trits(&trits, &mut zeroed), Ok(1));
        assert_eq!(pack_trits(&trits, &mut stale), Ok(1));
        assert_eq!(stale, zeroed);
        assert_eq!(stale, [0x52]);
    }

    /// An empty vector is all zero too: it normalizes to nothing and
    /// returns 0, as the doc says an all-zero vector does.
    #[test]
    fn absmax_of_an_empty_vector_is_0() {
        assert_eq!(absmax_normalize_q15(&[], &mut []), Ok(0));
    }

    /// `TooShort` for each buffer alone: weights one row short with `out`
    /// long enough, and `out` one row short with the weights long enough.
    #[test]
    fn matvec_refuses_each_short_buffer_alone() {
        let a8 = [1_i16; 8];
        let mut out = [0_i32; 2];
        assert_eq!(
            ternary_matvec(&[0x55; 3], &a8, 2, &mut out),
            Err(BridgeError::TooShort),
            "2 rows of 8 need 4 bytes"
        );
        let a4 = [1_i16; 4];
        let mut one = [0_i32; 1];
        assert_eq!(
            ternary_matvec(&[0x55; 2], &a4, 2, &mut one),
            Err(BridgeError::TooShort),
            "2 rows need 2 accumulators"
        );
    }

    /// `out` receives `rows` accumulators; a longer `out` keeps its tail.
    #[test]
    fn matvec_writes_rows_into_a_longer_out() {
        let mut packed = [0_u8; 1];
        pack_trits(&[Trit::One; 4], &mut packed).expect("pack");
        let mut out = [7_i32; 3];
        assert_eq!(ternary_matvec(&packed, &[1, 2, 3, 4], 1, &mut out), Ok(()));
        assert_eq!(out, [10, 7, 7]);
    }
}