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
// SPDX-FileCopyrightText: 2026 philo-the-dendron
// SPDX-License-Identifier: AGPL-3.0-or-later
//! NIR assembly gate (slice 2 / R18) — the GENERAL four-kind graph
//! assembly over the REFERENCE-emitted fixtures, in the family style
//! of `nir_format_gate`: test vectors derived from the pinned
//! reference implementation's own emissions, never from our
//! re-implementation of ourselves.
//!
//! Reference: `neuromorphs/NIR` @ 7883c3c85f1be27ed113ccc9e8d6ab47ab541df4
//! (BSD-3; clone at `nir-ref/`, gitignored; fixtures regenerated by
//! `tools/gen_nir_fixtures.py` — all graphs constructed with explicit
//! Input/Output nodes, every emission self-asserting its node/edge
//! set against the infer_types auto-wire trap).
//!
//! Gates:
//! 1. the branch graph assembles and EVERY population fires on a
//!    seeded drive — first-spike step + per-population counts pinned
//!    (deterministic: noise=0, integer math);
//! 2. the merge graph: summed fan-in fires where a single branch
//!    stalls (the `transmission_pulses_sum` property, encoder
//!    edition);
//! 3. the recurrent graph: an edge pulse demonstrably moves a
//!    postsynaptic neuron — exactly +10 centi-quanta, one step after
//!    the presynaptic spike (the D1 EDGE_PULSE_QUANTA contract);
//! 4. Linear→Linear fusion is the ONCE-quantized f64 product
//!    (W₂·W₁ composed at the setup seam, quantize_linear seam);
//! 5. the loud-rejections table: every named error, one negative
//!    fixture each — including Input→LIF direct drive and the
//!    mV-on-recurrent rejection with its copy-pasteable remedy;
//! 6. the frozen CHAIN fixtures re-run UNCHANGED through both
//!    builders: 9 spikes / 100 steps first at step 6 (the banked
//!    pin), the general builder's raster bit-identical.
//!
//! Honest-claim language (the language of record): structure,
//! per-edge type shapes, and quantization records are exact w.r.t.
//! the pinned document; dynamics are named substrate conventions
//! (EDGE_PULSE_QUANTA = 200, synaptic divisor 10, voltage grid,
//! one-step synaptic delay, frozen plasticity) pinned by exact-value
//! tests; the reference defines no execution semantics at this sha —
//! no numeric-parity claim is made or implied.
//!
//! Exits non-zero on any gate failure. No models, no network — the
//! fixtures are embedded.

use gresil::nir::{
    nir_export, LinearFusedRecord, NirAssemblyReport, NirError, NirGraphEncoder, Thousandths,
    EDGE_PULSE_QUANTA,
};
use gresil::{NirImport, NirImportOptions, SpikingNeuralNetwork, VoltageResolution};

const CHAIN: &[u8] = include_bytes!("../tests/nir_fixtures/chain.json");
const BRANCH: &[u8] = include_bytes!("../tests/nir_fixtures/branch.json");
const MERGE: &[u8] = include_bytes!("../tests/nir_fixtures/merge.json");
const RECURRENT: &[u8] = include_bytes!("../tests/nir_fixtures/recurrent.json");

fn fail(msg: &str) -> ! {
    eprintln!("NIR ASSEMBLY GATE: FAIL — {msg}");
    std::process::exit(1);
}

fn centi() -> NirImportOptions {
    NirImportOptions::new(1_000, VoltageResolution::CentiMillivolt)
}

/// (first-spike step, count) per neuron over a driven window.
fn raster(
    net: &mut SpikingNeuralNetwork,
    enc: &NirGraphEncoder,
    drive: &[&[Thousandths]],
    steps: usize,
) -> Vec<(usize, usize)> {
    let mut out = vec![(usize::MAX, 0usize); net.neurons().len()];
    for t in 0..steps {
        for s in net
            .step(&enc.encode(drive))
            .unwrap_or_else(|e| fail(&e.to_string()))
        {
            let e = &mut out[s.neuron_id as usize];
            e.0 = e.0.min(t);
            e.1 += 1;
        }
    }
    out
}

