Skip to content

Commit f16691b

Browse files
committed
Backup more stuff.
1 parent a1d979a commit f16691b

87 files changed

Lines changed: 23248 additions & 3579 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

benchmark_new_features.py

Lines changed: 503 additions & 0 deletions
Large diffs are not rendered by default.

check_lr_identity.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env python3
2+
"""Check if learning rates are properly shared."""
3+
4+
import sys
5+
import os
6+
import torch
7+
import torch.nn as nn
8+
9+
# Add the src directory to Python path for testing
10+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
11+
12+
from meta_learning.algorithms.meta_sgd import MetaSGD
13+
14+
def check_lr_identity():
15+
"""Check if cloned model shares learning rate objects."""
16+
print("🔍 Checking learning rate identity...")
17+
18+
model = nn.Linear(2, 1)
19+
meta_sgd = MetaSGD(model, lr=0.5)
20+
21+
# Clone the model
22+
cloned = meta_sgd.clone()
23+
24+
# Check if learning rates are the same objects
25+
for i, (orig_lr, cloned_lr) in enumerate(zip(meta_sgd.lrs, cloned.lrs)):
26+
print(f"LR {i}: Same object? {orig_lr is cloned_lr}")
27+
print(f"LR {i}: Values equal? {torch.allclose(orig_lr, cloned_lr)}")
28+
print(f"LR {i}: Same ID? Original: {id(orig_lr)}, Cloned: {id(cloned_lr)}")
29+
30+
# Try modifying original learning rates
31+
with torch.no_grad():
32+
meta_sgd.lrs[0].fill_(0.1)
33+
34+
print(f"After modifying original:")
35+
print(f"Original LR value: {meta_sgd.lrs[0].item()}")
36+
print(f"Cloned LR value: {cloned.lrs[0].item()}")
37+
38+
# Check if they are the same parameter list
39+
print(f"ParameterList identity: {meta_sgd.lrs is cloned.lrs}")
40+
41+
return meta_sgd.lrs is cloned.lrs
42+
43+
if __name__ == "__main__":
44+
same = check_lr_identity()
45+
if same:
46+
print("✅ Learning rates are properly shared")
47+
else:
48+
print("❌ Learning rates are NOT shared")

