pc-rl-core 1.1.1

Predictive Coding Actor-Critic reinforcement learning framework — pure Rust, zero ML dependencies
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
// Author: Julian Bolivar
// Version: 1.0.0
// Date: 2026-03-25

//! Dense neural network layer.
//!
//! Provides forward propagation, transpose forward (PC top-down pass),
//! and backward propagation with gradient/weight clipping. Building
//! block for both [`crate::PcActor`] and [`crate::MlpCritic`].

use rand::Rng;
use serde::{Deserialize, Serialize};

use crate::activation::Activation;
use crate::linalg::cpu::CpuLinAlg;
use crate::linalg::LinAlg;
use crate::matrix::{GRAD_CLIP, WEIGHT_CLIP};

/// Definition of a layer's shape and activation, used for topology configuration.
///
/// # Examples
///
/// ```
/// use pc_rl_core::activation::Activation;
/// use pc_rl_core::layer::LayerDef;
///
/// let def = LayerDef { size: 64, activation: Activation::Tanh };
/// assert_eq!(def.size, 64);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LayerDef {
    /// Number of neurons in this layer.
    pub size: usize,
    /// Activation function applied after the linear transform.
    pub activation: Activation,
}

/// A single dense layer with weights, bias, and activation function.
///
/// Generic over a [`LinAlg`] backend `L`. Defaults to [`CpuLinAlg`] for
/// backward compatibility.
///
/// Weights have shape `[output_size × input_size]`. Bias has length `output_size`.
///
/// # Examples
///
/// ```
/// use pc_rl_core::activation::Activation;
/// use pc_rl_core::layer::Layer;
/// use rand::SeedableRng;
/// use rand::rngs::StdRng;
///
/// let mut rng = StdRng::seed_from_u64(42);
/// let layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
/// let output: Vec<f64> = layer.forward(&vec![1.0, 0.0, -1.0, 0.5]);
/// assert_eq!(output.len(), 3);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(bound(
    serialize = "L::Matrix: Serialize, L::Vector: Serialize",
    deserialize = "L::Matrix: for<'a> Deserialize<'a>, L::Vector: for<'a> Deserialize<'a>"
))]
pub struct Layer<L: LinAlg = CpuLinAlg> {
    /// Weight matrix of shape `[output_size × input_size]`.
    pub weights: L::Matrix,
    /// Bias vector of length `output_size`.
    pub bias: L::Vector,
    /// Activation function applied element-wise after the linear transform.
    pub activation: Activation,
}

impl<L: LinAlg> Layer<L> {
    /// Creates a new layer with Xavier-initialized weights and zero bias.
    ///
    /// # Arguments
    ///
    /// * `input_size` - Number of inputs to this layer.
    /// * `output_size` - Number of neurons (outputs) in this layer.
    /// * `activation` - Activation function to apply after the linear transform.
    /// * `rng` - Random number generator for weight initialization.
    pub fn new(
        input_size: usize,
        output_size: usize,
        activation: Activation,
        rng: &mut impl Rng,
    ) -> Self {
        Self {
            weights: L::xavier_mat(output_size, input_size, rng),
            bias: L::zeros_vec(output_size),
            activation,
        }
    }

    /// Computes `activation(W * input + bias)`.
    ///
    /// # Panics
    ///
    /// Panics if `input.len() != input_size` (number of columns in weights).
    pub fn forward(&self, input: &L::Vector) -> L::Vector {
        let linear = L::mat_vec_mul(&self.weights, input);
        let biased = L::vec_add(&linear, &self.bias);
        L::apply_activation(&biased, self.activation)
    }

    /// Computes `activation(W^T * input)` (no bias).
    ///
    /// Used for PC top-down predictions. The `activation` parameter is
    /// separate from `self.activation` because at the output→last-hidden
    /// boundary, different activations may apply.
    ///
    /// # Panics
    ///
    /// Panics if `input.len() != output_size` (number of rows in weights).
    pub fn transpose_forward(&self, input: &L::Vector, activation: Activation) -> L::Vector {
        let wt = L::mat_transpose(&self.weights);
        let linear = L::mat_vec_mul(&wt, input);
        L::apply_activation(&linear, activation)
    }

