cortex-hybrid 0.2.0

Backend-neutral ANN stage layer and deterministic Vec reference backend for hybrid ANN/SNN systems.
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
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Backend-neutral SNN execution contract for ANN/SNN hybrid stages.
//!
//! Cortex stays hybrid-capable without embedding a bespoke SNN runtime inside
//! `MoeRouter`. Neuron dynamics live in focused reusable crates behind the
//! [`SnnBackend`] trait; this module defines the ANN↔SNN boundary:
//!
//! * **Encode:** [`SnnEncoder`] maps ANN-side signals (e.g. MoE gate scores or
//!   hidden activations) into backend stimulus channels.
//! * **Step:** [`SnnBackend::step`] / [`SnnBackend::step_frozen`] advance the
//!   backend one tick. `step_frozen` is the held-out evaluation path: runtime
//!   outputs are produced without retaining plasticity changes.
//! * **Decode:** [`SnnDecoder`] maps [`SnnStepOutput`] back into per-channel
//!   f32 readouts ANN stages can consume.
//! * **Semantics:** [`SnnBackend::reset`] starts a new epoch and
//!   [`SnnBackend::capabilities`] reports what the backend supports so
//!   orchestrators such as `hybrid-fusion` can pick execution paths.
//!
//! Adapters are optional and feature-gated. Enable `neuromod` for
//! `NeuromodNetwork`, the primary integration candidate backed by the
//! published `neuromod` crate's `SpikingNetwork`.
//!
//! [`SpikingMoeRouter`] composes a [`MoeRouter`] (gate scores + deterministic
//! top-k) with an `SnnBackend`, replacing the removed embedded `SpikingSim`
//! routing mode.
//!
//! # Twin contract in hybrid-fusion
//!
//! `hybrid-fusion` owns a parallel step contract for its orchestrator role
//! (`SpikingNetwork`, `SpikeEncoder` / `SpikeDecoder`, `SpikingExpertRouter`,
//! `NeuromodSnn`). cortex-hybrid keeps this one because the crate is meant to
//! handle both ANN and SNN (decision RM-2206 / RM-2360; the plan to fold this
//! surface into hybrid-fusion was abandoned unmerged). The two trait sets are
//! held in sync by the mapping in `docs/snn-contract-mapping.md` (hybrid-fusion
//! ADR 0002) and by the cross-crate parity tests in hybrid-fusion's
//! `smoke/cortex-neuromod` package, which run the same seeded inputs through
//! both routers and both neuromod adapters in CI and assert every intentional
//! difference.

use crate::error::{CortexError, Result};
use crate::moe::MoeRouter;

#[cfg(feature = "neuromod")]
mod neuromod_adapter;

#[cfg(feature = "neuromod")]
pub use neuromod_adapter::NeuromodNetwork;

#[cfg(feature = "axon-encoder")]
mod axon_adapter;

#[cfg(feature = "axon-encoder")]
pub use axon_adapter::AxonEncoder;

/// Capabilities a backend advertises to orchestrators.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnnCapabilities {
    /// Human-readable backend identity, e.g. `"neuromod::SpikingNetwork"`.
    pub backend_name: &'static str,
    /// Held-out evaluation path that preserves plasticity-controlled state.
    pub frozen_evaluation: bool,
    /// Normal stepping retains plasticity changes (eligibility traces, weights).
    pub plasticity: bool,
    /// Backend accepts caller-injected RNG for deterministic replay.
    pub caller_rng: bool,
    /// Backend consumes neuromodulator state (dopamine, ACh, …) per step.
    pub neuromodulation: bool,
}

/// One backend tick of spiking activity.
#[derive(Debug, Clone, Default)]
pub struct SnnStepOutput {
    /// Indices of channels/neurons that spiked this tick, in backend order.
    /// A channel may appear at most once per tick.
    pub spikes: Vec<usize>,
}

/// Execution contract an SNN crate adapter implements.
///
/// Implementations must be failure-atomic: a rejected input leaves backend
/// state unmodified, so callers can fail closed on NaN/length errors before a
/// tick is consumed.
pub trait SnnBackend {
    /// Stimulus width `step` expects — and the spike-index space of
    /// [`SnnStepOutput::spikes`] (`0..channels`). Backends whose output
    /// width differs must map or reject at construction.
    fn channels(&self) -> usize;