debug_gradient_flow.py

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
#!/usr/bin/env python3
2+
"""Debug gradient flow in Meta-SGD."""
3+
4+
import sys
5+
import os
6+
import torch
7+
import torch.nn as nn
8+
import torch.nn.functional as F
9+
10+
# Add the src directory to Python path for testing
11+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
12+
13+
from meta_learning.algorithms.meta_sgd import MetaSGD
14+
15+
def debug_gradient_flow():
16+
"""Debug gradient flow step by step."""
17+
print("🔍 Debugging gradient flow in Meta-SGD...")
18+
19+
# Simple model
20+
model = nn.Linear(2, 1)
21+
meta_sgd = MetaSGD(model, lr=0.5, first_order=False)
22+
23+
print(f"Learning rate requires grad: {meta_sgd.lrs[0].requires_grad}")
24+
print(f"Learning rate grad_fn: {meta_sgd.lrs[0].grad_fn}")
25+
26+
# Simple data
27+
x = torch.tensor([[1.0, 1.0]], dtype=torch.float32)
28+
y = torch.tensor([[0.5]], dtype=torch.float32)
29+
30+
# Clone model for adaptation
31+
task_model = meta_sgd.clone()
32+
print(f"Cloned model LR requires grad: {task_model.lrs[0].requires_grad}")
33+
print(f"Cloned model LR grad_fn: {task_model.lrs[0].grad_fn}")
34+
35+
# Forward pass
36+
pred = task_model(x)
37+
print(f"Prediction: {pred}")
38+
print(f"Prediction requires_grad: {pred.requires_grad}")
39+
print(f"Prediction grad_fn: {pred.grad_fn}")
40+
41+
# Compute loss
42+
loss = F.mse_loss(pred, y)
43+
print(f"Loss: {loss.item():.4f}")
44+
print(f"Loss requires_grad: {loss.requires_grad}")
45+
print(f"Loss grad_fn: {loss.grad_fn}")
46+
47+
# Before adaptation - check if LR has gradients
48+
if task_model.lrs[0].grad is not None:
49+
print(f"LR grad before adaptation: {task_model.lrs[0].grad}")
50+
else:
51+
print("LR grad before adaptation: None")
52+
53+
# Perform adaptation
54+
print("\n--- Performing adaptation ---")
55+
task_model.adapt(loss)
56+
57+
# After adaptation - check model parameters
58+
adapted_pred = task_model(x)
59+
print(f"Adapted prediction: {adapted_pred}")
60+
print(f"Adapted prediction requires_grad: {adapted_pred.requires_grad}")
61+
print(f"Adapted prediction grad_fn: {adapted_pred.grad_fn}")
62+
63+
# Meta loss
64+
meta_loss = F.mse_loss(adapted_pred, y)
65+
print(f"\nMeta-loss: {meta_loss.item():.4f}")
66+
print(f"Meta-loss requires_grad: {meta_loss.requires_grad}")
67+
print(f"Meta-loss grad_fn: {meta_loss.grad_fn}")
68+
69+
# Check if learning rates are in computational graph
70+
print("\n--- Checking computational graph ---")
71+
if meta_loss.grad_fn is not None:
72+
print("Meta-loss has grad_fn - computational graph exists")
73+
74+
# Check if we can compute gradients w.r.t. learning rates
75+
try:
76+
lr_grad = torch.autograd.grad(meta_loss, task_model.lrs[0], retain_graph=True)
77+
print(f"LR gradient computed: {lr_grad[0]}")
78+
return True
79+
except RuntimeError as e:
80+
print(f"❌ Cannot compute LR gradient: {e}")
81+
return False
82+
else:
83+
print("❌ Meta-loss has no grad_fn - no computational graph")
84+
return False
85+
86+
def debug_lr_connection():
87+
"""Debug if learning rates are connected to the forward pass."""
88+
print("\n🔍 Debugging LR connection to forward pass...")
89+
90+
model = nn.Linear(1, 1)
91+
meta_sgd = MetaSGD(model, lr=1.0, first_order=False)
92+
93+
# Manually check what happens in adaptation
94+
x = torch.tensor([[1.0]])
95+
y = torch.tensor([[0.0]])
96+
97+
# Forward pass to get loss
98+
pred = meta_sgd(x)
99+
loss = F.mse_loss(pred, y)
100+
101+
print(f"Initial loss: {loss.item():.4f}")
102+
103+
# Get gradients manually
104+
grads = torch.autograd.grad(loss, meta_sgd.module.parameters(), create_graph=True)
105+
print(f"Gradients computed: {[g.shape for g in grads]}")
106+
107+
# Check if gradients have grad_fn (for second-order)
108+
for i, g in enumerate(grads):
109+
print(f"Gradient {i} grad_fn: {g.grad_fn}")
110+
111+
# Manual update using learning rates
112+
updated_params = []
113+
for param, lr, grad in zip(meta_sgd.module.parameters(), meta_sgd.lrs, grads):
114+
updated_param = param - lr * grad # This should preserve gradients!
115+
updated_params.append(updated_param)
116+
print(f"Updated param grad_fn: {updated_param.grad_fn}")
117+
print(f"LR grad_fn: {lr.grad_fn}")
118+
119+
return True
120+
121+
if __name__ == "__main__":
122+
success1 = debug_gradient_flow()
123+
success2 = debug_lr_connection()
124+
125+
if success1 and success2:
126+
print("\n✅ Gradient flow debugging complete")
127+
else:
128+
print("\n❌ Issues found in gradient flow")