    /// Backpropagation with gradient and weight clipping.
    ///
    /// Returns the propagated delta for the layer below (length = input_size).
    ///
    /// # Arguments
    ///
    /// * `input` - Input that was fed to this layer during forward pass.
    /// * `output` - Output of this layer from the forward pass (post-activation).
    /// * `delta` - Error signal from the layer above.
    /// * `lr` - Base learning rate.
    /// * `surprise_scale` - Multiplier on `lr` based on surprise score.
    ///
    /// # Panics
    ///
    /// Panics on dimension mismatches.
    pub fn backward(
        &mut self,
        input: &L::Vector,
        output: &L::Vector,
        delta: &L::Vector,
        lr: f64,
        surprise_scale: f64,
    ) -> L::Vector {
        // 1. Activation derivative
        let deriv = L::apply_derivative(output, self.activation);

        // 2. Local gradient = delta * deriv (element-wise Hadamard product)
        let mut grad = L::vec_hadamard(delta, &deriv);

        // 3. Clip gradient
        L::clip_vec(&mut grad, GRAD_CLIP);

        // 4. Effective learning rate
        let effective_lr = lr * surprise_scale;

        // 5. Weight gradient: dW = outer(grad, input)
        let dw = L::outer_product(&grad, input);

        // 6. Update weights (scale_add includes WEIGHT_CLIP clamping)
        L::mat_scale_add(&mut self.weights, &dw, -effective_lr);

        // 7. Update bias with clamping
        let bias_update = L::vec_scale(&grad, effective_lr);
        let new_bias = L::vec_sub(&self.bias, &bias_update);
        self.bias = new_bias;
        L::clip_vec(&mut self.bias, WEIGHT_CLIP);

        // 8. Propagated delta: W^T * grad
        let wt = L::mat_transpose(&self.weights);
        L::mat_vec_mul(&wt, &grad)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    fn make_rng() -> StdRng {
        StdRng::seed_from_u64(42)
    }

    // ── forward tests ──────────────────────────────────────────────

    #[test]
    fn test_forward_output_length_equals_output_size() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 3, Activation::Linear, &mut rng);
        let out = layer.forward(&vec![1.0, 0.0, -1.0, 0.5]);
        assert_eq!(out.len(), 3);
    }

    #[test]
    fn test_forward_linear_known_value() {
        let mut rng = make_rng();
        let mut layer: Layer = Layer::new(2, 1, Activation::Linear, &mut rng);
        // Set known weights and bias
        layer.weights.set(0, 0, 2.0);
        layer.weights.set(0, 1, 3.0);
        layer.bias[0] = 1.0;
        // output = 2*1 + 3*2 + 1 = 9
        let out = layer.forward(&vec![1.0, 2.0]);
        assert!((out[0] - 9.0).abs() < 1e-12);
    }

    #[test]
    fn test_forward_tanh_output_bounded() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 5, Activation::Tanh, &mut rng);
        let out = layer.forward(&vec![10.0, -10.0, 5.0, -5.0]);
        for &v in &out {
            assert!(v > -1.0 && v < 1.0, "Tanh output {v} not in (-1,1)");
        }
    }

    #[test]
    fn test_forward_sigmoid_output_bounded() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 5, Activation::Sigmoid, &mut rng);
        let out = layer.forward(&vec![10.0, -10.0, 5.0, -5.0]);
        for &v in &out {
            assert!(v > 0.0 && v < 1.0, "Sigmoid output {v} not in (0,1)");
        }
    }

    #[test]
    fn test_forward_relu_no_negative_outputs() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 5, Activation::Relu, &mut rng);
        let out = layer.forward(&vec![10.0, -10.0, 5.0, -5.0]);
        for &v in &out {
            assert!(v >= 0.0, "ReLU output {v} is negative");
        }
    }

    #[test]
    fn test_forward_all_outputs_finite() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let out = layer.forward(&vec![1e6, -1e6, 1e3, -1e3]);
        for &v in &out {
            assert!(v.is_finite(), "Output {v} is not finite");
        }
    }

    #[test]
    #[should_panic]
    fn test_forward_panics_wrong_input_length() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 3, Activation::Linear, &mut rng);
        let _ = layer.forward(&vec![1.0, 2.0]); // wrong length
    }

    // ── transpose_forward tests ────────────────────────────────────

    #[test]
    fn test_transpose_forward_output_length_equals_input_size() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        // transpose_forward takes output_size input, returns input_size
        let out = layer.transpose_forward(&vec![0.5, -0.5, 0.0], Activation::Tanh);
        assert_eq!(out.len(), 4);
    }

    #[test]
    fn test_transpose_forward_all_finite() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let out = layer.transpose_forward(&vec![1e3, -1e3, 0.0], Activation::Tanh);
        for &v in &out {
            assert!(v.is_finite(), "transpose_forward output {v} is not finite");
        }
    }

    #[test]
    fn test_transpose_forward_different_activation_changes_output() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let input = vec![0.5, -0.5, 0.3];
        let out_tanh = layer.transpose_forward(&input, Activation::Tanh);
        let out_linear = layer.transpose_forward(&input, Activation::Linear);
        // At least one element should differ
        let differs = out_tanh
            .iter()
            .zip(out_linear.iter())
            .any(|(a, b)| (a - b).abs() > 1e-12);
        assert!(
            differs,
            "Different activations should produce different outputs"
        );
    }

    #[test]
    #[should_panic]
    fn test_transpose_forward_panics_wrong_input_length() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let _ = layer.transpose_forward(&vec![0.5, -0.5], Activation::Tanh); // wrong length
    }

    // ── backward tests ─────────────────────────────────────────────

    #[test]
    fn test_backward_changes_weights() {
        let mut rng = make_rng();
        let mut layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let input = vec![1.0, 0.5, -0.5, 0.0];
        let output = layer.forward(&input);
        let delta = vec![0.1, -0.2, 0.3];
        let weights_before = layer.weights.clone();
        let _ = layer.backward(&input, &output, &delta, 0.01, 1.0);
        // At least one weight should change
        let changed = (0..3).any(|r| {
            (0..4).any(|c| (layer.weights.get(r, c) - weights_before.get(r, c)).abs() > 1e-15)
        });
        assert!(changed, "Weights should change after backward");
    }

    #[test]
    fn test_backward_changes_bias() {
        let mut rng = make_rng();
        let mut layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let input = vec![1.0, 0.5, -0.5, 0.0];
        let output = layer.forward(&input);
        let delta = vec![0.1, -0.2, 0.3];
        let bias_before = layer.bias.clone();
        let _ = layer.backward(&input, &output, &delta, 0.01, 1.0);
        let changed = layer
            .bias
            .iter()
            .zip(bias_before.iter())
            .any(|(a, b)| (a - b).abs() > 1e-15);
        assert!(changed, "Bias should change after backward");
    }

    #[test]
    fn test_backward_returns_delta_of_correct_length() {
        let mut rng = make_rng();
        let mut layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let input = vec![1.0, 0.5, -0.5, 0.0];
        let output = layer.forward(&input);
        let delta = vec![0.1, -0.2, 0.3];
        let prop_delta = layer.backward(&input, &output, &delta, 0.01, 1.0);
        assert_eq!(prop_delta.len(), 4);
    }

    #[test]
    fn test_backward_clips_weights_to_weight_clip() {
        let mut rng = make_rng();
        let mut layer: Layer = Layer::new(4, 3, Activation::Linear, &mut rng);
        let input = vec![100.0, 100.0, 100.0, 100.0];
        let output = layer.forward(&input);
        let delta = vec![1e6, 1e6, 1e6];
        let _ = layer.backward(&input, &output, &delta, 1.0, 1.0);
        for r in 0..3 {
            for c in 0..4 {
                let w = layer.weights.get(r, c);
                assert!(
                    w.abs() <= WEIGHT_CLIP + 1e-12,
                    "Weight {w} exceeds WEIGHT_CLIP"
                );
            }
        }
        for &b in &layer.bias {
            assert!(
                b.abs() <= WEIGHT_CLIP + 1e-12,
                "Bias {b} exceeds WEIGHT_CLIP"
            );
        }
    }

    #[test]
    fn test_backward_returns_finite_delta() {
        let mut rng = make_rng();
        let mut layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let input = vec![1.0, 0.5, -0.5, 0.0];
        let output = layer.forward(&input);
        let delta = vec![0.1, -0.2, 0.3];
        let prop_delta = layer.backward(&input, &output, &delta, 0.01, 1.0);
        for &v in &prop_delta {
            assert!(v.is_finite(), "Propagated delta {v} is not finite");
        }
    }

    #[test]
    fn test_backward_zero_lr_does_not_change_weights() {
        let mut rng = make_rng();
        let mut layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let input = vec![1.0, 0.5, -0.5, 0.0];
        let output = layer.forward(&input);
        let delta = vec![0.1, -0.2, 0.3];
        let weights_before = layer.weights.clone();
        let bias_before = layer.bias.clone();
        let _ = layer.backward(&input, &output, &delta, 0.0, 1.0);
        for r in 0..3 {
            for c in 0..4 {
                assert!(
                    (layer.weights.get(r, c) - weights_before.get(r, c)).abs() < 1e-15,
                    "Weights changed with zero lr"
                );
            }
        }
        for (a, b) in layer.bias.iter().zip(bias_before.iter()) {
            assert!((a - b).abs() < 1e-15, "Bias changed with zero lr");
        }
    }

    // ── serde test ─────────────────────────────────────────────────

    #[test]
    fn test_serde_roundtrip_preserves_weights_and_activation() {
        let mut rng = make_rng();
        let layer: Layer = Layer::new(4, 3, Activation::Tanh, &mut rng);
        let json = serde_json::to_string(&layer).unwrap();
        let restored: Layer = serde_json::from_str(&json).unwrap();
        assert_eq!(layer.bias, restored.bias);
        assert_eq!(layer.activation, restored.activation);
        for r in 0..3 {
            for c in 0..4 {
                assert!(
                    (layer.weights.get(r, c) - restored.weights.get(r, c)).abs() < 1e-15,
                    "Weights not preserved in serde roundtrip"
                );
            }
        }
    }
}