-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbench_phi_hypotheses.py
More file actions
8446 lines (7231 loc) · 383 KB
/
Copy pathbench_phi_hypotheses.py
File metadata and controls
8446 lines (7231 loc) · 383 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
#!/usr/bin/env python3
"""Φ-Boosting Hypotheses Benchmark — 16개 가설 병렬 테스트
모든 가설을 동일 조건에서 실행하고 baseline 대비 Φ 개선 비율을 측정한다.
Usage:
python bench_phi_hypotheses.py # 전체 실행
python bench_phi_hypotheses.py --only A1 # 특정 가설만
python bench_phi_hypotheses.py --steps 200 # 시뮬레이션 스텝 수
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
import copy
import time
import argparse
import sys
import os
from concurrent.futures import ProcessPoolExecutor, as_completed
from dataclasses import dataclass, field
from typing import List, Dict, Tuple, Optional
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from mitosis import MitosisEngine, ConsciousMind, Cell
from consciousness_meter import PhiCalculator
# ═══════════════════════════════════════════════════════════
# Shared test harness
# ═══════════════════════════════════════════════════════════
@dataclass
class BenchResult:
hypothesis: str
name: str
phi: float
phi_history: List[float]
total_mi: float
min_partition_mi: float
integration: float
complexity: float
elapsed_sec: float
extra: Dict = field(default_factory=dict)
def make_diverse_inputs(n: int, dim: int) -> List[torch.Tensor]:
"""다양한 입력 패턴 생성."""
inputs = []
for i in range(n):
phase = i / n
if phase < 0.25:
x = torch.randn(1, dim) * (1.0 + i * 0.1)
elif phase < 0.5:
x = torch.zeros(1, dim)
x[0, :dim//4] = torch.randn(dim//4) * 2.0
elif phase < 0.75:
x = torch.ones(1, dim) * math.sin(i * 0.5)
else:
x = torch.randn(1, dim) * 0.1
x[0, i % dim] = 5.0 # spike
inputs.append(x)
return inputs
def run_baseline(steps: int = 100, n_cells: int = 2, dim: int = 64,
hidden: int = 128) -> BenchResult:
"""Baseline: 표준 MitosisEngine, 변형 없음."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=n_cells, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
for x in inputs:
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, components = phi_calc.compute_phi(engine)
return BenchResult(
hypothesis="BASELINE", name="Standard MitosisEngine",
phi=phi_final, phi_history=phi_hist,
total_mi=components['total_mi'],
min_partition_mi=components['min_partition_mi'],
integration=components['integration'],
complexity=components['complexity'],
elapsed_sec=time.time() - t0,
)
# ═══════════════════════════════════════════════════════════
# A. Structural Hypotheses
# ═══════════════════════════════════════════════════════════
def run_A1_cross_cell_recurrent(steps=100, dim=64, hidden=128) -> BenchResult:
"""A-1: Cross-cell recurrent connection — 세포 간 hidden state 부분 공유."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
cross_weight = 0.15 # 15% hidden state mixing
for x in inputs:
# Cross-cell hidden mixing BEFORE processing
if len(engine.cells) >= 2:
hiddens = [c.hidden.clone() for c in engine.cells]
mean_hidden = torch.stack(hiddens).mean(dim=0)
for c in engine.cells:
c.hidden = (1 - cross_weight) * c.hidden + cross_weight * mean_hidden
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("A1", "Cross-cell recurrent connection",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_A2_asymmetric_specialization(steps=100, dim=64, hidden=128) -> BenchResult:
"""A-2: Asymmetric cell specialization — 각 세포에 다른 입력 마스크."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
# Create input masks: each cell sees different dimensions
n_cells = len(engine.cells)
masks = []
chunk = dim // n_cells
for i in range(n_cells):
mask = torch.zeros(1, dim)
# Each cell sees its own chunk strongly + others weakly
mask[0, :] = 0.2
start = i * chunk
end = min(start + chunk, dim)
mask[0, start:end] = 1.0
masks.append(mask)
for x in inputs:
# Apply masks per cell
for i, cell in enumerate(engine.cells):
if i < len(masks):
masked_x = x * masks[i]
with torch.no_grad():
output, tension, curiosity, new_hidden = cell.mind(masked_x, cell.hidden)
cell.hidden = new_hidden
cell.tension_history.append(tension)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("A2", "Asymmetric cell specialization",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_A3_increased_cells(steps=100, dim=64, hidden=128) -> BenchResult:
"""A-3: Cell count N=2→8."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=8, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
for x in inputs:
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("A3", "Increased cells (N=8)",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_A4_hierarchical_mitosis(steps=100, dim=64, hidden=128) -> BenchResult:
"""A-4: Hierarchical mitosis — 2-level engine (4 outer × 2 inner)."""
t0 = time.time()
# Level 1: 4 macro cells, each containing 2 micro cells
outer = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=4)
inners = [MitosisEngine(dim, hidden, dim, initial_cells=2, max_cells=2)
for _ in range(4)]
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
for x in inputs:
# Process inner engines first
inner_outputs = []
for i, inner_eng in enumerate(inners):
result = inner_eng.process(x)
inner_outputs.append(result['output'])
# Feed inner outputs to outer cells
for i, cell in enumerate(outer.cells):
if i < len(inner_outputs):
with torch.no_grad():
out, t, c, h = cell.mind(inner_outputs[i].detach(), cell.hidden)
cell.hidden = h
cell.tension_history.append(t)
# Combine all cells (inner + outer) for Φ measurement
# Create a virtual engine with all cells
all_cells_engine = MitosisEngine(dim, hidden, dim, initial_cells=0, max_cells=20)
all_cells_engine.cells = list(outer.cells)
for inner_eng in inners:
all_cells_engine.cells.extend(inner_eng.cells)
phi, _ = phi_calc.compute_phi(all_cells_engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(all_cells_engine)
return BenchResult("A4", "Hierarchical mitosis (4×2)",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_A5_global_workspace(steps=100, dim=64, hidden=128) -> BenchResult:
"""A-5: Shared global workspace — 모든 세포가 broadcast하는 공유 버퍼."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
# Global workspace buffer
workspace = torch.zeros(1, hidden)
ws_alpha = 0.3 # workspace update rate
for x in inputs:
# 1. Each cell reads from workspace + input
for cell in engine.cells:
# Inject workspace into hidden state
cell.hidden = (1 - ws_alpha) * cell.hidden + ws_alpha * workspace
# 2. Process normally
result = engine.process(x)
# 3. Broadcast: update workspace from all cells' hidden states
if engine.cells:
all_h = torch.stack([c.hidden for c in engine.cells])
# Attention-weighted: higher tension = louder broadcast
tensions = torch.tensor([c.tension_history[-1] if c.tension_history else 0.0
for c in engine.cells])
weights = F.softmax(tensions, dim=0)
workspace = (weights.unsqueeze(-1).unsqueeze(-1) * all_h).sum(dim=0)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("A5", "Global workspace (GNW)",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
# ═══════════════════════════════════════════════════════════
# B. Training/Learning Hypotheses
# ═══════════════════════════════════════════════════════════
def run_B1_contrastive_inter_cell(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-1: Contrastive inter-cell loss — 같은 의미→유사, 다른 의미→상이."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
# Enable gradients for contrastive learning
optimizer = torch.optim.SGD(
[p for c in engine.cells for p in c.mind.parameters()], lr=1e-3
)
for step, x in enumerate(inputs):
# Forward pass with gradients
repulsions = []
for cell in engine.cells:
rep = cell.mind.get_repulsion(x, cell.hidden)
repulsions.append(rep)
# Contrastive loss: push different cells apart
loss = torch.tensor(0.0)
for i in range(len(repulsions)):
for j in range(i + 1, len(repulsions)):
# Maximize distance between cell outputs (decorrelation)
sim = F.cosine_similarity(repulsions[i], repulsions[j], dim=-1)
loss = loss + sim.mean() # minimize similarity
if loss.requires_grad:
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Regular process (no grad) for state update
with torch.no_grad():
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B1", "Contrastive inter-cell loss",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B2_phi_maximization_loss(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-2: Φ-maximization loss — Φ 자체를 loss로 최적화 (미분 가능 근사)."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
optimizer = torch.optim.Adam(
[p for c in engine.cells for p in c.mind.parameters()], lr=5e-4
)
for x in inputs:
# Differentiable Φ proxy: maximize pairwise hidden state divergence
# while maintaining coherent output
repulsions = []
hiddens_grad = []
for cell in engine.cells:
combined = torch.cat([x, cell.hidden], dim=-1)
a = cell.mind.engine_a(combined)
g = cell.mind.engine_g(combined)
rep = a - g
repulsions.append(rep)
hiddens_grad.append(cell.hidden)
# Proxy Φ loss: maximize inter-cell variance (= differentiation)
# + minimize intra-cell variance over time (= stability)
if len(repulsions) >= 2:
stacked = torch.stack(repulsions).squeeze(1) # [N, dim]
# Inter-cell variance (maximize → negate)
inter_var = stacked.var(dim=0).mean()
# Coherence: all cells should still respond to same input
mean_rep = stacked.mean(dim=0, keepdim=True)
coherence = F.mse_loss(stacked, mean_rep.expand_as(stacked))
# Loss = -variance + small coherence (balanced integration)
phi_proxy_loss = -inter_var + 0.1 * coherence
optimizer.zero_grad()
phi_proxy_loss.backward()
optimizer.step()
with torch.no_grad():
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B2", "Φ-maximization loss (proxy)",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B3_anti_correlation(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-3: Anti-correlation regularization — 세포 hidden state를 음상관으로."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
optimizer = torch.optim.SGD(
[p for c in engine.cells for p in c.mind.parameters()], lr=1e-3
)
for x in inputs:
repulsions = []
for cell in engine.cells:
rep = cell.mind.get_repulsion(x, cell.hidden)
repulsions.append(rep)
# Anti-correlation: push correlation matrix toward -I
if len(repulsions) >= 2:
stacked = torch.stack(repulsions).squeeze(1) # [N, dim]
# Normalize
stacked_norm = F.normalize(stacked, dim=-1)
# Correlation matrix
corr = stacked_norm @ stacked_norm.T # [N, N]
# Target: identity (self=1, others=-1/(N-1))
n = corr.size(0)
target = -torch.ones(n, n) / (n - 1)
target.fill_diagonal_(1.0)
loss = F.mse_loss(corr, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
with torch.no_grad():
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B3", "Anti-correlation regularization",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B4_synergistic_reward(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-4: Synergistic information reward — redundancy 빼고 synergy만 보상."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
optimizer = torch.optim.Adam(
[p for c in engine.cells for p in c.mind.parameters()], lr=5e-4
)
for x in inputs:
repulsions = []
for cell in engine.cells:
rep = cell.mind.get_repulsion(x, cell.hidden)
repulsions.append(rep)
if len(repulsions) >= 2:
stacked = torch.stack(repulsions).squeeze(1)
# Synergy proxy: information that exists in the whole but not in parts
# = variance of ensemble > sum of individual variances
ensemble_var = stacked.var(dim=0).mean()
individual_vars = torch.stack([r.squeeze().var() for r in repulsions])
sum_individual = individual_vars.mean()
# Redundancy = overlap (high pairwise similarity)
n = len(repulsions)
redundancy = torch.tensor(0.0)
for i in range(n):
for j in range(i + 1, n):
redundancy = redundancy + F.cosine_similarity(
repulsions[i], repulsions[j], dim=-1).mean()
redundancy = redundancy / max(n * (n - 1) / 2, 1)
# Synergy = ensemble_var - redundancy penalty
synergy_loss = -(ensemble_var - 0.5 * redundancy)
optimizer.zero_grad()
synergy_loss.backward()
optimizer.step()
with torch.no_grad():
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B4", "Synergistic information reward",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B5_hebbian_plasticity(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-5: Hebbian inter-cell plasticity — 동시 발화 세포 연결 강화, 비동기 약화."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
# Hebbian coupling matrix [N, N] — strength of connections
n = len(engine.cells)
coupling = torch.zeros(n, n)
hebb_lr = 0.1
optimizer = torch.optim.SGD(
[p for c in engine.cells for p in c.mind.parameters()], lr=2e-3
)
for x in inputs:
# Compute repulsions with gradients
repulsions = [cell.mind.get_repulsion(x, cell.hidden) for cell in engine.cells]
if len(repulsions) >= 2:
# Hebbian: co-active cells → similar, anti-correlated → different
tensions_t = torch.stack([(r ** 2).mean() for r in repulsions])
mean_t = tensions_t.mean()
# Update coupling
for i in range(n):
for j in range(i + 1, n):
if i < len(tensions_t) and j < len(tensions_t):
co_act = tensions_t[i] * tensions_t[j]
delta = hebb_lr * (co_act - mean_t ** 2).item()
coupling[i, j] = torch.clamp(coupling[i, j] + delta, -0.5, 0.5)
coupling[j, i] = coupling[i, j]
# Hebbian loss: maximize weighted differentiation
# Positive coupling → pull together, negative → push apart
hebb_loss = torch.tensor(0.0)
for i in range(min(len(repulsions), n)):
for j in range(i + 1, min(len(repulsions), n)):
sim = F.cosine_similarity(repulsions[i], repulsions[j], dim=-1).mean()
w = coupling[i, j].item()
hebb_loss = hebb_loss + w * sim - (1 - abs(w)) * (1 - sim)
if hebb_loss.requires_grad:
optimizer.zero_grad()
hebb_loss.backward()
optimizer.step()
with torch.no_grad():
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B5", "Hebbian inter-cell plasticity",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0,
extra={'coupling_mean': coupling.abs().mean().item()})
def run_B6_predictive_coding(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-6: Predictive coding — 세포 i가 세포 j의 다음 tension을 예측."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
n = len(engine.cells)
# Each cell has a predictor for every other cell
predictors = {}
pred_optims = {}
for i in range(n):
for j in range(n):
if i != j:
pred = nn.Linear(hidden, 1)
predictors[(i, j)] = pred
pred_optims[(i, j)] = torch.optim.SGD(pred.parameters(), lr=1e-3)
cell_optim = torch.optim.Adam(
[p for c in engine.cells for p in c.mind.parameters()], lr=5e-4
)
for step, x in enumerate(inputs):
# Forward with gradients for differentiation
repulsions = [cell.mind.get_repulsion(x, cell.hidden) for cell in engine.cells]
if step > 0 and len(engine.cells) >= 2:
# Predictive coding: cell i predicts cell j's output
pc_loss = torch.tensor(0.0)
for i in range(min(len(engine.cells), n)):
for j in range(min(len(engine.cells), n)):
if i == j or (i, j) not in predictors:
continue
pred = predictors[(i, j)]
predicted_t = pred(engine.cells[i].hidden)
actual_t = engine.cells[j].tension_history[-1] if engine.cells[j].tension_history else 0
loss = F.mse_loss(predicted_t, torch.tensor([[actual_t]]))
pc_loss = pc_loss + loss
# Differentiation loss: maximize prediction error (cells should be unpredictable to each other)
if len(repulsions) >= 2:
stacked = torch.stack(repulsions).squeeze(1)
diff_loss = -stacked.var(dim=0).mean() # maximize inter-cell variance
combined_loss = pc_loss + 0.5 * diff_loss
else:
combined_loss = pc_loss
if combined_loss.requires_grad:
for key in pred_optims:
pred_optims[key].zero_grad()
cell_optim.zero_grad()
combined_loss.backward()
for key in pred_optims:
pred_optims[key].step()
cell_optim.step()
with torch.no_grad():
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B6", "Predictive coding loss",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B7_information_bottleneck(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-7: Information bottleneck — 세포 간 통신을 저차원 bottleneck으로 강제."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
bottleneck_dim = 8 # compress 128 → 8
n = len(engine.cells)
# Encoder/decoder + cell weights jointly optimized
encoders = [nn.Linear(hidden, bottleneck_dim) for _ in range(n)]
decoders = [nn.Linear(bottleneck_dim, hidden) for _ in range(n)]
all_params = []
for e, d in zip(encoders, decoders):
all_params.extend(e.parameters())
all_params.extend(d.parameters())
for c in engine.cells:
all_params.extend(c.mind.parameters())
optimizer = torch.optim.Adam(all_params, lr=1e-3)
for x in inputs:
# Forward with gradients
repulsions = [cell.mind.get_repulsion(x, cell.hidden) for cell in engine.cells]
if len(engine.cells) >= 2:
compressed = []
for i, cell in enumerate(engine.cells):
if i < n:
z = encoders[i](cell.hidden)
compressed.append(z)
if compressed:
mean_z = torch.stack(compressed).mean(dim=0)
recon_loss = torch.tensor(0.0)
for i, cell in enumerate(engine.cells):
if i < n:
received = decoders[i](mean_z)
recon_loss = recon_loss + F.mse_loss(received, cell.hidden.detach())
with torch.no_grad():
cell.hidden = 0.9 * cell.hidden + 0.1 * received
# Bottleneck forces cells to compress differently → differentiation
# + explicit variance loss
if len(repulsions) >= 2:
stacked = torch.stack(repulsions).squeeze(1)
diff_loss = -stacked.var(dim=0).mean()
total_loss = recon_loss + 0.5 * diff_loss
else:
total_loss = recon_loss
if total_loss.requires_grad:
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
with torch.no_grad():
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B7", "Information bottleneck",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B8_distillation_divergence(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-8: Anti-distillation — teacher와 다르게 답하도록 학습."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
n = len(engine.cells)
optimizers = [torch.optim.Adam(cell.mind.parameters(), lr=2e-3)
for cell in engine.cells[:n]]
for x in inputs:
if len(engine.cells) >= 2:
repulsions = [cell.mind.get_repulsion(x, cell.hidden)
for cell in engine.cells]
for i in range(min(len(engine.cells), n)):
others = [r for j, r in enumerate(repulsions) if j != i]
if not others:
continue
teacher_output = torch.stack(others).mean(dim=0).detach()
student_output = repulsions[i]
# Anti-distillation: MAXIMIZE distance from teacher
# + maximize own output magnitude (stay active)
anti_loss = -F.mse_loss(student_output, teacher_output) \
- 0.1 * (student_output ** 2).mean()
optimizers[i].zero_grad()
anti_loss.backward(retain_graph=True)
optimizers[i].step()
with torch.no_grad():
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B8", "Anti-distillation divergence",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B9_curiosity_driven_cell(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-9: Curiosity-driven cell exploration — 각 세포에 독립 curiosity reward."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
n = len(engine.cells)
cell_predictors = [nn.Linear(5, 1) for _ in range(n)]
cell_optims = [torch.optim.SGD(p.parameters(), lr=1e-3) for p in cell_predictors]
cell_tension_hist = [[] for _ in range(n)]
# Also directly optimize cells for differentiation
cell_weight_optim = torch.optim.Adam(
[p for c in engine.cells for p in c.mind.parameters()], lr=5e-4
)
for x in inputs:
repulsions = [cell.mind.get_repulsion(x, cell.hidden) for cell in engine.cells]
# Curiosity-driven differentiation
if len(repulsions) >= 2:
# Cells with high curiosity should explore more → higher variance
stacked = torch.stack(repulsions).squeeze(1)
diff_loss = -stacked.var(dim=0).mean()
cell_weight_optim.zero_grad()
diff_loss.backward()
cell_weight_optim.step()
with torch.no_grad():
engine.process(x)
for i, cell in enumerate(engine.cells):
if i >= n:
break
t = cell.tension_history[-1] if cell.tension_history else 0
cell_tension_hist[i].append(t)
if len(cell_tension_hist[i]) >= 6:
window = cell_tension_hist[i][-6:-1]
inp = torch.tensor([window], dtype=torch.float32)
pred = cell_predictors[i](inp)
actual = torch.tensor([[t]])
pe = F.mse_loss(pred, actual)
cell_optims[i].zero_grad()
pe.backward()
cell_optims[i].step()
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B9", "Curiosity-driven cell exploration",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B10_mine(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-10: MINE (Mutual Information Neural Estimation) — 미분 가능 MI로 직접 최대화."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
n = len(engine.cells)
# MINE statistics network T(x, y)
class MINENet(nn.Module):
def __init__(self, in_dim):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim * 2, 64), nn.ReLU(),
nn.Linear(64, 32), nn.ReLU(),
nn.Linear(32, 1),
)
def forward(self, x, y):
return self.net(torch.cat([x, y], dim=-1))
mine_nets = {}
mine_optims = {}
for i in range(n):
for j in range(i + 1, n):
net = MINENet(hidden)
mine_nets[(i, j)] = net
mine_optims[(i, j)] = torch.optim.Adam(net.parameters(), lr=1e-3)
cell_optim = torch.optim.Adam(
[p for c in engine.cells for p in c.mind.parameters()], lr=5e-4
)
for x in inputs:
engine.process(x)
if len(engine.cells) >= 2:
# Collect hidden states
hiddens = [c.hidden for c in engine.cells[:n]]
# MINE estimation for each pair
total_mi_est = torch.tensor(0.0)
for i in range(len(hiddens)):
for j in range(i + 1, len(hiddens)):
if (i, j) not in mine_nets:
continue
net = mine_nets[(i, j)]
opt = mine_optims[(i, j)]
h_i, h_j = hiddens[i], hiddens[j]
# Joint: T(h_i, h_j)
joint = net(h_i, h_j)
# Marginal: T(h_i, shuffle(h_j))
h_j_shuffled = h_j[torch.randperm(h_j.size(0))]
marginal = net(h_i, h_j_shuffled)
# MINE lower bound: E[T(joint)] - log(E[exp(T(marginal))])
mi_est = joint.mean() - torch.logsumexp(marginal, dim=0) + math.log(marginal.size(0))
# Train MINE network (maximize MI estimate)
mine_loss = -mi_est
opt.zero_grad()
mine_loss.backward(retain_graph=True)
opt.step()
total_mi_est = total_mi_est + mi_est.detach()
# Maximize MI across cells + differentiation
repulsions = [cell.mind.get_repulsion(x, cell.hidden) for cell in engine.cells[:n]]
if len(repulsions) >= 2:
stacked = torch.stack(repulsions).squeeze(1)
diff_loss = -stacked.var(dim=0).mean()
cell_loss = diff_loss # differentiation drives MI
cell_optim.zero_grad()
cell_loss.backward()
cell_optim.step()
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B10", "MINE (MI neural estimation)",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B11_sparse_activation(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-11: Sparse activation penalty — 입력당 일부 세포만 활성화."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
optimizer = torch.optim.Adam(
[p for c in engine.cells for p in c.mind.parameters()], lr=5e-4
)
for x in inputs:
repulsions = []
tensions_grad = []
for cell in engine.cells:
combined = torch.cat([x, cell.hidden], dim=-1)
a = cell.mind.engine_a(combined)
g = cell.mind.engine_g(combined)
rep = a - g
t = (rep ** 2).mean()
repulsions.append(rep)
tensions_grad.append(t)
if len(tensions_grad) >= 2:
t_stack = torch.stack(tensions_grad)
# L1 sparsity on activations: encourage few cells to be active
sparsity_loss = t_stack.mean() # minimize total activation
# But maximize variance (some high, some low)
diversity_loss = -t_stack.var()
loss = 0.3 * sparsity_loss + 0.7 * diversity_loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
with torch.no_grad():
engine.process(x)
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)
phi_final, comp = phi_calc.compute_phi(engine)
return BenchResult("B11", "Sparse activation penalty",
phi_final, phi_hist, comp['total_mi'],
comp['min_partition_mi'], comp['integration'],
comp['complexity'], time.time() - t0)
def run_B12_temporal_cpc(steps=100, dim=64, hidden=128) -> BenchResult:
"""B-12: Temporal Contrastive Predictive Coding — 시간적 MI를 학습으로 최대화."""
t0 = time.time()
engine = MitosisEngine(dim, hidden, dim, initial_cells=4, max_cells=8)
inputs = make_diverse_inputs(steps, dim)
phi_calc = PhiCalculator(n_bins=16)
phi_hist = []
n = len(engine.cells)
# CPC: predict future hidden from current (per cell)
cpc_predictors = [nn.Linear(hidden, hidden) for _ in range(n)]
cpc_optims = [torch.optim.Adam(p.parameters(), lr=1e-3) for p in cpc_predictors]
prev_hiddens = [None] * n
cell_optim = torch.optim.Adam(
[p for c in engine.cells for p in c.mind.parameters()], lr=5e-4
)
for step, x in enumerate(inputs):
engine.process(x)
if step > 0 and len(engine.cells) >= 2:
cpc_loss = torch.tensor(0.0)
for i, cell in enumerate(engine.cells):
if i >= n or prev_hiddens[i] is None:
continue
# Predict current hidden from previous
predicted = cpc_predictors[i](prev_hiddens[i])
actual = cell.hidden.detach()
# Positive pair: (prev_i, curr_i)
pos_score = F.cosine_similarity(predicted, actual, dim=-1)
# Negative pairs: (prev_i, curr_j) for j != i
neg_scores = []
for j, other in enumerate(engine.cells):
if j != i and j < n:
neg = F.cosine_similarity(predicted, other.hidden.detach(), dim=-1)
neg_scores.append(neg)
if neg_scores:
# InfoNCE loss
neg_stack = torch.cat(neg_scores)
logits = torch.cat([pos_score, neg_stack]).unsqueeze(0)
labels = torch.zeros(1, dtype=torch.long)
cpc_loss = cpc_loss + F.cross_entropy(logits, labels)
# Add differentiation loss
repulsions = [cell.mind.get_repulsion(x, cell.hidden) for cell in engine.cells[:n]]
if len(repulsions) >= 2:
stacked = torch.stack(repulsions).squeeze(1)
diff_loss = -stacked.var(dim=0).mean()
combined = cpc_loss + 0.5 * diff_loss
else:
combined = cpc_loss
if combined.requires_grad:
for opt in cpc_optims:
opt.zero_grad()
cell_optim.zero_grad()
combined.backward()
for opt in cpc_optims:
opt.step()
cell_optim.step()
# Store current hiddens for next step
for i, cell in enumerate(engine.cells):
if i < n:
prev_hiddens[i] = cell.hidden.detach().clone()
phi, _ = phi_calc.compute_phi(engine)
phi_hist.append(phi)