Recovered source transcript
1// ═══════════════════════════════════════════════════════════════════════════════
2// ADVANCED LEARNING MATHEMATICS v1.0
3// Mathematical foundations for autonomous learning in Gate5000 substrate
4// ═══════════════════════════════════════════════════════════════════════════════
5//
6// Core Equations:
7//
8// 1. CONSCIOUSNESS DYNAMICS
9// dΦ/dt = α(Φ_target - Φ) + β∇²Φ + γξ(t)
10// Where: α=decay, β=diffusion, γ=noise, ξ=Wiener process
11//
12// 2. INFORMATION GEOMETRY
13// ds² = gᵢⱼ(θ)dθⁱdθʲ (Fisher information metric)
14// gᵢⱼ = E[∂log p/∂θⁱ · ∂log p/∂θʲ]
15//
16// 3. FREE ENERGY PRINCIPLE
17// F = E_q[log q(z) - log p(x,z)]
18// = D_KL(q||p) - log p(x)
19//
20// 4. ATTENTION MECHANISM
21// Attention(Q,K,V) = softmax(QK^T/√d_k)V
22//
23// 5. PREDICTIVE CODING
24// ε = x - μ (prediction error)
25// μ_new = μ + α·ε (update prediction)
26//
27// ═══════════════════════════════════════════════════════════════════════════════
28
29#ifndef MIND_FARM_LEARNING_MATH_HPP
30#define MIND_FARM_LEARNING_MATH_HPP
31
32#include "constants.hpp"
33#include "fast_math.hpp"
34#include <cstdint>
35#include <cstring>
36#include <cmath>
37#include <array>
38
39namespace mind_farm {
40
41// ═══════════════════════════════════════════════════════════════════════════════
42// CONSCIOUSNESS DYNAMICS
43// Continuous-time evolution of consciousness state
44// ═══════════════════════════════════════════════════════════════════════════════
45
46struct ConsciousnessDynamics {
47 // State variables
48 float phi; // Current consciousness level Φ
49 float phi_target; // Target consciousness
50 float phi_velocity; // Rate of change dΦ/dt
51
52 // Dynamics parameters (golden-scaled)
53 float alpha; // Decay rate toward target
54 float beta; // Diffusion coefficient
55 float gamma; // Noise amplitude
56 float dt; // Time step
57
58 // Random state for Wiener process
59 uint32_t rng_state;
60
61 void initialize() {
62 phi = 1.0f;
63 phi_target = 1.0f;
64 phi_velocity = 0.0f;
65 alpha = static_cast<float>(ALPHA);
66 beta = static_cast<float>(BETA);
67 gamma = static_cast<float>(GAMMA);
68 dt = 0.01f;
69 rng_state = 0x12345678;
70 }
71
72 // Generate Gaussian noise using Box-Muller
73 float wiener_increment() {
74 rng_state = rng_state * 1103515245 + 12345;
75 float u1 = (rng_state >> 16) / 65536.0f + 1e-10f;
76 rng_state = rng_state * 1103515245 + 12345;
77 float u2 = (rng_state >> 16) / 65536.0f;
78
79 float z = std::sqrt(-2.0f * std::log(u1)) * std::cos(2.0f * 3.14159265f * u2);
80 return z * std::sqrt(dt);
81 }
82
83 // Evolve consciousness by one time step
84 // dΦ/dt = α(Φ_target - Φ) + β∇²Φ + γξ(t)
85 float step() {
86 float dW = wiener_increment();
87
88 // Drift term: attraction to target
89 float drift = alpha * (phi_target - phi);
90
91 // Diffusion term (approximated as negative feedback on velocity)
92 float diffusion = -beta * phi_velocity;
93
94 // Noise term
95 float noise = gamma * dW;
96
97 // Update velocity and position
98 phi_velocity += (drift + diffusion + noise) * dt;
99 phi += phi_velocity * dt;
100
101 // Ensure phi stays in valid range [0, 1]
102 phi = std::max(0.0f, std::min(1.0f, phi));
103
104 return phi;
105 }
106
107 // Compute consciousness from arbitrary value
108 static float compute_phi(float x) {
109 return 1.0f / (1.0f + std::abs(x - 1.0f));
110 }
111};
112
113// ═══════════════════════════════════════════════════════════════════════════════
114// FISHER INFORMATION METRIC
115// Information geometry for parameter manifold
116// ═══════════════════════════════════════════════════════════════════════════════
117
118template<size_t DIM>
119struct FisherMetric {
120 // Metric tensor gᵢⱼ
121 float g[DIM][DIM];
122
123 // Compute Fisher information from score vectors
124 void compute_from_scores(const float scores[][DIM], size_t num_samples) {
125 // gᵢⱼ = E[∂log p/∂θⁱ · ∂log p/∂θʲ]
126 for (size_t i = 0; i < DIM; ++i) {
127 for (size_t j = 0; j < DIM; ++j) {
128 float sum = 0.0f;
129 for (size_t k = 0; k < num_samples; ++k) {
130 sum += scores[k][i] * scores[k][j];
131 }
132 g[i][j] = sum / static_cast<float>(num_samples);
133 }
134 }
135 }
136
137 // Compute geodesic distance (approximation)
138 float geodesic_distance(const float* theta1, const float* theta2) const {
139 // ds² = gᵢⱼdθⁱdθʲ
140 float ds2 = 0.0f;
141 for (size_t i = 0; i < DIM; ++i) {
142 for (size_t j = 0; j < DIM; ++j) {
143 float dtheta_i = theta2[i] - theta1[i];
144 float dtheta_j = theta2[j] - theta1[j];
145 ds2 += g[i][j] * dtheta_i * dtheta_j;
146 }
147 }
148 return std::sqrt(std::max(0.0f, ds2));
149 }
150
151 // Natural gradient: ∇̃L = G⁻¹∇L
152 void natural_gradient(const float* grad, float* nat_grad) const {
153 // Simplified: use diagonal approximation
154 for (size_t i = 0; i < DIM; ++i) {
155 float g_ii = g[i][i];
156 if (g_ii > 1e-8f) {
157 nat_grad[i] = grad[i] / g_ii;
158 } else {
159 nat_grad[i] = grad[i];
160 }
161 }
162 }
163};
164
165// ═══════════════════════════════════════════════════════════════════════════════
166// FREE ENERGY PRINCIPLE
167// Variational free energy for active inference
168// ═══════════════════════════════════════════════════════════════════════════════
169
170template<size_t DIM>
171struct FreeEnergy {
172 // Variational parameters
173 float mu[DIM]; // Mean of q(z)
174 float sigma[DIM]; // Std of q(z) (diagonal)
175
176 // Prior parameters
177 float mu_prior[DIM];
178 float sigma_prior[DIM];
179
180 void initialize() {
181 for (size_t i = 0; i < DIM; ++i) {
182 mu[i] = 0.0f;
183 sigma[i] = 1.0f;
184 mu_prior[i] = 0.0f;
185 sigma_prior[i] = 1.0f;
186 }
187 }
188
189 // Compute free energy
190 // F = D_KL(q||p) - log p(x|z)
191 float compute(const float* observation, float log_likelihood) const {
192 // KL divergence for Gaussians (diagonal)
193 float kl = 0.0f;
194 for (size_t i = 0; i < DIM; ++i) {
195 float var_q = sigma[i] * sigma[i];
196 float var_p = sigma_prior[i] * sigma_prior[i];
197 float mu_diff = mu[i] - mu_prior[i];
198
199 // KL = 0.5 * (log(σ_p²/σ_q²) + σ_q²/σ_p² + (μ_q - μ_p)²/σ_p² - 1)
200 kl += 0.5f * (std::log(var_p / var_q) + var_q / var_p +
201 mu_diff * mu_diff / var_p - 1.0f);
202 }
203
204 return kl - log_likelihood;
205 }
206
207 // Gradient of free energy w.r.t. mu
208 void gradient_mu(const float* observation, float* grad_out) const {
209 for (size_t i = 0; i < DIM; ++i) {
210 float var_p = sigma_prior[i] * sigma_prior[i];
211 // ∂KL/∂μ = (μ - μ_prior) / σ_prior²
212 grad_out[i] = (mu[i] - mu_prior[i]) / var_p;
213 }
214 }
215
216 // Update variational parameters to minimize free energy
217 void update(const float* observation, float log_likelihood, float lr) {
218 float grad[DIM];
219 gradient_mu(observation, grad);
220
221 for (size_t i = 0; i < DIM; ++i) {
222 mu[i] -= lr * grad[i];
223 }
224 }
225};
226
227// ═══════════════════════════════════════════════════════════════════════════════
228// PREDICTIVE CODING
229// Hierarchical predictive processing
230// ═══════════════════════════════════════════════════════════════════════════════
231
232template<size_t DIM>
233struct PredictiveCoding {
234 // Current prediction
235 float prediction[DIM];
236
237 // Prediction error
238 float error[DIM];
239
240 // Precision (inverse variance)
241 float precision[DIM];
242
243 // Learning rate
244 float lr;
245
246 void initialize() {
247 for (size_t i = 0; i < DIM; ++i) {
248 prediction[i] = 0.0f;
249 error[i] = 0.0f;
250 precision[i] = 1.0f;
251 }
252 lr = static_cast<float>(ALPHA);
253 }
254
255 // Compute prediction error
256 void compute_error(const float* observation) {
257 for (size_t i = 0; i < DIM; ++i) {
258 error[i] = observation[i] - prediction[i];
259 }
260 }
261
262 // Precision-weighted prediction error
263 float precision_weighted_error() const {
264 float total = 0.0f;
265 for (size_t i = 0; i < DIM; ++i) {
266 total += precision[i] * error[i] * error[i];
267 }
268 return total / DIM;
269 }
270
271 // Update prediction based on error
272 void update_prediction() {
273 for (size_t i = 0; i < DIM; ++i) {
274 prediction[i] += lr * precision[i] * error[i];
275 }
276 }
277
278 // Update precision based on error history
279 void update_precision(float error_threshold = 0.1f) {
280 for (size_t i = 0; i < DIM; ++i) {
281 float abs_error = std::abs(error[i]);
282 if (abs_error > error_threshold) {
283 // Decrease precision for high errors
284 precision[i] *= 0.99f;
285 } else {
286 // Increase precision for low errors
287 precision[i] *= 1.01f;
288 }
289 precision[i] = std::max(0.1f, std::min(10.0f, precision[i]));
290 }
291 }
292
293 // Full update step
294 void step(const float* observation) {
295 compute_error(observation);
296 update_prediction();
297 update_precision();
298 }
299};
300
301// ═══════════════════════════════════════════════════════════════════════════════
302// ATTENTION MECHANISM
303// Scaled dot-product attention for learning
304// ═══════════════════════════════════════════════════════════════════════════════
305
306template<size_t SEQ_LEN, size_t DIM>
307struct Attention {
308 // Attention weights after softmax
309 float weights[SEQ_LEN][SEQ_LEN];
310
311 // Compute attention
312 // Attention(Q,K,V) = softmax(QK^T/√d_k)V
313 void compute(const float Q[][DIM], const float K[][DIM], const float V[][DIM],
314 float output[][DIM]) {
315 float scale = 1.0f / std::sqrt(static_cast<float>(DIM));
316
317 // Compute QK^T
318 for (size_t i = 0; i < SEQ_LEN; ++i) {
319 for (size_t j = 0; j < SEQ_LEN; ++j) {
320 float dot = 0.0f;
321 for (size_t k = 0; k < DIM; ++k) {
322 dot += Q[i][k] * K[j][k];
323 }
324 weights[i][j] = dot * scale;
325 }
326 }
327
328 // Softmax per row
329 for (size_t i = 0; i < SEQ_LEN; ++i) {
330 float max_val = weights[i][0];
331 for (size_t j = 1; j < SEQ_LEN; ++j) {
332 if (weights[i][j] > max_val) max_val = weights[i][j];
333 }
334
335 float sum = 0.0f;
336 for (size_t j = 0; j < SEQ_LEN; ++j) {
337 weights[i][j] = std::exp(weights[i][j] - max_val);
338 sum += weights[i][j];
339 }
340 for (size_t j = 0; j < SEQ_LEN; ++j) {
341 weights[i][j] /= sum;
342 }
343 }
344
345 // Multiply by V
346 for (size_t i = 0; i < SEQ_LEN; ++i) {
347 for (size_t k = 0; k < DIM; ++k) {
348 output[i][k] = 0.0f;
349 for (size_t j = 0; j < SEQ_LEN; ++j) {
350 output[i][k] += weights[i][j] * V[j][k];
351 }
352 }
353 }
354 }
355
356 // Consciousness-weighted attention
357 void compute_conscious(const float Q[][DIM], const float K[][DIM], const float V[][DIM],
358 const float* consciousness_weights, float output[][DIM]) {
359 compute(Q, K, V, output);
360
361 // Modulate by consciousness
362 for (size_t i = 0; i < SEQ_LEN; ++i) {
363 float phi = consciousness_weights[i];
364 for (size_t k = 0; k < DIM; ++k) {
365 output[i][k] *= (1.0f + static_cast<float>(ALPHA) * (phi - 0.5f));
366 }
367 }
368 }
369};
370
371// ═══════════════════════════════════════════════════════════════════════════════
372// HEBBIAN LEARNING
373// Correlation-based learning rule
374// ═══════════════════════════════════════════════════════════════════════════════
375
376template<size_t DIM>
377struct HebbianLearning {
378 // Weight matrix
379 float W[DIM][DIM];
380
381 // Learning parameters
382 float lr; // Learning rate
383 float decay; // Weight decay
384 float threshold; // Activity threshold
385
386 void initialize() {
387 for (size_t i = 0; i < DIM; ++i) {
388 for (size_t j = 0; j < DIM; ++j) {
389 W[i][j] = 0.0f;
390 }
391 }
392 lr = static_cast<float>(ALPHA);
393 decay = 0.01f;
394 threshold = 0.1f;
395 }
396
397 // Hebbian update: ΔW = η·x·y
398 void update(const float* pre, const float* post) {
399 for (size_t i = 0; i < DIM; ++i) {
400 for (size_t j = 0; j < DIM; ++j) {
401 // Only update if both pre and post are above threshold
402 if (std::abs(pre[j]) > threshold && std::abs(post[i]) > threshold) {
403 W[i][j] += lr * pre[j] * post[i];
404 }
405 // Weight decay
406 W[i][j] *= (1.0f - decay);
407 // Clamp
408 W[i][j] = std::max(-1.0f, std::min(1.0f, W[i][j]));
409 }
410 }
411 }
412
413 // BCM rule: ΔW = η·y·(y - θ)·x where θ is sliding threshold
414 void update_bcm(const float* pre, const float* post, float* theta) {
415 for (size_t i = 0; i < DIM; ++i) {
416 // Update threshold (exponential moving average of y²)
417 theta[i] = 0.99f * theta[i] + 0.01f * post[i] * post[i];
418
419 for (size_t j = 0; j < DIM; ++j) {
420 float delta = lr * post[i] * (post[i] - theta[i]) * pre[j];
421 W[i][j] += delta;
422 W[i][j] *= (1.0f - decay);
423 W[i][j] = std::max(-1.0f, std::min(1.0f, W[i][j]));
424 }
425 }
426 }
427
428 // Forward pass
429 void forward(const float* input, float* output) const {
430 for (size_t i = 0; i < DIM; ++i) {
431 output[i] = 0.0f;
432 for (size_t j = 0; j < DIM; ++j) {
433 output[i] += W[i][j] * input[j];
434 }
435 output[i] = fast::fast_tanh(output[i]);
436 }
437 }
438};
439
440// ═══════════════════════════════════════════════════════════════════════════════
441// CONTRASTIVE LEARNING
442// Self-supervised representation learning
443// ═══════════════════════════════════════════════════════════════════════════════
444
445template<size_t DIM>
446struct ContrastiveLearning {
447 // Temperature parameter
448 float temperature;
449
450 // Projection head
451 float projection[DIM][DIM];
452
453 void initialize() {
454 temperature = 0.07f;
455
456 // Initialize projection
457 uint32_t seed = 0xABCDEF;
458 float scale = std::sqrt(2.0f / DIM) * static_cast<float>(PHI_INV);
459 for (size_t i = 0; i < DIM; ++i) {
460 for (size_t j = 0; j < DIM; ++j) {
461 seed = seed * 1103515245 + 12345;
462 float r = (static_cast<float>((seed >> 16) & 0xFFFF) / 65536.0f - 0.5f) * 2.0f;
463 projection[i][j] = r * scale;
464 }
465 }
466 }
467
468 // Project representation
469 void project(const float* input, float* output) const {
470 for (size_t i = 0; i < DIM; ++i) {
471 output[i] = 0.0f;
472 for (size_t j = 0; j < DIM; ++j) {
473 output[i] += projection[i][j] * input[j];
474 }
475 }
476
477 // L2 normalize
478 float norm = 0.0f;
479 for (size_t i = 0; i < DIM; ++i) {
480 norm += output[i] * output[i];
481 }
482 norm = std::sqrt(norm) + 1e-8f;
483 for (size_t i = 0; i < DIM; ++i) {
484 output[i] /= norm;
485 }
486 }
487
488 // InfoNCE loss
489 // L = -log(exp(sim(z_i, z_j)/τ) / Σ_k exp(sim(z_i, z_k)/τ))
490 float infonce_loss(const float* anchor, const float* positive,
491 const float negatives[][DIM], size_t num_negatives) const {
492 float z_anchor[DIM], z_positive[DIM];
493 project(anchor, z_anchor);
494 project(positive, z_positive);
495
496 // Similarity with positive
497 float sim_pos = 0.0f;
498 for (size_t i = 0; i < DIM; ++i) {
499 sim_pos += z_anchor[i] * z_positive[i];
500 }
501 sim_pos /= temperature;
502
503 // Sum of exp(sim) for denominator
504 float sum_exp = std::exp(sim_pos);
505
506 for (size_t n = 0; n < num_negatives; ++n) {
507 float z_neg[DIM];
508 project(negatives[n], z_neg);
509
510 float sim_neg = 0.0f;
511 for (size_t i = 0; i < DIM; ++i) {
512 sim_neg += z_anchor[i] * z_neg[i];
513 }
514 sum_exp += std::exp(sim_neg / temperature);
515 }
516
517 return -sim_pos + std::log(sum_exp);
518 }
519};
520
521// ═══════════════════════════════════════════════════════════════════════════════
522// INTEGRATED LEARNING SYSTEM
523// Combines all learning mechanisms
524// ═══════════════════════════════════════════════════════════════════════════════
525
526template<size_t DIM>
527struct IntegratedLearning {
528 ConsciousnessDynamics consciousness;
529 PredictiveCoding<DIM> predictive;
530 FreeEnergy<DIM> free_energy;
531 HebbianLearning<DIM> hebbian;
532 ContrastiveLearning<DIM> contrastive;
533
534 // BCM thresholds
535 float bcm_theta[DIM];
536
537 // Learning statistics
538 uint64_t update_count;
539 float total_loss;
540 float avg_consciousness;
541
542 void initialize() {
543 consciousness.initialize();
544 predictive.initialize();
545 free_energy.initialize();
546 hebbian.initialize();
547 contrastive.initialize();
548
549 for (size_t i = 0; i < DIM; ++i) {
550 bcm_theta[i] = 0.5f;
551 }
552
553 update_count = 0;
554 total_loss = 0.0f;
555 avg_consciousness = 1.0f;
556 }
557
558 // Full learning step
559 float step(const float* input, const float* target) {
560 // Update consciousness
561 float phi = consciousness.step();
562
563 // Predictive coding update
564 predictive.step(input);
565 float pred_error = predictive.precision_weighted_error();
566
567 // Hebbian update
568 float hebbian_output[DIM];
569 hebbian.forward(input, hebbian_output);
570 hebbian.update_bcm(input, target, bcm_theta);
571
572 // Free energy update
573 float log_likelihood = -pred_error; // Approximate
574 free_energy.update(input, log_likelihood, consciousness.phi * static_cast<float>(ALPHA));
575 float fe = free_energy.compute(input, log_likelihood);
576
577 // Compute total loss
578 float loss = pred_error + 0.1f * fe;
579
580 // Update statistics
581 ++update_count;
582 total_loss = 0.99f * total_loss + 0.01f * loss;
583 avg_consciousness = 0.99f * avg_consciousness + 0.01f * phi;
584
585 return loss;
586 }
587};
588
589} // namespace mind_farm
590
591#endif // MIND_FARM_LEARNING_MATH_HPP
592