fn print_report(rep: &NirAssemblyReport<'_>) {
    println!(
        "report  : {} neurons · {} synapses · {} inputs · {} drive Linears · {} stages",
        rep.neurons, rep.synapses, rep.inputs, rep.drive_linears, rep.stages
    );
    for LinearFusedRecord { chain, scales, .. } in &rep.fused {
        println!("fused   : {} (scales {:e})", chain.join("·"), scales[0]);
    }
    for n in &rep.undriven {
        println!("undriven: {n} (assembles silent — documented, never silently)");
    }
    if rep.multi_linear_gain {
        println!(
            "quant   : D6 note — >1 drive Linear; per-tensor absmax scales absorb branch gain"
        );
    }
    if !rep.plasticity_frozen {
        fail("plasticity must be frozen at assembly");
    }
}

fn main() {
    println!("=== NIR assembly gate — general four-kind graphs, reference-emitted vectors ===");
    println!("ref     : neuromorphs/NIR @ {}", gresil::nir::NIR_REF_SHA);
    println!("contract: EDGE_PULSE_QUANTA = {EDGE_PULSE_QUANTA} (20 pA pulse @ divisor 10)");
    println!();

    // ---- gate 1: branch — every population fires, pins exact -------
    let g = NirImport::from_json(
        BRANCH,
        NirImportOptions::new(1_000, VoltageResolution::Millivolt),
    )
    .unwrap_or_else(|e| fail(&e.to_string()));
    let (mut net, enc, rep) = g.build_network().unwrap_or_else(|e| fail(&e.to_string()));
    print_report(&rep);
    let pins = raster(&mut net, &enc, &[&[6_000, 0, 0].map(Thousandths)], 100);
    println!(
        "pins    : first-spike per neuron {:?} · counts {:?}",
        pins.iter().map(|p| p.0).collect::<Vec<_>>(),
        pins.iter().map(|p| p.1).collect::<Vec<_>>()
    );
    if pins.iter().any(|p| p.0 == usize::MAX) {
        fail("every population must fire on the seeded drive");
    }
    // THE deterministic pins (noise 0, integer math; hand-verified:
    // n0/n3 ct=98, V_ss=+28 -> g<=83 at step 3; n1 1-quanta/step crawl
    // 49->34 -> step 14; n2 g/10 decay -> -48 >= -50 at step 1)
    let firsts: Vec<usize> = pins.iter().map(|p| p.0).collect::<Vec<_>>();
    if firsts != vec![3, 14, 1, 3] {
        fail(&format!(
            "branch first-spike steps must be [3, 14, 1, 3], got {firsts:?}"
        ));
    }
    println!("gate 1  : PASS — all 4 neurons fire; first-spike steps pinned [3, 14, 1, 3]");

    // ---- gate 2: merge — summed fan-in fires, single stalls --------
    let g = NirImport::from_json(MERGE, centi()).unwrap_or_else(|e| fail(&e.to_string()));
    let (mut net, enc, rep) = g.build_network().unwrap_or_else(|e| fail(&e.to_string()));
    if !rep.multi_linear_gain {
        fail("merge graph must carry the D6 note");
    }
    let single = raster(&mut net, &enc, &[&[Thousandths(1_000); 2], &[]], 200);
    if single[0].1 != 0 {
        fail("a single 81 pA branch must stall below the climb");
    }
    if single[1].1 == 0 {
        fail("the 327 pA control row must fire — the encoder is live");
    }
    let g2 = NirImport::from_json(MERGE, centi()).unwrap();
    let (mut net2, enc2, _) = g2.build_network().unwrap();
    let one = [Thousandths(1_000); 2];
    let both = raster(&mut net2, &enc2, &[&one, &one], 100);
    if both[0].0 != 52 {
        fail(&format!(
            "summed 162 pA first spike must be step 52 (g: 1620->116 by g/20), got {}",
            both[0].0
        ));
    }
    println!(
        "gate 2  : PASS — single stalls (0/200), summed fires: neuron 0 first at step {}",
        both[0].0
    );

    // ---- gate 3: recurrent — the D1 pulse assert -------------------
    let g = NirImport::from_json(RECURRENT, centi()).unwrap_or_else(|e| fail(&e.to_string()));
    let (mut net, enc, rep) = g.build_network().unwrap_or_else(|e| fail(&e.to_string()));
    if rep.synapses != 4 {
        fail("recurrent fixture wires 4 synapses (a<->b, 2 neurons each)");
    }
    let mut moved_at: Option<usize> = None;
    for t in 0..80 {
        let fired_a0 = net
            .step(&enc.encode(&[&[1_000, 0].map(Thousandths)]))
            .unwrap()
            .iter()
            .any(|s| s.neuron_id == 0);
        if fired_a0 && moved_at.is_none() {
            if net.neurons()[2].membrane_potential() != -7_000 {
                fail("b0 unmoved on the spike step — the one-step delay is the contract");
            }
            moved_at = Some(t);
        } else if moved_at.is_some_and(|m| t == m + 1)
            && net.neurons()[2].membrane_potential() != -6_990
        {
            fail("b0 must sit at exactly -6990 one step after a0's spike (+10 quanta)");
        }
    }
    if moved_at.is_none() {
        fail("a0 must fire within 80 steps");
    }
    if net.neurons()[3].membrane_potential() != -7_000 {
        fail("b1 unmoved — a1 never fires (identity element mapping)");
    }
    if !net
        .synapses()
        .iter()
        .all(|s| s.weight() == EDGE_PULSE_QUANTA)
    {
        fail("edge quanta frozen (plasticity off)");
    }
    println!(
        "gate 3  : PASS — pulse moves b0 exactly +10 quanta one step after a0 fires (t={})",
        moved_at.unwrap_or(usize::MAX)
    );

    // ---- gate 4: fusion exactness through the seam -----------------
    let g = NirImport::from_json(
        BRANCH,
        NirImportOptions::new(1_000, VoltageResolution::Millivolt),
    )
    .unwrap();
    let (_, enc, rep) = g.build_network().unwrap();
    if rep.fused.len() != 1 || rep.fused[0].chain != vec!["l1", "l2"] {
        fail("the l1·l2 chain must fuse exactly once, recorded");
    }
    // f64 reference: the fixture's own source tensors, composed then
    // quantized ONCE through the same pub seam
    let w1 = [[0.5f64, -1.0, 0.25], [-0.25, 1.0, 0.5]];
    let w2 = [[1.0f64, 0.0], [0.0, -0.5]];
    let mut prod = [[0f64; 3]; 2];
    for r in 0..2 {
        for k in 0..3 {
            prod[r][k] = w2[r][0] * w1[0][k] + w2[r][1] * w1[1][k];
        }
    }
    let flat: Vec<f64> = prod.iter().flat_map(|r| r.iter().copied()).collect();
    let mut expect = vec![0i16; 6];
    gresil::nir::quantize_linear(&flat, 2, 3, &mut expect, 0).expect("seam quantizes");
    let fused_found =
        (0..enc.stage_count()).any(|i| enc.stage_quanta(i) == Some(expect.as_slice()));
    if !fused_found {
        fail("the fused stage must BE the once-quantized f64 product");
    }
    println!("gate 4  : PASS — W2·W1 composed in f64, quantized ONCE: {expect:?}");

    // ---- gate 5: the loud-rejections table -------------------------
    // (label, fixture, import opts, error check) — one row per named
    // rejection; the tuple shape IS the table
    #[allow(clippy::type_complexity)]
    let table: Vec<(&str, &[u8], NirImportOptions, fn(&NirError) -> bool)> = vec![
        (
            "pass-through",
            include_bytes!("../tests/nir_fixtures/neg_asm_passthrough.json"),
            centi(),
            |e| {
                matches!(
                    e,
                    NirError::UnsupportedTopology("Input->Output pass-through")
                )
            },
        ),
        (
            "direct drive (Input->LIF)",
            include_bytes!("../tests/nir_fixtures/neg_asm_direct_drive.json"),
            centi(),
            |e| {
                matches!(
                    e,
                    NirError::UnsupportedTopology(
                        "direct drive (Input->LIF) deferred — drive convention not yet named"
                    )
                )
            },
        ),
        (
            "readout (LIF->Linear->Output)",
            include_bytes!("../tests/nir_fixtures/neg_asm_lif_to_linear.json"),
            centi(),
            |e| {
                matches!(e, NirError::UnsupportedTopology(
                "readout (LIF->Linear->Output) deferred — spike-count readout convention not yet named"))
            },
        ),
        (
            "no LIF (encoder-only)",
            include_bytes!("../tests/nir_fixtures/neg_asm_no_lif.json"),
            centi(),
            |e| {
                matches!(
                    e,
                    NirError::UnsupportedTopology(
                        "graph without LIF: nothing to fire — encoder-only assembly deferred"
                    )
                )
            },
        ),
        (
            "self-loop",
            include_bytes!("../tests/nir_fixtures/neg_asm_self_loop.json"),
            centi(),
            |e| {
                matches!(
                    e,
                    NirError::UnsupportedTopology(
                        "LIF self-loop — the substrate forbids self-synapse"
                    )
                )
            },
        ),
        (
            "empty graph",
            include_bytes!("../tests/nir_fixtures/neg_asm_empty.json"),
            centi(),
            |e| matches!(e, NirError::UnsupportedTopology("empty graph")),
        ),
        (
            "shape mismatch",
            include_bytes!("../tests/nir_fixtures/neg_asm_shape_mismatch.json"),
            centi(),
            |e| {
                matches!(
                    e,
                    NirError::EdgeShapeMismatch { src, dst, .. }
                        if src == "input" && dst == "l1"
                )
            },
        ),
        (
            "cycle without Output",
            include_bytes!("../tests/nir_fixtures/neg_asm_cycle_no_output.json"),
            centi(),
            |e| matches!(e, NirError::UnsupportedTopology("no Output node")),
        ),
        (
            "no Input",
            include_bytes!("../tests/nir_fixtures/neg_asm_no_input.json"),
            centi(),
            |e| matches!(e, NirError::UnsupportedTopology("no Input node")),
        ),
        (
            "recurrent on mV",
            RECURRENT,
            NirImportOptions::new(1_000, VoltageResolution::Millivolt),
            |e| {
                matches!(e, NirError::UnsupportedTopology(m)
                if m.contains("CentiMillivolt") && m.contains("~200 pA dead zone"))
            },
        ),
    ];
    for (label, doc, opts, check) in &table {
        let g = NirImport::from_json(doc, *opts)
            .unwrap_or_else(|e| fail(&format!("{label}: must import: {e}")));
        let err = g
            .build_network()
            .err()
            .unwrap_or_else(|| fail(&format!("{label}: expected a named rejection")));
        if !check(&err) {
            fail(&format!("{label}: wrong error — {err}"));
        }
    }
    println!(
        "gate 5  : PASS — {} named rejections, one negative fixture each",
        table.len()
    );

    // ---- gate 6: frozen chain re-runs UNCHANGED through both -------
    let opts = NirImportOptions::new(1_000, VoltageResolution::Millivolt);
    let g = NirImport::from_json(CHAIN, opts).unwrap_or_else(|e| fail(&e.to_string()));
    let (mut net1, enc1) = g
        .build_chain_network()
        .unwrap_or_else(|e| fail(&e.to_string()));
    let (mut net2, enc2, _) = g.build_network().unwrap_or_else(|e| fail(&e.to_string()));
    let mut spikes1 = 0usize;
    let mut first1 = usize::MAX;
    let mut raster1 = Vec::new();
    let mut raster2 = Vec::new();
    for t in 0..100 {
        let f1 = net1.step(&enc1.encode(&[4, 0, 0])).unwrap();
        if !f1.is_empty() && first1 == usize::MAX {
            first1 = t;
        }
        spikes1 += f1.len();
        raster1.extend(f1.iter().map(|s| s.neuron_id));
        raster2.extend(
            net2.step(&enc2.encode(&[&[4_000, 0, 0].map(Thousandths)]))
                .unwrap()
                .iter()
                .map(|s| s.neuron_id),
        );
    }
    if (spikes1, first1) != (9, 6) {
        fail(&format!(
            "frozen chain pins must hold: 9 spikes/100 first at step 6, got ({spikes1}, {first1})"
        ));
    }
    if raster1 != raster2 {
        fail("the general builder's raster must be bit-identical to the chain builder's");
    }
    let mut out = vec![0u8; 4096];
    let n = nir_export(&g.nodes, &g.edges, &g.weights, &g.lifs, opts, &mut out).unwrap();
    if n != 826 {
        fail(&format!("chain export must stay 826 B (banked), got {n}"));
    }
    println!(
        "gate 6  : PASS — frozen pins byte-identical: 9 spikes/100 @ step 6, export {n} B, \
general-builder raster bit-identical"
    );

    println!();
    println!("NIR ASSEMBLY GATE: PASS — 6/6 gates on reference-emitted general graphs");
}