-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhopfield-components.js
More file actions
2046 lines (1866 loc) · 84.8 KB
/
Copy pathhopfield-components.js
File metadata and controls
2046 lines (1866 loc) · 84.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Hopfield-Netze Blog Components
// Interactive React components for hopfield.html.
// Vanilla React.createElement — no JSX, no build step.
// All math (Hebb, Pseudoinverse, Modern Hopfield) computed client-side
// from a 15 KB JSON of 10 MNIST patterns.
(function() {
'use strict';
// ====================================================================
// i18n — locale-aware UI strings (driven by <html lang="...">)
// Strings are written full-length per locale; `t(key, vars)` interpolates
// {name}-placeholders. Falls back to German if a key is missing in EN.
// ====================================================================
var LANG = (typeof document !== 'undefined'
&& document.documentElement
&& document.documentElement.lang === 'en') ? 'en' : 'de';
var STRINGS = {
de: {
loading: 'Lade MNIST-Daten ...',
energy_hint: 'Energie-Verlauf erscheint hier, sobald die Iteration läuft.',
energy_x: 'Flip-Nr.',
energy_y: 'Energie',
// Recall demo
recall_title: 'Demo: Hopfield-Recall live',
digit_pick: 'Ziffer zum Speichern und Abrufen:',
digit_aria: 'Ziffer {d} auswählen',
learning_rule: 'Lernregel: ',
noise: 'Rauschen: ',
btn_start: 'Start',
btn_running: 'Läuft …',
btn_restart: 'Neu starten',
btn_reset: 'Zurücksetzen',
btn_reseed: 'Anderes Rauschmuster',
label_original: 'Original {d}',
label_noisy: '{p} % verrauscht',
label_endstate_sim: 'Endzustand · sim={s}',
label_iter_flips: 'Iteration · {f} Flips',
panel_no_energy_title: 'Keine Energie-Treppe',
panel_no_energy_part1: 'Modern Hopfield arbeitet nicht mit der quadratischen Energie ',
panel_no_energy_part2: ', sondern mit einer log-sum-exp-Form. Die Konvergenz erfolgt in einem Schritt — eine Treppe entsteht nicht. Die zugrundeliegende Mathematik folgt in Kapitel 5.',
status_done_modern: 'Modern Hopfield konvergiert in einem Schritt — keine Treppe sichtbar.',
status_done_classical: 'Konvergiert nach {f} Flips. Endzustand-Ähnlichkeit zum Original: {p} %.',
status_idle: 'Bereit. „Start“ drücken.',
// Bias sink demo
bs_title: 'Demo: Bias-Sink — zehn Anfragen, ein Attraktor',
bs_stored: 'Gespeicherte Muster (Original-Ziffern):',
bs_noise_per_query: 'Rauschen pro Anfrage: ',
bs_btn_recall_all: 'Alle zurückrufen',
bs_btn_busy: 'Rechne …',
bs_row_noisy: 'Verrauschte Eingaben ({p} % Rauschen):',
bs_row_endstate: 'Endzustände nach Recall ({matrix}):',
bs_hebb_matrix: 'Hebb-Matrix',
bs_pi_matrix: 'Pseudoinverse-Matrix',
bs_results_empty: 'Noch keine Resultate. „Alle zurückrufen“ drücken.',
bs_hebb_collapse: 'Mittlere paarweise Ähnlichkeit der zehn Endzustände: {s}. Sämtliche Anfragen kollabieren in nahezu denselben Zustand — den Bias-Sink. Dieser Zustand ist visuell keine der gespeicherten Ziffern.',
bs_hebb_partial: 'Mittlere paarweise Ähnlichkeit: {s}. Die Endzustände liegen alle im selben Tal der Energie-Landschaft (Bias-Sink), mit kleinen Variationen durch die unterschiedlichen verrauschten Startpunkte.',
bs_pi_text: 'Mittlere paarweise Ähnlichkeit der zehn Endzustände: {s} — sie sind also strukturell verschieden. Jede Anfrage findet ihren eigenen Attraktor zurück — die Endzustände reproduzieren die gespeicherten Ziffern. Warum, ist Thema von Kapitel 4.',
// Spectral slider
spec_title: 'Demo: Spektrum-Slider — vom Bias-Sink zur Pseudoinverse',
spec_alpha_left: 'α = 0 (reines Hebb)',
spec_alpha_right: 'α = 1 (Pseudoinverse)',
spec_top_eig: 'Top-Eigenwert λ₁(W)',
spec_gap: 'Spektrale Lücke λ₁ / λ₂',
spec_recall_class: 'Recall → Klasse',
spec_digit_pick: 'Zu rekonstruierende Ziffer:',
spec_label_original: 'Original {d}',
spec_label_noise: '{p} % Rauschen',
spec_label_recall: 'Recall (α = {a}, sim = {s})',
spec_caption: 'Mit wachsendem α schrumpft λ₁ von etwa 6,7 auf 1,0, und die spektrale Lücke λ₁/λ₂ fällt von rund 10× auf 1× — die Energie-Landschaft wird gleichmäßig. Bis etwa α = 0,8 erkennt der Klassifikator den Recall noch nicht als Zielziffer (rot); bei α nahe 1 kippt das Bild um (grün). Die sim-Zahl am Recall-Bild bleibt unterdessen wegen des dunklen Hintergrundes oberhalb 0,8 — sie ist ein schlechter Indikator für Klassen-Recall, was den Klassifikator-Vergleich didaktisch nötig macht.',
// Beta slider
beta_title: 'Demo: β-Slider — von weicher Mittelung zur scharfen Wahl',
beta_left: 'β klein (weiche Mittelung)',
beta_right: 'β groß (scharfe Wahl)',
beta_softmax_intro: 'softmax-Verteilung über die zehn gespeicherten Ziffern ',
beta_entropy_paren: '(Entropie {e} nat)',
beta_recall_cont_prefix: 'Recall (kontinuierlich) → ',
beta_cap_high: 'Hohe Entropie: die softmax-Verteilung ist breit, das Recall-Bild ist eine Mischung mehrerer Ziffern (graue Mitteltöne).',
beta_cap_mid: 'Mittlere Entropie: einige wenige Ziffern dominieren die Mischung — das Recall-Bild beginnt eine erkennbare Form anzunehmen.',
beta_cap_low: 'Niedrige Entropie: die softmax konzentriert sich auf eine einzelne Ziffer — das Recall-Bild ist nahezu identisch zu einem gespeicherten Muster (1-NN-artig).',
// Three phases
phases_title: 'Demo: Drei Phasen — Storage, Learning, Generalisierung',
phases_rule_label: 'Lernregel:',
phases_L_label: 'Sparsity L: ',
phases_busy: 'Berechne Phasendiagramm …',
phases_busy_short: 'Berechne …',
phases_cursor_label: 'α-Cursor (gelb): ',
phases_band_storage: 'Storage',
phases_band_learning: 'Learning',
phases_band_generalisation: 'Generalisierung',
phases_xaxis: 'Speicherlast α = p / N',
phases_yaxis: 'mittlere Magnetisierung',
phases_stat_train: 'Train',
phases_stat_features: 'Features',
phases_stat_test: 'Test (ungesehen)',
phases_caption: 'N = {N}, D = {D}, L = {L} Bauteile pro Muster, {S} Stichproben je Pool. Bei kleinem α (Storage-Phase) ist Train hoch, Features und Test niedrig. Bei mittlerem α (Learning-Phase) übernehmen die Features. Bei großem α werden auch ungesehene Mischungen (Test) zu Attraktoren — echte Generalisierung. Mit der Pseudoinverse-Regel ist der Effekt deutlich stärker als mit Hebb.'
},
en: {
loading: 'Loading MNIST data ...',
energy_hint: 'The energy trace will appear here once the iteration starts.',
energy_x: 'Flip #',
energy_y: 'Energy',
recall_title: 'Demo: Hopfield recall, live',
digit_pick: 'Digit to store and recall:',
digit_aria: 'Select digit {d}',
learning_rule: 'Learning rule: ',
noise: 'Noise: ',
btn_start: 'Start',
btn_running: 'Running …',
btn_restart: 'Restart',
btn_reset: 'Reset',
btn_reseed: 'New noise pattern',
label_original: 'Original {d}',
label_noisy: '{p} % noisy',
label_endstate_sim: 'Final state · sim={s}',
label_iter_flips: 'Iteration · {f} flips',
panel_no_energy_title: 'No energy staircase',
panel_no_energy_part1: 'Modern Hopfield does not use the quadratic energy ',
panel_no_energy_part2: ', but a log-sum-exp form. Convergence happens in a single step — no staircase appears. The underlying mathematics follows in Chapter 5.',
status_done_modern: 'Modern Hopfield converges in one step — no staircase to be seen.',
status_done_classical: 'Converged after {f} flips. Final-state similarity to the original: {p} %.',
status_idle: 'Ready. Press “Start”.',
bs_title: 'Demo: bias sink — ten queries, one attractor',
bs_stored: 'Stored patterns (original digits):',
bs_noise_per_query: 'Noise per query: ',
bs_btn_recall_all: 'Recall all',
bs_btn_busy: 'Computing …',
bs_row_noisy: 'Noisy inputs ({p} % noise):',
bs_row_endstate: 'Final states after recall ({matrix}):',
bs_hebb_matrix: 'Hebb matrix',
bs_pi_matrix: 'Pseudoinverse matrix',
bs_results_empty: 'No results yet. Press “Recall all”.',
bs_hebb_collapse: 'Mean pairwise similarity of the ten final states: {s}. All queries collapse into nearly the same state — the bias sink. Visually, this state is none of the stored digits.',
bs_hebb_partial: 'Mean pairwise similarity: {s}. All final states sit in the same valley of the energy landscape (bias sink), with small variations from the different noisy starting points.',
bs_pi_text: 'Mean pairwise similarity of the ten final states: {s} — they are structurally distinct. Each query returns to its own attractor; the final states reproduce the stored digits. Why, is the subject of Chapter 4.',
spec_title: 'Demo: spectrum slider — from bias sink to pseudoinverse',
spec_alpha_left: 'α = 0 (pure Hebb)',
spec_alpha_right: 'α = 1 (pseudoinverse)',
spec_top_eig: 'Top eigenvalue λ₁(W)',
spec_gap: 'Spectral gap λ₁ / λ₂',
spec_recall_class: 'Recall → class',
spec_digit_pick: 'Digit to reconstruct:',
spec_label_original: 'Original {d}',
spec_label_noise: '{p} % noise',
spec_label_recall: 'Recall (α = {a}, sim = {s})',
spec_caption: 'As α grows, λ₁ shrinks from about 6.7 to 1.0, and the spectral gap λ₁/λ₂ falls from roughly 10× to 1× — the energy landscape becomes uniform. Up to about α = 0.8 the classifier does not yet recognise the recall as the target digit (red); for α close to 1 the picture flips over (green). Meanwhile the sim value on the recall image stays above 0.8 because of the dark background — a poor indicator for class recall, which is what makes the classifier comparison didactically necessary.',
beta_title: 'Demo: β-slider — from soft averaging to a sharp choice',
beta_left: 'β small (soft averaging)',
beta_right: 'β large (sharp choice)',
beta_softmax_intro: 'softmax distribution over the ten stored digits ',
beta_entropy_paren: '(entropy {e} nat)',
beta_recall_cont_prefix: 'Recall (continuous) → ',
beta_cap_high: 'High entropy: the softmax distribution is broad, the recall image is a blend of several digits (grey mid-tones).',
beta_cap_mid: 'Medium entropy: a few digits dominate the blend — the recall image begins to take on a recognisable shape.',
beta_cap_low: 'Low entropy: the softmax concentrates on a single digit — the recall image is almost identical to a stored pattern (1-NN-like).',
phases_title: 'Demo: three phases — storage, learning, generalisation',
phases_rule_label: 'Learning rule:',
phases_L_label: 'Sparsity L: ',
phases_busy: 'Computing phase diagram …',
phases_busy_short: 'Computing …',
phases_cursor_label: 'α cursor (yellow): ',
phases_band_storage: 'Storage',
phases_band_learning: 'Learning',
phases_band_generalisation: 'Generalisation',
phases_xaxis: 'Storage load α = p / N',
phases_yaxis: 'mean magnetisation',
phases_stat_train: 'Train',
phases_stat_features: 'Features',
phases_stat_test: 'Test (unseen)',
phases_caption: 'N = {N}, D = {D}, L = {L} components per pattern, {S} samples per pool. At small α (storage phase) Train is high, Features and Test are low. At medium α (learning phase) the features take over. At large α even unseen mixtures (Test) become attractors — genuine generalisation. With the pseudoinverse rule the effect is markedly stronger than with Hebb.'
}
};
function t(key, vars) {
var dict = STRINGS[LANG] || STRINGS.de;
var s = dict[key];
if (s === undefined) s = STRINGS.de[key];
if (s === undefined) return key;
if (vars) {
for (var k in vars) {
s = s.split('{' + k + '}').join(String(vars[k]));
}
}
return s;
}
// ====================================================================
// Shared math helpers
// ====================================================================
// Convert compressed {0,1} pattern to bipolar {-1,+1} Float32Array
function toBipolar(bits) {
var arr = new Float32Array(bits.length);
for (var i = 0; i < bits.length; i++) arr[i] = bits[i] * 2 - 1;
return arr;
}
// Build Hebb weight matrix: W = (1/N) * sum_p xi xi^T, diagonal zero
function buildHebbWeights(patterns, N) {
var p = patterns.length;
var W = new Float32Array(N * N);
for (var mu = 0; mu < p; mu++) {
var xi = patterns[mu];
for (var i = 0; i < N; i++) {
var xi_i = xi[i];
if (xi_i === 0) continue;
for (var j = 0; j < N; j++) {
W[i * N + j] += xi_i * xi[j];
}
}
}
var invN = 1.0 / N;
for (var k = 0; k < N * N; k++) W[k] *= invN;
for (var d = 0; d < N; d++) W[d * N + d] = 0; // diagonal zero
return W;
}
// Build Pseudoinverse weight matrix: W = X (X^T X)^{-1} X^T
// patterns: array of p Float32Arrays of length N
// For p << N (here p=10, N=784), this is cheap: invert a p×p matrix.
function buildPseudoInverseWeights(patterns, N) {
var p = patterns.length;
// Gram matrix G = X^T X, shape (p, p), where columns of X are patterns
var G = [];
for (var mu = 0; mu < p; mu++) {
G[mu] = new Float32Array(p);
for (var nu = 0; nu < p; nu++) {
var s = 0;
for (var i = 0; i < N; i++) s += patterns[mu][i] * patterns[nu][i];
G[mu][nu] = s;
}
}
// Invert G via Gauss-Jordan
var Ginv = invertSmallMatrix(G, p);
// W = X * Ginv * X^T = sum_{mu,nu} xi_mu Ginv[mu,nu] xi_nu^T
var W = new Float32Array(N * N);
for (var mu2 = 0; mu2 < p; mu2++) {
for (var nu2 = 0; nu2 < p; nu2++) {
var c = Ginv[mu2][nu2];
if (Math.abs(c) < 1e-12) continue;
var xi_mu = patterns[mu2];
var xi_nu = patterns[nu2];
for (var i2 = 0; i2 < N; i2++) {
var v_i = xi_mu[i2] * c;
for (var j2 = 0; j2 < N; j2++) {
W[i2 * N + j2] += v_i * xi_nu[j2];
}
}
}
}
return W;
}
// Gauss-Jordan inversion for small (p×p) symmetric positive-semi-definite matrices
function invertSmallMatrix(A, n) {
var M = [];
for (var i = 0; i < n; i++) {
M[i] = new Float32Array(2 * n);
for (var j = 0; j < n; j++) M[i][j] = A[i][j];
M[i][n + i] = 1;
}
for (var col = 0; col < n; col++) {
var pivot = col;
for (var r = col + 1; r < n; r++) {
if (Math.abs(M[r][col]) > Math.abs(M[pivot][col])) pivot = r;
}
if (pivot !== col) { var tmp = M[col]; M[col] = M[pivot]; M[pivot] = tmp; }
var diag = M[col][col];
if (Math.abs(diag) < 1e-10) continue;
for (var k = 0; k < 2 * n; k++) M[col][k] /= diag;
for (var rr = 0; rr < n; rr++) {
if (rr === col) continue;
var factor = M[rr][col];
for (var kk = 0; kk < 2 * n; kk++) M[rr][kk] -= factor * M[col][kk];
}
}
var inv = [];
for (var ii = 0; ii < n; ii++) {
inv[ii] = new Float32Array(n);
for (var jj = 0; jj < n; jj++) inv[ii][jj] = M[ii][n + jj];
}
return inv;
}
// Hopfield energy: E = -0.5 * v^T W v
function energy(W, v, N) {
var sum = 0;
for (var i = 0; i < N; i++) {
var vi = v[i];
if (vi === 0) continue;
for (var j = 0; j < N; j++) sum += vi * W[i * N + j] * v[j];
}
return -0.5 * sum;
}
// Modern Hopfield single-step update: v_new = sign(X * softmax(beta * X^T v))
function modernHopfieldStep(patterns, v, beta, N) {
var p = patterns.length;
var scores = new Float32Array(p);
var maxS = -Infinity;
for (var mu = 0; mu < p; mu++) {
var s = 0;
for (var i = 0; i < N; i++) s += patterns[mu][i] * v[i];
scores[mu] = beta * s;
if (scores[mu] > maxS) maxS = scores[mu];
}
var sumExp = 0;
var weights = new Float32Array(p);
for (var mu2 = 0; mu2 < p; mu2++) {
weights[mu2] = Math.exp(scores[mu2] - maxS);
sumExp += weights[mu2];
}
var vNew = new Float32Array(N);
for (var i2 = 0; i2 < N; i2++) {
var acc = 0;
for (var mu3 = 0; mu3 < p; mu3++) acc += weights[mu3] * patterns[mu3][i2];
vNew[i2] = acc >= 0 ? 1 : -1;
}
return vNew;
}
// Cosine similarity between two ±1 vectors
function cosineSim(a, b, N) {
var s = 0;
for (var i = 0; i < N; i++) s += a[i] * b[i];
return s / N;
}
// Permutation
function shuffle(arr, rng) {
for (var i = arr.length - 1; i > 0; i--) {
var j = Math.floor(rng() * (i + 1));
var t = arr[i]; arr[i] = arr[j]; arr[j] = t;
}
}
// Simple seeded PRNG (Mulberry32)
function makeRng(seed) {
var s = seed >>> 0;
return function() {
s = (s + 0x6D2B79F5) >>> 0;
var t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// Synchronous asynchronous-update recall — runs to fixed point in one call.
// For the Bias-Sink demo we don't need animation; just the end state.
function recallSync(W, v0, N, maxSweeps, seed) {
var v = new Float32Array(N);
for (var k = 0; k < N; k++) v[k] = v0[k];
var rng = makeRng(seed);
var order = []; for (var k2 = 0; k2 < N; k2++) order.push(k2);
for (var sweep = 0; sweep < maxSweeps; sweep++) {
shuffle(order, rng);
var changed = false;
for (var idx = 0; idx < N; idx++) {
var i = order[idx];
var s = 0;
for (var j = 0; j < N; j++) s += W[i * N + j] * v[j];
var nw = s >= 0 ? 1 : -1;
if (nw !== v[i]) { v[i] = nw; changed = true; }
}
if (!changed) break;
}
return v;
}
// ====================================================================
// Data loader (singleton — fetched once, shared across components)
// ====================================================================
var _dataPromise = null;
function loadHopfieldData() {
if (_dataPromise) return _dataPromise;
_dataPromise = fetch('/img/hopfield-mnist-data.json')
.then(function(r) { return r.json(); })
.then(function(raw) {
var patterns = raw.patterns_compressed.map(toBipolar);
return { N: raw.N, p: raw.p, patterns: patterns, labels: raw.labels };
});
return _dataPromise;
}
// ====================================================================
// PatternView — render a 28×28 ±1 vector as SVG
// ====================================================================
function PatternView(props) {
var h = React.createElement;
var v = props.v;
var label = props.label;
var highlight = props.highlight || null; // optional: array of indices to highlight (red)
var px = 6; // pixel size in SVG units
var rects = [];
for (var i = 0; i < 784; i++) {
var row = Math.floor(i / 28), col = i % 28;
var on = v[i] > 0;
var fill = on ? '#e2e8f0' : '#1f2937';
if (highlight && highlight[i]) fill = '#f87171';
rects.push(h('rect', { key: i,
x: col * px, y: row * px, width: px, height: px, fill: fill }));
}
return h('div', { className: 'flex flex-col items-center' },
h('svg', {
viewBox: '0 0 ' + (28 * px) + ' ' + (28 * px),
width: '100%',
style: { maxWidth: '140px', background: '#0f172a', borderRadius: '4px' }
}, rects),
h('div', { className: 'text-xs text-gray-400 mt-2 text-center' }, label)
);
}
// ====================================================================
// EnergyChart — plot of energy vs. flip number
// ====================================================================
function EnergyChart(props) {
var h = React.createElement;
var history = props.history; // [[flipNumber, energy], ...]
if (!history || history.length === 0) {
return h('div', { className: 'text-xs text-gray-500 text-center py-8' },
t('energy_hint'));
}
var W = 260, H = 140, pad = 28;
var xs = history.map(function(p) { return p[0]; });
var ys = history.map(function(p) { return p[1]; });
var xmin = 0, xmax = Math.max(1, xs[xs.length - 1]);
var ymin = Math.min.apply(null, ys), ymax = Math.max.apply(null, ys);
if (ymax === ymin) { ymax += 1; ymin -= 1; }
function sx(x) { return pad + (x - xmin) / (xmax - xmin) * (W - pad - 8); }
function sy(y) { return H - pad - (y - ymin) / (ymax - ymin) * (H - pad - 8); }
var path = history.map(function(p, i) {
return (i === 0 ? 'M' : 'L') + sx(p[0]) + ',' + sy(p[1]);
}).join(' ');
return h('svg', {
viewBox: '0 0 ' + W + ' ' + H,
width: '100%',
style: { maxWidth: '320px', background: '#0f172a', borderRadius: '4px' }
},
h('line', { x1: pad, y1: H - pad, x2: W - 8, y2: H - pad, stroke: '#374151', strokeWidth: 1 }),
h('line', { x1: pad, y1: 8, x2: pad, y2: H - pad, stroke: '#374151', strokeWidth: 1 }),
h('text', { x: W / 2, y: H - 6, fill: '#6b7280', fontSize: 10, textAnchor: 'middle' }, t('energy_x')),
h('text', { x: 8, y: H / 2, fill: '#6b7280', fontSize: 10, textAnchor: 'middle',
transform: 'rotate(-90 8 ' + (H / 2) + ')' }, t('energy_y')),
h('path', { d: path, stroke: '#22d3ee', strokeWidth: 1.5, fill: 'none' }),
h('circle', { cx: sx(xs[xs.length - 1]), cy: sy(ys[ys.length - 1]),
r: 3, fill: '#fbbf24' }),
h('text', { x: W - 8, y: 20, fill: '#94a3b8', fontSize: 10, textAnchor: 'end' },
'E = ' + ys[ys.length - 1].toFixed(1))
);
}
// ====================================================================
// HopfieldRecallDemo — main interactive component for chapter 2 + 5
// ====================================================================
function HopfieldRecallDemo() {
var h = React.createElement;
var dataState = React.useState(null);
var data = dataState[0], setData = dataState[1];
React.useEffect(function() {
loadHopfieldData().then(setData);
}, []);
// UI state
var digitState = React.useState(7);
var digit = digitState[0], setDigit = digitState[1];
var noiseState = React.useState(0.20);
var noise = noiseState[0], setNoise = noiseState[1];
var ruleState = React.useState('hebb');
var rule = ruleState[0], setRule = ruleState[1];
var seedState = React.useState(42);
var seed = seedState[0], setSeed = seedState[1];
// Dynamic state
var runStateS = React.useState('idle'); // idle | running | done
var runState = runStateS[0], setRunState = runStateS[1];
var vCurS = React.useState(null);
var vCur = vCurS[0], setVCur = vCurS[1];
var energyHistS = React.useState([]);
var energyHist = energyHistS[0], setEnergyHist = energyHistS[1];
var flipCountS = React.useState(0);
var flipCount = flipCountS[0], setFlipCount = flipCountS[1];
// Precomputed weight matrices, keyed by rule. Recomputed when data loads.
var weightsRef = React.useRef({});
React.useEffect(function() {
if (!data) return;
var N = data.N;
weightsRef.current = {
hebb: buildHebbWeights(data.patterns, N),
pi: buildPseudoInverseWeights(data.patterns, N),
};
}, [data]);
// The animation loop ref
var animRef = React.useRef(null);
// Generate noisy initial state
function makeNoisy() {
if (!data) return null;
var orig = data.patterns[digit];
var N = data.N;
var v = new Float32Array(N);
for (var i = 0; i < N; i++) v[i] = orig[i];
var nFlip = Math.round(noise * N);
var rng = makeRng(seed);
var indices = [];
for (var k = 0; k < N; k++) indices.push(k);
shuffle(indices, rng);
for (var f = 0; f < nFlip; f++) v[indices[f]] *= -1;
return v;
}
function handleStart() {
if (!data) return;
if (animRef.current) { clearInterval(animRef.current); animRef.current = null; }
var N = data.N;
var v = makeNoisy();
var rng = makeRng(seed + 1);
if (rule === 'modern') {
// Modern Hopfield: single-step, kein iteratives sign-Update mit
// quadratischer Energie. Die mathematisch korrekte Energie ist
// log-sum-exp, eine andere Funktionalform; sie wird in Kapitel 5
// eingeführt. Hier kein Energie-Plot, stattdessen ein Hinweis-Panel.
var vNew = modernHopfieldStep(data.patterns, v, 8.0, N);
setVCur(vNew);
setEnergyHist([]); // leer → skip plot, show explanation
setFlipCount(0);
setRunState('done');
return;
}
// Classical: animate asynchronous flips
var W = weightsRef.current[rule];
if (!W) return;
var e0 = energy(W, v, N);
setVCur(v);
setEnergyHist([[0, e0]]);
setFlipCount(0);
setRunState('running');
// Tick: do a batch of mikroschritte per tick. Wert hoch genug gewählt,
// damit ein voller Sweep (N=784 Mikroschritte) in unter einer Sekunde
// durchläuft. Mobile-Erkennung verdoppelt den Wert, damit auch auf
// schwächeren Geräten die Konvergenz unter ~5 s bleibt.
var isMobile = window.matchMedia && window.matchMedia('(max-width: 768px)').matches;
var STEPS_PER_TICK = isMobile ? 128 : 64;
var maxSweeps = 30;
var sweepCount = 0;
var sweepFlips = 0;
var order = []; for (var i = 0; i < N; i++) order.push(i);
shuffle(order, rng);
var orderPos = 0;
var curEnergy = e0;
var curFlipCount = 0;
var energyAcc = [[0, e0]];
animRef.current = setInterval(function() {
for (var step = 0; step < STEPS_PER_TICK; step++) {
if (orderPos >= N) {
sweepCount++;
if (sweepFlips === 0 || sweepCount >= maxSweeps) {
clearInterval(animRef.current); animRef.current = null;
setRunState('done');
setEnergyHist(energyAcc.slice());
setVCur(new Float32Array(v));
setFlipCount(curFlipCount);
return;
}
sweepFlips = 0;
shuffle(order, rng);
orderPos = 0;
}
var nIdx = order[orderPos++];
var s = 0;
for (var j = 0; j < N; j++) s += W[nIdx * N + j] * v[j];
var newVal = s >= 0 ? 1 : -1;
if (newVal !== v[nIdx]) {
v[nIdx] = newVal;
curFlipCount++;
sweepFlips++;
// Incrementally update energy (less expensive than full recompute);
// for now recompute occasionally
if (curFlipCount % 4 === 0) {
curEnergy = energy(W, v, N);
energyAcc.push([curFlipCount, curEnergy]);
}
}
}
// Push end-of-tick state
setVCur(new Float32Array(v));
setEnergyHist(energyAcc.slice());
setFlipCount(curFlipCount);
}, 40);
}
function handleReset() {
if (animRef.current) { clearInterval(animRef.current); animRef.current = null; }
setVCur(null);
setEnergyHist([]);
setFlipCount(0);
setRunState('idle');
}
// Cleanup on unmount
React.useEffect(function() {
return function() { if (animRef.current) clearInterval(animRef.current); };
}, []);
if (!data) {
return h('div', { className: 'p-8 text-center text-gray-500 text-sm' },
t('loading'));
}
var orig = data.patterns[digit];
var noisy = vCur ? null : makeNoisy();
var displayCurrent = vCur || makeNoisy();
var simToOrig = displayCurrent ? cosineSim(displayCurrent, orig, data.N) : 0;
var ruleLabel = { hebb: 'Hebb', pi: 'Pseudoinverse', modern: 'Modern Hopfield (β=8)' }[rule];
// Digit-picker buttons (10 small pattern previews)
var digitButtons = [];
for (var d = 0; d < 10; d++) {
var pat = data.patterns[d];
var thumbRects = [];
var px2 = 3;
for (var k = 0; k < 784; k++) {
var r = Math.floor(k / 28), c = k % 28;
thumbRects.push(h('rect', { key: k,
x: c * px2, y: r * px2, width: px2, height: px2,
fill: pat[k] > 0 ? '#e2e8f0' : '#1f2937' }));
}
var isSel = d === digit;
digitButtons.push(h('button', {
key: d,
onClick: (function(dd) { return function() { setDigit(dd); handleReset(); }; })(d),
className: 'p-1 rounded ' + (isSel ? 'ring-2 ring-cyan-400' : 'ring-1 ring-gray-700 hover:ring-gray-500'),
style: { background: '#0f172a' },
'aria-label': t('digit_aria', { d: d })
},
h('svg', { viewBox: '0 0 ' + (28 * px2) + ' ' + (28 * px2),
width: 44, height: 44 }, thumbRects)
));
}
return h('div', {
className: 'border border-gray-700 rounded-lg p-4 sm:p-6',
style: { background: 'rgba(17, 24, 39, 0.5)' }
},
// ----- Header -----
h('h4', { className: 'text-sm font-semibold text-cyan-400 uppercase tracking-wide mb-4' },
t('recall_title')),
// ----- Digit picker -----
h('div', { className: 'mb-4' },
h('label', { className: 'block text-xs text-gray-400 mb-2' }, t('digit_pick')),
h('div', { className: 'flex flex-wrap gap-2' }, digitButtons)
),
// ----- Rule and noise -----
h('div', { className: 'grid grid-cols-1 md:grid-cols-2 gap-4 mb-4' },
h('div', null,
h('label', { className: 'block text-xs text-gray-400 mb-2' },
t('learning_rule'), h('span', { className: 'text-cyan-400 font-semibold' }, ruleLabel)),
h('div', { className: 'flex gap-2' },
[['hebb', 'Hebb'], ['pi', 'Pseudoinverse'], ['modern', 'Modern Hopfield']].map(function(r) {
return h('button', {
key: r[0],
onClick: function() { setRule(r[0]); handleReset(); },
className: 'px-3 py-1.5 text-xs rounded transition ' +
(rule === r[0]
? 'bg-cyan-500/20 text-cyan-300 ring-1 ring-cyan-500'
: 'bg-gray-800 text-gray-400 ring-1 ring-gray-700 hover:bg-gray-700')
}, r[1]);
})
)
),
h('div', null,
h('label', { className: 'block text-xs text-gray-400 mb-2' },
t('noise'), h('span', { className: 'text-cyan-400 font-semibold' },
Math.round(noise * 100) + ' %')),
h('input', {
type: 'range', min: 0, max: 50, step: 1,
value: Math.round(noise * 100),
onChange: function(e) { setNoise(parseInt(e.target.value, 10) / 100); handleReset(); },
className: 'w-full',
style: { accentColor: '#22d3ee' }
})
)
),
// ----- Action buttons -----
h('div', { className: 'flex gap-2 mb-4' },
h('button', {
onClick: handleStart,
disabled: runState === 'running',
className: 'px-4 py-2 text-sm font-medium rounded transition ' +
(runState === 'running'
? 'bg-gray-700 text-gray-500 cursor-not-allowed'
: 'bg-cyan-600 hover:bg-cyan-500 text-white')
}, runState === 'running' ? t('btn_running') : (runState === 'done' ? t('btn_restart') : t('btn_start'))),
h('button', {
onClick: handleReset,
className: 'px-4 py-2 text-sm font-medium rounded bg-gray-800 hover:bg-gray-700 text-gray-300 transition'
}, t('btn_reset')),
h('button', {
onClick: function() { setSeed(seed + 1); handleReset(); },
className: 'px-4 py-2 text-sm font-medium rounded bg-gray-800 hover:bg-gray-700 text-gray-300 transition'
}, t('btn_reseed'))
),
// ----- Three patterns + energy chart -----
h('div', { className: 'grid grid-cols-2 md:grid-cols-4 gap-3 items-start' },
h(PatternView, { v: orig, label: t('label_original', { d: digit }) }),
h(PatternView, { v: makeNoisy(), label: t('label_noisy', { p: Math.round(noise * 100) }) }),
h(PatternView, {
v: displayCurrent,
label: runState === 'done'
? t('label_endstate_sim', { s: simToOrig.toFixed(2) })
: (runState === 'running' ? t('label_iter_flips', { f: flipCount }) : '—')
}),
h('div', { className: 'col-span-2 md:col-span-1' },
rule === 'modern'
? h('div', {
style: {
background: '#0f172a', borderRadius: '4px',
border: '1px solid #1f2937',
padding: '1rem', height: '100%',
display: 'flex', flexDirection: 'column',
justifyContent: 'center',
fontSize: '11px', color: '#94a3b8',
lineHeight: '1.5'
}
},
h('div', { style: { color: '#c4b5fd', fontWeight: 600, marginBottom: '6px' } },
t('panel_no_energy_title')),
h('div', null,
t('panel_no_energy_part1'),
h('span', { style: { fontFamily: 'monospace', color: '#cbd5e1' } },
'−½ vᵀWv'),
t('panel_no_energy_part2')))
: h(EnergyChart, { history: energyHist })
)
),
// ----- Status -----
h('div', { className: 'mt-4 text-xs text-gray-500' },
runState === 'done'
? (rule === 'modern'
? t('status_done_modern')
: t('status_done_classical', { f: flipCount, p: (simToOrig * 100).toFixed(0) }))
: (runState === 'running'
? t('btn_running')
: t('status_idle'))
)
);
}
// ====================================================================
// BiasSinkDemo — Chapter 3: all 10 queries collapse into one state (Hebb)
// vs. each query finds its own attractor (Pseudoinverse).
// ====================================================================
function BiasSinkDemo() {
var h = React.createElement;
var dataState = React.useState(null);
var data = dataState[0], setData = dataState[1];
React.useEffect(function() {
loadHopfieldData().then(setData);
}, []);
var ruleState = React.useState('hebb');
var rule = ruleState[0], setRule = ruleState[1];
var noiseState = React.useState(0.15);
var noise = noiseState[0], setNoise = noiseState[1];
var seedState = React.useState(123);
var seed = seedState[0], setSeed = seedState[1];
var resultsState = React.useState(null); // null | Array of Float32Array
var results = resultsState[0], setResults = resultsState[1];
// Noisy inputs are stored alongside the results so the user can see the
// exact starting points all ten queries were launched from — without
// this, the Pseudoinverse mode looks like an identity pass and the
// Hebb collapse loses half its visual punch.
var noisyState = React.useState(null); // null | Array of Float32Array
var noisyInputs = noisyState[0], setNoisyInputs = noisyState[1];
var busyState = React.useState(false);
var busy = busyState[0], setBusy = busyState[1];
function clearOutputs() { setResults(null); setNoisyInputs(null); }
var weightsRef = React.useRef({});
React.useEffect(function() {
if (!data) return;
weightsRef.current = {
hebb: buildHebbWeights(data.patterns, data.N),
pi: buildPseudoInverseWeights(data.patterns, data.N),
};
clearOutputs();
}, [data]);
function handleRecallAll() {
if (!data || busy) return;
setBusy(true);
// Defer so the UI can update to "busy" before the heavy loop
setTimeout(function() {
var N = data.N;
var W = weightsRef.current[rule];
var nFlip = Math.round(noise * N);
var idx = []; for (var i = 0; i < N; i++) idx.push(i);
var noisy = [];
var out = [];
for (var d = 0; d < data.patterns.length; d++) {
// Per-digit noise: shuffle a fresh index list with a derived seed
var v0 = new Float32Array(N);
for (var k = 0; k < N; k++) v0[k] = data.patterns[d][k];
var rng2 = makeRng(seed + d * 17);
shuffle(idx, rng2);
for (var f = 0; f < nFlip; f++) v0[idx[f]] *= -1;
noisy.push(new Float32Array(v0)); // snapshot before recall mutates it
var v_end = recallSync(W, v0, N, 30, seed + d * 31 + 100);
out.push(v_end);
}
setNoisyInputs(noisy);
setResults(out);
setBusy(false);
}, 30);
}
function handleReset() {
clearOutputs();
}
if (!data) {
return h('div', { className: 'p-8 text-center text-gray-500 text-sm' },
t('loading'));
}
// Helper: render a row of 10 small pattern thumbnails
function patternRow(arr, accent) {
var pxs = 3;
var cells = [];
for (var d = 0; d < 10; d++) {
var pat = arr[d];
var rects = [];
if (pat) {
for (var k = 0; k < 784; k++) {
var rr = Math.floor(k / 28), cc = k % 28;
rects.push(h('rect', { key: k,
x: cc * pxs, y: rr * pxs, width: pxs, height: pxs,
fill: pat[k] > 0 ? '#e2e8f0' : '#1f2937' }));
}
} else {
rects.push(h('rect', { key: 'bg',
x: 0, y: 0, width: 28 * pxs, height: 28 * pxs, fill: '#0f172a' }));
}
cells.push(h('div', { key: d, className: 'flex flex-col items-center gap-1' },
h('svg', { viewBox: '0 0 ' + (28 * pxs) + ' ' + (28 * pxs),
width: 56, height: 56,
style: { background: '#0f172a', borderRadius: '3px',
border: accent ? '1px solid ' + accent : '1px solid #1f2937' } },
rects),
h('div', { className: 'text-[10px] text-gray-500' }, '' + d)
));
}
return h('div', { className: 'grid grid-cols-5 sm:grid-cols-10 gap-2 justify-items-center' }, cells);
}
// Mittlere paarweise Cosinus-Ähnlichkeit aller Endzustände (45 Paare).
// = 1.0 → alle identisch. > 0.95 → kollabierter Bias-Sink. < 0.5 → separate Attraktoren.
var avgSim = null;
if (results) {
var sumSim = 0, nPairs = 0;
for (var a = 0; a < results.length; a++) {
for (var b = a + 1; b < results.length; b++) {
var dot = 0;
for (var k = 0; k < data.N; k++) dot += results[a][k] * results[b][k];
sumSim += dot / data.N;
nPairs++;
}
}
avgSim = nPairs > 0 ? sumSim / nPairs : 1.0;
}
return h('div', {
className: 'border border-gray-700 rounded-lg p-4 sm:p-6',
style: { background: 'rgba(17, 24, 39, 0.5)' }
},
h('h4', { className: 'text-sm font-semibold text-cyan-400 uppercase tracking-wide mb-4' },
t('bs_title')),
// Stored patterns (originals)
h('div', { className: 'mb-4' },
h('div', { className: 'text-xs text-gray-400 mb-2' }, t('bs_stored')),
patternRow(data.patterns, null)
),
// Controls
h('div', { className: 'grid grid-cols-1 md:grid-cols-2 gap-4 mb-4' },
h('div', null,
h('label', { className: 'block text-xs text-gray-400 mb-2' },
t('learning_rule'),
h('span', { className: 'text-cyan-400 font-semibold' },
rule === 'hebb' ? 'Hebb' : 'Pseudoinverse')),
h('div', { className: 'flex gap-2' },
[['hebb', 'Hebb'], ['pi', 'Pseudoinverse']].map(function(r) {
return h('button', {
key: r[0],
onClick: function() { setRule(r[0]); clearOutputs(); },
className: 'px-3 py-1.5 text-xs rounded transition ' +
(rule === r[0]
? 'bg-cyan-500/20 text-cyan-300 ring-1 ring-cyan-500'
: 'bg-gray-800 text-gray-400 ring-1 ring-gray-700 hover:bg-gray-700')
}, r[1]);
})
)
),
h('div', null,
h('label', { className: 'block text-xs text-gray-400 mb-2' },
t('bs_noise_per_query'),
h('span', { className: 'text-cyan-400 font-semibold' },
Math.round(noise * 100) + ' %')),
h('input', {
type: 'range', min: 0, max: 30, step: 1,
value: Math.round(noise * 100),
onChange: function(e) { setNoise(parseInt(e.target.value, 10) / 100); clearOutputs(); },
className: 'w-full',
style: { accentColor: '#22d3ee' }
})
)
),
h('div', { className: 'flex gap-2 mb-5' },
h('button', {
onClick: handleRecallAll,
disabled: busy,
className: 'px-4 py-2 text-sm font-medium rounded transition ' +
(busy
? 'bg-gray-700 text-gray-500 cursor-not-allowed'
: 'bg-cyan-600 hover:bg-cyan-500 text-white')
}, busy ? t('bs_btn_busy') : t('bs_btn_recall_all')),
h('button', {
onClick: function() { setSeed(seed + 1); clearOutputs(); },
className: 'px-4 py-2 text-sm font-medium rounded bg-gray-800 hover:bg-gray-700 text-gray-300 transition'
}, t('btn_reseed')),
h('button', {
onClick: handleReset,
className: 'px-4 py-2 text-sm font-medium rounded bg-gray-800 hover:bg-gray-700 text-gray-300 transition'
}, t('btn_reset'))
),
// Noisy-input row (only shown after a recall has been triggered):
// makes the comparison Original → Noisy → Final state evident,
// which is the whole point of the demo.
noisyInputs && h('div', { className: 'mb-3' },
h('div', { className: 'text-xs text-gray-400 mb-2' },
t('bs_row_noisy', { p: Math.round(noise * 100) })),
patternRow(noisyInputs, '#64748b')
),
// Results row
h('div', { className: 'mb-2' },
h('div', { className: 'text-xs text-gray-400 mb-2' },
t('bs_row_endstate', { matrix: rule === 'hebb' ? t('bs_hebb_matrix') : t('bs_pi_matrix') })),
results
? patternRow(results, rule === 'hebb' ? '#f59e0b' : '#22d3ee')
: h('div', { className: 'text-xs text-gray-500 py-6 text-center border border-dashed border-gray-700 rounded' },
t('bs_results_empty'))
),