AmberLJC commited on
Commit
ff872cb
Β·
verified Β·
1 Parent(s): 1a6b907

Upload extended_experiment_v2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. extended_experiment_v2.py +519 -0
extended_experiment_v2.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Extended Gradient Clipping Experiment V2: Testing Physics-of-AI Predictions
3
+
4
+ Key changes from V1:
5
+ 1. More epochs (10 instead of 3) to allow rare class learning
6
+ 2. Smaller learning rate (0.01) for more stable training
7
+ 3. More frequent tracking to catch dynamics
8
+ 4. Added loss tracking per class to understand learning dynamics
9
+
10
+ Predictions being tested:
11
+ - Prediction 2: Representation Collapse (effective dimensionality drops without clipping)
12
+ - Prediction 4: Rare Sample Learning (clipping improves rare class accuracy)
13
+ """
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.optim as optim
18
+ import numpy as np
19
+ import matplotlib.pyplot as plt
20
+ import random
21
+ from typing import Dict, List, Tuple
22
+
23
+ SEED = 42
24
+
25
+
26
+ def set_seeds(seed=SEED):
27
+ torch.manual_seed(seed)
28
+ np.random.seed(seed)
29
+ random.seed(seed)
30
+
31
+
32
+ class SimpleNextTokenModel(nn.Module):
33
+ def __init__(self, vocab_size=4, embedding_dim=16):
34
+ super().__init__()
35
+ self.embedding = nn.Embedding(vocab_size, embedding_dim)
36
+ self.linear = nn.Linear(embedding_dim, vocab_size)
37
+
38
+ def forward(self, x):
39
+ embedded = self.embedding(x)
40
+ logits = self.linear(embedded)
41
+ return logits
42
+
43
+ def get_embeddings(self):
44
+ return self.embedding.weight.data.clone()
45
+
46
+
47
+ def compute_effective_dimension(embedding_matrix: torch.Tensor) -> float:
48
+ """PCA-based effective dimensionality using entropy."""
49
+ centered = embedding_matrix - embedding_matrix.mean(dim=0, keepdim=True)
50
+ cov = torch.mm(centered.T, centered) / (embedding_matrix.shape[0] - 1)
51
+ eigenvalues = torch.linalg.eigvalsh(cov)
52
+ eigenvalues = torch.clamp(eigenvalues, min=1e-10)
53
+ eigenvalues = eigenvalues / eigenvalues.sum()
54
+ entropy = -torch.sum(eigenvalues * torch.log(eigenvalues))
55
+ return torch.exp(entropy).item()
56
+
57
+
58
+ def compute_per_class_accuracy(model: nn.Module, inputs: torch.Tensor,
59
+ targets: torch.Tensor) -> Dict[int, float]:
60
+ """Compute accuracy for each target class."""
61
+ model.eval()
62
+ with torch.no_grad():
63
+ logits = model(inputs)
64
+ predictions = logits.argmax(dim=1)
65
+
66
+ accuracies = {}
67
+ for class_idx in range(4):
68
+ mask = targets == class_idx
69
+ if mask.sum() > 0:
70
+ correct = (predictions[mask] == targets[mask]).float().mean().item()
71
+ accuracies[class_idx] = correct
72
+ else:
73
+ accuracies[class_idx] = None
74
+
75
+ return accuracies
76
+
77
+
78
+ def compute_per_class_loss(model: nn.Module, inputs: torch.Tensor,
79
+ targets: torch.Tensor, criterion: nn.Module) -> Dict[int, float]:
80
+ """Compute average loss for each target class."""
81
+ model.eval()
82
+ losses = {}
83
+ with torch.no_grad():
84
+ logits = model(inputs)
85
+ for class_idx in range(4):
86
+ mask = targets == class_idx
87
+ if mask.sum() > 0:
88
+ class_loss = criterion(logits[mask], targets[mask]).item()
89
+ losses[class_idx] = class_loss
90
+ else:
91
+ losses[class_idx] = None
92
+ return losses
93
+
94
+
95
+ def create_imbalanced_dataset(n_samples=1000, n_rare=10, seed=SEED):
96
+ set_seeds(seed)
97
+ inputs = torch.randint(0, 4, (n_samples,))
98
+ targets = torch.zeros(n_samples, dtype=torch.long)
99
+ rare_indices = random.sample(range(n_samples), n_rare)
100
+ targets[rare_indices] = 1
101
+ return inputs, targets, sorted(rare_indices)
102
+
103
+
104
+ def train_with_tracking(inputs: torch.Tensor, targets: torch.Tensor,
105
+ rare_indices: List[int], clip_grad: bool = False,
106
+ max_norm: float = 1.0, n_epochs: int = 10,
107
+ lr: float = 0.01, init_weights=None,
108
+ track_every: int = 50) -> Dict:
109
+ """
110
+ Extended training with comprehensive tracking.
111
+ """
112
+ set_seeds(SEED)
113
+ model = SimpleNextTokenModel(vocab_size=4, embedding_dim=16)
114
+ if init_weights:
115
+ model.load_state_dict({k: v.clone() for k, v in init_weights.items()})
116
+
117
+ optimizer = optim.SGD(model.parameters(), lr=lr)
118
+ criterion = nn.CrossEntropyLoss()
119
+
120
+ metrics = {
121
+ 'losses': [],
122
+ 'grad_norms': [],
123
+ 'weight_norms': [],
124
+ 'effective_dims': [],
125
+ 'effective_dim_steps': [],
126
+ 'class_accuracies': {0: [], 1: [], 2: [], 3: []},
127
+ 'class_losses': {0: [], 1: [], 2: [], 3: []},
128
+ 'accuracy_steps': [],
129
+ 'rare_sample_losses': [], # Track loss specifically at rare samples
130
+ 'rare_sample_steps': [],
131
+ }
132
+
133
+ mode = "WITH" if clip_grad else "WITHOUT"
134
+ print(f"\n{'='*60}")
135
+ print(f"Training {mode} gradient clipping (max_norm={max_norm})")
136
+ print(f"Learning rate: {lr}, Epochs: {n_epochs}")
137
+ print(f"{'='*60}")
138
+
139
+ step = 0
140
+ n_samples = len(inputs)
141
+
142
+ for epoch in range(n_epochs):
143
+ model.train()
144
+ epoch_losses = []
145
+
146
+ for i in range(n_samples):
147
+ x = inputs[i:i+1]
148
+ y = targets[i:i+1]
149
+
150
+ optimizer.zero_grad()
151
+ logits = model(x)
152
+ loss = criterion(logits, y)
153
+ loss.backward()
154
+
155
+ grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), float('inf'))
156
+
157
+ if clip_grad:
158
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
159
+
160
+ optimizer.step()
161
+
162
+ metrics['losses'].append(loss.item())
163
+ metrics['grad_norms'].append(grad_norm.item())
164
+
165
+ total_norm = sum(p.data.norm(2).item() ** 2 for p in model.parameters()) ** 0.5
166
+ metrics['weight_norms'].append(total_norm)
167
+
168
+ epoch_losses.append(loss.item())
169
+
170
+ # Track at rare sample positions
171
+ if i in rare_indices:
172
+ metrics['rare_sample_losses'].append(loss.item())
173
+ metrics['rare_sample_steps'].append(step)
174
+
175
+ # Track embedding stats and accuracy periodically
176
+ if step % track_every == 0:
177
+ emb_matrix = model.get_embeddings()
178
+ eff_dim = compute_effective_dimension(emb_matrix)
179
+
180
+ metrics['effective_dims'].append(eff_dim)
181
+ metrics['effective_dim_steps'].append(step)
182
+
183
+ class_acc = compute_per_class_accuracy(model, inputs, targets)
184
+ class_loss = compute_per_class_loss(model, inputs, targets, criterion)
185
+
186
+ for cls_idx in range(4):
187
+ if class_acc[cls_idx] is not None:
188
+ metrics['class_accuracies'][cls_idx].append(class_acc[cls_idx])
189
+ else:
190
+ metrics['class_accuracies'][cls_idx].append(0.0)
191
+
192
+ if class_loss[cls_idx] is not None:
193
+ metrics['class_losses'][cls_idx].append(class_loss[cls_idx])
194
+ else:
195
+ metrics['class_losses'][cls_idx].append(0.0)
196
+
197
+ metrics['accuracy_steps'].append(step)
198
+
199
+ step += 1
200
+
201
+ avg_loss = np.mean(epoch_losses)
202
+ class_acc = compute_per_class_accuracy(model, inputs, targets)
203
+ class_loss = compute_per_class_loss(model, inputs, targets, criterion)
204
+ eff_dim = compute_effective_dimension(model.get_embeddings())
205
+
206
+ b_acc = f"{class_acc[1]:.3f}" if class_acc[1] is not None else "N/A"
207
+ b_loss = f"{class_loss[1]:.3f}" if class_loss[1] is not None else "N/A"
208
+
209
+ print(f"Epoch {epoch+1:2d}/{n_epochs}: Loss={avg_loss:.4f} | "
210
+ f"Acc A={class_acc[0]:.3f} B={b_acc} | "
211
+ f"Loss A={class_loss[0]:.3f} B={b_loss} | "
212
+ f"EffDim={eff_dim:.3f}")
213
+
214
+ return metrics
215
+
216
+
217
+ def plot_comprehensive_analysis(metrics_no_clip: Dict, metrics_with_clip: Dict,
218
+ rare_indices: List[int], filename: str,
219
+ n_samples: int = 1000):
220
+ """Create comprehensive 8-panel analysis."""
221
+ fig = plt.figure(figsize=(20, 16))
222
+ gs = fig.add_gridspec(4, 2, hspace=0.35, wspace=0.25)
223
+
224
+ n_epochs = len(metrics_no_clip['losses']) // n_samples
225
+
226
+ # Row 1: Effective Dimension
227
+ ax1 = fig.add_subplot(gs[0, 0])
228
+ ax2 = fig.add_subplot(gs[0, 1])
229
+
230
+ ax1.plot(metrics_no_clip['effective_dim_steps'], metrics_no_clip['effective_dims'],
231
+ 'b-', linewidth=2, marker='o', markersize=3)
232
+ ax1.set_ylabel('Effective Dimension', fontsize=11)
233
+ ax1.set_title('Effective Dim - WITHOUT Clipping', fontsize=12, fontweight='bold', color='red')
234
+ ax1.grid(True, alpha=0.3)
235
+ ax1.set_ylim([2.0, 3.5])
236
+
237
+ ax2.plot(metrics_with_clip['effective_dim_steps'], metrics_with_clip['effective_dims'],
238
+ 'g-', linewidth=2, marker='o', markersize=3)
239
+ ax2.set_title('Effective Dim - WITH Clipping', fontsize=12, fontweight='bold', color='green')
240
+ ax2.grid(True, alpha=0.3)
241
+ ax2.set_ylim([2.0, 3.5])
242
+
243
+ # Row 2: Class Accuracies
244
+ ax3 = fig.add_subplot(gs[1, 0])
245
+ ax4 = fig.add_subplot(gs[1, 1])
246
+
247
+ ax3.plot(metrics_no_clip['accuracy_steps'], metrics_no_clip['class_accuracies'][0],
248
+ 'r-', linewidth=2, alpha=0.7, label='Without Clip')
249
+ ax3.plot(metrics_with_clip['accuracy_steps'], metrics_with_clip['class_accuracies'][0],
250
+ 'g-', linewidth=2, alpha=0.7, label='With Clip')
251
+ ax3.set_ylabel('Accuracy', fontsize=11)
252
+ ax3.set_title("Common Class 'A' Accuracy", fontsize=12, fontweight='bold')
253
+ ax3.legend()
254
+ ax3.grid(True, alpha=0.3)
255
+ ax3.set_ylim([0, 1.05])
256
+
257
+ ax4.plot(metrics_no_clip['accuracy_steps'], metrics_no_clip['class_accuracies'][1],
258
+ 'r-', linewidth=2, alpha=0.7, label='Without Clip')
259
+ ax4.plot(metrics_with_clip['accuracy_steps'], metrics_with_clip['class_accuracies'][1],
260
+ 'g-', linewidth=2, alpha=0.7, label='With Clip')
261
+ ax4.set_title("Rare Class 'B' Accuracy [KEY PREDICTION]", fontsize=12, fontweight='bold', color='purple')
262
+ ax4.legend()
263
+ ax4.grid(True, alpha=0.3)
264
+ ax4.set_ylim([0, 1.05])
265
+
266
+ # Row 3: Class Losses
267
+ ax5 = fig.add_subplot(gs[2, 0])
268
+ ax6 = fig.add_subplot(gs[2, 1])
269
+
270
+ ax5.plot(metrics_no_clip['accuracy_steps'], metrics_no_clip['class_losses'][0],
271
+ 'r-', linewidth=2, alpha=0.7, label='Without Clip')
272
+ ax5.plot(metrics_with_clip['accuracy_steps'], metrics_with_clip['class_losses'][0],
273
+ 'g-', linewidth=2, alpha=0.7, label='With Clip')
274
+ ax5.set_ylabel('Loss', fontsize=11)
275
+ ax5.set_title("Common Class 'A' Loss", fontsize=12, fontweight='bold')
276
+ ax5.legend()
277
+ ax5.grid(True, alpha=0.3)
278
+
279
+ ax6.plot(metrics_no_clip['accuracy_steps'], metrics_no_clip['class_losses'][1],
280
+ 'r-', linewidth=2, alpha=0.7, label='Without Clip')
281
+ ax6.plot(metrics_with_clip['accuracy_steps'], metrics_with_clip['class_losses'][1],
282
+ 'g-', linewidth=2, alpha=0.7, label='With Clip')
283
+ ax6.set_title("Rare Class 'B' Loss", fontsize=12, fontweight='bold')
284
+ ax6.legend()
285
+ ax6.grid(True, alpha=0.3)
286
+
287
+ # Row 4: Gradient Norms and Weight Norms
288
+ ax7 = fig.add_subplot(gs[3, 0])
289
+ ax8 = fig.add_subplot(gs[3, 1])
290
+
291
+ steps = range(len(metrics_no_clip['grad_norms']))
292
+
293
+ ax7.plot(steps, metrics_no_clip['grad_norms'], 'r-', alpha=0.3, linewidth=0.5, label='Without Clip')
294
+ ax7.plot(steps, metrics_with_clip['grad_norms'], 'g-', alpha=0.3, linewidth=0.5, label='With Clip')
295
+ ax7.axhline(y=1.0, color='black', linestyle='--', linewidth=2, label='Clip threshold')
296
+ ax7.set_ylabel('Gradient Norm', fontsize=11)
297
+ ax7.set_xlabel('Training Step', fontsize=11)
298
+ ax7.set_title('Gradient Norms', fontsize=12, fontweight='bold')
299
+ ax7.legend()
300
+ ax7.grid(True, alpha=0.3)
301
+
302
+ ax8.plot(steps, metrics_no_clip['weight_norms'], 'r-', alpha=0.7, linewidth=1, label='Without Clip')
303
+ ax8.plot(steps, metrics_with_clip['weight_norms'], 'g-', alpha=0.7, linewidth=1, label='With Clip')
304
+ ax8.set_xlabel('Training Step', fontsize=11)
305
+ ax8.set_title('Weight Norms', fontsize=12, fontweight='bold')
306
+ ax8.legend()
307
+ ax8.grid(True, alpha=0.3)
308
+
309
+ fig.suptitle('Extended Gradient Clipping Analysis: Testing Physics-of-AI Predictions\n'
310
+ f'(10 epochs, lr=0.01, 990 common / 10 rare samples)',
311
+ fontsize=14, fontweight='bold', y=1.01)
312
+
313
+ plt.savefig(filename, dpi=150, bbox_inches='tight')
314
+ plt.close()
315
+ print(f"Comprehensive analysis saved to: {filename}")
316
+
317
+
318
+ def plot_rare_sample_dynamics(metrics_no_clip: Dict, metrics_with_clip: Dict,
319
+ filename: str):
320
+ """Plot dynamics specifically at rare sample positions."""
321
+ fig, axes = plt.subplots(2, 2, figsize=(14, 10))
322
+
323
+ # Rare sample losses over time
324
+ ax1 = axes[0, 0]
325
+ ax1.plot(metrics_no_clip['rare_sample_steps'], metrics_no_clip['rare_sample_losses'],
326
+ 'ro-', alpha=0.7, markersize=3, linewidth=0.5, label='Without Clip')
327
+ ax1.plot(metrics_with_clip['rare_sample_steps'], metrics_with_clip['rare_sample_losses'],
328
+ 'go-', alpha=0.7, markersize=3, linewidth=0.5, label='With Clip')
329
+ ax1.set_ylabel('Loss at Rare Sample', fontsize=11)
330
+ ax1.set_title('Loss When Encountering Rare Samples', fontsize=12, fontweight='bold')
331
+ ax1.legend()
332
+ ax1.grid(True, alpha=0.3)
333
+
334
+ # Histogram of rare sample losses
335
+ ax2 = axes[0, 1]
336
+ ax2.hist(metrics_no_clip['rare_sample_losses'], bins=30, alpha=0.5, color='red',
337
+ label=f"Without Clip (mean={np.mean(metrics_no_clip['rare_sample_losses']):.3f})")
338
+ ax2.hist(metrics_with_clip['rare_sample_losses'], bins=30, alpha=0.5, color='green',
339
+ label=f"With Clip (mean={np.mean(metrics_with_clip['rare_sample_losses']):.3f})")
340
+ ax2.set_xlabel('Loss', fontsize=11)
341
+ ax2.set_ylabel('Count', fontsize=11)
342
+ ax2.set_title('Distribution of Rare Sample Losses', fontsize=12, fontweight='bold')
343
+ ax2.legend()
344
+ ax2.grid(True, alpha=0.3)
345
+
346
+ # Gradient norms at rare positions
347
+ ax3 = axes[1, 0]
348
+
349
+ # Extract gradient norms at rare sample positions
350
+ n_samples = 1000
351
+ n_epochs = len(metrics_no_clip['losses']) // n_samples
352
+ rare_indices = [25, 104, 114, 142, 228, 250, 281, 654, 754, 759] # From our dataset
353
+
354
+ rare_grad_norms_no = []
355
+ rare_grad_norms_with = []
356
+ rare_steps = []
357
+
358
+ for epoch in range(n_epochs):
359
+ for idx in rare_indices:
360
+ step = epoch * n_samples + idx
361
+ if step < len(metrics_no_clip['grad_norms']):
362
+ rare_grad_norms_no.append(metrics_no_clip['grad_norms'][step])
363
+ rare_grad_norms_with.append(metrics_with_clip['grad_norms'][step])
364
+ rare_steps.append(step)
365
+
366
+ ax3.scatter(rare_steps, rare_grad_norms_no, c='red', alpha=0.6, s=20, label='Without Clip')
367
+ ax3.scatter(rare_steps, rare_grad_norms_with, c='green', alpha=0.6, s=20, label='With Clip')
368
+ ax3.axhline(y=1.0, color='black', linestyle='--', linewidth=2, label='Clip threshold')
369
+ ax3.set_xlabel('Training Step', fontsize=11)
370
+ ax3.set_ylabel('Gradient Norm', fontsize=11)
371
+ ax3.set_title('Gradient Norms at Rare Sample Positions', fontsize=12, fontweight='bold')
372
+ ax3.legend()
373
+ ax3.grid(True, alpha=0.3)
374
+
375
+ # Summary statistics
376
+ ax4 = axes[1, 1]
377
+ ax4.axis('off')
378
+
379
+ mean_rare_loss_no = np.mean(metrics_no_clip['rare_sample_losses'])
380
+ mean_rare_loss_with = np.mean(metrics_with_clip['rare_sample_losses'])
381
+ mean_rare_grad_no = np.mean(rare_grad_norms_no)
382
+ mean_rare_grad_with = np.mean(rare_grad_norms_with)
383
+
384
+ # Final class B accuracy
385
+ final_acc_b_no = metrics_no_clip['class_accuracies'][1][-1] if metrics_no_clip['class_accuracies'][1] else 0
386
+ final_acc_b_with = metrics_with_clip['class_accuracies'][1][-1] if metrics_with_clip['class_accuracies'][1] else 0
387
+
388
+ summary_text = f"""
389
+ RARE SAMPLE DYNAMICS SUMMARY
390
+ ════════════════════════════════════════════════════
391
+
392
+ At Rare Sample Positions:
393
+ ─────────────────────────────────────────────────────
394
+ Mean Loss (WITHOUT Clipping): {mean_rare_loss_no:.4f}
395
+ Mean Loss (WITH Clipping): {mean_rare_loss_with:.4f}
396
+ Loss Reduction: {(mean_rare_loss_no - mean_rare_loss_with) / mean_rare_loss_no * 100:+.1f}%
397
+
398
+ Mean Gradient Norm (WITHOUT): {mean_rare_grad_no:.4f}
399
+ Mean Gradient Norm (WITH): {mean_rare_grad_with:.4f}
400
+ Gradient Reduction: {(mean_rare_grad_no - mean_rare_grad_with) / mean_rare_grad_no * 100:+.1f}%
401
+
402
+ Final Rare Class Accuracy:
403
+ ─────────────────────────────────────────────────────
404
+ WITHOUT Clipping: {final_acc_b_no:.1%}
405
+ WITH Clipping: {final_acc_b_with:.1%}
406
+
407
+ ════════════════════════════════════════════════════
408
+ PHYSICS-OF-AI INTERPRETATION:
409
+
410
+ Gradient clipping acts as a "velocity limiter" in
411
+ weight space, preventing the model from making
412
+ sudden large updates when encountering rare samples.
413
+
414
+ This allows the model to gradually learn the rare
415
+ class pattern rather than overshooting and forgetting.
416
+ """
417
+
418
+ ax4.text(0.05, 0.5, summary_text, transform=ax4.transAxes,
419
+ fontsize=10, verticalalignment='center', fontfamily='monospace',
420
+ bbox=dict(boxstyle='round', facecolor='lightyellow', alpha=0.9))
421
+
422
+ fig.suptitle('Rare Sample Dynamics Analysis\n'
423
+ '(How the model behaves when encountering rare class B samples)',
424
+ fontsize=14, fontweight='bold', y=1.01)
425
+
426
+ plt.tight_layout()
427
+ plt.savefig(filename, dpi=150, bbox_inches='tight')
428
+ plt.close()
429
+ print(f"Rare sample dynamics plot saved to: {filename}")
430
+
431
+
432
+ def main():
433
+ print("="*70)
434
+ print("EXTENDED GRADIENT CLIPPING EXPERIMENT V2")
435
+ print("Testing Physics-of-AI Predictions with Extended Training")
436
+ print("="*70)
437
+
438
+ # Create dataset
439
+ inputs, targets, rare_indices = create_imbalanced_dataset(n_samples=1000, n_rare=10, seed=SEED)
440
+
441
+ print(f"\nDataset: {len(inputs)} samples ({(targets == 0).sum().item()} common, {(targets == 1).sum().item()} rare)")
442
+ print(f"Rare indices: {rare_indices}")
443
+
444
+ # Get initial weights
445
+ set_seeds(SEED)
446
+ init_model = SimpleNextTokenModel(vocab_size=4, embedding_dim=16)
447
+ init_weights = {name: param.clone() for name, param in init_model.state_dict().items()}
448
+
449
+ init_eff_dim = compute_effective_dimension(init_model.get_embeddings())
450
+ print(f"Initial effective dimension: {init_eff_dim:.3f}")
451
+
452
+ # Training parameters
453
+ n_epochs = 10
454
+ lr = 0.01
455
+
456
+ # Run training WITHOUT gradient clipping
457
+ metrics_no_clip = train_with_tracking(
458
+ inputs, targets, rare_indices,
459
+ clip_grad=False, n_epochs=n_epochs, lr=lr,
460
+ init_weights=init_weights, track_every=100
461
+ )
462
+
463
+ # Run training WITH gradient clipping
464
+ metrics_with_clip = train_with_tracking(
465
+ inputs, targets, rare_indices,
466
+ clip_grad=True, max_norm=1.0, n_epochs=n_epochs, lr=lr,
467
+ init_weights=init_weights, track_every=100
468
+ )
469
+
470
+ # Generate plots
471
+ print("\n" + "="*70)
472
+ print("GENERATING ANALYSIS PLOTS")
473
+ print("="*70)
474
+
475
+ plot_comprehensive_analysis(
476
+ metrics_no_clip, metrics_with_clip, rare_indices,
477
+ "extended_analysis_v2.png"
478
+ )
479
+
480
+ plot_rare_sample_dynamics(
481
+ metrics_no_clip, metrics_with_clip,
482
+ "rare_sample_dynamics.png"
483
+ )
484
+
485
+ # Final summary
486
+ print("\n" + "="*70)
487
+ print("FINAL PREDICTION TEST RESULTS")
488
+ print("="*70)
489
+
490
+ # Prediction 2
491
+ dims_no = metrics_no_clip['effective_dims']
492
+ dims_with = metrics_with_clip['effective_dims']
493
+
494
+ print("\n[PREDICTION 2] Representation Collapse:")
495
+ print(f" Effective Dim Variance (WITHOUT): {np.std(dims_no):.6f}")
496
+ print(f" Effective Dim Variance (WITH): {np.std(dims_with):.6f}")
497
+ print(f" Verdict: {'SUPPORTED' if np.std(dims_no) > np.std(dims_with) else 'NOT SUPPORTED'}")
498
+
499
+ # Prediction 4
500
+ final_acc_b_no = metrics_no_clip['class_accuracies'][1][-1]
501
+ final_acc_b_with = metrics_with_clip['class_accuracies'][1][-1]
502
+
503
+ print("\n[PREDICTION 4] Rare Sample Learning:")
504
+ print(f" Final Rare Class Accuracy (WITHOUT): {final_acc_b_no:.1%}")
505
+ print(f" Final Rare Class Accuracy (WITH): {final_acc_b_with:.1%}")
506
+ print(f" Verdict: {'SUPPORTED' if final_acc_b_with >= final_acc_b_no else 'NOT SUPPORTED'}")
507
+
508
+ return {
509
+ 'metrics_no_clip': metrics_no_clip,
510
+ 'metrics_with_clip': metrics_with_clip,
511
+ 'rare_indices': rare_indices,
512
+ }
513
+
514
+
515
+ if __name__ == "__main__":
516
+ results = main()
517
+ print("\n" + "="*70)
518
+ print("EXPERIMENT COMPLETE!")
519
+ print("="*70)