@aleph-ai/tinyaleph 1.5.6 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/core/alexander-module.js +1469 -0
  2. package/core/arithmetic-link-kernel.js +1338 -0
  3. package/core/index.js +95 -2
  4. package/examples/01-hello-world.js +69 -0
  5. package/examples/02-basic-hash.js +90 -0
  6. package/examples/02-observer-stack.js +385 -0
  7. package/examples/03-quantum-coin.js +136 -0
  8. package/examples/05-symbolic-resonance.js +146 -0
  9. package/examples/06-symbol-database.js +150 -0
  10. package/examples/07-semantic-inference.js +223 -0
  11. package/examples/08-compound-symbols.js +219 -0
  12. package/examples/README.md +170 -0
  13. package/examples/ai/01-embeddings.js +155 -0
  14. package/examples/ai/02-semantic-memory.js +243 -0
  15. package/examples/ai/03-reasoning.js +243 -0
  16. package/examples/ai/04-knowledge-graph.js +279 -0
  17. package/examples/ai/05-llm-integration.js +333 -0
  18. package/examples/ai/06-agent.js +294 -0
  19. package/examples/ai/07-hybrid-ai.js +223 -0
  20. package/examples/ai/08-entropy-reasoning.js +259 -0
  21. package/examples/ai/09-concept-learning.js +271 -0
  22. package/examples/ai/10-prompt-primes.js +312 -0
  23. package/examples/ai/11-rag.js +332 -0
  24. package/examples/ai/12-neuro-symbolic.js +321 -0
  25. package/examples/ai/README.md +80 -0
  26. package/examples/arithmetic-topology/01-legendre-symbol.js +78 -0
  27. package/examples/arithmetic-topology/02-redei-symbol.js +126 -0
  28. package/examples/arithmetic-topology/03-alk-kuramoto.js +138 -0
  29. package/examples/arithmetic-topology/04-alexander-module.js +117 -0
  30. package/examples/arithmetic-topology/05-signature-memory.js +118 -0
  31. package/examples/arithmetic-topology/README.md +291 -0
  32. package/examples/bioinformatics/01-dna-encoding.js +108 -0
  33. package/examples/bioinformatics/02-central-dogma.js +162 -0
  34. package/examples/bioinformatics/03-protein-folding.js +206 -0
  35. package/examples/bioinformatics/04-dna-computing.js +192 -0
  36. package/examples/bioinformatics/05-molecular-binding.js +209 -0
  37. package/examples/chat.js +105 -0
  38. package/examples/crt-homology/01-residue-encoding.js +87 -0
  39. package/examples/crt-homology/02-birkhoff-attention.js +100 -0
  40. package/examples/crt-homology/03-homology-loss.js +132 -0
  41. package/examples/crt-homology/04-crt-resoformer.js +132 -0
  42. package/examples/crt-homology/README.md +67 -0
  43. package/examples/crypto/01-password-hash.js +210 -0
  44. package/examples/crypto/02-key-derivation.js +210 -0
  45. package/examples/crypto/03-hmac.js +229 -0
  46. package/examples/crypto/04-file-integrity.js +263 -0
  47. package/examples/crypto/05-content-hash.js +263 -0
  48. package/examples/crypto/README.md +99 -0
  49. package/examples/demo-modular.js +223 -0
  50. package/examples/demo-two-layer.js +196 -0
  51. package/examples/discrete/01-integer-sine-table.js +120 -0
  52. package/examples/discrete/02-codebook-tunneling.js +118 -0
  53. package/examples/discrete/03-canonical-fusion.js +135 -0
  54. package/examples/discrete/04-tick-gate.js +139 -0
  55. package/examples/discrete/README.md +142 -0
  56. package/examples/formal-semantics/01-typed-terms.js +156 -0
  57. package/examples/formal-semantics/02-reduction.js +202 -0
  58. package/examples/formal-semantics/03-lambda-translation.js +206 -0
  59. package/examples/formal-semantics/04-enochian-language.js +257 -0
  60. package/examples/formal-semantics/README.md +98 -0
  61. package/examples/math/01-quaternions.js +237 -0
  62. package/examples/math/02-octonions.js +192 -0
  63. package/examples/math/03-prime-factorization.js +215 -0
  64. package/examples/math/04-vector-spaces.js +210 -0
  65. package/examples/math/05-gaussian-primes.js +234 -0
  66. package/examples/math/README.md +93 -0
  67. package/examples/physics/01-oscillator.js +177 -0
  68. package/examples/physics/02-lyapunov.js +201 -0
  69. package/examples/physics/03-collapse.js +183 -0
  70. package/examples/physics/04-kuramoto.js +212 -0
  71. package/examples/physics/05-entropy.js +226 -0
  72. package/examples/physics/05-sync-models.js +298 -0
  73. package/examples/physics/06-primeon-ladder.js +233 -0
  74. package/examples/physics/07-kuramoto-coupled-ladder.js +298 -0
  75. package/examples/physics/README.md +126 -0
  76. package/examples/resonance/01-prime-hilbert-space.js +140 -0
  77. package/examples/resonance/02-prime-resonance-network.js +221 -0
  78. package/examples/resonance/03-resoformer.js +349 -0
  79. package/examples/resonance/04-resoformer-training.js +329 -0
  80. package/examples/resonance/05-language-model.js +484 -0
  81. package/examples/resonance/README.md +238 -0
  82. package/examples/run-examples.js +417 -0
  83. package/examples/scientific/01-single-qubit.js +185 -0
  84. package/examples/scientific/02-two-qubit.js +209 -0
  85. package/examples/scientific/03-quantum-circuits.js +270 -0
  86. package/examples/scientific/04-measurement.js +229 -0
  87. package/examples/scientific/05-algorithms.js +245 -0
  88. package/examples/scientific/06-random.js +225 -0
  89. package/examples/scientific/07-wavefunction.js +192 -0
  90. package/examples/scientific/README.md +118 -0
  91. package/examples/semantic/01-vocabulary.js +186 -0
  92. package/examples/semantic/02-similarity.js +263 -0
  93. package/examples/semantic/03-word-algebra.js +295 -0
  94. package/examples/semantic/04-clustering.js +348 -0
  95. package/examples/semantic/05-classification.js +386 -0
  96. package/examples/semantic/06-dna-encoding.js +228 -0
  97. package/examples/semantic/07-search.js +304 -0
  98. package/examples/semantic/08-qa-system.js +278 -0
  99. package/examples/semantic/README.md +116 -0
  100. package/examples/topology/01-108-invariant.js +81 -0
  101. package/examples/topology/02-trefoil-constants.js +112 -0
  102. package/examples/topology/03-gauge-symmetry.js +112 -0
  103. package/examples/topology/04-free-energy-dynamics.js +124 -0
  104. package/examples/topology/README.md +129 -0
  105. package/index.js +32 -0
  106. package/modular.js +63 -2
  107. package/observer/agency.js +885 -0
  108. package/observer/assays.js +973 -0
  109. package/observer/boundary.js +1155 -0
  110. package/observer/entanglement.js +673 -0
  111. package/observer/hqe.js +1465 -0
  112. package/observer/index.js +158 -0
  113. package/observer/prsc.js +1289 -0
  114. package/observer/safety.js +815 -0
  115. package/observer/smf.js +1015 -0
  116. package/observer/symbolic-smf.js +726 -0
  117. package/observer/symbolic-temporal.js +790 -0
  118. package/observer/temporal.js +669 -0
  119. package/package.json +9 -3
  120. package/physics/alk-kuramoto.js +817 -0
  121. package/physics/index.js +23 -2
