feagi-npu-plasticity 0.0.13

FEAGI plasticity algorithms - STDP and memory formation
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
// Copyright 2025 Neuraville Inc.
// SPDX-License-Identifier: Apache-2.0

/*
 * Copyright 2025 Neuraville Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 */

//! STDP (Spike-Timing-Dependent Plasticity) computation
//!
//! Pure functions for computing synaptic weight changes based on spike timing.
//! RTOS-friendly with deterministic execution and no dynamic allocation in hot paths.

use feagi_npu_neural::types::*;
use std::collections::HashMap;

/// STDP configuration parameters
#[derive(Debug, Clone, Copy)]
pub struct STDPConfig {
    /// Number of timesteps to look back for spike history
    pub lookback_steps: u32,

    /// Pre-synaptic time constant (τ_pre)
    pub tau_pre: f32,

    /// Post-synaptic time constant (τ_post)
    pub tau_post: f32,

    /// Potentiation learning rate (A+)
    pub a_plus: f32,

    /// Depression learning rate (A-)
    pub a_minus: f32,

    /// Maximum spike pairs to consider per synapse
    pub max_pairs_per_synapse: usize,
}

impl Default for STDPConfig {
    fn default() -> Self {
        Self {
            lookback_steps: 20,
            tau_pre: 20.0,
            tau_post: 20.0,
            a_plus: 0.01,
            a_minus: 0.012,
            max_pairs_per_synapse: 8,
        }
    }
}

/// Compute activity-based STDP factors for synapses
///
/// This is a simplified Hebbian approximation that uses presence/absence
/// of spikes in the lookback window rather than precise timing.
pub fn compute_activity_factors(
    syn_source_ids: &[NeuronId],
    syn_target_ids: &[NeuronId],
    source_history: &[NeuronId],
    target_history: &[NeuronId],
) -> (Vec<f32>, Vec<f32>) {
    let count = syn_source_ids.len();
    if count == 0 {
        return (Vec::new(), Vec::new());
    }

    // Build fast lookup sets for pre and post activity
    let pre_active: std::collections::HashSet<u32> = source_history.iter().map(|n| n.0).collect();
    let post_active: std::collections::HashSet<u32> = target_history.iter().map(|n| n.0).collect();

    // Compute activity factors
    let mut pre_activity = Vec::with_capacity(count);
    let mut post_activity = Vec::with_capacity(count);

    for (src, tgt) in syn_source_ids.iter().zip(syn_target_ids.iter()) {
        let pre = if pre_active.contains(&src.0) {
            1.0
        } else {
            0.0
        };
        let post = if post_active.contains(&tgt.0) {
            1.0
        } else {
            0.0
        };
        pre_activity.push(pre);
        post_activity.push(post);
    }

    (pre_activity, post_activity)
}

/// Compute timing-based STDP factors for synapses
///
/// Uses exponential STDP rule:
/// - Δw = A+ * exp(-Δt/τ_pre) if pre before post (potentiation)
/// - Δw = -A- * exp(Δt/τ_post) if post before pre (depression)
pub fn compute_timing_factors(
    syn_source_ids: &[NeuronId],
    syn_target_ids: &[NeuronId],
    source_history: &[(u64, NeuronId)], // (timestep, neuron_id)
    target_history: &[(u64, NeuronId)], // (timestep, neuron_id)
    config: &STDPConfig,
) -> Vec<f32> {
    let count = syn_source_ids.len();
    if count == 0 {
        return Vec::new();
    }

    // Build last-spike maps (neuron_id -> timestep)
    let mut pre_last: HashMap<u32, u64> = HashMap::new();
    let mut post_last: HashMap<u32, u64> = HashMap::new();

    for &(ts, nid) in source_history.iter() {
        pre_last.entry(nid.0).or_insert(ts);
    }

    for &(ts, nid) in target_history.iter() {
        post_last.entry(nid.0).or_insert(ts);
    }

    // Compute timing factors
    let mut factors = vec![0.0f32; count];

    for (i, (src, tgt)) in syn_source_ids.iter().zip(syn_target_ids.iter()).enumerate() {
        if let (Some(&pre_ts), Some(&post_ts)) = (pre_last.get(&src.0), post_last.get(&tgt.0)) {
            // Compute time difference (positive if pre before post)
            let dt = post_ts as i64 - pre_ts as i64;

            if dt > 0 {
                // Pre fired before post -> potentiation
                let dt_f = dt as f32;
                factors[i] = config.a_plus * (-dt_f / config.tau_pre.max(1e-6)).exp();
            } else if dt < 0 {
                // Post fired before pre -> depression
                let dt_f = (-dt) as f32;
                factors[i] = -config.a_minus * (-dt_f / config.tau_post.max(1e-6)).exp();
            } else {
                // Same timestep -> strong potentiation
                factors[i] = config.a_plus;
            }
        }
    }

    factors
}

