-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_diagnostic.py
More file actions
221 lines (190 loc) Β· 7.98 KB
/
run_diagnostic.py
File metadata and controls
221 lines (190 loc) Β· 7.98 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
#!/usr/bin/env python3
# Standalone diagnostic that loads the model like wakeup.py does
import torch
from babyLLM import BABYLLM
from config import *
from school.staffroom.calligraphist import S_OUTPUT
from school.staffroom.counsellor import COUNSELLOR
from school.staffroom.HE_IS_SCRIBE import SCRIBE
from school.staffroom.librarian import LIBRARIAN
print("=" * 80)
print("ATTENTION2 EXPLOSION DIAGNOSTIC")
print("=" * 80)
# Initialize components like wakeup.py does
print("\n[1/5] Initializing counsellor...")
counsellor = COUNSELLOR("diagnostic", _debug=False, _durations=False)
print("[2/5] Initializing librarian...")
librarian = LIBRARIAN(
_counsellor=counsellor, _baseTokenizerPath=None, _forceRetrain=False
)
print("[3/5] Initializing calligraphist...")
calligraphist = S_OUTPUT(_counsellor=counsellor)
print("[4/5] Initializing scribe...")
scribe = SCRIBE(
_counsellor=counsellor,
_calligraphist=calligraphist,
_librarian=librarian,
_numTokensPerStep=264,
)
print("[5/5] Loading babyLLM...")
model = BABYLLM(
_counsellor=counsellor,
_calligraphist=calligraphist,
_scribe=scribe,
_librarian=librarian,
_device=modelDevice,
_numTokensPerStep=264,
_first=True,
_learningRateGOAL=learningRateGOAL,
)
print("\n" + "=" * 80)
print("RUNNING DIAGNOSTICS")
print("=" * 80)
# ============================================================================
# DIAGNOSTIC 1: Check weight norms
# ============================================================================
print("\n1. Checking ATTENTION2 weight norms...")
explosion_detected = False
for name, param in model.attention2.attn.named_parameters():
norm = param.norm().item()
mean = param.mean().item()
has_nan = torch.isnan(param).any().item()
has_inf = torch.isinf(param).any().item()
status = ""
if has_nan:
status += " β οΈ NaN!"
explosion_detected = True
if has_inf:
status += " β οΈ Inf!"
explosion_detected = True
if norm > 1e6:
status += " π₯ EXPLODED!"
explosion_detected = True
print(f" {name}: norm={norm:.2e}, mean={mean:.2e}{status}")
# ============================================================================
# DIAGNOSTIC 2: Check expansion weights
# ============================================================================
print("\n2. Checking EXPANSION module weights...")
print(
f" Tangling.project_up norm: {model.tangling.project_up.weight.norm().item():.2e}"
)
print(
f" Tangling.project_down norm: {model.tangling.project_down.weight.norm().item():.2e}"
)
print(
f" Tangling.embed_gate: {torch.sigmoid(model.tangling.embed_tangle_gate).item():.6f}"
)
print(
f" Tangling.memory_gate: {torch.sigmoid(model.tangling.memory_tangle_gate).item():.6f}"
)
print(
f" Scratchpad.write_strength: {torch.sigmoid(model.scratchpad.write_strength).item():.6f}"
)
print(
f" Scratchpad.erase_strength: {torch.sigmoid(model.scratchpad.erase_strength).item():.6f}"
)
# ============================================================================
# DIAGNOSTIC 3: Test attention2 on clean input
# ============================================================================
print("\n3. Testing ATTENTION2 on clean random input...")
test_10k = torch.randn(64, 10000, device=model.device) * 0.1 # Small random values
print(f" Test input norm: {test_10k.norm().item():.2e}")
with torch.no_grad():
try:
out = model.attention2(test_10k)
out_norm = out.norm().item()
print(f" Attention2 output norm: {out_norm:.2e}")
if out_norm > 1e9:
print(" π₯ EXPLOSION CONFIRMED!")
print(f" Contains NaN: {torch.isnan(out).any().item()}")
print(f" Contains Inf: {torch.isinf(out).any().item()}")
print(f" Max value: {out.max().item():.2e}")
print(f" Min value: {out.min().item():.2e}")
explosion_detected = True
else:
print(" β Output is reasonable")
except Exception as e:
print(f" β ERROR: {e}")
explosion_detected = True
# ============================================================================
# DIAGNOSTIC 4: Test with expansion disabled
# ============================================================================
print("\n4. Testing with EXPANSION DISABLED...")
with torch.no_grad():
# Save original values
orig_embed = model.tangling.embed_tangle_gate.clone()
orig_memory = model.tangling.memory_tangle_gate.clone()
orig_write = model.scratchpad.write_strength.clone()
orig_erase = model.scratchpad.erase_strength.clone()
# Disable expansion
model.tangling.embed_tangle_gate.fill_(-100) # sigmoid(-100) β 0
model.tangling.memory_tangle_gate.fill_(-100)
model.scratchpad.write_strength.fill_(-100)
model.scratchpad.erase_strength.fill_(-100)
# Test forward pass
test_input = torch.randint(0, len(librarian.vocabList), (64,), device=model.device)
try:
output = model(test_input)
stats = model.getForwardStats()
att2_norm = stats.get("4A_1_0_attnOut_norm", "N/A")
mem_norm = stats.get("5M_memory_4M_x_FINAL_norm", "N/A")
print(f" Attention2 attnOut_norm: {att2_norm}")
print(f" Memory FINAL_norm: {mem_norm}")
if isinstance(att2_norm, (int, float)) and att2_norm > 1e9:
print(" π₯ ATTENTION2 EXPLODES EVEN WITHOUT EXPANSION!")
print(" β This is a PRE-EXISTING issue, not caused by new modules")
explosion_detected = True
else:
print(" β Model is stable when expansion disabled")
print(" β Explosion is CAUSED BY NEW MODULES")
except Exception as e:
print(f" β ERROR during forward pass: {e}")
explosion_detected = True
# Restore values
model.tangling.embed_tangle_gate.copy_(orig_embed)
model.tangling.memory_tangle_gate.copy_(orig_memory)
model.scratchpad.write_strength.copy_(orig_write)
model.scratchpad.erase_strength.copy_(orig_erase)
# ============================================================================
# DIAGNOSTIC 5: Test with only tangling enabled
# ============================================================================
print("\n5. Testing with ONLY TANGLING ENABLED...")
with torch.no_grad():
# Disable scratchpad only
model.scratchpad.write_strength.fill_(-100)
model.scratchpad.erase_strength.fill_(-100)
test_input = torch.randint(0, len(librarian.vocabList), (64,), device=model.device)
try:
output = model(test_input)
stats = model.getForwardStats()
att2_norm = stats.get("4A_1_0_attnOut_norm", "N/A")
print(f" Attention2 attnOut_norm: {att2_norm}")
if isinstance(att2_norm, (int, float)) and att2_norm > 1e9:
print(" π₯ TANGLING CAUSES EXPLOSION!")
else:
print(" β Tangling alone is stable")
except Exception as e:
print(f" β ERROR: {e}")
# Restore
model.scratchpad.write_strength.copy_(orig_write)
model.scratchpad.erase_strength.copy_(orig_erase)
# ============================================================================
# SUMMARY
# ============================================================================
print("\n" + "=" * 80)
print("DIAGNOSTIC SUMMARY")
print("=" * 80)
if explosion_detected:
print("β οΈ EXPLOSION DETECTED")
print("\nRecommended actions:")
print("1. Check if attention2 weights were already exploded before expansion")
print("2. Review the diagnostic output above to identify the source")
print("3. Consider reverting to a checkpoint before the explosion")
print("4. Add gradient clipping if not already present")
else:
print("β No explosion detected in diagnostics")
print("\nIf you're seeing explosions in training:")
print("1. The issue may be intermittent or input-dependent")
print("2. Try running diagnostics during an actual training step")
print("3. Check for NaN/Inf in gradients during training")
print("\n" + "=" * 80)