forked from kushalk173-sc/HiCL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathl.py
More file actions
4661 lines (3928 loc) · 200 KB
/
Copy pathl.py
File metadata and controls
4661 lines (3928 loc) · 200 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
"""
Train Hippocampal MoE with DG-based Gating + Analyze Model
This script implements a novel gating mechanism based on Dentate Gyrus (DG)
pattern similarity instead of a separate gating network.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import logging
from tqdm import tqdm
import argparse
import os
from datetime import datetime
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
import json
import torch.optim as optim
import sys
from sklearn.metrics import confusion_matrix, silhouette_score, davies_bouldin_score, pairwise_distances
import random
from collections import defaultdict
from scipy.spatial.distance import cdist
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
# Import from the optimal training script
from train_hippocampal_optimal_moe import *
# Import SparseActivation for our custom DG expert
from train_hippocampal_optimal_moe import SparseActivation
dg_dim=512
# ============================================================================
# GRID CELL LAYER
# ============================================================================
class GridCellLayer(nn.Module):
"""
Implements grid cell-like spatial encoding from entorhinal cortex
Uses multiple spatial frequencies to create hexagonal grid patterns
"""
def __init__(self, channels: int):
super().__init__()
self.channels = channels
# Different spatial frequencies (like biological grid cells)
self.freq1 = nn.Conv2d(channels, channels//4, 1)
self.freq2 = nn.Conv2d(channels, channels//4, 1)
self.freq3 = nn.Conv2d(channels, channels//4, 1)
self.freq4 = nn.Conv2d(channels, channels//4, 1)
# Phase offsets (creates hexagonal patterns)
self.register_buffer('phase1', torch.randn(1, channels//4, 1, 1))
self.register_buffer('phase2', torch.randn(1, channels//4, 1, 1))
self.register_buffer('phase3', torch.randn(1, channels//4, 1, 1))
self.register_buffer('phase4', torch.randn(1, channels//4, 1, 1))
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Different spatial frequencies with phase offsets
y1 = torch.sin(self.freq1(x) + self.phase1)
y2 = torch.sin(self.freq2(x) + self.phase2)
y3 = torch.sin(self.freq3(x) + self.phase3)
y4 = torch.sin(self.freq4(x) + self.phase4)
return torch.cat([y1, y2, y3, y4], dim=1)
# ============================================================================
# STANDARD FEATURE EXTRACTOR (COPIED FROM Y.PY)
# ============================================================================
class StandardFeatureExtractor(nn.Module):
"""
Standard LeNet-style feature extractor with regular convolutions.
"""
def __init__(self, input_channels, use_small_features=False):
super().__init__()
self.use_small_features = use_small_features
if use_small_features:
# Small version: 3→32→64→128 (like HippoLeNet small)
self.net = nn.Sequential(
nn.Conv2d(input_channels, 32, kernel_size=3, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2, 2),
GridCellLayer(32),
nn.Conv2d(32, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(2, 2)
)
else:
# Standard version: 3→64→128→256
self.net = nn.Sequential(
nn.Conv2d(input_channels, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2, 2),
GridCellLayer(64),
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Conv2d(128, 256, kernel_size=3, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.MaxPool2d(2, 2)
)
def forward(self, x):
return self.net(x)
# ============================================================================
# CUSTOM ENHANCED HIPPOCAMPAL EXPERT FOR DG-GATED MODEL
# ============================================================================
class CustomDentateGyrusExpert(nn.Module):
"""
CORRECTED Dentate Gyrus Expert with feature reduction to control parameters.
This version ensures that the final output of the module is the sparse representation,
which is critical for the DG-gating mechanism to work correctly.
"""
def __init__(self, input_dim, hidden_dim, sparsity=0.05, expansion_factor=1 ):
super().__init__()
# Reduce input dimension to control parameter count
reduced_dim = min(input_dim, 1024) # Cap at 1024 to prevent parameter explosion
expanded_dim = reduced_dim * expansion_factor
# Feature reduction layer
self.feature_reduction = nn.Linear(input_dim, reduced_dim) if input_dim > reduced_dim else nn.Identity()
# All dense transformations happen *before* sparsity is applied
self.pre_sparse_processing = nn.Sequential(
SparseActivation(percent_on=sparsity),
nn.Linear(reduced_dim, expanded_dim),
nn.ReLU(),
nn.LayerNorm(expanded_dim),
nn.Linear(expanded_dim, hidden_dim),
nn.ReLU(),
nn.LayerNorm(hidden_dim),
#SparseActivation(percent_on=sparsity),
)
self.out_features = hidden_dim
def forward(self, x):
# Apply feature reduction first
x_reduced = self.feature_reduction(x)
return self.pre_sparse_processing(x_reduced)
class CustomCA3PatternCompletion(nn.Module):
"""
Custom CA3 Pattern Completion for the DG-Gated model with reduced dim.
"""
def __init__(self, input_dim, hidden_dim):
super().__init__()
self.pattern_completion = nn.Sequential(
nn.Linear(input_dim, hidden_dim), # No expansion
nn.ReLU(),
nn.LayerNorm(hidden_dim),
nn.Dropout(0.1),
nn.Linear(hidden_dim, hidden_dim), # Keep dim
nn.ReLU(),
nn.LayerNorm(hidden_dim)
)
def forward(self, x):
# print(f"[CA3] Input shape: {x.shape}")
out = self.pattern_completion(x)
# print(f"[CA3] Output shape: {out.shape}")
return out
class CustomEnhancedHippocampalExpert(nn.Module):
"""
Custom Enhanced Hippocampal Expert for the DG-Gated model with expanded dims.
"""
def __init__(self, input_dim, dg_dim, ca3_dim, target_sparsity=0.05, dropout_rate=0.1):
super().__init__()
self.dg = CustomDentateGyrusExpert(input_dim, dg_dim, target_sparsity)
self.ca3 = CustomCA3PatternCompletion(dg_dim, ca3_dim)
# CA1 integration: [DG + CA3 + raw features] -> dg_dim -> 256 -> 128
self.ca1_integration = nn.Sequential(
nn.Linear(dg_dim + ca3_dim + input_dim, dg_dim),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.LayerNorm(dg_dim),
nn.Linear(dg_dim, 256),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.LayerNorm(256),
nn.Linear(256, 128), # Changed from 256 to 128 to match output layers
nn.Dropout(dropout_rate)
)
def forward(self, features):
dg_output = self.dg(features)
ca3_output = self.ca3(dg_output)
combined = torch.cat([dg_output, ca3_output, features], dim=1)
ca1_output = self.ca1_integration(combined)
return dg_output, ca1_output
# ============================================================================
# NEW DG-GATED HIPPOCAMPAL MOE
# ============================================================================
class DGGatedHippocampalMoE(OptimalHippocampalMoE):
"""
DG-Gated Hippocampal MoE with online per-class EMA prototype computation.
"""
def __init__(self, num_experts, classes_per_task, input_channels, target_sparsity=0.05, memory_size=200, use_small_features=False):
# Call parent with correct parameters
super().__init__(num_experts, classes_per_task, input_channels, target_sparsity, memory_size)
# Store target_sparsity as instance variable
self.target_sparsity = target_sparsity
# Initialize prototype tracking variables
self.class_proto_ema = None
self.class_proto_counts = None
self.frozen_class_mask = None
self.warmup_batches = 30
self.ema_momentum = 0.9
self.num_classes = num_experts * classes_per_task
# Initialize EWC data storage
self.ewc_data = []
# Initialize replay buffer
self.replay_buffer = [[] for _ in range(num_experts)]
self.memory_size_per_task = memory_size
# Gating parameters
self.gating_strategy = 'soft_hard'
self.gating_temperature = 1.0
# Task classes will be set later
self.task_classes = None
logging.info(f"🔧 Initialized DG-Gated Hippocampal MoE with {num_experts} experts, {classes_per_task} classes per task")
logging.info(f"🔧 Target DG sparsity: {target_sparsity}, Memory size per task: {memory_size}")
logging.info(f"🔧 EMA parameters: warmup={self.warmup_batches}, momentum={self.ema_momentum}")
# Use StandardFeatureExtractor with optional small features
self.feature_extractor = StandardFeatureExtractor(input_channels, use_small_features=use_small_features)
# Calculate feature dimension (256 channels * spatial dimensions, no global pooling)
with torch.no_grad():
dummy_input = torch.zeros(1, input_channels, 32, 32)
dummy_output = self.feature_extractor(dummy_input)
feature_extractor_output_dim = dummy_output.numel()
feature_size_desc = "128 channels" if use_small_features else "256 channels"
logging.info(f"🔧 Feature extractor output dimension: {feature_extractor_output_dim} ({feature_size_desc} * spatial dims)")
logging.info(f"🔧 Using {'small' if use_small_features else 'standard'} feature extractor")
# No need for feature projector since we have full feature dimensions
self.feature_projector = None
# Use CustomEnhancedHippocampalExpert with controlled parameters
self.hippocampal_experts = nn.ModuleList([
CustomEnhancedHippocampalExpert(
input_dim=feature_extractor_output_dim,
dg_dim=dg_dim,
ca3_dim=256,
target_sparsity=target_sparsity,
dropout_rate=0.1
) for _ in range(num_experts)
])
# Use parent class output layers (CA1 output dimension is 128)
self.output_layers = nn.ModuleList([
nn.Linear(128, classes_per_task) for _ in range(num_experts)
])
# Initialize online EMA tracking for prototypes
self.class_proto_ema = None # Will be initialized when first expert starts
self.class_proto_counts = None # Will be initialized when first expert starts
self.frozen_class_mask = None # Will be initialized when first expert starts
self.ema_momentum = 0.9 # EMA momentum for prototype updates
self.warmup_batches = 30 # Number of batches for warm-up (cumulative mean)
# Track which experts have finished training
self.trained_experts = 0
# Add memory buffer for replay
self.memory_size = memory_size
self.replay_buffer = [[] for _ in range(self.num_experts)]
self.memory_size_per_task = self.memory_size
# Initialize DG prototypes buffer (will be updated by EMA)
self.register_buffer('dg_prototypes', torch.zeros(num_experts, dg_dim))
self.prototypes_computed = False
# Remove gating network since we use DG-based gating
self.gating_network = None
# Add feature_to_ca1 projection for feature distillation (from parent class)
self.feature_to_ca1 = nn.Linear(feature_extractor_output_dim, 128) # Full feature dim -> 128 to match CA1 output dim
# Log parameter counts for verification
total_params = sum(p.numel() for p in self.parameters())
expert_params = sum(p.numel() for expert in self.hippocampal_experts for p in expert.parameters())
logging.info(f"🔧 Total model parameters: {total_params:,}")
logging.info(f"🔧 Expert parameters: {expert_params:,} ({expert_params/num_experts:,} per expert)")
def compute_fisher_importance(self, dataloader, device, num_samples=500):
"""
Compute Fisher Information Matrix for EWC.
This is the one-time calculation between tasks.
IMPROVED: Now captures ALL trainable parameters, not just those with gradients.
"""
self.eval()
fisher_info = {}
# Initialize fisher info for ALL trainable parameters
total_params = 0
for name, param in self.named_parameters():
if param.requires_grad:
fisher_info[name] = torch.zeros_like(param.data)
total_params += param.numel()
logging.info(f"🔧 EWC: Initializing Fisher info for {len(fisher_info)} parameter groups ({total_params:,} total parameters)")
# Sample data for Fisher computation
sample_count = 0
for inputs, labels in dataloader:
if sample_count >= num_samples:
break
inputs, labels = inputs.to(device), labels.to(device)
# Forward pass - use a simplified version that doesn't require DG prototypes
self.zero_grad()
# Extract features
features = self.feature_extractor(inputs).view(inputs.size(0), -1)
# Get outputs from all experts (without gating)
all_outputs = []
for expert_id in range(self.num_experts):
dg_output, ca1_output = self.hippocampal_experts[expert_id](features)
expert_output = self.output_layers[expert_id](ca1_output)
all_outputs.append(expert_output)
# Concatenate all expert outputs
outputs = torch.cat(all_outputs, dim=1)
# Compute loss (assuming classification)
loss = F.cross_entropy(outputs, labels)
# Backward pass to get gradients
loss.backward()
# Accumulate Fisher information for ALL parameters
for name, param in self.named_parameters():
if param.requires_grad:
if param.grad is not None:
fisher_info[name] += param.grad.data ** 2
else:
# For parameters without gradients, add small epsilon to avoid zeros
# This ensures all parameters are protected by EWC
fisher_info[name] += torch.ones_like(param.data) * 1e-8
sample_count += inputs.size(0)
# Average over samples
for name in fisher_info:
fisher_info[name] /= sample_count
# Log statistics about Fisher information
non_zero_params = sum(1 for fisher in fisher_info.values() if fisher.sum() > 1e-8)
total_fisher_params = sum(fisher.numel() for fisher in fisher_info.values())
logging.info(f"🔧 EWC: Computed Fisher info for {non_zero_params}/{len(fisher_info)} parameter groups")
logging.info(f"🔧 EWC: Total Fisher parameters: {total_fisher_params:,}")
self.train()
return fisher_info
def compute_fisher_importance_enhanced(self, dataloader, device, num_samples=500, num_forward_passes=3):
"""
Enhanced Fisher Information Matrix computation for EWC.
Uses multiple forward passes with different inputs to get more robust estimates.
"""
self.eval()
fisher_info = {}
# Initialize fisher info for ALL trainable parameters
total_params = 0
for name, param in self.named_parameters():
if param.requires_grad:
fisher_info[name] = torch.zeros_like(param.data)
total_params += param.numel()
logging.info(f"🔧 EWC Enhanced: Initializing Fisher info for {len(fisher_info)} parameter groups ({total_params:,} total parameters)")
# Sample data for Fisher computation
sample_count = 0
for inputs, labels in dataloader:
if sample_count >= num_samples:
break
inputs, labels = inputs.to(device), labels.to(device)
# Multiple forward passes with different inputs for robustness
batch_fisher = {name: torch.zeros_like(param.data) for name, param in self.named_parameters() if param.requires_grad}
for pass_idx in range(num_forward_passes):
self.zero_grad()
# Extract features
features = self.feature_extractor(inputs).view(inputs.size(0), -1)
# Get outputs from all experts (without gating)
all_outputs = []
for expert_id in range(self.num_experts):
dg_output, ca1_output = self.hippocampal_experts[expert_id](features)
expert_output = self.output_layers[expert_id](ca1_output)
all_outputs.append(expert_output)
# Concatenate all expert outputs
outputs = torch.cat(all_outputs, dim=1)
# Compute loss (assuming classification)
loss = F.cross_entropy(outputs, labels)
# Backward pass to get gradients
loss.backward()
# Accumulate Fisher information for this forward pass
for name, param in self.named_parameters():
if param.requires_grad:
if param.grad is not None:
batch_fisher[name] += param.grad.data ** 2
else:
# For parameters without gradients, add small epsilon
batch_fisher[name] += torch.ones_like(param.data) * 1e-8
# Average over forward passes and accumulate
for name in batch_fisher:
batch_fisher[name] /= num_forward_passes
fisher_info[name] += batch_fisher[name]
sample_count += inputs.size(0)
# Average over samples
for name in fisher_info:
fisher_info[name] /= sample_count
# Log statistics about Fisher information
non_zero_params = sum(1 for fisher in fisher_info.values() if fisher.sum() > 1e-8)
total_fisher_params = sum(fisher.numel() for fisher in fisher_info.values())
logging.info(f"🔧 EWC Enhanced: Computed Fisher info for {non_zero_params}/{len(fisher_info)} parameter groups")
logging.info(f"🔧 EWC Enhanced: Total Fisher parameters: {total_fisher_params:,}")
self.train()
return fisher_info
def analyze_fisher_quality(self, fisher_matrix):
"""
Analyze the quality of Fisher information matrix.
Provides diagnostics to ensure EWC is capturing meaningful parameter importance.
"""
if not fisher_matrix:
return {}
analysis = {}
# Count parameters by type
total_params = 0
non_zero_params = 0
param_types = {}
for name, fisher_values in fisher_matrix.items():
param_count = fisher_values.numel()
total_params += param_count
# Count non-zero Fisher values
non_zero_count = (fisher_values > 1e-8).sum().item()
non_zero_params += non_zero_count
# Categorize by parameter type
if 'feature_extractor' in name:
param_type = 'feature_extractor'
elif 'hippocampal_experts' in name:
param_type = 'hippocampal_experts'
elif 'output_layers' in name:
param_type = 'output_layers'
elif 'gate' in name:
param_type = 'gating'
else:
param_type = 'other'
if param_type not in param_types:
param_types[param_type] = {'total': 0, 'non_zero': 0}
param_types[param_type]['total'] += param_count
param_types[param_type]['non_zero'] += non_zero_count
# Calculate statistics
analysis['total_parameters'] = total_params
analysis['non_zero_parameters'] = non_zero_params
analysis['coverage_ratio'] = non_zero_params / total_params if total_params > 0 else 0
analysis['param_types'] = param_types
# Fisher value statistics
all_fisher_values = torch.cat([f.flatten() for f in fisher_matrix.values()])
analysis['fisher_stats'] = {
'mean': float(all_fisher_values.mean()),
'std': float(all_fisher_values.std()),
'min': float(all_fisher_values.min()),
'max': float(all_fisher_values.max()),
'median': float(all_fisher_values.median())
}
# Log analysis
logging.info(f"🔧 EWC Fisher Analysis:")
logging.info(f" - Total parameters: {total_params:,}")
logging.info(f" - Non-zero Fisher values: {non_zero_params:,}")
logging.info(f" - Coverage ratio: {analysis['coverage_ratio']:.3f}")
logging.info(f" - Fisher value range: [{analysis['fisher_stats']['min']:.2e}, {analysis['fisher_stats']['max']:.2e}]")
logging.info(f" - Fisher mean/std: {analysis['fisher_stats']['mean']:.2e}/{analysis['fisher_stats']['std']:.2e}")
for param_type, stats in param_types.items():
coverage = stats['non_zero'] / stats['total'] if stats['total'] > 0 else 0
logging.info(f" - {param_type}: {stats['non_zero']:,}/{stats['total']:,} ({coverage:.3f})")
return analysis
def calculate_ewc_loss(self, ewc_lambda=1000.0):
"""
Calculate EWC loss to prevent forgetting of previous tasks.
IMPROVED: Better logging and more robust calculation.
"""
if not self.ewc_data:
return torch.tensor(0.0, device=next(self.parameters()).device)
ewc_loss = 0.0
total_ewc_terms = 0
for task_idx, task_data in enumerate(self.ewc_data):
fisher_matrix = task_data['fisher']
star_params = task_data['star_params']
task_ewc_loss = 0.0
task_terms = 0
for name, param in self.named_parameters():
if name in fisher_matrix and name in star_params:
if param.requires_grad:
# Compute squared difference from optimal parameters
param_diff = param - star_params[name]
fisher_weighted_diff = fisher_matrix[name] * (param_diff ** 2)
task_ewc_loss += fisher_weighted_diff.sum()
task_terms += fisher_weighted_diff.numel()
ewc_loss += task_ewc_loss
total_ewc_terms += task_terms
# Log per-task EWC contribution
if task_ewc_loss > 0:
logging.debug(f"🔧 EWC Task {task_idx}: Loss={task_ewc_loss:.6f}, Terms={task_terms:,}")
# Apply lambda scaling
final_ewc_loss = ewc_lambda * ewc_loss
# Log EWC statistics
if ewc_loss > 0:
logging.debug(f"🔧 EWC Total: Loss={ewc_loss:.6f}, Scaled={final_ewc_loss:.6f}, Total Terms={total_ewc_terms:,}")
return final_ewc_loss
def initialize_prototype_tracking(self, dg_dim, num_classes, device):
"""Initialize EMA tracking variables for online prototype computation."""
self.class_proto_ema = torch.zeros(num_classes, dg_dim, device=device)
self.class_proto_counts = torch.zeros(num_classes, device=device)
self.frozen_class_mask = torch.zeros(num_classes, dtype=torch.bool, device=device)
logging.info(f"🔧 Initialized online prototype tracking: {num_classes} classes, {dg_dim} DG dims")
def update_class_prototype_ema(self, dg_outputs, labels, expert_id):
"""
Update class prototypes using EMA for the current expert's classes.
Args:
dg_outputs: DG outputs from current expert [batch_size, dg_dim]
labels: Global class labels [batch_size]
expert_id: Current expert being trained
"""
if self.class_proto_ema is None:
# Initialize tracking on first call
dg_dim = dg_outputs.size(1)
num_classes = self.num_classes
self.initialize_prototype_tracking(dg_dim, num_classes, dg_outputs.device)
# Check if task_classes is initialized
if not hasattr(self, 'task_classes') or self.task_classes is None or len(self.task_classes) <= expert_id:
return # Skip if task_classes not ready
# Check if tracking variables are initialized
if (self.class_proto_ema is None or self.class_proto_counts is None or
self.frozen_class_mask is None):
return
with torch.no_grad():
# Get classes for current expert
expert_classes = self.task_classes[expert_id]
for class_id in expert_classes:
if self.frozen_class_mask[class_id]:
continue # Skip frozen classes
# Find samples belonging to this class
class_mask = (labels == class_id)
if class_mask.sum() > 0:
class_dg_outputs = dg_outputs[class_mask]
class_mean = class_dg_outputs.mean(dim=0)
if self.class_proto_counts[class_id] < self.warmup_batches:
# Cumulative mean during warm-up
total_prev = self.class_proto_counts[class_id].item()
self.class_proto_ema[class_id] = (self.class_proto_ema[class_id] * total_prev + class_mean) / (total_prev + 1)
else:
# EMA update after warm-up
self.class_proto_ema[class_id] = (1 - self.ema_momentum) * self.class_proto_ema[class_id] + self.ema_momentum * class_mean
self.class_proto_counts[class_id] += 1
def freeze_expert_prototypes(self, expert_id):
"""Freeze prototypes for all classes of the given expert."""
if (self.frozen_class_mask is not None and
hasattr(self, 'task_classes') and
self.task_classes is not None and
len(self.task_classes) > expert_id):
expert_classes = self.task_classes[expert_id]
for class_id in expert_classes:
self.frozen_class_mask[class_id] = True
logging.info(f"🔒 Frozen prototypes for expert {expert_id} classes: {expert_classes}")
def compute_expert_prototypes_from_classes(self, expert_id):
"""Compute expert prototype as mean of its class prototypes."""
if (self.class_proto_ema is None or
not hasattr(self, 'task_classes') or
self.task_classes is None or
len(self.task_classes) <= expert_id):
return None
expert_classes = self.task_classes[expert_id]
class_prototypes = self.class_proto_ema[expert_classes]
expert_prototype = class_prototypes.mean(dim=0)
return expert_prototype
def get_active_prototypes_for_diagnostics(self, expert_id):
"""
Get active prototypes for diagnostics, including current expert's prototype
even if not yet frozen.
"""
if not hasattr(self, 'dg_prototypes') or self.dg_prototypes is None:
return None, 0
# Determine active experts (trained + current)
active_E = max(self.trained_experts, expert_id + 1)
# Create temporary prototypes tensor
temp_protos = self.dg_prototypes.clone()
# Synthesize current expert prototype from EMA if not frozen yet
if expert_id >= self.trained_experts:
cur_proto = self.compute_expert_prototypes_from_classes(expert_id)
if cur_proto is not None:
temp_protos[expert_id] = cur_proto
# Return only active prototypes
active_protos = temp_protos[:active_E]
return active_protos, active_E
def update_dg_prototypes_from_ema(self):
"""Update dg_prototypes tensor from current EMA class prototypes."""
if self.class_proto_ema is None:
return
for expert_id in range(self.trained_experts):
expert_prototype = self.compute_expert_prototypes_from_classes(expert_id)
if expert_prototype is not None:
with torch.no_grad():
# Use proper tensor indexing
if hasattr(self, 'dg_prototypes') and self.dg_prototypes is not None:
self.dg_prototypes[expert_id] = expert_prototype
# Mark prototypes as computed if we have at least one expert
if self.trained_experts > 0:
self.prototypes_computed = True
logging.info(f"🔄 Updated DG prototypes for {self.trained_experts} trained experts")
def log_prototype_stats(self):
"""Log statistics about current prototype quality."""
if self.class_proto_ema is None or self.trained_experts == 0:
return
# Calculate prototype separation
with torch.no_grad():
if hasattr(self, 'dg_prototypes') and self.dg_prototypes is not None:
trained_prototypes = self.dg_prototypes[:self.trained_experts]
if trained_prototypes.size(0) > 1:
prototypes_norm = F.normalize(trained_prototypes, p=2, dim=1)
sim_matrix = prototypes_norm @ prototypes_norm.T
# Off-diagonal similarities (should be low for good separation)
mask = ~torch.eye(trained_prototypes.size(0), dtype=torch.bool, device=trained_prototypes.device)
off_diag_sims = sim_matrix[mask]
mean_separation = off_diag_sims.mean().item()
min_separation = off_diag_sims.min().item()
logging.info(f"📊 Prototype separation - Mean: {mean_separation:.3f}, Min: {min_separation:.3f}")
# Log class prototype counts
if self.class_proto_counts is not None:
active_classes = (self.class_proto_counts > 0).sum().item()
total_classes = self.class_proto_counts.size(0)
else:
active_classes = 0
total_classes = 0
logging.info(f"📊 Class prototypes - Active: {active_classes}/{total_classes}")
def set_task_classes(self, task_classes):
"""Set the task classes for the model."""
self.task_classes = task_classes
def add_to_replay_buffer(self, inputs, labels, task_id):
"""Adds samples to the replay buffer for a given task using random replacement."""
for i in range(inputs.size(0)):
if len(self.replay_buffer[task_id]) < self.memory_size_per_task:
self.replay_buffer[task_id].append((inputs[i], labels[i]))
else:
# Randomly replace an existing sample
idx = np.random.randint(0, self.memory_size_per_task)
self.replay_buffer[task_id][idx] = (inputs[i], labels[i])
def sample_from_replay_buffer(self, task_id, batch_size):
"""Samples a batch from the replay buffer of a given task."""
if not self.replay_buffer[task_id] or batch_size == 0:
return None, None
buffer = self.replay_buffer[task_id]
# Ensure batch_size is not larger than the number of available samples
actual_batch_size = min(batch_size, len(buffer))
sample_indices = np.random.choice(len(buffer), size=actual_batch_size, replace=len(buffer) < actual_batch_size)
samples = [buffer[i] for i in sample_indices]
inputs = torch.stack([s[0] for s in samples])
labels = torch.stack([s[1] for s in samples])
return inputs, labels
def set_gating_strategy(self, strategy):
"""Sets the gating strategy for inference."""
if strategy not in ['hard', 'soft', 'top2', 'soft_hard']:
raise ValueError("Gating strategy must be one of 'hard', 'soft', 'top2', or 'soft_hard'")
self.gating_strategy = strategy
logging.info(f"🚪 Set gating strategy to: {self.gating_strategy}")
def set_gating_temperature(self, temperature):
"""Sets the temperature for softmax gating."""
self.gating_temperature = temperature
logging.info(f"🌡️ Set gating temperature to: {self.gating_temperature}")
def forward_all_tasks(self, x):
"""
Forward pass for Class-IL evaluation using DG-gating.
This simply calls the standard forward method without a task_id.
"""
final_outputs, _, _ = self.forward(x)
return final_outputs
def compute_dg_prototypes(self, train_loaders, device):
"""
Computes the prototype DG pattern for each expert by averaging the DG
output over all training samples for that expert's task.
"""
logging.info("🧠 Computing all DG Prototypes post-Phase 1...")
self.eval()
with torch.no_grad():
for task_id, train_loader in enumerate(tqdm(train_loaders, desc="Computing Prototypes")):
all_dg_outputs = []
for inputs, _ in train_loader:
inputs = inputs.to(device)
features = self.feature_extractor(inputs).view(inputs.size(0), -1)
dg_output, _ = self.hippocampal_experts[task_id](features)
all_dg_outputs.append(dg_output)
# Average all DG outputs for this task
with torch.no_grad():
self.dg_prototypes[task_id] = torch.cat(all_dg_outputs, dim=0).mean(dim=0)
self.prototypes_computed = True
logging.info("✅ All expert prototypes computed and stored.")
def forward(self, x, task_id=None):
"""
Forward pass with DG-based gating.
If task_id is provided, it uses oracle routing. Otherwise, it uses
DG pattern similarity to find the best expert.
Returns a dictionary in the third position for analysis data.
"""
if not self.prototypes_computed and task_id is None:
# During inference, prototypes must have been computed.
if not self.training:
raise RuntimeError("DG prototypes have not been computed. Call compute_dg_prototypes() first.")
features = self.feature_extractor(x).view(x.size(0), -1)
gate_logits = None # Default for oracle routing
analysis_data = {}
if self.training and task_id is not None:
# Oracle routing for training experts
# Process through the single chosen expert
dg_output, ca1_output = self.hippocampal_experts[task_id](features)
expert_output = self.output_layers[task_id](ca1_output)
final_outputs = torch.zeros(x.size(0), self.num_classes, device=x.device)
start_idx = task_id * self.classes_per_task
end_idx = start_idx + self.classes_per_task
final_outputs[:, start_idx:end_idx] = expert_output
analysis_data['dg_output'] = dg_output
return final_outputs, gate_logits, analysis_data
# --- Gating for Inference ---
all_dg_outputs = []
for i in range(self.num_experts):
dg_output, _ = self.hippocampal_experts[i](features)
all_dg_outputs.append(dg_output)
all_dg_outputs = torch.stack(all_dg_outputs, dim=1)
all_dg_outputs_norm = F.normalize(all_dg_outputs, p=2, dim=2)
# Only use prototypes for trained experts
trained_prototypes = self.dg_prototypes[:self.trained_experts]
if trained_prototypes.size(0) == 0:
# No prototypes available, use uniform routing
gate_logits = torch.zeros(x.size(0), self.num_experts, device=x.device)
else:
prototypes_norm = F.normalize(trained_prototypes, p=2, dim=1).to(x.device)
# Calculate DG pattern similarity for gating (only for trained experts)
gate_logits = torch.einsum('bne,ne->bn', all_dg_outputs_norm[:, :self.trained_experts], prototypes_norm)
# Pad with zeros for untrained experts
if self.trained_experts < self.num_experts:
padding = torch.zeros(x.size(0), self.num_experts - self.trained_experts, device=x.device)
gate_logits = torch.cat([gate_logits, padding], dim=1)
# --- Apply Gating Strategy ---
final_outputs = torch.zeros(x.size(0), self.num_classes, device=x.device)
if self.gating_strategy == 'hard':
# Winner-take-all: choose the expert with the highest similarity
chosen_experts = torch.argmax(gate_logits, dim=1)
for i in range(x.size(0)):
expert_id = int(chosen_experts[i].item())
_, ca1_output = self.hippocampal_experts[expert_id](features[i].unsqueeze(0))
expert_output = self.output_layers[expert_id](ca1_output)
start_idx = expert_id * self.classes_per_task
end_idx = start_idx + self.classes_per_task
final_outputs[i, start_idx:end_idx] = expert_output
elif self.gating_strategy == 'soft':
# Soft gating: weighted average of all expert outputs
gating_weights = F.softmax(gate_logits / self.gating_temperature, dim=1)
for expert_id in range(self.num_experts):
weight = gating_weights[:, expert_id].unsqueeze(1)
_, ca1_output = self.hippocampal_experts[expert_id](features)
expert_output = self.output_layers[expert_id](ca1_output)
start_idx = expert_id * self.classes_per_task
end_idx = start_idx + self.classes_per_task
final_outputs[:, start_idx:end_idx] += weight * expert_output
elif self.gating_strategy == 'top2':
# Top-2 gating: weighted average of the top two expert outputs
top2_logits, top2_indices = torch.topk(gate_logits, 2, dim=1)
top2_weights = F.softmax(top2_logits / self.gating_temperature, dim=1)
for i in range(x.size(0)):
for j in range(2):
expert_id = int(top2_indices[i, j].item())
weight = top2_weights[i, j]
_, ca1_output = self.hippocampal_experts[expert_id](features[i].unsqueeze(0))
expert_output = self.output_layers[expert_id](ca1_output)
start_idx = expert_id * self.classes_per_task
end_idx = start_idx + self.classes_per_task
final_outputs[i, start_idx:end_idx] += weight * expert_output.squeeze(0)
elif self.gating_strategy == 'soft_hard':
# Soft-hard gating: always use soft gating, hard gating only in final evaluation
# This will be handled in the evaluation function
gating_weights = F.softmax(gate_logits / self.gating_temperature, dim=1)
for expert_id in range(self.num_experts):
weight = gating_weights[:, expert_id].unsqueeze(1)
_, ca1_output = self.hippocampal_experts[expert_id](features)
expert_output = self.output_layers[expert_id](ca1_output)
start_idx = expert_id * self.classes_per_task
end_idx = start_idx + self.classes_per_task
final_outputs[:, start_idx:end_idx] += weight * expert_output
analysis_data['chosen_experts'] = torch.argmax(gate_logits, dim=1) if gate_logits is not None else None
return final_outputs, gate_logits, analysis_data
def analyze_dg_gated_model(model, test_loaders, device, save_dir):
"""Analyze the DG-Gated model."""
logging.info("\n" + "🔬" * 60)
logging.info("🔬 ANALYZING THE DG-GATED MODEL")
logging.info("🔬" * 60)
model.eval()
analysis_dir = os.path.join(save_dir, 'dg_gated_analysis')
os.makedirs(analysis_dir, exist_ok=True)
# Collect data
all_gate_logits = []
all_dg_outputs = []
all_ca1_outputs = []
all_task_labels = []
routing_matrix = np.zeros((model.num_experts, model.num_experts))
with torch.no_grad():
for task_id, test_loader in enumerate(test_loaders):
for inputs, labels in tqdm(test_loader, desc=f"Analyzing DG-Gated Task {task_id}"):
inputs = inputs.to(device)
# Get DG-based gating decisions
_, gate_logits, analysis_data = model(inputs)
predicted_experts = analysis_data['chosen_experts']
for pred_expert in predicted_experts:
routing_matrix[task_id, pred_expert.item()] += 1
# Get representations
features_flat = model.feature_extractor(inputs).view(inputs.size(0), -1)
dg_output, ca1_output = model.hippocampal_experts[task_id](features_flat)
all_gate_logits.append(gate_logits)
all_dg_outputs.append(dg_output)
all_ca1_outputs.append(ca1_output)
all_task_labels.extend([task_id] * inputs.size(0))
all_gate_logits = torch.cat(all_gate_logits, dim=0)
all_dg_outputs = torch.cat(all_dg_outputs, dim=0)
all_ca1_outputs = torch.cat(all_ca1_outputs, dim=0)
all_task_labels = np.array(all_task_labels)
routing_matrix = routing_matrix / (routing_matrix.sum(axis=1, keepdims=True) + 1e-8)
expert_utilization = np.bincount(all_gate_logits.detach().numpy().argmax(axis=1), minlength=model.num_experts) / len(all_gate_logits)
create_dg_gated_visualizations(
all_gate_logits.detach().numpy(), all_dg_outputs.numpy(), all_ca1_outputs.numpy(),
all_task_labels, routing_matrix, expert_utilization, model.dg_prototypes.numpy(), analysis_dir
)
return {
'routing_matrix': routing_matrix,
'expert_utilization': expert_utilization,
'routing_accuracy': np.diag(routing_matrix).mean()
}
def create_dg_gated_visualizations(gate_logits, dg_outputs, ca1_outputs, task_labels,
routing_matrix, expert_utilization, dg_prototypes, save_dir):
"""Create visualizations for the DG-Gated model."""
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
fig.suptitle('🧠 DG-Gated Hippocampal MoE Analysis', fontsize=16, fontweight='bold')
# 1. Routing Matrix
sns.heatmap(routing_matrix, annot=True, fmt='.3f', cmap='Blues', ax=axes[0,0], square=True)
axes[0,0].set_title('🚪 DG-Gated Task→Expert Routing')
axes[0,0].set_xlabel('Predicted Expert ID')
axes[0,0].set_ylabel('True Task ID')
# 2. DG Prototype Similarity
proto_sim = np.dot(dg_prototypes, dg_prototypes.T) / (np.linalg.norm(dg_prototypes, axis=1, keepdims=True) * np.linalg.norm(dg_prototypes, axis=1, keepdims=True).T)
sns.heatmap(proto_sim, annot=True, fmt='.3f', cmap='RdBu_r', center=0, ax=axes[0,1], square=True)
axes[0,1].set_title('🧠 DG Prototype Similarity')
axes[0,1].set_xlabel('Prototype ID')
axes[0,1].set_ylabel('Prototype ID')
# 3. CA1 Representations t-SNE
n_samples = min(2000, len(ca1_outputs))
indices = np.random.choice(len(ca1_outputs), n_samples, replace=False)
pca = PCA(n_components=50)
ca1_pca = pca.fit_transform(ca1_outputs[indices])
tsne = TSNE(n_components=2, random_state=42)