Deepity
Ultra-fast, SIMD-accelerated Predictive Coding
Loading...
Searching...
No Matches
FullPCLayer.h
Go to the documentation of this file.
1#pragma once
2
9#include <map>
10#include <memory>
11#include <random>
12#include <vector>
13
36
37namespace Deep
38{
43class FullPCLayer : public Layer
44{
45protected:
46 size_t size;
47 size_t nextSize;
48 size_t terminalSize;
49 size_t batchSize;
50
51 float lr;
52 float ir;
53 float fl;
54 float lmbda;
55
56 // muPC scaling: mu = a * (W @ phi(z)) + b [+ z if useResidual].
57 // a=1.0, useResidual=false reproduces plain PC exactly.
58 float a = 1.0f;
59 bool useResidual = false;
60
61 bool isClamped = false;
62 bool muCacheValid = false;
63
67
69
72
75 using BackendDeleter = void (*)(IComputeBackend*);
76 std::unique_ptr<IComputeBackend, BackendDeleter> backend;
77
78 float* z = nullptr;
79 float* e = nullptr;
80
81 float* W = nullptr;
82 float* b = nullptr;
83 float* mu = nullptr;
84 float* cachedMu = nullptr;
85 float* Psi = nullptr;
86 float* proj = nullptr;
87
88 float* grad_W = nullptr;
89 float* grad_b = nullptr;
90 float* m_W = nullptr;
91 float* v_W = nullptr;
92 float* m_b = nullptr;
93 float* v_b = nullptr;
94
95 float* grad_Psi = nullptr;
96 float* m_Psi = nullptr;
97 float* v_Psi = nullptr;
98
99 int* t_device = nullptr;
100 float* lr_device = nullptr;
101 int* tPsi_device = nullptr;
102 float* fl_device = nullptr;
103
104 float* zF = nullptr;
105 float* zFDeriv = nullptr;
106 float* feedbackScratch = nullptr;
107
108 float* v = nullptr;
109 bool useMomentum = false;
110 float momentumBeta = 0.9f;
111
112 bool useCrossEntropy = false;
113 float* rowEnergies = nullptr;
114
119 float* biasGradScratch = nullptr;
120
121 std::unique_ptr<MemoryArena> localArena;
122
123public:
140 FullPCLayer(size_t size, size_t nextSize, size_t terminalSize, size_t batchSize,
141 float learningRate, float inferenceRate, float feedback, float lmbda,
142 ActivationType aType, ActivationType dType, IComputeBackend* backend = nullptr);
143
144 ~FullPCLayer() override = default;
145
149 template <typename ArenaT> void BindMemory(ArenaT& arena);
151 size_t GetRequiredFloats() const noexcept;
153 void RandomizeWeights(std::mt19937& seedGenerator) noexcept;
154
155 std::map<std::string, TensorDescriptor> GetStateDict() const override;
156
158 void SetLayerAbove(FullPCLayer* l) noexcept
159 {
160 layerAbove = l;
161 }
162
163 void SetLayerBelow(FullPCLayer* l) noexcept
164 {
165 layerBelow = l;
166 }
167
169 {
170 terminalLayer = l;
171 }
172
176 void SetMuPCScale(float a) noexcept
177 {
178 this->a = a;
179 }
180
182 float GetMuPCScale() const noexcept
183 {
184 return a;
185 }
186
191 void SetResidual(bool enabled) noexcept
192 {
193 useResidual = enabled;
194 }
195
197 bool GetResidual() const noexcept
198 {
199 return useResidual;
200 }
201
208 void SetCrossEntropy(bool enabled) noexcept
209 {
210 useCrossEntropy = enabled;
211 }
212
214 bool GetCrossEntropy() const noexcept
215 {
216 return useCrossEntropy;
217 }
218
221 float CalculateState() noexcept override
222 {
223 return CalculateState(true);
224 }
225
228 float CalculateState(bool needEnergy) noexcept;
229
231 void ComputeMuOnly() noexcept;
232 void UpdateState() noexcept override;
233 void UpdateWeights() noexcept override;
237 void DirectFeedbackUpdate() noexcept;
238
241 void ClampState(const std::vector<float>& inputData) noexcept;
243 void UnclampState() noexcept;
245 void ResetState() noexcept;
246
248 bool IsClamped() const noexcept
249 {
250 return isClamped;
251 }
252
258 void InvalidateMuCache() noexcept
259 {
260 muCacheValid = false;
261 }
262
270 void SetMomentum(bool enabled, float beta = 0.9f) noexcept
271 {
272 useMomentum = enabled;
273 momentumBeta = beta;
274 }
275
276 bool GetMomentum() const noexcept
277 {
278 return useMomentum;
279 }
280
281 float GetMomentumBeta() const noexcept
282 {
283 return momentumBeta;
284 }
285
288 {
289 opt = o;
290 }
291
293 {
294 optPsi = o;
295 }
296
297 void SetLearningRate(float learningRate) noexcept;
299 void SetInferenceRate(float inferenceRate) noexcept
300 {
301 ir = inferenceRate;
302 }
303
304 void SetFeedbackRate(float feedbackRate) noexcept;
306 void SetLambda(float lmbda) noexcept
307 {
308 this->lmbda = lmbda;
309 }
310
311 float* GetBeliefs() noexcept override
312 {
313 return z;
314 }
315 const float* GetErrors() const noexcept override
316 {
317 return e;
318 }
319
320 const float* GetMu() const noexcept
321 {
322 return mu;
323 }
324
325 const float* GetWeights() const noexcept
326 {
327 return W;
328 }
329
330 const float* GetDirectFeedbackWeights() const noexcept
331 {
332 return Psi;
333 }
334
335 const float* GetBiases() const noexcept
336 {
337 return b;
338 }
339
340 size_t GetBatchSize() const noexcept override
341 {
342 return batchSize;
343 }
344 size_t GetInputSize() const noexcept override
345 {
346 return size;
347 }
348 size_t GetOutputSize() const noexcept override
349 {
350 return nextSize;
351 }
352
353 size_t GetTerminalSize() const noexcept
354 {
355 return terminalSize;
356 }
357};
358} // namespace Deep
Defines the activation functions of a predictive coding model.
Vectorized AdamW update, operating per-element over an array of weights (or biases) – NOT the single-...
A 64-byte-aligned bump-pointer allocator over a single device buffer, mirroring this codebase's host-...
Virtual Layer.
A 64-byte-aligned bump-pointer allocator over a single heap-allocated block, used to pack every layer...
bool muCacheValid
Whether cachedMu holds a valid, up-to-date value.
Definition FullPCLayer.h:62
float GetMomentumBeta() const noexcept
Returns the momentum EMA decay rate – see SetMomentum().
Definition FullPCLayer.h:281
float * biasGradScratch
nextSize-length scratch for SumRows' output in UpdateWeights()'s SGD branch (accumulate,...
Definition FullPCLayer.h:119
bool isClamped
Whether ClampState() is currently active.
Definition FullPCLayer.h:61
void ClampState(const std::vector< float > &inputData) noexcept
Clamps this layer's beliefs to inputData, fixing them against UpdateState() until UnclampState() is c...
Definition FullPCLayer.cpp:546
size_t nextSize
Size of the layer above (0 marks a terminal layer).
Definition FullPCLayer.h:47
float * v
Momentum buffer for the settling update – see SetMomentum().
Definition FullPCLayer.h:108
bool useResidual
Whether the residual/skip connection is enabled – see SetResidual().
Definition FullPCLayer.h:59
void SetCrossEntropy(bool enabled) noexcept
Enables softmax cross-entropy energy for THIS layer's error against layerBelow's mu (i....
Definition FullPCLayer.h:208
const float * GetMu() const noexcept
Returns this layer's forward prediction buffer.
Definition FullPCLayer.h:320
bool GetResidual() const noexcept
Returns whether the residual connection is enabled – see SetResidual().
Definition FullPCLayer.h:197
size_t size
This layer's own belief (z) size.
Definition FullPCLayer.h:46
float fl
Feedback rate for Psi.
Definition FullPCLayer.h:53
void SetOptimizer(OptimizerType o) noexcept
Sets the optimizer for W. Call before Compile().
Definition FullPCLayer.h:287
FullPCLayer(size_t size, size_t nextSize, size_t terminalSize, size_t batchSize, float learningRate, float inferenceRate, float feedback, float lmbda, ActivationType aType, ActivationType dType, IComputeBackend *backend=nullptr)
Definition FullPCLayer.cpp:37
FullPCLayer * layerAbove
The next layer up, or nullptr if this is terminal.
Definition FullPCLayer.h:64
void SetResidual(bool enabled) noexcept
Set by the owning network at Compile() time. Requires size == nextSize (checked at the point it's act...
Definition FullPCLayer.h:191
void UpdateState() noexcept override
Updates the states after calculation.
Definition FullPCLayer.cpp:329
const float * GetWeights() const noexcept
Returns the weight matrix W, shape [nextSize, size].
Definition FullPCLayer.h:325
float * W
Weight matrix, shape [nextSize, size].
Definition FullPCLayer.h:81
size_t GetBatchSize() const noexcept override
Should return batch size.
Definition FullPCLayer.h:340
void SetFeedbackRate(float feedbackRate) noexcept
Sets the feedback rate, propagating it to the optimizer state.
Definition FullPCLayer.cpp:62
float ir
Inference rate (Euler integration step size).
Definition FullPCLayer.h:52
size_t GetInputSize() const noexcept override
Should return input size.
Definition FullPCLayer.h:344
void SetLayerAbove(FullPCLayer *l) noexcept
Sets the layer immediately above this one in the network.
Definition FullPCLayer.h:158
float lmbda
Weight decay (L2 regularization) coefficient, shared between W and Psi.
Definition FullPCLayer.h:54
float * grad_Psi
Psi's gradient scratch buffer.
Definition FullPCLayer.h:95
size_t GetTerminalSize() const noexcept
Returns the network's final output layer size, as given at construction.
Definition FullPCLayer.h:353
float * v_b
Adam/AdamW second-moment buffer for b.
Definition FullPCLayer.h:93
int * t_device
Device-resident Adam/AdamW step count for W/b, for graph-captured steps.
Definition FullPCLayer.h:99
bool GetCrossEntropy() const noexcept
Returns whether softmax cross-entropy energy is enabled – see SetCrossEntropy().
Definition FullPCLayer.h:214
float CalculateState() noexcept override
Matches Layer's virtual interface exactly (always computes real energy).
Definition FullPCLayer.h:221
void UpdateWeights() noexcept override
Updates the weights after state updates.
Definition FullPCLayer.cpp:383
void SetLambda(float lmbda) noexcept
Sets the weight decay coefficient.
Definition FullPCLayer.h:306
float * GetBeliefs() noexcept override
Should return belief state z.
Definition FullPCLayer.h:311
ActivationType activationType
This layer's activation type.
Definition FullPCLayer.h:68
FullPCLayer * layerBelow
The next layer down, or nullptr if this is the input layer.
Definition FullPCLayer.h:65
const float * GetDirectFeedbackWeights() const noexcept
Returns the direct feedback (DFA) weight matrix Psi, shape [size, terminalSize].
Definition FullPCLayer.h:330
std::map< std::string, TensorDescriptor > GetStateDict() const override
Returns a dictionary of this.
Definition FullPCLayer.cpp:223
OptimizerType optPsi
Optimizer for Psi.
Definition FullPCLayer.h:71
float * z
This layer's belief buffer, shape [batchSize, size].
Definition FullPCLayer.h:78
const float * GetBiases() const noexcept
Returns the bias vector, length nextSize.
Definition FullPCLayer.h:335
void SetTerminalLayer(FullPCLayer *l) noexcept
Sets the network's terminal layer, for DirectFeedbackUpdate().
Definition FullPCLayer.h:168
void UnclampState() noexcept
Releases a previous ClampState() call.
Definition FullPCLayer.cpp:554
float * grad_W
W's gradient scratch buffer.
Definition FullPCLayer.h:88
float * proj
Scratch buffer: terminal error projected back through layerAbove's Psi, for DirectFeedbackUpdate()'s ...
Definition FullPCLayer.h:86
void ResetState() noexcept
Resets this layer's beliefs (z) without touching learned weights.
Definition FullPCLayer.cpp:559
float * lr_device
Device-resident mirror of lr.
Definition FullPCLayer.h:100
float * Psi
Direct feedback (DFA) weight matrix, shape [size, terminalSize].
Definition FullPCLayer.h:85
float * m_b
Adam/AdamW first-moment buffer for b.
Definition FullPCLayer.h:92
float * fl_device
Device-resident mirror of fl.
Definition FullPCLayer.h:102
void RandomizeWeights(std::mt19937 &seedGenerator) noexcept
Randomizes W and Psi.
Definition FullPCLayer.cpp:205
float * e
This layer's error buffer, shape [batchSize, size].
Definition FullPCLayer.h:79
float a
muPC forward-scaling factor – see SetMuPCScale().
Definition FullPCLayer.h:58
~FullPCLayer() override=default
size_t batchSize
Batch size.
Definition FullPCLayer.h:49
float * zFDeriv
Activation derivative at z, for the feedback term.
Definition FullPCLayer.h:105
float * rowEnergies
Per-row energy scratch for the cross-entropy path, length batchSize.
Definition FullPCLayer.h:113
void SetMomentum(bool enabled, float beta=0.9f) noexcept
Enables momentum (inertial) settling: the update direction is EMA-smoothed (decay beta) before being ...
Definition FullPCLayer.h:270
float * mu
Forward prediction buffer, shape [batchSize, nextSize].
Definition FullPCLayer.h:83
float * zF
Activated belief, phi(z), used as the forward GEMM's input.
Definition FullPCLayer.h:104
float GetMuPCScale() const noexcept
Returns the current muPC forward-scaling factor – see SetMuPCScale().
Definition FullPCLayer.h:182
FullPCLayer * terminalLayer
The network's terminal layer, for DirectFeedbackUpdate().
Definition FullPCLayer.h:66
void SetLayerBelow(FullPCLayer *l) noexcept
Sets the layer immediately below this one in the network.
Definition FullPCLayer.h:163
size_t GetOutputSize() const noexcept override
Should return output size.
Definition FullPCLayer.h:348
float * cachedMu
Cached mu, valid when muCacheValid is true.
Definition FullPCLayer.h:84
float * v_Psi
Adam/AdamW second-moment buffer for Psi.
Definition FullPCLayer.h:97
std::unique_ptr< IComputeBackend, BackendDeleter > backend
This layer's compute backend.
Definition FullPCLayer.h:76
size_t GetRequiredFloats() const noexcept
Total floats this layer needs from its MemoryArena.
Definition FullPCLayer.cpp:164
size_t terminalSize
Size of the network's final output layer.
Definition FullPCLayer.h:48
void DirectFeedbackUpdate() noexcept
Perturbs W using the layer above's Psi and the terminal layer's error – the DFA phase,...
Definition FullPCLayer.cpp:510
void SetLearningRate(float learningRate) noexcept
Sets the learning rate, propagating it to the optimizer state.
Definition FullPCLayer.cpp:55
const float * GetErrors() const noexcept override
Should return errors e.
Definition FullPCLayer.h:315
float * feedbackScratch
Scratch buffer for the feedback GEMM's output.
Definition FullPCLayer.h:106
float * m_W
Adam/AdamW first-moment buffer for W.
Definition FullPCLayer.h:90
float momentumBeta
Momentum EMA decay rate – see SetMomentum().
Definition FullPCLayer.h:110
OptimizerType opt
Optimizer for W/b.
Definition FullPCLayer.h:70
void(*)(IComputeBackend *) BackendDeleter
Custom deleter type for backend, needed since IComputeBackend is an abstract base – see the member be...
Definition FullPCLayer.h:75
bool useMomentum
Whether momentum settling is enabled – see SetMomentum().
Definition FullPCLayer.h:109
float * m_Psi
Adam/AdamW first-moment buffer for Psi.
Definition FullPCLayer.h:96
int * tPsi_device
Device-resident Adam/AdamW step count for Psi.
Definition FullPCLayer.h:101
float * b
Bias vector, length nextSize.
Definition FullPCLayer.h:82
void ComputeMuOnly() noexcept
Computes only mu (forward prediction), skipping error/energy.
Definition FullPCLayer.cpp:266
float * grad_b
b's gradient scratch buffer.
Definition FullPCLayer.h:89
void BindMemory(ArenaT &arena)
Binds this layer's buffers into a pre-allocated arena (MemoryArena for CPU, DeviceMemoryArena for GPU...
Definition FullPCLayer.cpp:69
void InvalidateMuCache() noexcept
Forces the next ComputeMuOnly() call to recompute mu from scratch, even if this layer is clamped....
Definition FullPCLayer.h:258
bool useCrossEntropy
Whether softmax cross-entropy energy is enabled – see SetCrossEntropy().
Definition FullPCLayer.h:112
bool GetMomentum() const noexcept
Returns whether momentum settling is enabled – see SetMomentum().
Definition FullPCLayer.h:276
std::unique_ptr< MemoryArena > localArena
This layer's own arena, used when it isn't bound into a network-wide one.
Definition FullPCLayer.h:121
void SetPsiOptimizer(OptimizerType o) noexcept
Sets the optimizer for Psi. Call before Compile().
Definition FullPCLayer.h:292
float * v_W
Adam/AdamW second-moment buffer for W.
Definition FullPCLayer.h:91
void SetMuPCScale(float a) noexcept
Set by the owning network at Compile() time, once the full layer_sizes list (and therefore d_in/N/L) ...
Definition FullPCLayer.h:176
float lr
Learning rate for W.
Definition FullPCLayer.h:51
void SetInferenceRate(float inferenceRate) noexcept
Sets the inference rate.
Definition FullPCLayer.h:299
bool IsClamped() const noexcept
Whether ClampState() is currently active on this layer.
Definition FullPCLayer.h:248
Device-agnostic compute backend interface: every numerical primitive a layer/network needs,...
Definition IComputeBackend.h:14
A deepity layer virtual class.
Definition Layer.h:40
This file exists to provide both Tensor.h and IComputeBackend.h with device types without introducing...
Definition Backend.cpp:10
ActivationType
Identifies an activation function or its derivative, for dispatch tables and layer/backend APIs that ...
Definition ActivationType.h:25
OptimizerType
Selects which weight-update rule a layer applies during UpdateWeights().
Definition AdamOptimizer.h:52
@ SGD
Plain stochastic gradient descent (this codebase's existing cblas-based update).
Definition AdamOptimizer.h:53
A named, shaped view into a layer's weight/bias data, for ModelIO's save/load (see Layer::GetStateDic...
Definition Layer.h:34