-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpretraining_analysis.py
More file actions
1981 lines (1752 loc) · 95.7 KB
/
pretraining_analysis.py
File metadata and controls
1981 lines (1752 loc) · 95.7 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
"""
Post-hoc analysis of the pretraining → post-training transfer experiment.
For each saved run, compares hidden-state (and optionally modulation) geometry
between pretraining tasks and the post-training task via cross-validated PCA:
- Fit PCA on the post-training task representations
- Project pretraining task representations into that basis
- Measure cumulative variance explained and participation ratio
Aggregates results across seeds and produces summary figures.
Outputs saved to ./pretraining_analysis/.
"""
import numpy as np
import pickle
import os
import re
import copy
import json
from pathlib import Path
import torch
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn.decomposition import PCA
from scipy.linalg import subspace_angles
import mpn
c_vals = ['#e53e3e', '#3182ce', '#38a169', '#805ad5', '#dd6b20',
'#319795', '#718096', '#d53f8c', '#d69e2e'] * 10
mpl.rcParams.update({
"font.family": "sans-serif",
"font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"],
"font.size": 8,
"axes.labelsize": 8,
"axes.titlesize": 8,
"xtick.labelsize": 7,
"ytick.labelsize": 7,
"pdf.fonttype": 42,
"ps.fonttype": 42,
})
# ─────────────────────────────────────────────────────────────────────────────
# Configuration
# ─────────────────────────────────────────────────────────────────────────────
basepath = "./pretraining"
outpath = "./pretraining_analysis"
# Existing outputs are preserved across runs; new outputs only overwrite
# files that share the same name. Aggregate figures embed `addon_name` in
# their filenames so different model variants (e.g. L2 strength, batch
# size) coexist in the same folder.
os.makedirs(outpath, exist_ok=True)
# Pretraining rulesets to run (must match rules_dict in pretraining.py).
# Each one is processed independently; their learning curves are then
# combined into a single cross-ruleset figure.
rulesets_to_run = ["fdgo_delaygo", "fdanti_delaygo"]
# Optional cap on how many seeds to analyze per ruleset. Useful for a fast
# iteration loop: set to a small int (e.g. 2) to skim through all the
# per-seed work in a fraction of the time, then set back to None to run
# every available seed for the final figures. When an int, seeds are
# sampled randomly without replacement from all that exist on disk; the
# random choice is reproducible via `seed_sample_rng_seed` below.
n_seeds_per_ruleset = None
seed_sample_rng_seed = 0
# Active ruleset / stage-1 tasks are (re)assigned at the top of each
# iteration of the main loop below. Functions that build file paths
# read `ruleset` from module scope at call time.
ruleset = None
stage1_tasks = None
def _stage1_tasks_for(rs):
return ["fdanti", "delaygo"] if rs == "fdanti_delaygo" else ["fdgo", "delaygo"]
# Post-training task
final_task = "delayanti"
# Per-ruleset plotting colors for the cross-ruleset combined figure.
ruleset_colors = {
"fdgo_delaygo": c_vals[1],
"fdanti_delaygo": c_vals[2],
}
chosen_network = "dmpn"
N = 300
# PCA component cap for modulation / modulation_weighted analyses.
# Hidden uses N (the ambient dim). Modulation lives in N² = 40 000 dims, so a
# larger cap is needed to see whether CVE eventually saturates. sklearn still
# requires n_components ≤ min(n_samples, n_features); the call sites clamp to
# that limit to stay safe.
N_MOD_PCS = 1000
# Top-k cap for principal-angle analysis. Subspace angles are computed
# between the top-K PC bases of the pretraining and novel representations;
# the returned spectrum has K ascending values. Keep it modest because the
# cost scales like K³ and most of the interpretive content lies in the
# first few angles (zero-angle directions = shared axes, π/2 = orthogonal).
N_ANGLES = 20
# Naming components that form addon_name in pretraining.py:
# addon_name = f"+hidden{N}+L21e4+batch{batch}+{metric}"
metric = "angle"
reg = "L21e4"
addon_name = f"+hidden{N}+{reg}+batch128+{metric}"
# ─────────────────────────────────────────────────────────────────────────────
# Path construction (matches pretraining.py naming convention)
# ─────────────────────────────────────────────────────────────────────────────
def build_paths(seed):
"""Build file paths for a given seed, matching pretraining.py output naming."""
base = f"{ruleset}_{chosen_network}_seed{seed}_{addon_name}"
return {
"stage1_output": f"{basepath}/output_{base}_stage1.npz",
"stage2_output": f"{basepath}/output_{base}_stage2.npz",
"param_result": f"{basepath}/param_{base}_result.npz",
}
def hist_path(seed):
"""Full training-history pickle path (see pretraining.py)."""
return f"{basepath}/hist_{ruleset}_{chosen_network}_seed{seed}_{addon_name}.pkl"
def ckpt_path(seed):
"""Network checkpoint path (see pretraining.py)."""
return f"{basepath}/savednet_{ruleset}_{chosen_network}_seed{seed}_{addon_name}.pt"
def config_path(seed):
"""
Hyperparameter JSON path (see pretraining.py). Note: unlike the other
per-seed files, this one omits `chosen_network` from its filename.
"""
return f"{basepath}/param_{ruleset}_seed{seed}_{addon_name}_param.json"
def load_train_params(seed):
"""Load the stage-1 train_params dict saved alongside the checkpoint."""
with open(config_path(seed)) as f:
cfg = json.load(f)
return cfg["train_params"]
def load_mpn_W(seed):
"""
Load the frozen plastic-layer weight W from the saved checkpoint.
Returns an (N, N) numpy array. W is identical across stage 1 and stage 2
(frozen in expand_and_freeze), so a single W multiplies both stages' M.
"""
ckpt = torch.load(ckpt_path(seed), map_location="cpu", weights_only=False)
return ckpt["state_dict"]["mp_layer1.W"].numpy()
def load_rule_vectors(seed):
"""
Extract the 3 rule-input column vectors from the checkpoint.
W_initial_linear.weight has shape (n_hidden, n_input); its last 3
columns are the task-indicator rows in the input layout:
[fix1, fix2, r1cos, r1sin, r2cos, r2sin, task1, task2, task3]
Column 6 (task1) = pretraining task 0 (e.g. fdgo / fdanti)
Column 7 (task2) = pretraining task 1 (delaygo)
Column 8 (task3) = post-training task (delayanti), trained in stage 2
Returns (v_pre0, v_pre1, v_novel) as three (n_hidden,) numpy arrays.
"""
ckpt = torch.load(ckpt_path(seed), map_location="cpu", weights_only=False)
W_in = ckpt["state_dict"]["W_initial_linear.weight"].numpy()
return W_in[:, -3], W_in[:, -2], W_in[:, -1]
def _rule_vector_stats(v_pre0, v_pre1, v_novel):
"""
Per-seed scalar summaries of the rule-input vector geometry.
Returns a dict with:
- cos_pre0_pre1, cos_novel_pre0, cos_novel_pre1: pairwise cosines
- in_span_fraction: ‖P_{span(pre0, pre1)} v_novel‖ / ‖v_novel‖
(1 → novel is a linear combination of pretrained rule vectors;
0 → novel is orthogonal to the pretrained rule subspace)
- norm_pre0, norm_pre1, norm_novel: Frobenius norms for context
"""
v_pre0 = np.asarray(v_pre0)
v_pre1 = np.asarray(v_pre1)
v_novel = np.asarray(v_novel)
# Project v_novel onto span(v_pre0, v_pre1) via least-squares:
# minimize ‖v_novel - (a·v_pre0 + b·v_pre1)‖ → coefficients from lstsq.
basis = np.stack([v_pre0, v_pre1], axis=1) # (n_hidden, 2)
coeffs, _, _, _ = np.linalg.lstsq(basis, v_novel, rcond=None)
v_proj = basis @ coeffs
norm_novel = np.linalg.norm(v_novel)
in_span = float(np.linalg.norm(v_proj) / norm_novel) if norm_novel > 0 else float("nan")
return {
"cos_pre0_pre1": _cosine_sim(v_pre0, v_pre1),
"cos_novel_pre0": _cosine_sim(v_novel, v_pre0),
"cos_novel_pre1": _cosine_sim(v_novel, v_pre1),
"in_span_fraction": in_span,
"norm_pre0": float(np.linalg.norm(v_pre0)),
"norm_pre1": float(np.linalg.norm(v_pre1)),
"norm_novel": float(norm_novel),
}
def load_final_net(seed, device):
"""
Reconstruct the post-stage-2 network from its checkpoint and return it
in eval mode on `device`. Mirrors the reload pattern in pretraining.py.
"""
ckpt = torch.load(ckpt_path(seed), map_location="cpu", weights_only=False)
net_params = ckpt["net_params"]
net = mpn.DeepMultiPlasticNet(net_params).to(device)
net.load_state_dict(ckpt["state_dict"])
net.eval()
return net
def _plot_input_output_panel(
fig_path, test_input_np, test_output_np, net_out_np,
task_names, test_task, n_trials=10,
):
"""
Two-column figure: left = net output (solid) over ground truth (faded),
right = input channels. One row per trial. Titles identify the task.
test_input_np (batch, time, n_input)
test_output_np (batch, time, n_output)
net_out_np (batch, time, n_output)
task_names list of rule names for this stage (stage-1 or stage-2)
test_task per-trial integer index into task_names
"""
n_trials = min(n_trials, test_input_np.shape[0])
fig, axs = plt.subplots(n_trials, 2, figsize=(4 * 2, 2 * n_trials))
if n_trials == 1:
axs = axs[np.newaxis, :]
for b in range(n_trials):
tname = task_names[int(test_task[b])] if task_names is not None else "?"
# Output column: net (solid) vs ground truth (thick faded).
for oi in range(test_output_np.shape[-1]):
axs[b, 0].plot(net_out_np[b, :, oi], color=c_vals[oi], linewidth=1)
axs[b, 0].plot(test_output_np[b, :, oi], color=c_vals[oi],
linewidth=5, alpha=0.25)
axs[b, 0].set_title(f"{tname} — out vs target")
axs[b, 0].set_ylim([-1.6, 1.6])
# Input column: every channel.
for ii in range(test_input_np.shape[-1]):
axs[b, 1].plot(test_input_np[b, :, ii], color=c_vals[ii], alpha=0.9)
axs[b, 1].set_title(f"{tname} — input")
axs[b, 1].set_ylim([-1.6, 1.6])
fig.tight_layout()
fig.savefig(fig_path, dpi=120)
plt.close(fig)
def evaluate_backbone_on_delayanti(
seed, device, stage2_output, n_random_rule_inits=10, rng_seed=0,
n_batch=128,
):
"""
Measure the frozen backbone's starting-point competence on delayanti.
Protocol
────────
Load the post-stage-2 checkpoint. Everything in that state_dict except
the last column of W_initial_linear is identical to the end-of-stage-1
network (stage 2 only trains that column via the gradient hook in
expand_and_freeze). We can therefore reconstruct the stage-2 STARTING
point by overwriting that last column with a fresh random init, then
run a forward pass on freshly generated delayanti test data to see how
close the backbone is to solving delayanti BEFORE any stage-2 gradient
step.
Loss and accuracy are computed via the network's own `compute_loss` /
`compute_acc` so the numbers are directly comparable to training-time
loss/accuracy. This requires the trial mask, which is not saved in the
npz, so a fresh batch is generated from the saved task_params.
Returns dict of per-sample numpy arrays (length n_random_rule_inits):
loss — full training loss (output MSE + regularization)
loss_out — output-label-MSE component only
acc — angle-based accuracy on the response period
"""
import math
import mpn_tasks # local import so the helper stays self-contained
# Load network and task config.
net = load_final_net(seed, device)
# compute_loss reads regularization attributes that are normally set by
# net.fit(train_params, ...) during training. load_state_dict doesn't
# restore those (they're not tensors), so we re-inject them from the
# saved JSON config to match the training-time loss computation.
train_params = load_train_params(seed)
net.weight_reg = train_params.get("weight_reg", None)
net.reg_lambda = train_params.get("reg_lambda", 0.0)
net.activity_reg = train_params.get("activity_reg", None)
net.reg_omit = train_params.get("reg_omit", [])
net.gradient_type = train_params.get("gradient_type", "backprop")
task_params = stage2_output["task_params"].item()
# Generate a fresh test batch for delayanti. pretraining_shift=2 pads
# the two stage-1 task-indicator slots with zeros so the input has the
# correct 9-channel layout the checkpoint expects.
task_params_test = copy.deepcopy(task_params)
task_params_test["long_response"] = "normal"
(test_input, test_output, test_mask), _ = mpn_tasks.generate_trials_wrap(
task_params_test, n_batch, device=device, rules=["delayanti"],
mode_input="random", pretraining_shift=2,
)
# Grab the trained rule-vector column so we can restore it afterward.
orig_col = net.W_initial_linear.weight.data[:, -1].detach().clone()
rng = np.random.default_rng(rng_seed + seed)
loss_full, loss_out_only, acc_vals = [], [], []
with torch.no_grad():
for _ in range(n_random_rule_inits):
# Kaiming-uniform init matching expand_and_freeze.
new_col = torch.empty_like(orig_col)
torch.manual_seed(int(rng.integers(0, 2**31)))
torch.nn.init.kaiming_uniform_(new_col.view(-1, 1).t(), a=math.sqrt(5))
net.W_initial_linear.weight.data[:, -1] = new_col
# Forward through the full batch at once; compute_loss/acc
# expect the whole batch, not mini-chunks.
net_out, hidden, _ = net.iterate_sequence_batch(
test_input, run_mode="minimal")
loss, loss_components, _ = net.compute_loss(
net_out, test_output, test_mask, hidden=hidden)
acc, _ = net.compute_acc(
net_out, test_output, test_mask, test_input,
isvalid=True, mode=net.acc_measure)
loss_full.append(float(loss.detach().cpu().item()))
# loss_components is (output_label_term, reg_term); keep the
# output-only term separately since reg_term is not meaningful
# for a random rule vector (it penalizes all weights equally
# regardless of the task-match).
loss_out_only.append(float(loss_components[0]))
acc_vals.append(float(acc.detach().cpu().item()))
# Clear per-layer state before the next init.
if hasattr(net, "reset_state"):
try:
net.reset_state(B=1)
except Exception:
pass
net.W_initial_linear.weight.data[:, -1] = orig_col
return {
"loss": np.array(loss_full),
"loss_out": np.array(loss_out_only),
"acc": np.array(acc_vals),
}
def run_final_net_sanity_check(
seed, device, stage1_output, stage2_output, n_trials=10,
):
"""
Load the final (post-stage-2) network and run it on BOTH stages' saved
test inputs. The npzs already contain correctly zero-padded task
indicator dimensions for each stage (see pretraining.py), so we reuse
them verbatim and only need to reconstruct the network. Saves two
figures: a stage-1 view (final net on pretraining test inputs) and a
stage-2 view (final net on post-training test inputs).
"""
net = load_final_net(seed, device)
# Stage 1: pretraining tasks, evaluated with the *final* (post-stage-2) net.
ti1 = np.asarray(stage1_output["test_input_np"])
to1 = np.asarray(stage1_output["test_output_np"])
task_params1 = stage1_output["task_params"].item()
tt1 = np.asarray(stage1_output["test_task"])
# Stage 2: post-training task, evaluated with the final net.
ti2 = np.asarray(stage2_output["test_input_np"])
to2 = np.asarray(stage2_output["test_output_np"])
task_params2 = stage2_output["task_params"].item()
tt2 = np.asarray(stage2_output["test_task"])
def _run_on(ti_np):
# Run in minibatches to mirror train_network's minibatch=8.
out_chunks = []
bsz = 8
with torch.no_grad():
for s in range(0, ti_np.shape[0], bsz):
e = min(s + bsz, ti_np.shape[0])
batch = torch.as_tensor(ti_np[s:e], dtype=torch.float, device=device)
out_batch, _, _ = net.iterate_sequence_batch(batch, run_mode="minimal")
out_chunks.append(out_batch.detach().cpu().numpy())
return np.concatenate(out_chunks, axis=0)
out1 = _run_on(ti1)
out2 = _run_on(ti2)
checkname = f"{ruleset}_{chosen_network}_seed{seed}_{addon_name}"
_plot_input_output_panel(
f"{outpath}/{checkname}_finalnet_on_stage1.png",
ti1, to1, out1, task_params1["rules"], tt1, n_trials=n_trials,
)
_plot_input_output_panel(
f"{outpath}/{checkname}_finalnet_on_stage2.png",
ti2, to2, out2, task_params2["rules"], tt2, n_trials=n_trials,
)
def discover_seeds():
"""Find all available seeds by scanning the pretraining output directory."""
pattern = re.compile(
rf"param_{re.escape(ruleset)}_{re.escape(chosen_network)}"
rf"_seed(\d+)_{re.escape(addon_name)}_result\.npz"
)
seeds = []
for fname in os.listdir(basepath):
m = pattern.match(fname)
if m:
seeds.append(int(m.group(1)))
return sorted(seeds)
# ─────────────────────────────────────────────────────────────────────────────
# Analysis utilities
# ─────────────────────────────────────────────────────────────────────────────
def _participation_ratio(cov_mat):
"""
Effective dimensionality: (sum λ)² / sum λ².
Returns 1 for a rank-1 matrix and d for isotropic d-dimensional variance.
Higher PR → representations spread across more dimensions.
"""
eigvals = np.linalg.eigvalsh(cov_mat)
eigvals = np.clip(eigvals, 0, None)
s1 = np.sum(eigvals)
s2 = np.sum(eigvals ** 2)
if s1 == 0 or s2 == 0:
return 0.0
return (s1 ** 2) / s2
def _mean_M_over_period(Ms_period):
"""
Collapse a period slice of M down to a single (N, N) matrix.
Ms_period shape: (batch, time_in_period, N, N), where time_in_period is
already trimmed to the relevant epoch (after period_shift). Averaging
over both batch and time handles variable trial lengths automatically —
the output shape depends only on N, not on how many timesteps were in
the slice. Uses the same period slices that feed the PCA analysis, so
cosine similarity numbers here are directly comparable to the PCA.
"""
return Ms_period.mean(axis=(0, 1))
def _stim_direction_indices(test_input_np, epochs, task_name, mask=None, n_dirs=8):
"""
Return a per-trial integer stimulus-direction index in [0, n_dirs).
Reads the r1cos (channel 2) and r1sin (channel 3) inputs at the midpoint
of the task's stim1 period (where the stimulus is on), computes
θ = atan2(sin, cos), and bins to the nearest of n_dirs evenly-spaced
angles. Assumes sigma_x = 0 (noise-free inputs), which is the case in
pretraining.py.
"""
if mask is not None:
test_input_np = test_input_np[mask]
start, end = epochs[task_name]["stim1"]
t_mid = (start + end) // 2
r1cos = test_input_np[:, t_mid, 2]
r1sin = test_input_np[:, t_mid, 3]
thetas = np.arctan2(r1sin, r1cos)
bin_size = 2 * np.pi / n_dirs
return (np.round(thetas / bin_size).astype(int)) % n_dirs
def direction_averaged_cve(
X_period, Y_period, dir_idxs_X, dir_idxs_Y,
n_components, datatype, n_dirs=8,
):
"""
Per-stimulus-direction CVE averaged across directions.
Variance-decomposition diagnostic: the pooled CVE marginalizes over
all stimulus directions before fitting PCA. If the two tasks share
a per-direction subspace structure (e.g. a ring attractor whose axial
geometry is identical at every θ but rotated), pooling washes that
out. Running the full CVE analysis within each direction bin and
averaging at the end reveals a shared structure that would otherwise
be hidden.
For each direction with trials on both sides, subset both period
slices to those trials and call `pca_cross_variance`. Average the
resulting `cev_Y` and `cev_Y_self` curves across directions. Returns
length-min_len arrays truncated to the shortest achievable curve
(a direction with few samples produces a shorter PCA spectrum).
Note: alignment is by *stimulus* direction, not response direction —
so for the go-period comparison a pro-task trial at stimulus θ is
paired with a delayanti trial at stimulus θ (which responds toward
θ+π). This tests whether the computational trajectories under the
same input differ, regardless of target response.
Returns
-------
dict with:
cev_Y_mean : (k,) direction-averaged novel-in-pretraining CVE
cev_Y_self_mean : (k,) direction-averaged novel-self CVE
n_dirs_used : int, how many direction bins contributed
"""
cev_Y_list = []
cev_Y_self_list = []
for d in range(n_dirs):
mask_X = (dir_idxs_X == d)
mask_Y = (dir_idxs_Y == d)
if not mask_X.any() or not mask_Y.any():
continue
X_d = X_period[mask_X]
Y_d = Y_period[mask_Y]
# Cap n_components to what this direction's subset can support
# (some bins have only a handful of trials × timesteps).
if datatype == "hidden":
nX = X_d.shape[0] * X_d.shape[1]
nY = Y_d.shape[0] * Y_d.shape[1]
else:
nX = X_d.shape[0] * X_d.shape[1]
nY = Y_d.shape[0] * Y_d.shape[1]
k_d = min(n_components, nX - 1, nY - 1)
if k_d < 1:
continue
res_d = pca_cross_variance(
X_d, Y_d, n_components=k_d, datatype=datatype)
cev_Y_list.append(res_d["cev_Y"])
cev_Y_self_list.append(res_d["cev_Y_self"])
if not cev_Y_list:
return {
"cev_Y_mean": np.array([]),
"cev_Y_self_mean": np.array([]),
"n_dirs_used": 0,
}
min_len = min(len(c) for c in cev_Y_list)
cev_Y_trunc = np.stack([c[:min_len] for c in cev_Y_list], axis=0)
cev_self_trunc = np.stack([c[:min_len] for c in cev_Y_self_list], axis=0)
return {
"cev_Y_mean": cev_Y_trunc.mean(axis=0),
"cev_Y_self_mean": cev_self_trunc.mean(axis=0),
"n_dirs_used": len(cev_Y_list),
}
def _mean_M_by_direction(M_period, dir_idxs, n_dirs=8):
"""
Per-direction mean of M over batch and time.
Returns a (n_dirs, N, N) array; bins with no trials produce NaNs.
"""
N = M_period.shape[-1]
out = np.full((n_dirs, N, N), np.nan, dtype=M_period.dtype)
for d in range(n_dirs):
trials = (dir_idxs == d)
if trials.any():
out[d] = M_period[trials].mean(axis=(0, 1))
return out
def _stim_aligned_scalars(M_A_by_dir, M_B_by_dir):
"""
Stimulus-aligned (direction-matched) cosine and Frobenius-difference.
For each direction that has data on both sides, compute cos(M_A_θ, M_B_θ)
and ‖M_A_θ − M_B_θ‖. Return the mean over directions for each.
"""
n_dirs = M_A_by_dir.shape[0]
cos_vals, frob_vals = [], []
for d in range(n_dirs):
A, B = M_A_by_dir[d], M_B_by_dir[d]
if np.isnan(A).any() or np.isnan(B).any():
continue
cos_vals.append(_cosine_sim(A, B))
frob_vals.append(float(np.linalg.norm(A - B)))
if not cos_vals:
return float("nan"), float("nan")
return float(np.mean(cos_vals)), float(np.mean(frob_vals))
def _cosine_sim(A, B):
"""Cosine similarity between two tensors, flattened."""
a, b = np.asarray(A).ravel(), np.asarray(B).ravel()
na, nb = np.linalg.norm(a), np.linalg.norm(b)
if na == 0 or nb == 0:
return float("nan")
return float(a @ b / (na * nb))
def principal_angles(X, Y, k, datatype="hidden"):
"""
Principal angles (radians) between X's and Y's top-k PC subspaces.
Complements CVE: CVE asks "what fraction of Y's variance lives in X's
subspace?" which is variance-weighted. Principal angles ask "how
aligned are the K dominant directions of X with the K dominant
directions of Y?" — a per-direction geometric readout. 0 rad means a
shared axis; π/2 means orthogonal. Reveals cases where CVE is low
because the top-1 directions disagree but secondary directions still
align (or vice versa).
X, Y reshape follows the same rules as `pca_cross_variance`:
"hidden" — (batch×time, n_hidden)
"modulation" — (batch×time, n_hidden²)
"modulation_weighted" — same flatten; caller pre-multiplies W⊙M.
Returns
-------
angles : ndarray of shape (k_eff,), sorted ASCENDING. scipy's native
order is descending (largest angle first, smallest last), so
the returned array is reversed to put the most-aligned
direction at index 0. k_eff = min(k, rank(X basis), rank(Y
basis)) so you get at most k values.
"""
if datatype == "hidden":
X2d = X.reshape(-1, X.shape[-1])
Y2d = Y.reshape(-1, Y.shape[-1])
elif datatype in ("modulation", "modulation_weighted"):
X2d = X.reshape(-1, X.shape[-1] * X.shape[-2])
Y2d = Y.reshape(-1, Y.shape[-1] * Y.shape[-2])
else:
raise ValueError(f"Unknown datatype: {datatype}")
# Clamp k to what each PCA can support.
k_eff = min(k, min(X2d.shape) - 1, min(Y2d.shape) - 1)
if k_eff < 1:
return np.array([])
pca_X = PCA(n_components=k_eff, svd_solver="randomized", random_state=0)
pca_X.fit(X2d)
pca_Y = PCA(n_components=k_eff, svd_solver="randomized", random_state=0)
pca_Y.fit(Y2d)
# components_ is (k, n_features); subspace_angles expects (n_features, k)
# columns spanning each subspace.
basis_X = pca_X.components_.T
basis_Y = pca_Y.components_.T
# scipy returns angles in descending order (largest first). Reverse
# so index 0 is the most-aligned (smallest) angle, matching the
# "top-k shared directions" convention used in the rest of the file.
return subspace_angles(basis_X, basis_Y)[::-1]
def _pr_from_data(X_c):
"""
PR from centered data, using whichever Gram side is smaller.
Covariance (X_c.T @ X_c) and kernel (X_c @ X_c.T) share the same non-zero
eigenvalues, so PR is identical; eigendecomposing the smaller matrix is
strictly faster. Essential for modulation (n_features = n_hidden² ≫
n_samples), harmless for hidden.
"""
n, f = X_c.shape
if f <= n:
M = (X_c.T @ X_c) / n
else:
M = (X_c @ X_c.T) / n
return _participation_ratio(M)
def period_slice(op, epochs, task_name, key, *, shift_percentage=0, mask=None):
"""
Extract one task epoch from op (batch × time × features).
shift_percentage skips the leading fraction of the epoch (e.g. 0.25
discards the transient onset and focuses on the steady-state window).
mask selects a subset of trials (e.g. trials belonging to one task).
"""
start, end = epochs[task_name][key]
shift = int((end - start) * shift_percentage)
if mask is not None:
op = op[mask, :, :]
return op[:, start + shift:end, :]
def pca_cross_variance(X, Y, n_components=None, center_on="X", datatype="hidden"):
"""
Driscoll-style subspace-overlap analysis (see Driscoll et al.,
Nature Neurosci. 2024, Fig. 6c/k captions).
Convention (matches Driscoll exactly):
X = basis data — the task whose top-k PCs define the reference
subspace (typically a pretraining task).
Y = target data — the task whose variance is being measured in
each basis (typically the novel / post-training
task, e.g. delayanti = Driscoll's MemoryAnti).
Two cumulative-variance-explained curves are computed on the target:
cev_Y_self : Y's variance captured by Y's own PCs (Driscoll "black")
— saturates to 1.0, serves as the self-reference.
cev_Y : Y's variance captured by X's PCs (Driscoll "purple")
— measures how much of the target lives in the basis
task's subspace; high means the two tasks share
representational geometry, low means they're orthogonal.
cev_X : X's variance captured by X's own PCs — auxiliary
(sanity check that the basis spans its own variance).
PR_X, PR_Y : participation ratio of each dataset in its native space.
PR_Y_in_Xbasis : effective dim of Y after projection into X's basis;
lower than PR_Y means the shared subspace is narrower
than the target's full representation.
datatype controls reshaping before PCA
───────────────────────────────────────
"hidden" — (batch×time, n_hidden): neuron activations
"modulation" — (batch×time, n_hidden²): full M matrix flattened
"modulation_weighted" — (batch×time, n_hidden²): W⊙M flattened (caller
must pre-multiply M by W elementwise)
"""
if datatype == "hidden":
X2d = X.reshape(-1, X.shape[-1])
Y2d = Y.reshape(-1, Y.shape[-1])
elif datatype in ("modulation", "modulation_weighted"):
# Full (W⊙)M flattened: n_hidden² features — very high-dimensional.
X2d = X.reshape(-1, X.shape[-1] * X.shape[-2])
Y2d = Y.reshape(-1, Y.shape[-1] * Y.shape[-2])
else:
raise ValueError(f"Unknown datatype: {datatype}")
assert X2d.shape[1] == Y2d.shape[1]
# --- PCA on X (the reference / basis task) ---------------------------
# Randomized SVD is much faster than the full solver when we only need
# the top k components (k ≪ min(n_samples, n_features)), especially for
# modulation where n_features = n_hidden² is large.
pca_X = PCA(n_components=n_components, svd_solver="randomized", random_state=0)
pca_X.fit(X2d)
evr_X = pca_X.explained_variance_ratio_
cev_X = np.cumsum(evr_X)
# --- PCA on Y in its own basis (Driscoll's "black" reference curve) --
# Separate PCA fit so the self-reference saturates at 1.0 naturally
# and uses the same n_components truncation as the cross-basis curve.
pca_Y = PCA(n_components=n_components, svd_solver="randomized", random_state=0)
pca_Y.fit(Y2d)
evr_Y_self = pca_Y.explained_variance_ratio_
cev_Y_self = np.cumsum(evr_Y_self)
# --- Y projected into X's basis (Driscoll's "purple" cross curve) ----
# Center Y on X's mean: asks how much of Y's variance falls in X's
# subspace when measured from X's origin (center_on="X" is the
# standard choice and matches Driscoll's convention).
if center_on == "X":
Y_centered = Y2d - pca_X.mean_
elif center_on == "Y":
Y_centered = Y2d - Y2d.mean(axis=0, keepdims=True)
else:
raise ValueError('center_on must be "X" or "Y"')
Y_proj = Y_centered @ pca_X.components_.T # project Y into X's PC basis
var_total_Y = np.var(Y_centered, axis=0, ddof=0).sum()
if var_total_Y == 0:
evr_Y = np.zeros(pca_X.components_.shape[0])
else:
# Fraction of Y's total variance captured by each of X's PCs.
evr_Y = np.var(Y_proj, axis=0, ddof=0) / var_total_Y
cev_Y = np.cumsum(evr_Y)
# --- Participation ratios --------------------------------------------
X_c = X2d - X2d.mean(axis=0, keepdims=True)
PR_X = _pr_from_data(X_c)
Y_c = Y2d - Y2d.mean(axis=0, keepdims=True)
PR_Y = _pr_from_data(Y_c)
# PR of Y after projection: how many of X's PCs does Y actually use?
# Y_proj is (n_samples, n_components), centered on X's mean rather
# than Y's mean. Mean-center Y_proj before the covariance product so
# PR reflects Y's spread in X's basis, not the mean offset between
# the two tasks (which would otherwise show up as an extra rank-1
# eigenvalue and inflate PR). Keeps this PR consistent with how
# evr_Y is computed via np.var above.
Y_proj_c = Y_proj - Y_proj.mean(axis=0, keepdims=True)
cov_Yp = (Y_proj_c.T @ Y_proj_c) / Y_proj_c.shape[0]
PR_Y_in_Xbasis = _participation_ratio(cov_Yp)
return {
"evr_X": evr_X, "cev_X": cev_X,
"evr_Y_self": evr_Y_self, "cev_Y_self": cev_Y_self,
"evr_Y": evr_Y, "cev_Y": cev_Y,
"PR_X": PR_X, "PR_Y": PR_Y, "PR_Y_in_Xbasis": PR_Y_in_Xbasis,
}
# ─────────────────────────────────────────────────────────────────────────────
# Main analysis
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
period_shift_percentage = 1 / 4
# Device for the sanity-check re-runs of the final (post-stage-2) net.
# Falls back to CPU if CUDA isn't available.
sanity_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Determine which analyses to run based on network type
if chosen_network == "dmpn":
analysis_types = ["hidden", "modulation", "modulation_weighted"]
else:
analysis_types = ["hidden"]
# Accumulate per-ruleset seed results for the cross-ruleset combined figure.
all_results_by_ruleset = {}
for active_ruleset in rulesets_to_run:
# Rebind module-level ruleset/stage1_tasks so the helper functions
# (build_paths, ckpt_path, hist_path, discover_seeds) see the right
# names for this iteration.
ruleset = active_ruleset
stage1_tasks = _stage1_tasks_for(active_ruleset)
print(f"\n{'#'*60}")
print(f" Ruleset: {ruleset}")
print(f"{'#'*60}")
seeds = discover_seeds()
if not seeds:
print(
f" No matching result files found in {basepath}/ for "
f"ruleset={ruleset}, network={chosen_network}, addon={addon_name}; "
f"skipping this ruleset."
)
continue
print(f"Found {len(seeds)} seeds: {seeds}")
# Optional subsample for fast iteration. Draw without replacement
# using a deterministic RNG so two runs with the same cap see the
# same subset. Seeded per-ruleset so each ruleset picks its own
# subset rather than aligning indices across rulesets.
if n_seeds_per_ruleset is not None and len(seeds) > n_seeds_per_ruleset:
rng = np.random.default_rng(seed_sample_rng_seed + hash(ruleset) % (2**31))
seeds = sorted(rng.choice(seeds, size=n_seeds_per_ruleset,
replace=False).tolist())
print(f"Subsampled to {len(seeds)} seeds: {seeds}")
all_seed_results = []
for seed in seeds:
print(f"\n{'='*60}")
print(f" Processing seed {seed}")
print(f"{'='*60}")
paths = build_paths(seed)
for key, path in paths.items():
if not os.path.exists(path):
print(f" WARNING: missing {key} → {path}, skipping seed")
break
else:
# All files exist, proceed
stage1_output = np.load(paths["stage1_output"], allow_pickle=True)
stage2_output = np.load(paths["stage2_output"], allow_pickle=True)
final_param = np.load(paths["param_result"], allow_pickle=True)
# Sanity-check figure: load the post-stage-2 network and run
# it on both stages' test inputs (already correctly padded in
# each stage's npz). Lets us visually verify the saved model
# actually solves both tasks before trusting downstream PCA.
try:
run_final_net_sanity_check(
seed, sanity_device, stage1_output, stage2_output,
n_trials=10,
)
except (FileNotFoundError, KeyError, RuntimeError) as e:
print(f" WARNING: final-net sanity check failed ({e}); "
f"continuing without it")
seed_result = {"seed": seed}
# Starting-point probe: reconstruct the stage-2 init state
# (rule-vector column reset to a random Kaiming-uniform) and
# measure delayanti loss over several random draws. This
# localizes the transfer advantage to the frozen backbone
# rather than to anything the stage-2 optimizer does.
try:
backbone_probe = evaluate_backbone_on_delayanti(
seed, sanity_device, stage2_output,
n_random_rule_inits=10,
)
seed_result["backbone_probe"] = backbone_probe
except (FileNotFoundError, KeyError, RuntimeError) as e:
print(f" WARNING: backbone-probe failed ({e}); "
f"continuing without it")
test_task = stage1_output["test_task"]
stage1_hs = final_param["hs_stage1"]
stage2_hs = final_param["hs_stage2"]
stage1_ms = final_param["Ms_orig_stage1"]
stage2_ms = final_param["Ms_orig_stage2"]
stage1_rules_epochs = stage1_output["rules_epochs"].item()
stage2_rules_epochs = stage2_output["rules_epochs2"].item()
# Validation accuracy.
# `valid_acc_iter` is monotonic across both stages, but the
# transition iter (stop+1) is recorded twice — once as the last
# stage-1 validation, once as the first stage-2 validation.
# Exclude the boundary from both sides so the post-training
# curve starts cleanly at the first fresh stage-2 measurement.
stop = final_param["pretrain_stop"]
acc_iter = final_param["valid_acc_iter"]
acc = final_param["valid_acc"]
post_mask = acc_iter > stop + 1
pre_mask = acc_iter < stop
acc_iter_post = acc_iter[post_mask] - stop
acc_post = acc[post_mask]
acc_iter_pre = acc_iter[pre_mask]
acc_pre = acc[pre_mask]
# Trial masks for stage 1 tasks
mask0 = (test_task == 0)
mask1 = (test_task == 1)
# ---- Extract periods ----
# period_shift_percentage skips the onset transient of each epoch
# so the PCA captures steady-state geometry; applied consistently
# to both stim and go periods.
# Stimulus period: compare stage1_tasks[0] vs final_task
stage1_stim = period_slice(
stage1_hs, stage1_rules_epochs, stage1_tasks[0], "stim1",
shift_percentage=period_shift_percentage, mask=mask0)
final_stim = period_slice(
stage2_hs, stage2_rules_epochs, final_task, "stim1",
shift_percentage=period_shift_percentage)
# Go period: compare stage1_tasks[1] vs final_task
stage1_go = period_slice(
stage1_hs, stage1_rules_epochs, stage1_tasks[1], "go1",
shift_percentage=period_shift_percentage, mask=mask1)
final_go = period_slice(
stage2_hs, stage2_rules_epochs, final_task, "go1",
shift_percentage=period_shift_percentage)
# Per-trial stimulus-direction index for each task, used
# by the direction-averaged (stimulus-aligned) CVE below.
# Alignment is by input stimulus direction, so a pro-task
# trial at θ gets paired with a delayanti trial at θ even
# though delayanti responds toward θ+π.
stage1_test_input = np.asarray(stage1_output["test_input_np"])
stage2_test_input = np.asarray(stage2_output["test_input_np"])
dir_task0 = _stim_direction_indices(
stage1_test_input, stage1_rules_epochs,
stage1_tasks[0], mask=mask0)
dir_task1 = _stim_direction_indices(
stage1_test_input, stage1_rules_epochs,
stage1_tasks[1], mask=mask1)
dir_final = _stim_direction_indices(
stage2_test_input, stage2_rules_epochs, final_task)
# Hidden state analysis.
# Driscoll convention: X = pretraining (basis), Y = novel
# (delayanti). cev_Y = novel's variance in pretraining's PCs
# (Driscoll "purple"); cev_Y_self = novel in its own PCs
# (Driscoll "black").
res_h_stim = pca_cross_variance(
stage1_stim, final_stim, n_components=N, datatype="hidden")
res_h_go = pca_cross_variance(
stage1_go, final_go, n_components=N, datatype="hidden")
# Direction-averaged variant: run CVE within each stimulus
# bin separately, then average. Diagnoses whether pooling
# over direction is what makes the pooled CVE look low.
dir_h_stim = direction_averaged_cve(
stage1_stim, final_stim, dir_task0, dir_final,
n_components=N, datatype="hidden")
dir_h_go = direction_averaged_cve(
stage1_go, final_go, dir_task1, dir_final,
n_components=N, datatype="hidden")
seed_result["hidden"] = {
"stimulus": res_h_stim,
"response": res_h_go,
"stimulus_dir_avg": dir_h_stim,
"response_dir_avg": dir_h_go,
"angles_stimulus": principal_angles(
stage1_stim, final_stim, k=N_ANGLES, datatype="hidden"),
"angles_response": principal_angles(
stage1_go, final_go, k=N_ANGLES, datatype="hidden"),
}
# Modulation analysis (dmpn only)
if chosen_network == "dmpn" and stage1_ms.size > 0 and stage2_ms.size > 0:
stage1_stim_m = period_slice(
stage1_ms, stage1_rules_epochs, stage1_tasks[0], "stim1",