Deepity
Ultra-fast, SIMD-accelerated Predictive Coding
Loading...
Searching...
No Matches
DirectKPPCLayer.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
27
28namespace Deep {
34class DirectKPPCLayer : public Layer {
35protected:
36 size_t size;
37 size_t nextSize;
38 size_t terminalSize;
39 size_t batchSize;
40
41 float lr;
42 float ir;
43 float fl;
44 float lmbda;
45
46 bool isClamped = false;
47 bool muCacheValid = false;
48
52
57
60 int t = 0;
61 int tPsi = 0;
62
65 using BackendDeleter = void (*)(IComputeBackend *);
66 std::unique_ptr<IComputeBackend, BackendDeleter> backend;
67
68 float *z = nullptr;
69 float *e = nullptr;
70
71 float *W = nullptr;
72 float *b = nullptr;
73 float *mu = nullptr;
74 float *cachedMu = nullptr;
75 float *Psi = nullptr;
76 float *proj = nullptr;
77
78 float *grad_W = nullptr;
79 float *grad_b = nullptr;
80 float *m_W = nullptr;
81 float *v_W = nullptr;
82 float *m_b = nullptr;
83 float *v_b = nullptr;
84
85 float *grad_Psi = nullptr;
86 float *m_Psi = nullptr;
87 float *v_Psi = nullptr;
88
89 int *t_device = nullptr;
90 float *lr_device = nullptr;
91 int *tPsi_device = nullptr;
92 float *fl_device = nullptr;
93
94 float *zF = nullptr;
95 float *zFDeriv = nullptr;
96 float *feedbackScratch = nullptr;
97
105 float *biasGradScratch = nullptr;
106
107 std::unique_ptr<MemoryArena> localArena;
108
109public:
126 DirectKPPCLayer(size_t size, size_t nextSize, size_t terminalSize,
127 size_t batchSize, float learningRate, float inferenceRate,
128 float feedback, float lmbda, ActivationType aType,
129 ActivationType dType, IComputeBackend *backend = nullptr);
130
131 ~DirectKPPCLayer() override = default;
132
136 template <typename ArenaT> void BindMemory(ArenaT &arena);
138 size_t GetRequiredFloats() const noexcept;
140 void RandomizeWeights(std::mt19937 &seedGenerator) noexcept;
141
142 std::map<std::string, TensorDescriptor> GetStateDict() const override;
143
145 void SetLayerAbove(DirectKPPCLayer *l) noexcept { layerAbove = l; }
147 void SetLayerBelow(DirectKPPCLayer *l) noexcept { layerBelow = l; }
150
153 float CalculateState() noexcept override { return CalculateState(true); }
158 float CalculateState(bool needEnergy) noexcept;
159
161 void ComputeMuOnly() noexcept;
162 void UpdateState() noexcept override;
163 void UpdateWeights() noexcept override;
167 void DirectFeedbackUpdate() noexcept;
168
171 void ClampState(const std::vector<float> &inputData) noexcept;
173 void UnclampState() noexcept;
175 void ResetState() noexcept;
176
183 bool IsClamped() const noexcept { return isClamped; }
184
186 void SetOptimizer(OptimizerType o) noexcept { opt = o; }
188 void SetPsiOptimizer(OptimizerType o) noexcept { optPsi = o; }
190 void SetLearningRate(float learningRate) noexcept;
192 void SetInferenceRate(float inferenceRate) noexcept { ir = inferenceRate; }
194 void SetFeedbackRate(float feedbackRate) noexcept;
196 void SetLambda(float lmbda) noexcept { this->lmbda = lmbda; }
197
198 float *GetBeliefs() noexcept override { return z; }
199 const float *GetErrors() const noexcept override { return e; }
201 const float *GetMu() const noexcept { return mu; }
203 const float *GetWeights() const noexcept { return W; }
205 const float *GetDirectFeedbackWeights() const noexcept { return Psi; }
207 const float *GetBiases() const noexcept { return b; }
208
209 size_t GetBatchSize() const noexcept override { return batchSize; }
210 size_t GetInputSize() const noexcept override { return size; }
211 size_t GetOutputSize() const noexcept override { return nextSize; }
213 size_t GetTerminalSize() const noexcept { return terminalSize; }
214};
215} // 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...
void DirectFeedbackUpdate() noexcept
Perturbs W using the layer above's Psi and the terminal layer's error – the DFA phase,...
Definition DirectKPPCLayer.cpp:404
float lmbda
Weight decay (L2 regularization) coefficient, shared between W and Psi.
Definition DirectKPPCLayer.h:44
void BindMemory(ArenaT &arena)
Binds this layer's buffers into a pre-allocated arena (MemoryArena for CPU, DeviceMemoryArena for GPU...
Definition DirectKPPCLayer.cpp:73
void ResetState() noexcept
Resets this layer's beliefs (z) without touching learned weights.
Definition DirectKPPCLayer.cpp:439
DerivativeFn2 activationDerivativeInto
Two-buffer variant of activationDerivative.
Definition DirectKPPCLayer.h:56
size_t GetBatchSize() const noexcept override
Should return batch size.
Definition DirectKPPCLayer.h:209
float * lr_device
Device-resident mirror of lr.
Definition DirectKPPCLayer.h:90
float * grad_Psi
Psi's gradient scratch buffer.
Definition DirectKPPCLayer.h:85
DirectKPPCLayer * terminalLayer
The network's terminal layer, for DirectFeedbackUpdate().
Definition DirectKPPCLayer.h:51
float * m_Psi
Adam/AdamW first-moment buffer for Psi.
Definition DirectKPPCLayer.h:86
int t
Adam/AdamW step count for W/b.
Definition DirectKPPCLayer.h:60
void UnclampState() noexcept
Releases a previous ClampState() call.
Definition DirectKPPCLayer.cpp:434
int * t_device
Device-resident mirror of t, for graph-captured Adam steps.
Definition DirectKPPCLayer.h:89
float * fl_device
Device-resident mirror of fl.
Definition DirectKPPCLayer.h:92
const float * GetMu() const noexcept
Returns this layer's forward prediction buffer.
Definition DirectKPPCLayer.h:201
std::map< std::string, TensorDescriptor > GetStateDict() const override
Returns a dictionary of this.
Definition DirectKPPCLayer.cpp:222
size_t batchSize
Batch size.
Definition DirectKPPCLayer.h:39
void ClampState(const std::vector< float > &inputData) noexcept
Clamps this layer's beliefs to inputData, fixing them against UpdateState() until UnclampState() is c...
Definition DirectKPPCLayer.cpp:426
~DirectKPPCLayer() override=default
std::unique_ptr< IComputeBackend, BackendDeleter > backend
This layer's compute backend.
Definition DirectKPPCLayer.h:66
std::unique_ptr< MemoryArena > localArena
This layer's own arena, used when it isn't bound into a network-wide one.
Definition DirectKPPCLayer.h:107
float * cachedMu
Cached mu, valid when muCacheValid is true.
Definition DirectKPPCLayer.h:74
void SetFeedbackRate(float feedbackRate) noexcept
Sets the feedback rate, propagating it to the optimizer state.
Definition DirectKPPCLayer.cpp:65
void SetTerminalLayer(DirectKPPCLayer *l) noexcept
Sets the network's terminal layer, for DirectFeedbackUpdate().
Definition DirectKPPCLayer.h:149
void UpdateWeights() noexcept override
Updates the weights after state updates.
Definition DirectKPPCLayer.cpp:316
float * z
This layer's belief buffer, shape [batchSize, size].
Definition DirectKPPCLayer.h:68
void RandomizeWeights(std::mt19937 &seedGenerator) noexcept
Randomizes W and Psi.
Definition DirectKPPCLayer.cpp:204
size_t size
This layer's own belief (z) size.
Definition DirectKPPCLayer.h:36
float * Psi
Direct feedback (DFA) weight matrix, shape [size, terminalSize].
Definition DirectKPPCLayer.h:75
float * v_b
Adam/AdamW second-moment buffer for b.
Definition DirectKPPCLayer.h:83
float * e
This layer's error buffer, shape [batchSize, size].
Definition DirectKPPCLayer.h:69
void SetLayerAbove(DirectKPPCLayer *l) noexcept
Sets the layer immediately above this one in the network.
Definition DirectKPPCLayer.h:145
float * grad_W
W's gradient scratch buffer.
Definition DirectKPPCLayer.h:78
float * m_W
Adam/AdamW first-moment buffer for W.
Definition DirectKPPCLayer.h:80
size_t GetOutputSize() const noexcept override
Should return output size.
Definition DirectKPPCLayer.h:211
void SetInferenceRate(float inferenceRate) noexcept
Sets the inference rate.
Definition DirectKPPCLayer.h:192
size_t terminalSize
Size of the network's final output layer.
Definition DirectKPPCLayer.h:38
const float * GetDirectFeedbackWeights() const noexcept
Returns the direct feedback (DFA) weight matrix Psi, shape [size, terminalSize].
Definition DirectKPPCLayer.h:205
void ComputeMuOnly() noexcept
Computes only mu (forward prediction), skipping error/energy.
Definition DirectKPPCLayer.cpp:254
ActivationFn activation
Resolved function pointer for activationType.
Definition DirectKPPCLayer.h:54
int tPsi
Adam/AdamW step count for Psi.
Definition DirectKPPCLayer.h:61
const float * GetWeights() const noexcept
Returns the weight matrix W, shape [nextSize, size].
Definition DirectKPPCLayer.h:203
bool IsClamped() const noexcept
Whether this layer is currently clamped – needed so DirectKPPCNetwork::ProjectForward() can skip over...
Definition DirectKPPCLayer.h:183
DirectKPPCLayer(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 DirectKPPCLayer.cpp:34
DerivativeFn activationDerivative
Resolved function pointer for the derivative.
Definition DirectKPPCLayer.h:55
float * v_Psi
Adam/AdamW second-moment buffer for Psi.
Definition DirectKPPCLayer.h:87
DirectKPPCLayer * layerBelow
The next layer down, or nullptr if this is the input layer.
Definition DirectKPPCLayer.h:50
void(*)(IComputeBackend *) BackendDeleter
Custom deleter type for backend, needed since IComputeBackend is an abstract base – see the member be...
Definition DirectKPPCLayer.h:65
float * b
Bias vector, length nextSize.
Definition DirectKPPCLayer.h:72
float * v_W
Adam/AdamW second-moment buffer for W.
Definition DirectKPPCLayer.h:81
float * m_b
Adam/AdamW first-moment buffer for b.
Definition DirectKPPCLayer.h:82
float lr
Learning rate for W.
Definition DirectKPPCLayer.h:41
size_t GetRequiredFloats() const noexcept
Total floats this layer needs from its MemoryArena.
Definition DirectKPPCLayer.cpp:164
void SetLayerBelow(DirectKPPCLayer *l) noexcept
Sets the layer immediately below this one in the network.
Definition DirectKPPCLayer.h:147
size_t GetTerminalSize() const noexcept
Returns the network's final output layer size, as given at construction.
Definition DirectKPPCLayer.h:213
float * zFDeriv
Activation derivative at z, for the feedback term.
Definition DirectKPPCLayer.h:95
float * grad_b
b's gradient scratch buffer.
Definition DirectKPPCLayer.h:79
size_t nextSize
Size of the layer above (0 marks a terminal layer).
Definition DirectKPPCLayer.h:37
float * GetBeliefs() noexcept override
Should return belief state z.
Definition DirectKPPCLayer.h:198
ActivationType activationType
This layer's activation type.
Definition DirectKPPCLayer.h:53
const float * GetErrors() const noexcept override
Should return errors e.
Definition DirectKPPCLayer.h:199
const float * GetBiases() const noexcept
Returns the bias vector, length nextSize.
Definition DirectKPPCLayer.h:207
void SetOptimizer(OptimizerType o) noexcept
Sets the optimizer for W. Call before Compile().
Definition DirectKPPCLayer.h:186
float CalculateState() noexcept override
Matches Layer's virtual interface exactly (always computes real energy).
Definition DirectKPPCLayer.h:153
DirectKPPCLayer * layerAbove
The next layer up, or nullptr if this is terminal.
Definition DirectKPPCLayer.h:49
void SetLambda(float lmbda) noexcept
Sets the weight decay coefficient.
Definition DirectKPPCLayer.h:196
bool isClamped
Whether ClampState() is currently active.
Definition DirectKPPCLayer.h:46
void UpdateState() noexcept override
Updates the states after calculation.
Definition DirectKPPCLayer.cpp:289
void SetLearningRate(float learningRate) noexcept
Sets the learning rate, propagating it to the optimizer state.
Definition DirectKPPCLayer.cpp:58
float * mu
Forward prediction buffer, shape [batchSize, nextSize].
Definition DirectKPPCLayer.h:73
int * tPsi_device
Device-resident mirror of tPsi.
Definition DirectKPPCLayer.h:91
float fl
Feedback rate for Psi.
Definition DirectKPPCLayer.h:43
size_t GetInputSize() const noexcept override
Should return input size.
Definition DirectKPPCLayer.h:210
float * proj
Scratch buffer: terminal error projected back through layerAbove's Psi, for DirectFeedbackUpdate()'s ...
Definition DirectKPPCLayer.h:76
OptimizerType optPsi
Optimizer for Psi.
Definition DirectKPPCLayer.h:59
bool muCacheValid
Whether cachedMu holds a valid, up-to-date value.
Definition DirectKPPCLayer.h:47
float * feedbackScratch
Scratch buffer for the feedback GEMM's output.
Definition DirectKPPCLayer.h:96
float * zF
Activated belief, phi(z), used as the forward GEMM's input.
Definition DirectKPPCLayer.h:94
OptimizerType opt
Optimizer for W/b.
Definition DirectKPPCLayer.h:58
float * biasGradScratch
nextSize-length scratch buffer for SumRows' output in UpdateWeights()'s SGD branch – SGD needs b += l...
Definition DirectKPPCLayer.h:105
void SetPsiOptimizer(OptimizerType o) noexcept
Sets the optimizer for Psi. Call before Compile().
Definition DirectKPPCLayer.h:188
float * W
Weight matrix, shape [nextSize, size].
Definition DirectKPPCLayer.h:71
float ir
Inference rate (Euler integration step size).
Definition DirectKPPCLayer.h:42
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
void(*)(float *RESTRICT, const float *RESTRICT, size_t) DerivativeFn2
Pointer to a two-buffer activation derivative: reads src, writes the derivative into dst,...
Definition ActivationDispatch.h:27
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
void(*)(float *, size_t, bool) DerivativeFn
Pointer to an in-place activation derivative: f(buf, n, activated).
Definition ActivationDispatch.h:20
void(*)(float *, size_t) ActivationFn
Pointer to an in-place activation function: f(buf, n).
Definition ActivationDispatch.h:18
A named, shaped view into a layer's weight/bias data, for ModelIO's save/load (see Layer::GetStateDic...
Definition Layer.h:34