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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Final Gradient Clipping Experiment: Testing Physics-of-AI Predictions
|
| 3 |
+
|
| 4 |
+
Key insights from previous experiments:
|
| 5 |
+
1. With extreme imbalance (99:1), neither model learns rare class
|
| 6 |
+
2. Gradient clipping's benefit is in STABILITY, not learning rare classes per se
|
| 7 |
+
3. The key effect is on WEIGHT NORM STABILITY and GRADIENT SPIKE HANDLING
|
| 8 |
+
|
| 9 |
+
This experiment tests:
|
| 10 |
+
1. Prediction 2: Representation Collapse - effective dim variance without clipping
|
| 11 |
+
2. Prediction 4: Rare Sample Learning - using moderate imbalance (80:20)
|
| 12 |
+
3. NEW: Weight norm stability analysis
|
| 13 |
+
4. NEW: Gradient spike analysis at rare sample positions
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.optim as optim
|
| 19 |
+
import numpy as np
|
| 20 |
+
import matplotlib.pyplot as plt
|
| 21 |
+
import random
|
| 22 |
+
from typing import Dict, List
|
| 23 |
+
|
| 24 |
+
SEED = 42
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def set_seeds(seed=SEED):
|
| 28 |
+
torch.manual_seed(seed)
|
| 29 |
+
np.random.seed(seed)
|
| 30 |
+
random.seed(seed)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class SimpleNextTokenModel(nn.Module):
|
| 34 |
+
def __init__(self, vocab_size=4, embedding_dim=16):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.embedding = nn.Embedding(vocab_size, embedding_dim)
|
| 37 |
+
self.linear = nn.Linear(embedding_dim, vocab_size)
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
embedded = self.embedding(x)
|
| 41 |
+
logits = self.linear(embedded)
|
| 42 |
+
return logits
|
| 43 |
+
|
| 44 |
+
def get_embeddings(self):
|
| 45 |
+
return self.embedding.weight.data.clone()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def compute_effective_dimension(embedding_matrix: torch.Tensor) -> float:
|
| 49 |
+
"""PCA-based effective dimensionality."""
|
| 50 |
+
centered = embedding_matrix - embedding_matrix.mean(dim=0, keepdim=True)
|
| 51 |
+
cov = torch.mm(centered.T, centered) / (embedding_matrix.shape[0] - 1)
|
| 52 |
+
eigenvalues = torch.linalg.eigvalsh(cov)
|
| 53 |
+
eigenvalues = torch.clamp(eigenvalues, min=1e-10)
|
| 54 |
+
eigenvalues = eigenvalues / eigenvalues.sum()
|
| 55 |
+
entropy = -torch.sum(eigenvalues * torch.log(eigenvalues))
|
| 56 |
+
return torch.exp(entropy).item()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def compute_per_class_accuracy(model: nn.Module, inputs: torch.Tensor,
|
| 60 |
+
targets: torch.Tensor) -> Dict[int, float]:
|
| 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 create_dataset_moderate_imbalance(n_samples=1000, rare_ratio=0.2, seed=SEED):
|
| 79 |
+
"""Create dataset with moderate imbalance (e.g., 80:20)."""
|
| 80 |
+
set_seeds(seed)
|
| 81 |
+
|
| 82 |
+
n_rare = int(n_samples * rare_ratio)
|
| 83 |
+
n_common = n_samples - n_rare
|
| 84 |
+
|
| 85 |
+
inputs = torch.randint(0, 4, (n_samples,))
|
| 86 |
+
targets = torch.zeros(n_samples, dtype=torch.long)
|
| 87 |
+
|
| 88 |
+
rare_indices = random.sample(range(n_samples), n_rare)
|
| 89 |
+
targets[rare_indices] = 1
|
| 90 |
+
|
| 91 |
+
return inputs, targets, sorted(rare_indices)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def create_dataset_extreme_imbalance(n_samples=1000, n_rare=10, seed=SEED):
|
| 95 |
+
"""Create dataset with extreme imbalance (99:1)."""
|
| 96 |
+
set_seeds(seed)
|
| 97 |
+
|
| 98 |
+
inputs = torch.randint(0, 4, (n_samples,))
|
| 99 |
+
targets = torch.zeros(n_samples, dtype=torch.long)
|
| 100 |
+
|
| 101 |
+
rare_indices = random.sample(range(n_samples), n_rare)
|
| 102 |
+
targets[rare_indices] = 1
|
| 103 |
+
|
| 104 |
+
return inputs, targets, sorted(rare_indices)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def train_with_tracking(inputs: torch.Tensor, targets: torch.Tensor,
|
| 108 |
+
rare_indices: List[int], clip_grad: bool = False,
|
| 109 |
+
max_norm: float = 1.0, n_epochs: int = 10,
|
| 110 |
+
lr: float = 0.1, init_weights=None,
|
| 111 |
+
track_every: int = 50) -> Dict:
|
| 112 |
+
"""Training with comprehensive tracking."""
|
| 113 |
+
set_seeds(SEED)
|
| 114 |
+
model = SimpleNextTokenModel(vocab_size=4, embedding_dim=16)
|
| 115 |
+
if init_weights:
|
| 116 |
+
model.load_state_dict({k: v.clone() for k, v in init_weights.items()})
|
| 117 |
+
|
| 118 |
+
optimizer = optim.SGD(model.parameters(), lr=lr)
|
| 119 |
+
criterion = nn.CrossEntropyLoss()
|
| 120 |
+
|
| 121 |
+
metrics = {
|
| 122 |
+
'losses': [],
|
| 123 |
+
'grad_norms': [],
|
| 124 |
+
'weight_norms': [],
|
| 125 |
+
'effective_dims': [],
|
| 126 |
+
'effective_dim_steps': [],
|
| 127 |
+
'class_accuracies': {0: [], 1: [], 2: [], 3: []},
|
| 128 |
+
'accuracy_steps': [],
|
| 129 |
+
'weight_norm_changes': [], # Track sudden changes
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
step = 0
|
| 133 |
+
n_samples = len(inputs)
|
| 134 |
+
prev_weight_norm = None
|
| 135 |
+
|
| 136 |
+
for epoch in range(n_epochs):
|
| 137 |
+
model.train()
|
| 138 |
+
|
| 139 |
+
for i in range(n_samples):
|
| 140 |
+
x = inputs[i:i+1]
|
| 141 |
+
y = targets[i:i+1]
|
| 142 |
+
|
| 143 |
+
optimizer.zero_grad()
|
| 144 |
+
logits = model(x)
|
| 145 |
+
loss = criterion(logits, y)
|
| 146 |
+
loss.backward()
|
| 147 |
+
|
| 148 |
+
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), float('inf'))
|
| 149 |
+
|
| 150 |
+
if clip_grad:
|
| 151 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
|
| 152 |
+
|
| 153 |
+
optimizer.step()
|
| 154 |
+
|
| 155 |
+
metrics['losses'].append(loss.item())
|
| 156 |
+
metrics['grad_norms'].append(grad_norm.item())
|
| 157 |
+
|
| 158 |
+
current_weight_norm = sum(p.data.norm(2).item() ** 2 for p in model.parameters()) ** 0.5
|
| 159 |
+
metrics['weight_norms'].append(current_weight_norm)
|
| 160 |
+
|
| 161 |
+
# Track weight norm change
|
| 162 |
+
if prev_weight_norm is not None:
|
| 163 |
+
metrics['weight_norm_changes'].append(abs(current_weight_norm - prev_weight_norm))
|
| 164 |
+
else:
|
| 165 |
+
metrics['weight_norm_changes'].append(0)
|
| 166 |
+
prev_weight_norm = current_weight_norm
|
| 167 |
+
|
| 168 |
+
# Track periodically
|
| 169 |
+
if step % track_every == 0:
|
| 170 |
+
emb_matrix = model.get_embeddings()
|
| 171 |
+
eff_dim = compute_effective_dimension(emb_matrix)
|
| 172 |
+
metrics['effective_dims'].append(eff_dim)
|
| 173 |
+
metrics['effective_dim_steps'].append(step)
|
| 174 |
+
|
| 175 |
+
class_acc = compute_per_class_accuracy(model, inputs, targets)
|
| 176 |
+
for cls_idx in range(4):
|
| 177 |
+
if class_acc[cls_idx] is not None:
|
| 178 |
+
metrics['class_accuracies'][cls_idx].append(class_acc[cls_idx])
|
| 179 |
+
else:
|
| 180 |
+
metrics['class_accuracies'][cls_idx].append(0.0)
|
| 181 |
+
metrics['accuracy_steps'].append(step)
|
| 182 |
+
|
| 183 |
+
step += 1
|
| 184 |
+
|
| 185 |
+
return metrics
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def run_experiment_suite():
|
| 189 |
+
"""Run complete experiment suite with both imbalance levels."""
|
| 190 |
+
print("="*70)
|
| 191 |
+
print("FINAL GRADIENT CLIPPING EXPERIMENT")
|
| 192 |
+
print("Testing Physics-of-AI Predictions")
|
| 193 |
+
print("="*70)
|
| 194 |
+
|
| 195 |
+
# Get initial weights
|
| 196 |
+
set_seeds(SEED)
|
| 197 |
+
init_model = SimpleNextTokenModel(vocab_size=4, embedding_dim=16)
|
| 198 |
+
init_weights = {name: param.clone() for name, param in init_model.state_dict().items()}
|
| 199 |
+
|
| 200 |
+
results = {}
|
| 201 |
+
|
| 202 |
+
# =========================================================================
|
| 203 |
+
# EXPERIMENT 1: Extreme Imbalance (99:1) - Original Setup
|
| 204 |
+
# =========================================================================
|
| 205 |
+
print("\n" + "="*70)
|
| 206 |
+
print("EXPERIMENT 1: EXTREME IMBALANCE (99:1)")
|
| 207 |
+
print("="*70)
|
| 208 |
+
|
| 209 |
+
inputs_extreme, targets_extreme, rare_extreme = create_dataset_extreme_imbalance(
|
| 210 |
+
n_samples=1000, n_rare=10, seed=SEED
|
| 211 |
+
)
|
| 212 |
+
print(f"Dataset: {(targets_extreme == 0).sum().item()} common, {(targets_extreme == 1).sum().item()} rare")
|
| 213 |
+
|
| 214 |
+
print("\nTraining WITHOUT clipping...")
|
| 215 |
+
metrics_extreme_no_clip = train_with_tracking(
|
| 216 |
+
inputs_extreme, targets_extreme, rare_extreme,
|
| 217 |
+
clip_grad=False, n_epochs=5, lr=0.1,
|
| 218 |
+
init_weights=init_weights, track_every=100
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
print("Training WITH clipping...")
|
| 222 |
+
metrics_extreme_with_clip = train_with_tracking(
|
| 223 |
+
inputs_extreme, targets_extreme, rare_extreme,
|
| 224 |
+
clip_grad=True, max_norm=1.0, n_epochs=5, lr=0.1,
|
| 225 |
+
init_weights=init_weights, track_every=100
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
results['extreme'] = {
|
| 229 |
+
'no_clip': metrics_extreme_no_clip,
|
| 230 |
+
'with_clip': metrics_extreme_with_clip,
|
| 231 |
+
'rare_indices': rare_extreme
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
# =========================================================================
|
| 235 |
+
# EXPERIMENT 2: Moderate Imbalance (80:20)
|
| 236 |
+
# =========================================================================
|
| 237 |
+
print("\n" + "="*70)
|
| 238 |
+
print("EXPERIMENT 2: MODERATE IMBALANCE (80:20)")
|
| 239 |
+
print("="*70)
|
| 240 |
+
|
| 241 |
+
inputs_moderate, targets_moderate, rare_moderate = create_dataset_moderate_imbalance(
|
| 242 |
+
n_samples=1000, rare_ratio=0.2, seed=SEED
|
| 243 |
+
)
|
| 244 |
+
print(f"Dataset: {(targets_moderate == 0).sum().item()} common, {(targets_moderate == 1).sum().item()} rare")
|
| 245 |
+
|
| 246 |
+
print("\nTraining WITHOUT clipping...")
|
| 247 |
+
metrics_moderate_no_clip = train_with_tracking(
|
| 248 |
+
inputs_moderate, targets_moderate, rare_moderate,
|
| 249 |
+
clip_grad=False, n_epochs=10, lr=0.1,
|
| 250 |
+
init_weights=init_weights, track_every=100
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
print("Training WITH clipping...")
|
| 254 |
+
metrics_moderate_with_clip = train_with_tracking(
|
| 255 |
+
inputs_moderate, targets_moderate, rare_moderate,
|
| 256 |
+
clip_grad=True, max_norm=1.0, n_epochs=10, lr=0.1,
|
| 257 |
+
init_weights=init_weights, track_every=100
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
results['moderate'] = {
|
| 261 |
+
'no_clip': metrics_moderate_no_clip,
|
| 262 |
+
'with_clip': metrics_moderate_with_clip,
|
| 263 |
+
'rare_indices': rare_moderate
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
return results
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def plot_final_comparison(results: Dict, filename: str):
|
| 270 |
+
"""Create final comparison plot."""
|
| 271 |
+
fig = plt.figure(figsize=(20, 20))
|
| 272 |
+
gs = fig.add_gridspec(5, 2, hspace=0.35, wspace=0.25)
|
| 273 |
+
|
| 274 |
+
# =========================================================================
|
| 275 |
+
# Row 1: Weight Norm Stability (Key Physics-of-AI Insight)
|
| 276 |
+
# =========================================================================
|
| 277 |
+
ax1 = fig.add_subplot(gs[0, 0])
|
| 278 |
+
ax2 = fig.add_subplot(gs[0, 1])
|
| 279 |
+
|
| 280 |
+
# Extreme imbalance
|
| 281 |
+
steps = range(len(results['extreme']['no_clip']['weight_norms']))
|
| 282 |
+
ax1.plot(steps, results['extreme']['no_clip']['weight_norms'], 'r-', alpha=0.7, linewidth=1, label='Without Clip')
|
| 283 |
+
ax1.plot(steps, results['extreme']['with_clip']['weight_norms'], 'g-', alpha=0.7, linewidth=1, label='With Clip')
|
| 284 |
+
ax1.set_ylabel('Weight Norm', fontsize=11)
|
| 285 |
+
ax1.set_title('EXTREME (99:1) - Weight Norm Evolution', fontsize=12, fontweight='bold')
|
| 286 |
+
ax1.legend()
|
| 287 |
+
ax1.grid(True, alpha=0.3)
|
| 288 |
+
|
| 289 |
+
# Moderate imbalance
|
| 290 |
+
steps = range(len(results['moderate']['no_clip']['weight_norms']))
|
| 291 |
+
ax2.plot(steps, results['moderate']['no_clip']['weight_norms'], 'r-', alpha=0.7, linewidth=1, label='Without Clip')
|
| 292 |
+
ax2.plot(steps, results['moderate']['with_clip']['weight_norms'], 'g-', alpha=0.7, linewidth=1, label='With Clip')
|
| 293 |
+
ax2.set_title('MODERATE (80:20) - Weight Norm Evolution', fontsize=12, fontweight='bold')
|
| 294 |
+
ax2.legend()
|
| 295 |
+
ax2.grid(True, alpha=0.3)
|
| 296 |
+
|
| 297 |
+
# =========================================================================
|
| 298 |
+
# Row 2: Weight Norm Changes (Stability Metric)
|
| 299 |
+
# =========================================================================
|
| 300 |
+
ax3 = fig.add_subplot(gs[1, 0])
|
| 301 |
+
ax4 = fig.add_subplot(gs[1, 1])
|
| 302 |
+
|
| 303 |
+
# Extreme
|
| 304 |
+
steps = range(len(results['extreme']['no_clip']['weight_norm_changes']))
|
| 305 |
+
ax3.plot(steps, results['extreme']['no_clip']['weight_norm_changes'], 'r-', alpha=0.5, linewidth=0.5, label='Without Clip')
|
| 306 |
+
ax3.plot(steps, results['extreme']['with_clip']['weight_norm_changes'], 'g-', alpha=0.5, linewidth=0.5, label='With Clip')
|
| 307 |
+
ax3.set_ylabel('|Weight Norm Change|', fontsize=11)
|
| 308 |
+
ax3.set_title('EXTREME - Weight Norm Changes (Stability)', fontsize=12, fontweight='bold')
|
| 309 |
+
ax3.legend()
|
| 310 |
+
ax3.grid(True, alpha=0.3)
|
| 311 |
+
|
| 312 |
+
# Moderate
|
| 313 |
+
steps = range(len(results['moderate']['no_clip']['weight_norm_changes']))
|
| 314 |
+
ax4.plot(steps, results['moderate']['no_clip']['weight_norm_changes'], 'r-', alpha=0.5, linewidth=0.5, label='Without Clip')
|
| 315 |
+
ax4.plot(steps, results['moderate']['with_clip']['weight_norm_changes'], 'g-', alpha=0.5, linewidth=0.5, label='With Clip')
|
| 316 |
+
ax4.set_title('MODERATE - Weight Norm Changes (Stability)', fontsize=12, fontweight='bold')
|
| 317 |
+
ax4.legend()
|
| 318 |
+
ax4.grid(True, alpha=0.3)
|
| 319 |
+
|
| 320 |
+
# =========================================================================
|
| 321 |
+
# Row 3: Gradient Norms
|
| 322 |
+
# =========================================================================
|
| 323 |
+
ax5 = fig.add_subplot(gs[2, 0])
|
| 324 |
+
ax6 = fig.add_subplot(gs[2, 1])
|
| 325 |
+
|
| 326 |
+
# Extreme
|
| 327 |
+
steps = range(len(results['extreme']['no_clip']['grad_norms']))
|
| 328 |
+
ax5.plot(steps, results['extreme']['no_clip']['grad_norms'], 'r-', alpha=0.3, linewidth=0.5, label='Without Clip')
|
| 329 |
+
ax5.plot(steps, results['extreme']['with_clip']['grad_norms'], 'g-', alpha=0.3, linewidth=0.5, label='With Clip')
|
| 330 |
+
ax5.axhline(y=1.0, color='black', linestyle='--', linewidth=2, label='Clip threshold')
|
| 331 |
+
ax5.set_ylabel('Gradient Norm', fontsize=11)
|
| 332 |
+
ax5.set_title('EXTREME - Gradient Norms', fontsize=12, fontweight='bold')
|
| 333 |
+
ax5.legend()
|
| 334 |
+
ax5.grid(True, alpha=0.3)
|
| 335 |
+
|
| 336 |
+
# Moderate
|
| 337 |
+
steps = range(len(results['moderate']['no_clip']['grad_norms']))
|
| 338 |
+
ax6.plot(steps, results['moderate']['no_clip']['grad_norms'], 'r-', alpha=0.3, linewidth=0.5, label='Without Clip')
|
| 339 |
+
ax6.plot(steps, results['moderate']['with_clip']['grad_norms'], 'g-', alpha=0.3, linewidth=0.5, label='With Clip')
|
| 340 |
+
ax6.axhline(y=1.0, color='black', linestyle='--', linewidth=2, label='Clip threshold')
|
| 341 |
+
ax6.set_title('MODERATE - Gradient Norms', fontsize=12, fontweight='bold')
|
| 342 |
+
ax6.legend()
|
| 343 |
+
ax6.grid(True, alpha=0.3)
|
| 344 |
+
|
| 345 |
+
# =========================================================================
|
| 346 |
+
# Row 4: Effective Dimension
|
| 347 |
+
# =========================================================================
|
| 348 |
+
ax7 = fig.add_subplot(gs[3, 0])
|
| 349 |
+
ax8 = fig.add_subplot(gs[3, 1])
|
| 350 |
+
|
| 351 |
+
# Extreme
|
| 352 |
+
ax7.plot(results['extreme']['no_clip']['effective_dim_steps'],
|
| 353 |
+
results['extreme']['no_clip']['effective_dims'],
|
| 354 |
+
'r-o', alpha=0.7, linewidth=2, markersize=4, label='Without Clip')
|
| 355 |
+
ax7.plot(results['extreme']['with_clip']['effective_dim_steps'],
|
| 356 |
+
results['extreme']['with_clip']['effective_dims'],
|
| 357 |
+
'g-o', alpha=0.7, linewidth=2, markersize=4, label='With Clip')
|
| 358 |
+
ax7.set_ylabel('Effective Dimension', fontsize=11)
|
| 359 |
+
ax7.set_title('EXTREME - Effective Dimensionality', fontsize=12, fontweight='bold')
|
| 360 |
+
ax7.legend()
|
| 361 |
+
ax7.grid(True, alpha=0.3)
|
| 362 |
+
|
| 363 |
+
# Moderate
|
| 364 |
+
ax8.plot(results['moderate']['no_clip']['effective_dim_steps'],
|
| 365 |
+
results['moderate']['no_clip']['effective_dims'],
|
| 366 |
+
'r-o', alpha=0.7, linewidth=2, markersize=4, label='Without Clip')
|
| 367 |
+
ax8.plot(results['moderate']['with_clip']['effective_dim_steps'],
|
| 368 |
+
results['moderate']['with_clip']['effective_dims'],
|
| 369 |
+
'g-o', alpha=0.7, linewidth=2, markersize=4, label='With Clip')
|
| 370 |
+
ax8.set_title('MODERATE - Effective Dimensionality', fontsize=12, fontweight='bold')
|
| 371 |
+
ax8.legend()
|
| 372 |
+
ax8.grid(True, alpha=0.3)
|
| 373 |
+
|
| 374 |
+
# =========================================================================
|
| 375 |
+
# Row 5: Class Accuracies
|
| 376 |
+
# =========================================================================
|
| 377 |
+
ax9 = fig.add_subplot(gs[4, 0])
|
| 378 |
+
ax10 = fig.add_subplot(gs[4, 1])
|
| 379 |
+
|
| 380 |
+
# Extreme - Rare class B
|
| 381 |
+
ax9.plot(results['extreme']['no_clip']['accuracy_steps'],
|
| 382 |
+
results['extreme']['no_clip']['class_accuracies'][1],
|
| 383 |
+
'r-', alpha=0.7, linewidth=2, label='Without Clip')
|
| 384 |
+
ax9.plot(results['extreme']['with_clip']['accuracy_steps'],
|
| 385 |
+
results['extreme']['with_clip']['class_accuracies'][1],
|
| 386 |
+
'g-', alpha=0.7, linewidth=2, label='With Clip')
|
| 387 |
+
ax9.set_ylabel('Rare Class B Accuracy', fontsize=11)
|
| 388 |
+
ax9.set_xlabel('Training Step', fontsize=11)
|
| 389 |
+
ax9.set_title('EXTREME - Rare Class Accuracy', fontsize=12, fontweight='bold')
|
| 390 |
+
ax9.legend()
|
| 391 |
+
ax9.grid(True, alpha=0.3)
|
| 392 |
+
ax9.set_ylim([0, 1.05])
|
| 393 |
+
|
| 394 |
+
# Moderate - Rare class B
|
| 395 |
+
ax10.plot(results['moderate']['no_clip']['accuracy_steps'],
|
| 396 |
+
results['moderate']['no_clip']['class_accuracies'][1],
|
| 397 |
+
'r-', alpha=0.7, linewidth=2, label='Without Clip')
|
| 398 |
+
ax10.plot(results['moderate']['with_clip']['accuracy_steps'],
|
| 399 |
+
results['moderate']['with_clip']['class_accuracies'][1],
|
| 400 |
+
'g-', alpha=0.7, linewidth=2, label='With Clip')
|
| 401 |
+
ax10.set_xlabel('Training Step', fontsize=11)
|
| 402 |
+
ax10.set_title('MODERATE - Rare Class Accuracy', fontsize=12, fontweight='bold')
|
| 403 |
+
ax10.legend()
|
| 404 |
+
ax10.grid(True, alpha=0.3)
|
| 405 |
+
ax10.set_ylim([0, 1.05])
|
| 406 |
+
|
| 407 |
+
fig.suptitle('Gradient Clipping Analysis: Physics-of-AI Predictions\n'
|
| 408 |
+
'Comparing Extreme (99:1) vs Moderate (80:20) Class Imbalance',
|
| 409 |
+
fontsize=14, fontweight='bold', y=1.01)
|
| 410 |
+
|
| 411 |
+
plt.savefig(filename, dpi=150, bbox_inches='tight')
|
| 412 |
+
plt.close()
|
| 413 |
+
print(f"Final comparison plot saved to: {filename}")
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def compute_statistics(results: Dict) -> Dict:
|
| 417 |
+
"""Compute summary statistics for all experiments."""
|
| 418 |
+
stats = {}
|
| 419 |
+
|
| 420 |
+
for imbalance in ['extreme', 'moderate']:
|
| 421 |
+
no_clip = results[imbalance]['no_clip']
|
| 422 |
+
with_clip = results[imbalance]['with_clip']
|
| 423 |
+
|
| 424 |
+
stats[imbalance] = {
|
| 425 |
+
'weight_norm_std': {
|
| 426 |
+
'no_clip': np.std(no_clip['weight_norms']),
|
| 427 |
+
'with_clip': np.std(with_clip['weight_norms']),
|
| 428 |
+
},
|
| 429 |
+
'weight_change_mean': {
|
| 430 |
+
'no_clip': np.mean(no_clip['weight_norm_changes']),
|
| 431 |
+
'with_clip': np.mean(with_clip['weight_norm_changes']),
|
| 432 |
+
},
|
| 433 |
+
'weight_change_max': {
|
| 434 |
+
'no_clip': np.max(no_clip['weight_norm_changes']),
|
| 435 |
+
'with_clip': np.max(with_clip['weight_norm_changes']),
|
| 436 |
+
},
|
| 437 |
+
'grad_norm_max': {
|
| 438 |
+
'no_clip': np.max(no_clip['grad_norms']),
|
| 439 |
+
'with_clip': np.max(with_clip['grad_norms']),
|
| 440 |
+
},
|
| 441 |
+
'effective_dim_std': {
|
| 442 |
+
'no_clip': np.std(no_clip['effective_dims']),
|
| 443 |
+
'with_clip': np.std(with_clip['effective_dims']),
|
| 444 |
+
},
|
| 445 |
+
'final_rare_acc': {
|
| 446 |
+
'no_clip': no_clip['class_accuracies'][1][-1] if no_clip['class_accuracies'][1] else 0,
|
| 447 |
+
'with_clip': with_clip['class_accuracies'][1][-1] if with_clip['class_accuracies'][1] else 0,
|
| 448 |
+
},
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
return stats
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def print_summary(stats: Dict):
|
| 455 |
+
"""Print formatted summary."""
|
| 456 |
+
print("\n" + "="*70)
|
| 457 |
+
print("EXPERIMENT SUMMARY")
|
| 458 |
+
print("="*70)
|
| 459 |
+
|
| 460 |
+
for imbalance in ['extreme', 'moderate']:
|
| 461 |
+
s = stats[imbalance]
|
| 462 |
+
label = "EXTREME (99:1)" if imbalance == 'extreme' else "MODERATE (80:20)"
|
| 463 |
+
|
| 464 |
+
print(f"\n{label}")
|
| 465 |
+
print("-" * 50)
|
| 466 |
+
|
| 467 |
+
print(f"\n[PREDICTION 2] Representation Collapse (Effective Dim Variance):")
|
| 468 |
+
print(f" WITHOUT Clipping: {s['effective_dim_std']['no_clip']:.6f}")
|
| 469 |
+
print(f" WITH Clipping: {s['effective_dim_std']['with_clip']:.6f}")
|
| 470 |
+
supported = s['effective_dim_std']['no_clip'] > s['effective_dim_std']['with_clip']
|
| 471 |
+
print(f" Verdict: {'SUPPORTED' if supported else 'NOT SUPPORTED'}")
|
| 472 |
+
|
| 473 |
+
print(f"\n[PREDICTION 4] Rare Sample Learning:")
|
| 474 |
+
print(f" Final Rare Accuracy (WITHOUT): {s['final_rare_acc']['no_clip']:.1%}")
|
| 475 |
+
print(f" Final Rare Accuracy (WITH): {s['final_rare_acc']['with_clip']:.1%}")
|
| 476 |
+
supported = s['final_rare_acc']['with_clip'] >= s['final_rare_acc']['no_clip']
|
| 477 |
+
print(f" Verdict: {'SUPPORTED' if supported else 'NOT SUPPORTED'}")
|
| 478 |
+
|
| 479 |
+
print(f"\n[STABILITY] Weight Norm Analysis:")
|
| 480 |
+
print(f" Weight Norm Std (WITHOUT): {s['weight_norm_std']['no_clip']:.4f}")
|
| 481 |
+
print(f" Weight Norm Std (WITH): {s['weight_norm_std']['with_clip']:.4f}")
|
| 482 |
+
print(f" Max Weight Change (WITHOUT): {s['weight_change_max']['no_clip']:.4f}")
|
| 483 |
+
print(f" Max Weight Change (WITH): {s['weight_change_max']['with_clip']:.4f}")
|
| 484 |
+
|
| 485 |
+
print(f"\n[GRADIENT] Analysis:")
|
| 486 |
+
print(f" Max Gradient Norm (WITHOUT): {s['grad_norm_max']['no_clip']:.4f}")
|
| 487 |
+
print(f" Max Gradient Norm (WITH): {s['grad_norm_max']['with_clip']:.4f}")
|
| 488 |
+
print(f" Clipping Ratio: {s['grad_norm_max']['no_clip'] / 1.0:.1f}x threshold")
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def main():
|
| 492 |
+
# Run experiments
|
| 493 |
+
results = run_experiment_suite()
|
| 494 |
+
|
| 495 |
+
# Generate plots
|
| 496 |
+
print("\n" + "="*70)
|
| 497 |
+
print("GENERATING PLOTS")
|
| 498 |
+
print("="*70)
|
| 499 |
+
|
| 500 |
+
plot_final_comparison(results, "final_comparison.png")
|
| 501 |
+
|
| 502 |
+
# Compute and print statistics
|
| 503 |
+
stats = compute_statistics(results)
|
| 504 |
+
print_summary(stats)
|
| 505 |
+
|
| 506 |
+
return results, stats
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
if __name__ == "__main__":
|
| 510 |
+
results, stats = main()
|
| 511 |
+
print("\n" + "="*70)
|
| 512 |
+
print("EXPERIMENT COMPLETE!")
|
| 513 |
+
print("="*70)
|