Deepity
Ultra-fast, SIMD-accelerated Predictive Coding
Loading...
Searching...
No Matches
DiscriminativePCLayer.h
Go to the documentation of this file.
1#pragma once
2
3#include <vector>
4#include <stdexcept>
5#include <random>
6#include <memory>
7#include <cstdlib>
12
32
33namespace Deep
34{
35 class PCNDiagnostics;
50 {
51 public:
62 DiscriminativePCLayer(int size, int nextSize, int batchSize = 1,
63 float learningRate = 1e-6, float inferenceRate = 0.1f, float precisionRate = 0.01f, float lmbda = 1e-2f,
64 void (*act)(float *, size_t) = relu,
65 void (*dAct)(float *, size_t, bool) = dRelu);
66
78 DiscriminativePCLayer(int size, int nextSize, int batchSize = 1,
79 float learningRate = 1e-6, float inferenceRate = 0.1f, float precisionRate = 0.01f, float lmbda = 1e-2f,
81
88 float CalculateState() noexcept override;
89
95 void UpdateState() noexcept override;
96
102 void UpdateWeights() noexcept override;
103
106 void UpdatePrecision() noexcept;
107
109 void Flush() noexcept override {} // no buffer
110
112 void ResyncLogPrecision() noexcept;
113
116 void ClampState(const std::vector<float> &inputData) noexcept;
118 void UnclampState() noexcept;
119
122 float *GetBeliefs() noexcept override { return z; }
125 const float *GetErrors() const noexcept override { return e; }
126
129 const float *GetMu() const noexcept { return mu; }
132 size_t GetInputSize() const noexcept override { return size; }
135 size_t GetOutputSize() const noexcept override { return nextSize; }
138 size_t GetBatchSize() const noexcept override { return batchSize; }
139
142 const float *GetWeights() const noexcept { return W; }
145 float *GetWeights() noexcept { return W; }
148 const float *GetBiases() const noexcept { return b; }
151 float *GetBiases() noexcept { return b; }
152
155 const float *GetPrecisions() const { return p; }
156
159 float GetLearningRate() const noexcept { return lr; }
162 float GetInferenceRate() const noexcept { return ir; }
165 float GetPrecisionRate() const noexcept { return pr; }
168 float GetLambda() const noexcept { return lmbda; }
169
172 void SetLearningRate(float lr) noexcept { this->lr = lr; }
175 void SetInferenceRate(float ir) noexcept { this->ir = ir; }
178 void SetPrecisionRate(float pr) noexcept { this->pr = pr; }
181 void SetLambda(float l) noexcept { this->lmbda = l; }
184 void SetOptimizer(OptimizerType o) noexcept { this->opt = o; }
185
188 void SetLayerAbove(DiscriminativePCLayer *above) noexcept { layerAbove = above; }
191 void SetLayerBelow(DiscriminativePCLayer *below) noexcept { layerBelow = below; }
192
194 void ResetState() noexcept;
195
198 const DiscriminativePCLayer &GetLayerAbove() const noexcept { return *layerAbove; }
201 const DiscriminativePCLayer &GetLayerBelow() const noexcept { return *layerBelow; }
202
205 void RandomizeWeights(std::mt19937 &twister) noexcept;
206
209 ActivationType GetActivationType() const noexcept { return To_AType(activation); }
212 ActivationType GetDerivativeType() const noexcept { return To_AType(activationDerivative); }
213
215 size_t GetRequiredFloats() const noexcept;
216
218 void BindMemory(MemoryArena &arena);
219
225 void ComputeMuOnly() noexcept;
226
227 private:
229 std::unique_ptr<MemoryArena> localArena;
231 float *W;
233 float *b;
235 float *e;
237 float *z;
239 float *p;
241 float *log_p;
242
246 float *cachedMu = nullptr;
248 bool muCacheValid = false;
249
252 float *zF = nullptr;
255 float *zFDeriv = nullptr;
258 float *feedbackScratch = nullptr;
259
261 int batchSize;
262
263 // @internal --- For inference ---
265 float *mu;
267 float *dz_dt;
269 float *bottom_up;
270 // ------
271
273 float lr;
275 float ir;
277 float pr;
279 float lmbda;
281 bool isClamped = false;
282
286 int t = 0;
288 float *grad_W = nullptr;
290 float *m_W = nullptr;
292 float *v_W = nullptr;
294 float *grad_b = nullptr;
296 float *m_b = nullptr;
298 float *v_b = nullptr;
299
301 DiscriminativePCLayer *layerAbove;
303 DiscriminativePCLayer *layerBelow;
305 ActivationFn activation;
307 DerivativeFn activationDerivative;
308
310 ActivationType activationType;
311
312 friend class PCNDiagnostics;
313 };
314
315} // namespace Deep
316
317/*
318 * MHSA USING PCNs:
319 * In a standard Transformer, Multi-Head Self-Attention (MHSA) computes Queries, Keys,
320 * and Values in a rigid, one-shot forward pass to route token context. If implemented
321 * using a PCN, the attention scores and context vectors would become dynamic latent
322 * states (z). When a sequence is input, the attention routing wouldn't be calculated
323 * instantly; instead, it would iteratively settle over artificial time. The network
324 * would adjust its attention states to minimize the prediction error between the
325 * bottom-up token data and the top-down expectations from higher layers. The Q, K,
326 * and V projection matrices would serve as the local weights (W) for this mechanism,
327 * and would be updated entirely in parallel via local Hebbian rules once the attention
328 * routing reached its minimum-energy equilibrium.
329 */
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-...
Virtual Layer.
A 64-byte-aligned bump-pointer allocator over a single heap-allocated block, used to pack every layer...
Definition DiscriminativePCLayer.h:50
void SetLambda(float l) noexcept
Sets the weight-decay (L2 regularization) coefficient.
Definition DiscriminativePCLayer.h:181
ActivationType GetActivationType() const noexcept
Returns this layer's configured activation type.
Definition DiscriminativePCLayer.h:209
void ClampState(const std::vector< float > &inputData) noexcept
Clamps the layer to the input data.
Definition DiscriminativePCLayer.cpp:481
DiscriminativePCLayer(int size, int nextSize, int batchSize=1, float learningRate=1e-6, float inferenceRate=0.1f, float precisionRate=0.01f, float lmbda=1e-2f, void(*act)(float *, size_t)=relu, void(*dAct)(float *, size_t, bool)=dRelu)
Constructor for a Deepity Layer.
Definition DiscriminativePCLayer.cpp:21
const float * GetErrors() const noexcept override
Returns errors.
Definition DiscriminativePCLayer.h:125
friend class PCNDiagnostics
Definition DiscriminativePCLayer.h:312
void UpdateWeights() noexcept override
Computes weight updates via gradient descent, with L2 weight decay.
Definition DiscriminativePCLayer.cpp:273
void UpdateState() noexcept override
Computes the state derivatives for inference.
Definition DiscriminativePCLayer.cpp:220
float GetLearningRate() const noexcept
Returns the learning rate used for weight updates.
Definition DiscriminativePCLayer.h:159
const float * GetPrecisions() const
Returns a read-only version of the stored precisions.
Definition DiscriminativePCLayer.h:155
float GetPrecisionRate() const noexcept
Returns the learning rate used for precision updates.
Definition DiscriminativePCLayer.h:165
float CalculateState() noexcept override
Calculates the total network energy state.
Definition DiscriminativePCLayer.cpp:73
size_t GetOutputSize() const noexcept override
Returns nextSize (output size).
Definition DiscriminativePCLayer.h:135
const DiscriminativePCLayer & GetLayerBelow() const noexcept
Gets const pointer to layer below.
Definition DiscriminativePCLayer.h:201
float GetInferenceRate() const noexcept
Returns the inference rate used for state updates.
Definition DiscriminativePCLayer.h:162
const float * GetMu() const noexcept
Returns this layer's outgoing prediction buffer.
Definition DiscriminativePCLayer.h:129
void Flush() noexcept override
Does nothing; exists for class extension.
Definition DiscriminativePCLayer.h:109
float * GetBiases() noexcept
Returns a mutable version of the stored biases.
Definition DiscriminativePCLayer.h:151
void SetLayerAbove(DiscriminativePCLayer *above) noexcept
Ties this layer to one above it.
Definition DiscriminativePCLayer.h:188
void ResetState() noexcept
Resets 'z' (beliefs) to 0.
Definition DiscriminativePCLayer.cpp:475
size_t GetInputSize() const noexcept override
Returns size (input size).
Definition DiscriminativePCLayer.h:132
void ResyncLogPrecision() noexcept
Recomputes log of precision if it falls behind.
Definition DiscriminativePCLayer.cpp:494
void ComputeMuOnly() noexcept
Computes only mu (forward prediction), skipping error and energy computation entirely....
Definition DiscriminativePCLayer.cpp:190
void UpdatePrecision() noexcept
Updates this layer's precision weighting based on the current prediction error.
Definition DiscriminativePCLayer.cpp:342
void SetPrecisionRate(float pr) noexcept
Sets the learning rate used for precision updates.
Definition DiscriminativePCLayer.h:178
void SetInferenceRate(float ir) noexcept
Sets the inference rate used for state updates.
Definition DiscriminativePCLayer.h:175
float * GetWeights() noexcept
Returns a mutable version of the stored weights.
Definition DiscriminativePCLayer.h:145
void SetLayerBelow(DiscriminativePCLayer *below) noexcept
Ties this layer to one below it.
Definition DiscriminativePCLayer.h:191
void RandomizeWeights(std::mt19937 &twister) noexcept
Makes the weights W randomized to [0.0, 0.1] using an OpenMP-parallelized uniform real distribution.
Definition DiscriminativePCLayer.cpp:52
float * GetBeliefs() noexcept override
Returns beliefs.
Definition DiscriminativePCLayer.h:122
void BindMemory(MemoryArena &arena)
Binds all tensor pointers to the contiguous memory block.
Definition DiscriminativePCLayer.cpp:529
void SetOptimizer(OptimizerType o) noexcept
Selects the optimizer used for weight updates.
Definition DiscriminativePCLayer.h:184
const DiscriminativePCLayer & GetLayerAbove() const noexcept
Gets const pointer to layer above.
Definition DiscriminativePCLayer.h:198
void UnclampState() noexcept
Unclamps the layer to the input data.
Definition DiscriminativePCLayer.cpp:489
float GetLambda() const noexcept
Returns the weight-decay (L2 regularization) coefficient.
Definition DiscriminativePCLayer.h:168
const float * GetWeights() const noexcept
Returns a read-only version of the stored weights.
Definition DiscriminativePCLayer.h:142
ActivationType GetDerivativeType() const noexcept
Returns this layer's configured activation-derivative type.
Definition DiscriminativePCLayer.h:212
const float * GetBiases() const noexcept
Returns a read-only version of the stored biases.
Definition DiscriminativePCLayer.h:148
void SetLearningRate(float lr) noexcept
Sets the learning rate used for weight updates.
Definition DiscriminativePCLayer.h:172
size_t GetRequiredFloats() const noexcept
Calculates exact float count required by this layer's architecture.
Definition DiscriminativePCLayer.cpp:500
size_t GetBatchSize() const noexcept override
Returns batchSize.
Definition DiscriminativePCLayer.h:138
A deepity layer virtual class.
Definition Layer.h:40
size_t nextSize
Size of output.
Definition Layer.h:76
size_t size
Size of input.
Definition Layer.h:74
A 64-byte-aligned bump-pointer allocator over a single contiguous block of host memory....
Definition MemoryArena.h:141
This file exists to provide both Tensor.h and IComputeBackend.h with device types without introducing...
Definition Backend.cpp:10
static ActivationType To_AType(ActivationFn fn)
Reverse lookup of To_Fn(): maps a function pointer back to its ActivationType, by identity comparison...
Definition ActivationDispatch.h:152
ActivationType
Identifies an activation function or its derivative, for dispatch tables and layer/backend APIs that ...
Definition ActivationType.h:25
@ RELU
Definition ActivationType.h:26
@ dRELU
Definition ActivationType.h:27
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
static void relu(float *, size_t) noexcept
See Relu.h.
void(*)(float *, size_t, bool) DerivativeFn
Pointer to an in-place activation derivative: f(buf, n, activated).
Definition ActivationDispatch.h:20
static void dRelu(float *, size_t, bool) noexcept
See Relu.h.
void(*)(float *, size_t) ActivationFn
Pointer to an in-place activation function: f(buf, n).
Definition ActivationDispatch.h:18