thefinalboss commited on
Commit
b65956a
·
verified ·
1 Parent(s): 815ba07

Upload scripts/train_salience_head.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/train_salience_head.py +130 -0
scripts/train_salience_head.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Train the salience head by perturbation of trajectory.
3
+
4
+ The salience head learns INTRINSICALLY: at each tick with memory active, it
5
+ predicts how much the memory injection will perturb the thought state. The
6
+ signal is ||h_after - h_before||, normalized by a running max. No external
7
+ labels, no REINFORCE — just the dynamical system learning its own sensitivity.
8
+
9
+ This runs the slow per-tick path (memory is only in `tick`, not `tick_chunk`).
10
+ ~25 tok/s on CPU. Budget: 50k tokens (~30 min).
11
+
12
+ Usage:
13
+ python scripts/train_salience_head.py [--tokens 50000] [--budget-corpus 200000]
14
+ """
15
+ import argparse, os, sys, time, math
16
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
17
+ import torch
18
+ import torch.nn.functional as F
19
+ import experiments.edt_ab.ablib as ablib
20
+ from fractus.memory import PersistentMemory
21
+
22
+ CORPUS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
23
+ "data", "communication_corpus.pt")
24
+ SALIENCE_LAMBDA = 0.01 # weight of salience loss vs CE
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("--tokens", type=int, default=50_000, help="training tokens")
30
+ ap.add_argument("--budget-corpus", type=int, default=200_000)
31
+ ap.add_argument("--lr", type=float, default=3e-4)
32
+ ap.add_argument("--seed", type=int, default=42)
33
+ args = ap.parse_args()
34
+
35
+ torch.set_num_threads(os.cpu_count() or 6)
36
+ torch.manual_seed(args.seed)
37
+
38
+ print("=== Salience Head Training (perturbation of trajectory) ===", flush=True)
39
+ split = ablib.load_corpus(CORPUS, n_train=args.budget_corpus,
40
+ n_holdout=10_000, n_phase1=int(args.budget_corpus * 0.15))
41
+ tokens = split["train"][:args.tokens]
42
+ holdout = split["holdout"]
43
+
44
+ # Build engine + attach memory.
45
+ eng = ablib.build_engine(seed=args.seed)
46
+ mem = PersistentMemory(d_model=128, max_memories=128)
47
+ eng.attach_memory(mem)
48
+ eng.memory_active = True
49
+
50
+ # Snapshot salience head weights to detect movement.
51
+ sal_before = eng.salience_head.weight.detach().clone()
52
+ sal_bias_before = eng.salience_head.bias.detach().clone()
53
+
54
+ opt = torch.optim.AdamW(eng.parameters(), lr=args.lr, weight_decay=0.01)
55
+ eng.train()
56
+ eng.reset_thought(batch_size=1)
57
+
58
+ t0 = time.time()
59
+ total_ce, total_sal, n = 0.0, 0.0, 0
60
+ for t in range(len(tokens) - 1):
61
+ obs = tokens[t:t + 1]
62
+ target = tokens[t + 1:t + 2]
63
+ logits, conf = eng.tick(obs)
64
+ ce = F.cross_entropy(logits, target)
65
+ sal_loss = getattr(eng, 'last_salience_loss', torch.tensor(0.0))
66
+ loss = ce + SALIENCE_LAMBDA * sal_loss
67
+
68
+ opt.zero_grad()
69
+ loss.backward()
70
+ torch.nn.utils.clip_grad_norm_(eng.parameters(), 1.0)
71
+ opt.step()
72
+
73
+ total_ce += ce.item()
74
+ total_sal += sal_loss.item()
75
+ n += 1
76
+
77
+ if (t + 1) % 2000 == 0:
78
+ elapsed = time.time() - t0
79
+ rate = (t + 1) / max(elapsed, 1)
80
+ print(f" t={t+1:>6} ce={total_ce/n:.3f} sal={total_sal/n:.4f} "
81
+ f"mem={len(mem)} pert_max={eng._pert_max:.3f} "
82
+ f"{rate:.0f} tok/s", flush=True)
83
+
84
+ elapsed = time.time() - t0
85
+ # Check if the salience head actually learned.
86
+ sal_after = eng.salience_head.weight.detach()
87
+ sal_bias_after = eng.salience_head.bias.detach()
88
+ weight_delta = (sal_after - sal_before).norm().item()
89
+ bias_delta = (sal_bias_after - sal_bias_before).norm().item()
90
+
91
+ print(f"\n{'='*60}", flush=True)
92
+ print(f"Training done: {n} tokens in {elapsed/60:.1f}min ({n/elapsed:.0f} tok/s)", flush=True)
93
+ print(f"Final CE: {total_ce/n:.3f} Final salience loss: {total_sal/n:.4f}", flush=True)
94
+ print(f"Memories consolidated: {len(mem)}", flush=True)
95
+ print(f"Salience head weight delta: {weight_delta:.6f} (should be > 0 if learned)", flush=True)
96
+ print(f"Salience head bias delta: {bias_delta:.6f}", flush=True)
97
+ print(f"Perturbation running max: {eng._pert_max:.4f}", flush=True)
98
+
99
+ if weight_delta > 1e-6:
100
+ print("VERDICT: salience head LEARNED (weights moved).", flush=True)
101
+ else:
102
+ print("VERDICT: salience head did NOT learn (weights unchanged).", flush=True)
103
+
104
+ # Evaluate: does the salience head now predict perturbation?
105
+ eng.eval()
106
+ eng.reset_thought(batch_size=1)
107
+ predicted, actual = [], []
108
+ with torch.no_grad():
109
+ for t in range(min(500, len(tokens) - 1)):
110
+ obs = tokens[t:t + 1]
111
+ logits, _ = eng.tick(obs)
112
+ predicted.append(torch.sigmoid(eng.salience_head(
113
+ eng.thought_state[:, 0, :])).item())
114
+ actual.append(getattr(eng, '_last_perturbation', 0.0))
115
+ if max(actual) > 0:
116
+ corr_n = min(len(predicted), len(actual))
117
+ pm, am = sum(predicted[:corr_n])/corr_n, sum(actual[:corr_n])/corr_n
118
+ cov = sum((p-pm)*(a-am) for p,a in zip(predicted[:corr_n], actual[:corr_n]))
119
+ vp = sum((p-pm)**2 for p in predicted[:corr_n])
120
+ va = sum((a-am)**2 for a in actual[:corr_n])
121
+ import math as m
122
+ denom = m.sqrt(vp * va) if vp > 0 and va > 0 else 0
123
+ corr = cov / denom if denom > 0 else 0
124
+ print(f"Correlation(predicted_salience, actual_perturbation) = {corr:.3f}", flush=True)
125
+ else:
126
+ print("No perturbations measured during eval — memory may be empty.", flush=True)
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()