debug_meta_sgd_lrs.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#!/usr/bin/env python3
2+
"""Debug Meta-SGD learning rates."""
3+
4+
import sys
5+
import os
6+
import torch
7+
import torch.nn as nn
8+
import torch.nn.functional as F
9+
10+
# Add the src directory to Python path for testing
11+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
12+
13+
from meta_learning.algorithms.meta_sgd import MetaSGD
14+
15+
def debug_learning_rates():
16+
"""Debug why learning rates aren't updating."""
17+
print("🔍 Debugging Meta-SGD learning rates...")
18+
19+
# Create simple model
20+
model = nn.Linear(3, 2)
21+
meta_sgd = MetaSGD(model, lr=0.05)
22+
23+
print(f"Number of learning rate parameters: {len(meta_sgd.lrs)}")
24+
print(f"Learning rate requires_grad: {[lr.requires_grad for lr in meta_sgd.lrs]}")
25+
26+
# Check if learning rates are in meta_sgd.parameters()
27+
all_params = list(meta_sgd.parameters())
28+
print(f"Total MetaSGD parameters: {len(all_params)}")
29+
30+
# Separate module params from lr params
31+
module_params = list(meta_sgd.module.parameters())
32+
lr_params = list(meta_sgd.lrs)
33+
34+
print(f"Module parameters: {len(module_params)}")
35+
print(f"LR parameters: {len(lr_params)}")
36+
37+
# Check if LR params are properly included
38+
lr_param_ids = {id(p) for p in lr_params}
39+
all_param_ids = {id(p) for p in all_params}
40+
41+
lr_in_all = lr_param_ids.intersection(all_param_ids)
42+
print(f"LR params in all params: {len(lr_in_all)}/{len(lr_param_ids)}")
43+
44+
if len(lr_in_all) != len(lr_param_ids):
45+
print("❌ Learning rate parameters are NOT included in meta_sgd.parameters()!")
46+
print("This is why they're not being updated by the meta-optimizer")
47+
return False
48+
else:
49+
print("✅ Learning rate parameters are properly included")
50+
return True
51+
52+
if __name__ == "__main__":
53+
debug_learning_rates()

debug_ridge_gradients.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env python3
2+
"""Debug Ridge regression gradient flow."""
3+
4+
import sys
5+
import os
6+
import torch
7+
import torch.nn.functional as F
8+
9+
# Add the src directory to Python path for testing
10+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
11+
12+
from meta_learning.algorithms.metaoptnet import DifferentiableRidge
13+
14+
def debug_ridge_gradients():
15+
"""Debug what's happening with Ridge gradients."""
16+
print("🔍 Debugging Ridge regression gradients...")
17+
18+
# Create Ridge solver
19+
ridge = DifferentiableRidge(lam=1.0)
20+
21+
# Create data with requires_grad
22+
support_embeddings = torch.randn(10, 8, requires_grad=True)
23+
support_labels = torch.randint(0, 3, (10,))
24+
query_embeddings = torch.randn(5, 8, requires_grad=True)
25+
26+
print(f"Support embeddings requires_grad: {support_embeddings.requires_grad}")
27+
print(f"Query embeddings requires_grad: {query_embeddings.requires_grad}")
28+
29+
# Forward pass
30+
predictions = ridge(support_embeddings, support_labels, query_embeddings)
31+
32+
print(f"Predictions requires_grad: {predictions.requires_grad}")
33+
print(f"Predictions grad_fn: {predictions.grad_fn}")
34+
35+
# Try to backpropagate
36+
if predictions.requires_grad:
37+
loss = predictions.sum()
38+
loss.backward()
39+
print(f"Support grad exists: {support_embeddings.grad is not None}")
40+
print(f"Query grad exists: {query_embeddings.grad is not None}")
41+
else:
42+
print("❌ Cannot backpropagate - no grad_fn")
43+
44+
return predictions.requires_grad
45+
46+
if __name__ == "__main__":
47+
success = debug_ridge_gradients()
48+
if success:
49+
print("✅ Ridge gradients working")
50+
else:
51+
print("❌ Ridge gradients broken")

0 commit comments

Comments
 (0)