Deepity
Ultra-fast, SIMD-accelerated Predictive Coding
Loading...
Searching...
No Matches
SimplePCLayer.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>
14
71
72namespace Deep
73{
74 class SimplePCNDiagnostics;
75
78 class SimplePCLayer : public Layer
79 {
80 public:
97 SimplePCLayer(size_t size, size_t nextSize, size_t batchSize = 1,
98 float learningRate = 1e-6f, float inferenceRate = 0.1f, float lmbda = 1e-2f,
99 void (*act)(float *, size_t) = relu,
100 void (*dAct)(float *, size_t, bool) = dRelu,
101 IComputeBackend *backend = nullptr);
102
117 SimplePCLayer(size_t size, size_t nextSize, size_t batchSize = 1,
118 float learningRate = 1e-6f, float inferenceRate = 0.1f, float lmbda = 1e-2f,
120 IComputeBackend *backend = nullptr);
121
135 float CalculateState(bool needEnergy = true) noexcept;
136
137 float CalculateState() noexcept override { return CalculateState(true); }
138
148 void UpdateState() noexcept override;
149
151 void UpdateWeights() noexcept override;
152
154 void Flush() noexcept override {}
155
159 void ClampState(const std::vector<float> &inputData) noexcept;
162 void UnclampState() noexcept;
163
165 bool IsClamped() const noexcept { return isClamped; }
166
169 float *GetBeliefs() noexcept override { return z; }
170
176 const float *GetMu() const noexcept { return mu; }
177
180 const float *GetErrors() const noexcept override { return e; }
182 size_t GetInputSize() const noexcept override { return size; }
185 size_t GetOutputSize() const noexcept override { return nextSize; }
187 size_t GetBatchSize() const noexcept override { return batchSize; }
188
190 const float *GetWeights() const noexcept { return W; }
192 float *GetWeights() noexcept { return W; }
194 const float *GetBiases() const noexcept { return b; }
196 float *GetBiases() noexcept { return b; }
197
199 float GetLearningRate() const noexcept { return lr; }
201 float GetInferenceRate() const noexcept { return ir; }
203 float GetLambda() const noexcept { return lmbda; }
204
207 void SetLearningRate(float lr) noexcept;
210 void SetInferenceRate(float ir) noexcept { this->ir = ir; }
213 void SetLambda(float l) noexcept { this->lmbda = l; }
214
218 void SetOptimizer(const OptimizerType o) noexcept { opt = o; }
219
231 void SetMuCacheThreshold(float threshold) noexcept { muCacheThreshold = threshold; }
234 float GetMuCacheThreshold() const noexcept { return muCacheThreshold; }
235
241 void ComputeMuOnly() noexcept;
242
246 void SetLayerAbove(SimplePCLayer *above) noexcept { layerAbove = above; }
250 void SetLayerBelow(SimplePCLayer *below) noexcept { layerBelow = below; }
251
254 void ResetState() noexcept;
255
260 const SimplePCLayer &GetLayerAbove() const noexcept { return *layerAbove; }
265 const SimplePCLayer &GetLayerBelow() const noexcept { return *layerBelow; }
266
270 void RandomizeWeights(std::mt19937 &twister, const char *distribution = "normal") noexcept;
271
273 ActivationType GetActivationType() const noexcept { return To_AType(activation); }
275 ActivationType GetDerivativeType() const noexcept { return To_AType(activationDerivative); }
276
281 size_t GetRequiredFloats() const noexcept;
289 template <typename ArenaT>
290 void BindMemory(ArenaT &arena);
291
292 private:
293 std::unique_ptr<MemoryArena> localArena;
294
303 using BackendDeleter = void (*)(IComputeBackend *);
304 std::unique_ptr<IComputeBackend, BackendDeleter> backend;
305
306 float *W;
307 float *b;
308 float *e;
309 float *z;
310
311 int batchSize;
312
313 float *mu;
314 float *cachedMu; // separate from mu -- mu gets mutated in-place by
315 // UpdateState() every step (converted to its
316 // derivative), so caching must copy a preserved
317 // value back INTO mu each skipped step, not just
318 // skip writing to mu entirely
319 float *zF; // this layer's OWN activated belief,
320 // phi(z) -- needed both for the forward
321 // GEMM (mu=zF@W+b) AND the weight
322 // gradient (dW uses zF, not raw z),
323 // matching ngc-learn's documented
324 // convention: mu_l = W_l . phi(z_{l-1})
325 float *zFDeriv; // SEPARATE scratch for f'(z), computed
326 // from RAW z (activated=false flag) --
327 // zF itself must stay clean/activated
328 // for the weight-gradient step
329 float *feedbackScratch; // own_state_size scratch for the raw
330 // feedback GEMM's output -- the f'(z)
331 // multiply applies ONLY to the feedback
332 // term, not the -e term already in
333 // dz_dt, so it can't accumulate directly
334 // into dz_dt via the GEMM itself
335 float lr;
336 float ir;
337 float lmbda;
338 bool isClamped = false;
339
340 int *t_device = nullptr;
341 float *lr_device = nullptr;
342
343 float muCacheThreshold = -1.0f; // -1 = disabled. 0 = exact clamped-only
344 // (today's validated behavior). >0 =
345 // approximate, extends to unclamped
346 // layers too.
347 bool muCacheValid = false; // true once mu computed at least once
348 // since the most recent ClampState()
349
350 SimplePCLayer *layerAbove;
351 SimplePCLayer *layerBelow;
352 ActivationFn activation;
353 DerivativeFn activationDerivative;
354 DerivativeFn2 activationDerivativeInto; // fused two-buffer derivative
355 // (dst, src, n), resolved once
356 // at construction alongside
357 // activation/activationDerivative
358 ActivationType activationType;
360 // @private Optional Adam weights
361 float *grad_W = nullptr;
362 float *grad_b = nullptr;
363 float *m_W = nullptr;
364 float *v_W = nullptr;
365 float *m_b = nullptr;
366 float *v_b = nullptr;
367 int t = 0;
368
370 };
371
372} // 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...
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
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
Predictive Coding layer without precision weighting – the simpler, unweighted-energy counterpart to D...
Definition SimplePCLayer.h:79
void UnclampState() noexcept
Releases a previous ClampState() call, allowing this layer's beliefs to update normally again.
Definition SimplePCLayer.cpp:245
void ClampState(const std::vector< float > &inputData) noexcept
Clamps this layer's beliefs to externally-provided data, preventing them from being updated by Update...
Definition SimplePCLayer.cpp:238
ActivationType GetDerivativeType() const noexcept
Returns this layer's configured activation-derivative type.
Definition SimplePCLayer.h:275
const float * GetWeights() const noexcept
Returns this layer's weight buffer.
Definition SimplePCLayer.h:190
void ResetState() noexcept
Resets this layer's beliefs/errors back to their initial values, without touching learned weights.
Definition SimplePCLayer.cpp:233
size_t GetRequiredFloats() const noexcept
Computes the total number of floats this layer requires from a MemoryArena (weights,...
Definition SimplePCLayer.cpp:247
float GetInferenceRate() const noexcept
Returns the inference rate (Euler integration step size).
Definition SimplePCLayer.h:201
ActivationType GetActivationType() const noexcept
Returns this layer's configured activation type.
Definition SimplePCLayer.h:273
float GetMuCacheThreshold() const noexcept
Returns the current mu-cache staleness threshold – see SetMuCacheThreshold() above.
Definition SimplePCLayer.h:234
void UpdateState() noexcept override
Computes the state derivatives for inference.
Definition SimplePCLayer.cpp:158
const float * GetMu() const noexcept
Returns a prediction buffer exposed specifically for forward-projection initialization (seeding the n...
Definition SimplePCLayer.h:176
friend class SimplePCNDiagnostics
Definition SimplePCLayer.h:369
void RandomizeWeights(std::mt19937 &twister, const char *distribution="normal") noexcept
Randomizes this layer's weights (and biases) in place.
Definition SimplePCLayer.cpp:83
const SimplePCLayer & GetLayerAbove() const noexcept
Returns the layer immediately above this one.
Definition SimplePCLayer.h:260
size_t GetOutputSize() const noexcept override
Returns this layer's outgoing prediction size (0 for a terminal layer).
Definition SimplePCLayer.h:185
void SetInferenceRate(float ir) noexcept
Sets the inference rate (Euler integration step size).
Definition SimplePCLayer.h:210
size_t GetInputSize() const noexcept override
Returns this layer's own belief size.
Definition SimplePCLayer.h:182
void SetOptimizer(const OptimizerType o) noexcept
Selects the optimizer used for weight updates (SGD or Adam). Adam's moment buffers are lazily allocat...
Definition SimplePCLayer.h:218
float CalculateState() noexcept override
Calculates the internal state of the layer.
Definition SimplePCLayer.h:137
void UpdateWeights() noexcept override
Computes weight updates via gradient descent, with L2 weight decay.
Definition SimplePCLayer.cpp:184
float * GetBeliefs() noexcept override
Returns this layer's belief buffer.
Definition SimplePCLayer.h:169
float * GetWeights() noexcept
Returns this layer's weight buffer.
Definition SimplePCLayer.h:192
void SetLayerAbove(SimplePCLayer *above) noexcept
Sets the layer immediately above this one in the network.
Definition SimplePCLayer.h:246
const float * GetBiases() const noexcept
Returns this layer's bias buffer.
Definition SimplePCLayer.h:194
void BindMemory(ArenaT &arena)
Binds this layer's weight/state/scratch buffers into the supplied arena. Must be called before any ot...
Definition SimplePCLayer.cpp:279
void ComputeMuOnly() noexcept
Computes only mu (forward prediction), skipping error/energy entirely. Extracted from CalculateState(...
Definition SimplePCLayer.cpp:133
SimplePCLayer(size_t size, size_t nextSize, size_t batchSize=1, float learningRate=1e-6f, float inferenceRate=0.1f, float lmbda=1e-2f, void(*act)(float *, size_t)=relu, void(*dAct)(float *, size_t, bool)=dRelu, IComputeBackend *backend=nullptr)
Constructor for a SimplePCLayer.
Definition SimplePCLayer.cpp:43
float GetLambda() const noexcept
Returns the weight-decay (L2 regularization) coefficient.
Definition SimplePCLayer.h:203
float GetLearningRate() const noexcept
Returns the learning rate used for weight updates.
Definition SimplePCLayer.h:199
void SetMuCacheThreshold(float threshold) noexcept
Sets the mu-cache staleness threshold: mu is recomputed only when ||z - z_at_last_recompute|| / (||z_...
Definition SimplePCLayer.h:231
bool IsClamped() const noexcept
Whether ClampState() is currently active on this layer.
Definition SimplePCLayer.h:165
const SimplePCLayer & GetLayerBelow() const noexcept
Returns the layer immediately below this one.
Definition SimplePCLayer.h:265
float * GetBiases() noexcept
Returns this layer's bias buffer.
Definition SimplePCLayer.h:196
size_t GetBatchSize() const noexcept override
Returns the batch size this layer was constructed with.
Definition SimplePCLayer.h:187
void SetLayerBelow(SimplePCLayer *below) noexcept
Sets the layer immediately below this one in the network.
Definition SimplePCLayer.h:250
void SetLearningRate(float lr) noexcept
Sets the learning rate used for weight updates.
Definition SimplePCLayer.cpp:274
void SetLambda(float l) noexcept
Sets the weight-decay (L2 regularization) coefficient.
Definition SimplePCLayer.h:213
void Flush() noexcept override
No-op; exists for Layer interface conformance.
Definition SimplePCLayer.h:154
const float * GetErrors() const noexcept override
Returns this layer's prediction-error buffer.
Definition SimplePCLayer.h:180
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
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
@ 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