/// Group synapses by (source_area, target_area) pairs for batch processing
pub fn group_synapses_by_area_pairs(
    syn_source_ids: &[NeuronId],
    syn_target_ids: &[NeuronId],
    neuron_to_area: &HashMap<u32, u32>,
) -> HashMap<(u32, u32), Vec<usize>> {
    let count = syn_source_ids.len();
    let mut groups: HashMap<(u32, u32), Vec<usize>> = HashMap::new();

    for i in 0..count {
        let src = syn_source_ids[i].0;
        let tgt = syn_target_ids[i].0;

        if let (Some(&s_area), Some(&t_area)) = (neuron_to_area.get(&src), neuron_to_area.get(&tgt))
        {
            groups.entry((s_area, t_area)).or_default().push(i);
        }
    }

    groups
}

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

    #[test]
    fn test_stdp_config_default() {
        let config = STDPConfig::default();
        assert_eq!(config.lookback_steps, 20);
        assert_eq!(config.tau_pre, 20.0);
        assert_eq!(config.tau_post, 20.0);
        assert_eq!(config.a_plus, 0.01);
        assert_eq!(config.a_minus, 0.012);
    }

    #[test]
    fn test_stdp_config_custom() {
        let config = STDPConfig {
            lookback_steps: 50,
            tau_pre: 30.0,
            tau_post: 25.0,
            a_plus: 0.02,
            a_minus: 0.015,
            max_pairs_per_synapse: 10,
        };

        assert_eq!(config.lookback_steps, 50);
        assert_eq!(config.tau_pre, 30.0);
    }

    #[test]
    fn test_activity_factors_empty() {
        let sources = vec![];
        let targets = vec![];
        let source_history = vec![];
        let target_history = vec![];

        let (pre, post) =
            compute_activity_factors(&sources, &targets, &source_history, &target_history);

        assert_eq!(pre.len(), 0);
        assert_eq!(post.len(), 0);
    }

    #[test]
    fn test_activity_factors() {
        let sources = vec![NeuronId(1), NeuronId(2)];
        let targets = vec![NeuronId(10), NeuronId(11)];
        let source_history = vec![NeuronId(1)]; // Only neuron 1 fired
        let target_history = vec![NeuronId(10)]; // Only neuron 10 fired

        let (pre, post) =
            compute_activity_factors(&sources, &targets, &source_history, &target_history);

        assert_eq!(pre[0], 1.0); // Neuron 1 was active
        assert_eq!(pre[1], 0.0); // Neuron 2 was not active
        assert_eq!(post[0], 1.0); // Neuron 10 was active
        assert_eq!(post[1], 0.0); // Neuron 11 was not active
    }

    #[test]
    fn test_activity_factors_all_active() {
        let sources = vec![NeuronId(1), NeuronId(2), NeuronId(3)];
        let targets = vec![NeuronId(10), NeuronId(11), NeuronId(12)];
        let source_history = vec![NeuronId(1), NeuronId(2), NeuronId(3)];
        let target_history = vec![NeuronId(10), NeuronId(11), NeuronId(12)];

        let (pre, post) =
            compute_activity_factors(&sources, &targets, &source_history, &target_history);

        assert_eq!(pre.len(), 3);
        assert_eq!(post.len(), 3);
        assert!(pre.iter().all(|&x| x == 1.0));
        assert!(post.iter().all(|&x| x == 1.0));
    }

    #[test]
    fn test_timing_factors_empty() {
        let config = STDPConfig::default();
        let sources = vec![];
        let targets = vec![];
        let source_history = vec![];
        let target_history = vec![];

        let factors = compute_timing_factors(
            &sources,
            &targets,
            &source_history,
            &target_history,
            &config,
        );

        assert_eq!(factors.len(), 0);
    }

    #[test]
    fn test_timing_factors_potentiation() {
        let config = STDPConfig::default();
        let sources = vec![NeuronId(1)];
        let targets = vec![NeuronId(10)];

        // Pre fired at t=5, post fired at t=10 (pre before post)
        let source_history = vec![(5, NeuronId(1))];
        let target_history = vec![(10, NeuronId(10))];

        let factors = compute_timing_factors(
            &sources,
            &targets,
            &source_history,
            &target_history,
            &config,
        );

        assert!(factors[0] > 0.0); // Should be positive (potentiation)
        assert!(factors[0] <= config.a_plus); // Should be bounded by a_plus
    }

    #[test]
    fn test_timing_factors_depression() {
        let config = STDPConfig::default();
        let sources = vec![NeuronId(1)];
        let targets = vec![NeuronId(10)];

        // Post fired at t=5, pre fired at t=10 (post before pre)
        let source_history = vec![(10, NeuronId(1))];
        let target_history = vec![(5, NeuronId(10))];

        let factors = compute_timing_factors(
            &sources,
            &targets,
            &source_history,
            &target_history,
            &config,
        );

        assert!(factors[0] < 0.0); // Should be negative (depression)
        assert!(factors[0] >= -config.a_minus); // Should be bounded by -a_minus
    }

    #[test]
    fn test_timing_factors_same_timestep() {
        let config = STDPConfig::default();
        let sources = vec![NeuronId(1)];
        let targets = vec![NeuronId(10)];

        // Both fired at same timestep
        let source_history = vec![(5, NeuronId(1))];
        let target_history = vec![(5, NeuronId(10))];

        let factors = compute_timing_factors(
            &sources,
            &targets,
            &source_history,
            &target_history,
            &config,
        );

        assert_eq!(factors[0], config.a_plus); // Should be strong potentiation
    }

    #[test]
    fn test_timing_factors_no_history() {
        let config = STDPConfig::default();
        let sources = vec![NeuronId(1), NeuronId(2)];
        let targets = vec![NeuronId(10), NeuronId(11)];

        // No firing history for these neurons
        let source_history = vec![(5, NeuronId(99))];
        let target_history = vec![(10, NeuronId(99))];

        let factors = compute_timing_factors(
            &sources,
            &targets,
            &source_history,
            &target_history,
            &config,
        );

        assert_eq!(factors[0], 0.0); // No change if neurons didn't fire
        assert_eq!(factors[1], 0.0);
    }

    #[test]
    fn test_timing_factors_exponential_decay() {
        let config = STDPConfig::default();
        let sources = vec![NeuronId(1)];
        let targets = vec![NeuronId(10)];

        // Test that closer spikes have stronger effects
        let source_history1 = vec![(5, NeuronId(1))];
        let target_history1 = vec![(6, NeuronId(10))]; // dt = 1

        let factors1 = compute_timing_factors(
            &sources,
            &targets,
            &source_history1,
            &target_history1,
            &config,
        );

        let source_history2 = vec![(5, NeuronId(1))];
        let target_history2 = vec![(15, NeuronId(10))]; // dt = 10

        let factors2 = compute_timing_factors(
            &sources,
            &targets,
            &source_history2,
            &target_history2,
            &config,
        );

        assert!(factors1[0] > factors2[0]); // Closer spikes should have stronger effect
    }

    #[test]
    fn test_group_synapses_by_area_pairs() {
        let mut neuron_to_area = HashMap::new();
        neuron_to_area.insert(1, 10);
        neuron_to_area.insert(2, 10);
        neuron_to_area.insert(3, 20);
        neuron_to_area.insert(11, 30);
        neuron_to_area.insert(12, 30);
        neuron_to_area.insert(13, 40);

        let sources = vec![NeuronId(1), NeuronId(2), NeuronId(3)];
        let targets = vec![NeuronId(11), NeuronId(12), NeuronId(13)];

        let groups = group_synapses_by_area_pairs(&sources, &targets, &neuron_to_area);

        // Should have 3 groups: (10,30), (10,30), (20,40)
        assert!(groups.contains_key(&(10, 30)));
        assert!(groups.contains_key(&(20, 40)));

        let group_10_30 = &groups[&(10, 30)];
        assert_eq!(group_10_30.len(), 2); // Two synapses from area 10 to area 30
    }

    #[test]
    fn test_group_synapses_missing_neurons() {
        let neuron_to_area = HashMap::new(); // Empty mapping

        let sources = vec![NeuronId(1), NeuronId(2)];
        let targets = vec![NeuronId(10), NeuronId(11)];

        let groups = group_synapses_by_area_pairs(&sources, &targets, &neuron_to_area);

        assert_eq!(groups.len(), 0); // Should have no groups if neurons not found
    }
}