    /// Advance one tick with learning-enabled dynamics.
    fn step(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput>;

    /// Advance one tick for held-out evaluation without retaining
    /// plasticity-controlled state. Backends without a frozen path may
    /// delegate to [`Self::step`] and report `frozen_evaluation = false`.
    fn step_frozen(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput>;

    /// Reset runtime state (membranes, spike times, tick counter) while
    /// keeping learned weights and configured parameters.
    fn reset(&mut self);

    /// Report what this backend supports.
    fn capabilities(&self) -> SnnCapabilities;
}

/// ANN → SNN boundary: map an ANN-side f32 signal into backend stimuli.
///
/// `&mut self` because real encoders are stateful (phase accumulators,
/// streaming windows); one `encode` call is one backend tick. Encoder state
/// advances when `encode` is called — it is NOT failure-atomic with respect
/// to later forward errors; callers needing a clean epoch reset the encoder.
pub trait SnnEncoder {
    /// Produce a stimulus vector of exactly `channels` length, or an error
    /// when the encoding cannot be represented in `channels` (e.g. spikes
    /// outside the channel space).
    fn encode(&mut self, ann_signal: &[f32], channels: usize) -> Result<Vec<f32>>;

    /// Restore the encoder's streaming state (phase/window) to a clean epoch.
    /// Called by [`SpikingMoeRouter::reset`] alongside the backend reset.
    /// Stateless encoders use the no-op default.
    fn reset(&mut self) {}
}

/// SNN → ANN boundary: map one step of spikes into per-channel f32 readouts.
pub trait SnnDecoder {
    /// Produce a readout vector of exactly `channels` length, or an error
    /// when `channels` exceeds [`MAX_SNN_CHANNELS`] and the readout cannot
    /// be allocated safely.
    fn decode(&self, output: &SnnStepOutput, channels: usize) -> Result<Vec<f32>>;
}

/// Linear encoder: scales each input by `gain` and tiles it across the
/// backend's channel count. Expert *i* occupies channel `i % len`, so with
/// `channels >= len` each signal element owns a contiguous prefix of channels.
#[derive(Debug, Clone, Copy)]
pub struct RateEncoder {
    /// Multiplier applied to every input element.
    pub gain: f32,
}

impl Default for RateEncoder {
    fn default() -> Self {
        Self { gain: 1.0 }
    }
}

impl SnnEncoder for RateEncoder {
    fn encode(&mut self, ann_signal: &[f32], channels: usize) -> Result<Vec<f32>> {
        check_snn_channels(channels)?;
        let mut stimulus = vec![0.0f32; channels];
        if ann_signal.is_empty() {
            return Ok(stimulus);
        }
        for (idx, slot) in stimulus.iter_mut().enumerate() {
            *slot = ann_signal[idx % ann_signal.len()] * self.gain;
        }
        Ok(stimulus)
    }
}

/// Per-channel spike-count readout: each channel's output is the number of
/// times it spiked in the tick (0 or 1 for index-style backends). Indices
/// outside `0..channels` are ignored here; `SpikingMoeRouter` validates the
/// spike list before decoding so such indices never reach this decoder.
#[derive(Debug, Clone, Copy, Default)]
pub struct SpikeCountDecoder;

impl SnnDecoder for SpikeCountDecoder {
    fn decode(&self, output: &SnnStepOutput, channels: usize) -> Result<Vec<f32>> {
        check_snn_channels(channels)?;
        let mut counts = vec![0.0f32; channels];
        for &idx in &output.spikes {
            if idx < channels {
                counts[idx] += 1.0;
            }
        }
        Ok(counts)
    }
}

/// Spiking MoE routing through an external SNN backend.
///
/// Replaces the removed embedded `RoutingMode::SpikingSim`: gate scores are
/// computed by [`MoeRouter`], encoded into backend stimuli by `E`, stepped by
/// `B`, and decoded by `D`.
///
/// # Routing contract
///
/// * **Scores:** `gate + spike_boost * activity`, where `activity` is the
///   decoder readout for the expert's channel (≥ 0) and `spike_boost` is
///   [`DEFAULT_SPIKE_BOOST`] unless changed with [`Self::with_spike_boost`].
///   The boost is additive so it is monotone in spike activity for *any*
///   logit sign: a spike can only promote its expert, never demote it (the
///   earlier multiplicative `gate * (1 + spikes)` pushed negative logits
///   further down the ranking). Selection is `route_top_k` over those scores;
///   `expert_weights` is their softmax.
/// * **Hidden state:** `embedding * Σ_{selected} expert_weights[e] * a[e]`,
///   where `a[e] = activity[e] / max(activity)` lies in `[0, 1]`. The gain is
///   therefore bounded by the selected softmax mass (≤ 1), like
///   `MoeRouter::forward`, whatever the decoder's count scale. When none of
///   the selected experts is active (a silent tick, or spikes only on
///   unselected channels) `a[e] = 1` for every selected expert, so the
///   output degrades to the dense selected mass instead of a zero hidden
///   state.
///
/// # Validation
///
/// NaN gate scores, NaN encoder output, and an encoder stimulus whose length
/// is not the backend channel count ([`CortexError::SnnStimulusLength`]) are
/// rejected before the backend steps, preserving the fail-closed ordering of
/// the old embedded path.
/// After the step, the backend's spike list is checked against its contract
/// — every index in `0..channels` ([`CortexError::SnnSpikeOutOfRange`]) and
/// each channel at most once ([`CortexError::SnnDuplicateSpike`]) — and the
/// decoder readout must have exactly `channels` entries
/// ([`CortexError::SnnReadoutLength`]), be NaN-free ([`CortexError::SnnNan`])
/// and be finite and non-negative ([`CortexError::SnnInvalidReadout`]). Errors raised after the step consume
/// the tick — `reset()` restores a clean epoch.
///
/// `B` is generic (not `dyn`) so callers keep concrete backend types for
/// checkpointing and backend-specific tuning.
pub struct SpikingMoeRouter<B, E = RateEncoder, D = SpikeCountDecoder>
where
    B: SnnBackend,
    E: SnnEncoder,
    D: SnnDecoder,
{
    router: MoeRouter,
    backend: B,
    encoder: E,
    decoder: D,
    spike_boost: f32,
}

/// Default additive routing boost per unit of decoded spike activity: one
/// spike on a channel adds `1.0` to its expert's gate logit.
pub const DEFAULT_SPIKE_BOOST: f32 = 1.0;

/// Largest channel count the SNN boundary accepts.
///
/// `channels` is backend-controlled, and the encoder, decoder, spike
/// validation and `SpikingMoeRouter` all allocate `channels`-sized buffers
/// per tick. Without a bound, a backend reporting `usize::MAX` is a
/// capacity-overflow panic or an allocator abort. 1 Mi channels keeps the
/// largest per-tick buffers at 4 MiB of `f32`.
pub const MAX_SNN_CHANNELS: usize = 1 << 20;

/// Reject a backend-reported channel count above [`MAX_SNN_CHANNELS`] before
/// any `channels`-sized buffer is allocated.
fn check_snn_channels(channels: usize) -> Result<()> {
    if channels > MAX_SNN_CHANNELS {
        return Err(CortexError::InvalidConfig(format!(
            "SNN channel count {channels} exceeds MAX_SNN_CHANNELS ({MAX_SNN_CHANNELS})"
        )));
    }
    Ok(())
}

/// Validate one backend tick against the [`SnnStepOutput`] contract.
fn validate_spikes(step_out: &SnnStepOutput, channels: usize) -> Result<()> {
    check_snn_channels(channels)?;
    let mut seen = vec![false; channels];
    for &channel in &step_out.spikes {
        if channel >= channels {
            return Err(CortexError::SnnSpikeOutOfRange { channel, channels });
        }
        if seen[channel] {
            return Err(CortexError::SnnDuplicateSpike { channel });
        }
        seen[channel] = true;
    }
    Ok(())
}

/// Validate a decoder readout: exactly `channels` entries, each finite and
/// non-negative. NaN keeps its dedicated variant.
fn validate_readout(decoded: &[f32], channels: usize) -> Result<()> {
    if decoded.len() != channels {
        return Err(CortexError::SnnReadoutLength {
            expected: channels,
            got: decoded.len(),
        });
    }
    for (channel, &value) in decoded.iter().enumerate() {
        if value.is_nan() {
            return Err(CortexError::SnnNan {
                stage: "decoder readout",
            });
        }
        if !value.is_finite() || value < 0.0 {
            return Err(CortexError::SnnInvalidReadout { channel, value });
        }
    }
    Ok(())
}

/// Validate the gate scores before they reach the encoder. NaN is rejected by
/// [`crate::moe::reject_nan_routing_scores`]; ±Inf gets its own variant,
/// because unlike plain `MoeRouter` it is not rankable here: backends such as
/// neuromod reject non-finite stimulus, and that would surface after the
/// encoder state had already advanced.
fn validate_gate_scores(gate_scores: &[f32]) -> Result<()> {
    if let Some((channel, &value)) = gate_scores
        .iter()
        .enumerate()
        .find(|(_, v)| v.is_infinite())
    {
        return Err(CortexError::SnnInvalidStimulus { channel, value });
    }
    Ok(())
}

/// Validate an encoder stimulus against the backend channel width it has to
/// fill: exactly `channels` entries, none NaN and none infinite. Encoders may
/// inject non-finite stimuli, so this runs before the backend consumes a tick
/// and the whole forward stays fail-closed.
fn validate_stimulus(stimulus: &[f32], channels: usize) -> Result<()> {
    if stimulus.len() != channels {
        return Err(CortexError::SnnStimulusLength {
            expected: channels,
            got: stimulus.len(),
        });
    }
    if stimulus.iter().any(|v| v.is_nan()) {
        return Err(CortexError::SnnNan {
            stage: "encoder stimulus",
        });
    }
    if let Some((channel, &value)) = stimulus.iter().enumerate().find(|(_, v)| v.is_infinite()) {
        return Err(CortexError::SnnInvalidStimulus { channel, value });
    }
    Ok(())
}

impl<B, E, D> SpikingMoeRouter<B, E, D>
where
    B: SnnBackend,
    E: SnnEncoder,
    D: SnnDecoder,
{
    /// Every expert must own a dedicated backend channel: expert *i* is
    /// encoded/decoded at channel *i*, so `channels < num_experts` would
    /// silently leave trailing experts permanently ANN-only.
    pub fn new(router: MoeRouter, backend: B, encoder: E, decoder: D) -> Result<Self> {
        check_snn_channels(backend.channels())?;
        if backend.channels() < router.num_experts() {
            return Err(CortexError::SnnChannelMismatch {
                experts: router.num_experts(),
                channels: backend.channels(),
            });
        }
        Ok(Self {
            router,
            backend,
            encoder,
            decoder,
            spike_boost: DEFAULT_SPIKE_BOOST,
        })
    }

    /// Set the additive routing boost per unit of decoded spike activity
    /// (default [`DEFAULT_SPIKE_BOOST`]). Must be finite and non-negative so
    /// the boost stays monotone; `0.0` makes routing purely ANN-driven while
    /// the backend still steps and shapes the hidden state. For a finite gate
    /// the score `gate + spike_boost * activity` saturates at `f32::MAX`
    /// instead of overflowing to `+Inf`; gate scores are finite (±Inf is rejected
    /// with `SnnInvalidStimulus`), so the boost never produces NaN.
    pub fn with_spike_boost(mut self, spike_boost: f32) -> Result<Self> {
        if !spike_boost.is_finite() || spike_boost < 0.0 {
            return Err(CortexError::InvalidConfig(format!(
                "spike_boost must be finite and >= 0, got {spike_boost}"
            )));
        }
        self.spike_boost = spike_boost;
        Ok(self)
    }

    /// Additive routing boost per unit of decoded spike activity.
    pub fn spike_boost(&self) -> f32 {
        self.spike_boost
    }

    /// Encode the gate scores into a validated backend stimulus.
    ///
    /// Every check runs before the backend ticks, so an invalid encoder
    /// output fails closed without consuming a step.
    fn encode_stimulus(&mut self, gate_scores: &[f32], num_experts: usize) -> Result<Vec<f32>> {
        // The one-channel-per-expert invariant is checked in `new`, but
        // `channels()` is re-read every tick (a backend may be resized through
        // `backend_mut`, and user backends need not be constant-width).
        // Re-check it before the tick so `decoded[expert_id]` below cannot
        // index past the readout, and fail closed without consuming a step.
        let channels = self.backend.channels();
        check_snn_channels(channels)?;
        if channels < num_experts {
            return Err(CortexError::SnnChannelMismatch {
                experts: num_experts,
                channels,
            });
        }
        let stimulus = self.encoder.encode(gate_scores, channels)?;
        validate_stimulus(&stimulus, channels)?;
        Ok(stimulus)
    }

    /// Shared forward path. `frozen` selects [`SnnBackend::step_frozen`].
    fn forward_impl(&mut self, embedding: &[f32], frozen: bool) -> Result<crate::moe::MoeOutput> {
        let gate_scores = self.router.gate_scores(embedding)?;
        // Fail closed before the encoder or backend consumes a tick.
        crate::moe::reject_nan_routing_scores(&gate_scores)?;
        validate_gate_scores(&gate_scores)?;
        let num_experts = self.router.num_experts();
        let stimulus = self.encode_stimulus(&gate_scores, num_experts)?;
        let step_out = if frozen {
            self.backend.step_frozen(&stimulus)?
        } else {
            self.backend.step(&stimulus)?
        };
        // Failures past this point have consumed a backend tick; callers that
        // need a clean epoch should `reset()` after such an error.
        //
        // `channels()` defines the spike-index space, so the post-step width
        // is the one spikes and the readout must be validated against. A
        // backend that shrank below the expert count during the step is
        // rejected here rather than indexed past below.
        let channels = self.backend.channels();
        check_snn_channels(channels)?;
        if channels < num_experts {
            return Err(CortexError::SnnChannelMismatch {
                experts: num_experts,
                channels,
            });
        }
        validate_spikes(&step_out, channels)?;
        let decoded = self.decoder.decode(&step_out, channels)?;
        validate_readout(&decoded, channels)?;

        // Additive boost: monotone in activity for any logit sign (issue #93).
        // Both factors are finite and >= 0, so the bonus is finite once its
        // product is capped; a finite gate plus that bonus is then saturated
        // at f32::MAX so it can never become +Inf (gates are finite here: ±Inf
        // is rejected above).
        let routing_scores: Vec<f32> = (0..num_experts)
            .map(|expert_id| {
                let gate = gate_scores[expert_id];
                let bonus = (self.spike_boost * decoded[expert_id]).min(f32::MAX);
                if gate.is_finite() {
                    (gate + bonus).min(f32::MAX)
                } else {
                    gate
                }
            })
            .collect();
        let (expert_weights, selected_experts) =
            crate::moe::route_top_k(&routing_scores, self.router.top_k())?;

        // Hidden gain = selected softmax mass weighted by activity normalised
        // to the tick's peak, so it stays within [0, 1] regardless of the
        // decoder's count scale. When no selected expert is active (silent
        // tick, or spikes only on unselected channels) the gain falls back to
        // the dense selected mass rather than collapsing to zero.
        let peak_activity = decoded[..num_experts]
            .iter()
            .copied()
            .fold(0.0f32, f32::max);
        let selected_active = selected_experts.iter().any(|&idx| decoded[idx] > 0.0);
        let spiking_mass: f32 = selected_experts
            .iter()
            .map(|&idx| {
                let activity = if selected_active {
                    decoded[idx] / peak_activity
                } else {
                    1.0
                };
                expert_weights[idx] * activity
            })
            .sum();
        let hidden: Vec<f32> = embedding.iter().map(|&v| v * spiking_mass).collect();

        Ok(crate::moe::MoeOutput {
            expert_weights,
            selected_experts,
            hidden,
        })
    }

    /// Learning-enabled forward: backend steps retain plasticity.
    pub fn forward(&mut self, embedding: &[f32]) -> Result<crate::moe::MoeOutput> {
        if embedding.len() != crate::types::EMBEDDING_DIM {
            return Err(CortexError::InputLengthMismatch {
                expected: crate::types::EMBEDDING_DIM,
                got: embedding.len(),
            });
        }
        self.forward_impl(embedding, false)
    }

    /// Held-out forward: backend runs its frozen evaluation path.
    pub fn forward_frozen(&mut self, embedding: &[f32]) -> Result<crate::moe::MoeOutput> {
        if embedding.len() != crate::types::EMBEDDING_DIM {
            return Err(CortexError::InputLengthMismatch {
                expected: crate::types::EMBEDDING_DIM,
                got: embedding.len(),
            });
        }
        self.forward_impl(embedding, true)
    }

    /// Reset the backend and encoder epochs; router (ANN) state is untouched.
    pub fn reset(&mut self) {
        self.encoder.reset();
        self.backend.reset();
    }

    /// Capabilities of the wrapped backend, for orchestrator reporting.
    pub fn capabilities(&self) -> SnnCapabilities {
        self.backend.capabilities()
    }

    pub fn router(&self) -> &MoeRouter {
        &self.router
    }

    pub fn backend(&self) -> &B {
        &self.backend
    }

    pub fn backend_mut(&mut self) -> &mut B {
        &mut self.backend
    }

    pub fn encoder(&self) -> &E {
        &self.encoder
    }

    /// Access the encoder (e.g. to reset its streaming state after an error).
    pub fn encoder_mut(&mut self) -> &mut E {
        &mut self.encoder
    }
}

#[cfg(test)]
mod tests;