@@ -0,0 +1,329 @@
1
+ /**
2
+ * Example 04: TensorFlow.js ResoFormer Training
3
+ *
4
+ * This example demonstrates training a ResoFormer model using TensorFlow.js.
5
+ * The model uses:
6
+ * - Quaternion-valued embeddings (H_Q = H_P ⊗ ℍ)
7
+ * - Sparse prime state representations
8
+ * - Resonant attention with phase coherence
9
+ * - Coherence-gated adaptive computation
10
+ * - Entropy collapse to 64 attractors
11
+ *
12
+ * Run with: node examples/resonance/04-resoformer-training.js
13
+ */
14
+
15
+ const tf = require('@tensorflow/tfjs-node');
16
+ const {
17
+ QuaternionDense,
18
+ SparsePrimeEmbedding,
19
+ ResonantAttention,
20
+ ResoFormerBlock,
21
+ createResoFormerModel,
22
+ createResoFormerClassifier,
23
+ createResoFormerEmbedder
24
+ } = require('../../core/rformer-tf');
25
+
26
+ // ============================================================================
27
+ // SYNTHETIC DATA GENERATION
28
+ // ============================================================================
29
+
30
+ /**
31
+ * Generate synthetic sequence classification data
32
+ * Task: Classify sequences by their "prime pattern"
33
+ */
34
+ function generatePrimePatternData(numSamples = 1000, seqLen = 32, vocabSize = 100, numClasses = 5) {
35
+ console.log(`\nGenerating ${numSamples} synthetic sequences...`);
36
+
37
+ // Simple primes for pattern creation
38
+ const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47];
39
+
40
+ const sequences = [];
41
+ const labels = [];
42
+
43
+ for (let i = 0; i < numSamples; i++) {
44
+ const classIdx = i % numClasses;
45
+ const seq = [];
46
+
47
+ // Each class has a different "prime signature"
48
+ // Class 0: multiples of 2
49
+ // Class 1: multiples of 3
50
+ // Class 2: multiples of 5
51
+ // Class 3: prime indices
52
+ // Class 4: alternating pattern
53
+
54
+ for (let j = 0; j < seqLen; j++) {
55
+ let token;
56
+
57
+ switch (classIdx) {
58
+ case 0:
59
+ // Multiples of 2 with noise
60
+ token = (j * 2 + Math.floor(Math.random() * 3)) % vocabSize;
61
+ break;
62
+ case 1:
63
+ // Multiples of 3 with noise
64
+ token = (j * 3 + Math.floor(Math.random() * 3)) % vocabSize;
65
+ break;
66
+ case 2:
67
+ // Multiples of 5 with noise
68
+ token = (j * 5 + Math.floor(Math.random() * 3)) % vocabSize;
69
+ break;
70
+ case 3:
71
+ // Prime sequence
72
+ token = primes[j % primes.length] % vocabSize;
73
+ break;
74
+ case 4:
75
+ // Alternating 2-3-5-7 pattern
76
+ token = primes[j % 4] * (j + 1) % vocabSize;
77
+ break;
78
+ default:
79
+ token = Math.floor(Math.random() * vocabSize);
80
+ }
81
+
82
+ seq.push(token);
83
+ }
84
+
85
+ sequences.push(seq);
86
+ labels.push(classIdx);
87
+ }
88
+
89
+ // Convert to tensors
90
+ const xData = tf.tensor2d(sequences, [numSamples, seqLen], 'int32');
91
+ const yData = tf.oneHot(tf.tensor1d(labels, 'int32'), numClasses);
92
+
93
+ return { x: xData, y: yData, numClasses };
94
+ }
95
+
96
+ /**
97
+ * Split data into train/test sets
98
+ */
99
+ function splitData(x, y, trainRatio = 0.8) {
100
+ const numSamples = x.shape[0];
101
+ const numTrain = Math.floor(numSamples * trainRatio);
102
+
103
+ const xTrain = x.slice([0, 0], [numTrain, -1]);
104
+ const yTrain = y.slice([0, 0], [numTrain, -1]);
105
+ const xTest = x.slice([numTrain, 0], [-1, -1]);
106
+ const yTest = y.slice([numTrain, 0], [-1, -1]);
107
+
108
+ return { xTrain, yTrain, xTest, yTest };
109
+ }
110
+
111
+ // ============================================================================
112
+ // MODEL INSPECTION
113
+ // ============================================================================
114
+
115
+ function inspectModel(model) {
116
+ console.log('\n=== Model Architecture ===');
117
+ console.log(`Name: ${model.name}`);
118
+ console.log(`Layers: ${model.layers.length}`);
119
+
120
+ let totalParams = 0;
121
+ model.layers.forEach((layer, i) => {
122
+ const numParams = layer.countParams();
123
+ totalParams += numParams;
124
+ console.log(` [${i}] ${layer.name}: ${layer.getClassName()} (${numParams} params)`);
125
+ });
126
+
127
+ console.log(`Total parameters: ${totalParams.toLocaleString()}`);
128
+ console.log('');
129
+ }
130
+
131
+ // ============================================================================
132
+ // TRAINING LOOP
133
+ // ============================================================================
134
+
135
+ async function trainResoFormer() {
136
+ console.log('='.repeat(60));
137
+ console.log('TensorFlow.js ResoFormer Training Example');
138
+ console.log('='.repeat(60));
139
+
140
+ // Configuration
141
+ const config = {
142
+ vocabSize: 100,
143
+ seqLen: 32,
144
+ dim: 64, // Smaller for demo
145
+ numLayers: 2, // Fewer layers for demo
146
+ numHeads: 4,
147
+ ffnDim: 128,
148
+ numClasses: 5,
149
+ dropout: 0.1
150
+ };
151
+
152
+ // Generate synthetic data
153
+ const { x, y, numClasses } = generatePrimePatternData(
154
+ 1000, // samples
155
+ config.seqLen,
156
+ config.vocabSize,
157
+ config.numClasses
158
+ );
159
+
160
+ // Split into train/test
161
+ const { xTrain, yTrain, xTest, yTest } = splitData(x, y, 0.8);
162
+ console.log(`Train samples: ${xTrain.shape[0]}`);
163
+ console.log(`Test samples: ${xTest.shape[0]}`);
164
+
165
+ // Create model
166
+ console.log('\nCreating ResoFormer classifier...');
167
+ const model = createResoFormerClassifier(config);
168
+
169
+ // Inspect architecture
170
+ inspectModel(model);
171
+
172
+ // Compile model
173
+ model.compile({
174
+ optimizer: tf.train.adam(0.001),
175
+ loss: 'categoricalCrossentropy',
176
+ metrics: ['accuracy']
177
+ });
178
+
179
+ // Training configuration
180
+ const epochs = 10;
181
+ const batchSize = 32;
182
+
183
+ console.log(`\nTraining for ${epochs} epochs with batch size ${batchSize}...`);
184
+ console.log('-'.repeat(50));
185
+
186
+ // Train with callbacks
187
+ await model.fit(xTrain, yTrain, {
188
+ epochs,
189
+ batchSize,
190
+ validationData: [xTest, yTest],
191
+ callbacks: {
192
+ onEpochEnd: (epoch, logs) => {
193
+ const acc = (logs.acc * 100).toFixed(1);
194
+ const valAcc = (logs.val_acc * 100).toFixed(1);
195
+ const loss = logs.loss.toFixed(4);
196
+ const valLoss = logs.val_loss.toFixed(4);
197
+ console.log(`Epoch ${epoch + 1}/${epochs} - loss: ${loss}, acc: ${acc}% | val_loss: ${valLoss}, val_acc: ${valAcc}%`);
198
+ }
199
+ }
200
+ });
201
+
202
+ // Final evaluation
203
+ console.log('\n=== Final Evaluation ===');
204
+ const evalResult = model.evaluate(xTest, yTest);
205
+ const [finalLoss, finalAcc] = await Promise.all([
206
+ evalResult[0].data(),
207
+ evalResult[1].data()
208
+ ]);
209
+ console.log(`Test Loss: ${finalLoss[0].toFixed(4)}`);
210
+ console.log(`Test Accuracy: ${(finalAcc[0] * 100).toFixed(2)}%`);
211
+
212
+ // Demonstrate inference
213
+ console.log('\n=== Inference Demo ===');
214
+ const sampleBatch = xTest.slice([0, 0], [5, -1]);
215
+ const predictions = model.predict(sampleBatch);
216
+ const predClasses = predictions.argMax(-1);
217
+ const trueClasses = yTest.slice([0, 0], [5, -1]).argMax(-1);
218
+
219
+ const predData = await predClasses.data();
220
+ const trueData = await trueClasses.data();
221
+
222
+ console.log('Sample predictions:');
223
+ for (let i = 0; i < 5; i++) {
224
+ const match = predData[i] === trueData[i] ? '✓' : '✗';
225
+ console.log(` Sample ${i + 1}: Predicted=${predData[i]}, True=${trueData[i]} ${match}`);
226
+ }
227
+
228
+ // Cleanup
229
+ x.dispose();
230
+ y.dispose();
231
+ xTrain.dispose();
232
+ yTrain.dispose();
233
+ xTest.dispose();
234
+ yTest.dispose();
235
+ model.dispose();
236
+
237
+ console.log('\n' + '='.repeat(60));
238
+ console.log('Training complete!');
239
+ console.log('='.repeat(60));
240
+ }
241
+
242
+ // ============================================================================
243
+ // EMBEDDER DEMO
244
+ // ============================================================================
245
+
246
+ async function demoEmbedder() {
247
+ console.log('\n' + '='.repeat(60));
248
+ console.log('ResoFormer Embedder Demo');
249
+ console.log('='.repeat(60));
250
+
251
+ const config = {
252
+ vocabSize: 100,
253
+ seqLen: 32,
254
+ dim: 64,
255
+ numLayers: 2,
256
+ numHeads: 4,
257
+ ffnDim: 128,
258
+ embeddingDim: 32
259
+ };
260
+
261
+ console.log('\nCreating ResoFormer embedder...');
262
+ const embedder = createResoFormerEmbedder(config);
263
+ inspectModel(embedder);
264
+
265
+ // Create sample sequences
266
+ const seq1 = tf.tensor2d([[2, 4, 6, 8, 10, 12, 14, 16, ...Array(24).fill(0)]], [1, 32], 'int32');
267
+ const seq2 = tf.tensor2d([[3, 6, 9, 12, 15, 18, 21, 24, ...Array(24).fill(0)]], [1, 32], 'int32');
268
+ const seq3 = tf.tensor2d([[2, 4, 6, 8, 10, 12, 14, 16, ...Array(24).fill(0)]], [1, 32], 'int32');
269
+
270
+ // Get embeddings
271
+ const emb1 = embedder.predict(seq1);
272
+ const emb2 = embedder.predict(seq2);
273
+ const emb3 = embedder.predict(seq3);
274
+
275
+ // Compute cosine similarities
276
+ function cosineSimilarity(a, b) {
277
+ return tf.tidy(() => {
278
+ const dot = tf.sum(a.mul(b));
279
+ const normA = tf.sqrt(tf.sum(a.square()));
280
+ const normB = tf.sqrt(tf.sum(b.square()));
281
+ return dot.div(normA.mul(normB));
282
+ });
283
+ }
284
+
285
+ const sim12 = await cosineSimilarity(emb1, emb2).data();
286
+ const sim13 = await cosineSimilarity(emb1, emb3).data();
287
+ const sim23 = await cosineSimilarity(emb2, emb3).data();
288
+
289
+ console.log('\nSequence similarities:');
290
+ console.log(` Seq1 (2x) vs Seq2 (3x): ${sim12[0].toFixed(4)}`);
291
+ console.log(` Seq1 (2x) vs Seq3 (2x identical): ${sim13[0].toFixed(4)}`);
292
+ console.log(` Seq2 (3x) vs Seq3 (2x): ${sim23[0].toFixed(4)}`);
293
+
294
+ // Cleanup
295
+ seq1.dispose();
296
+ seq2.dispose();
297
+ seq3.dispose();
298
+ emb1.dispose();
299
+ emb2.dispose();
300
+ emb3.dispose();
301
+ embedder.dispose();
302
+
303
+ console.log('\nEmbedder demo complete!');
304
+ }
305
+
306
+ // ============================================================================
307
+ // MAIN
308
+ // ============================================================================
309
+
310
+ async function main() {
311
+ try {
312
+ // Show TensorFlow backend info
313
+ console.log(`TensorFlow.js backend: ${tf.getBackend()}`);
314
+ console.log(`TensorFlow.js version: ${tf.version.tfjs}`);
315
+
316
+ // Run training demo
317
+ await trainResoFormer();
318
+
319
+ // Run embedder demo
320
+ await demoEmbedder();
321
+
322
+ } catch (err) {
323
+ console.error('Error:', err.message);
324
+ console.error(err.stack);
325
+ process.exit(1);
326
+ }
327
+ }
328
+
329
+ main();