File size: 43,091 Bytes
0293aec | 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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 | import sys
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from tqdm import tqdm
import json
import time
# Add the parent directory to the path to import from PureLogits
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
grandparent_dir = os.path.dirname(parent_dir)
sys.path.append(grandparent_dir)
sys.path.append(parent_dir)
# Import necessary components from the calibrator
from calibrator.Component.metrics import (
BrierLoss, CrossEntropyLoss, MSELoss, SoftECE, ECE
)
# Set random seed for reproducibility
def set_seed(seed):
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# Load logits and labels from cache directory
def load_data(cache_dir):
val_logits = np.load(os.path.join(cache_dir, "val_logits.npy"))
val_labels = np.load(os.path.join(cache_dir, "val_labels.npy"))
test_logits = np.load(os.path.join(cache_dir, "test_logits.npy"))
test_labels = np.load(os.path.join(cache_dir, "test_labels.npy"))
print(f"Loaded data: val_logits shape: {val_logits.shape}, val_labels shape: {val_labels.shape}")
print(f"Loaded data: test_logits shape: {test_logits.shape}, test_labels shape: {test_labels.shape}")
return val_logits, val_labels, test_logits, test_labels
# Compute hardness as the gap between top logit and runner-up
def compute_hardness(logits):
logits_tensor = torch.tensor(logits, dtype=torch.float32)
sorted_logits, _ = torch.sort(logits_tensor, descending=True)
logit_gap = (sorted_logits[0] - sorted_logits[1]).item()
return logit_gap
# Custom ECE wrapper to ensure it returns a tensor that can be backpropagated
class ECEWrapper(nn.Module):
def __init__(self, n_bins=15):
super(ECEWrapper, self).__init__()
self.ece = ECE(n_bins=n_bins)
def forward(self, logits, labels):
# ECE returns a scalar value, we need to wrap it in a tensor with requires_grad=True
ece_value = self.ece(logits, labels)
# Check if the result is already a tensor with grad
if isinstance(ece_value, torch.Tensor) and ece_value.requires_grad:
return ece_value
# Otherwise, create a tensor with requires_grad=True
if isinstance(ece_value, torch.Tensor):
return ece_value.clone().detach().requires_grad_(True)
else:
return torch.tensor(ece_value, requires_grad=True, device=logits.device)
# Custom Brier Loss implementation that ensures it's different from MSE
class CustomBrierLoss(nn.Module):
def __init__(self):
super(CustomBrierLoss, self).__init__()
def forward(self, logits, labels):
# Get predicted probabilities
outputs = F.softmax(logits, dim=1)
# Convert labels to one-hot
one_hot = torch.zeros(labels.size(0), outputs.size(1), device=labels.device)
one_hot.scatter_(1, labels.unsqueeze(1), 1)
# Compute Brier loss
brier_score = torch.mean(torch.sum((outputs - one_hot) ** 2, dim=1))
# Explicitly scale by 0.5 to differentiate from MSE
return brier_score * 0.5
# Experiment 1: Compare gradient stability of different calibration objectives
def experiment_1_gradient_stability(test_logits, test_labels, cache_dir, output_dir="results"):
print("\nExperiment 1: Comparing Gradient Stability of Different Calibration Objectives")
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Convert data to PyTorch tensors
logits_tensor = torch.tensor(test_logits, dtype=torch.float32)
labels_tensor = torch.tensor(test_labels, dtype=torch.long)
# Initialize different loss functions
soft_ece = SoftECE(n_bins=15)
traditional_ece = ECEWrapper(n_bins=15) # Use wrapper for ECE
brier_score = BrierLoss()
cross_entropy = CrossEntropyLoss()
mse_loss = MSELoss()
# Temperature parameter with gradient tracking
temperature = nn.Parameter(torch.ones(1))
# Sample a subset of data for visualization (to avoid clutter)
num_samples = 1000
indices = np.random.choice(len(test_logits), num_samples, replace=False)
# Confidence bins for analysis
confidence_bins = np.linspace(0.5, 1.0, 10)
bin_width = confidence_bins[1] - confidence_bins[0]
# Store gradients for each loss function across confidence levels
results = {
"SoftECE": {"grads": [], "conf_bins": []},
"ECE": {"grads": [], "conf_bins": []},
"Brier": {"grads": [], "conf_bins": []},
"CrossEntropy": {"grads": [], "conf_bins": []},
"MSE": {"grads": [], "conf_bins": []}
}
# Calculate gradients for different temperature values
temp_values = [0.5, 0.8, 1.0, 1.2, 1.5, 2.0]
for temp_val in temp_values:
print(f"\nAnalyzing gradients at temperature = {temp_val}")
# Set temperature to current value
with torch.no_grad():
temperature.fill_(temp_val)
# Process samples in batches to avoid memory issues
batch_size = 100
num_batches = (num_samples + batch_size - 1) // batch_size
for batch_idx in tqdm(range(num_batches)):
start_idx = batch_idx * batch_size
end_idx = min((batch_idx + 1) * batch_size, num_samples)
batch_indices = indices[start_idx:end_idx]
batch_logits = logits_tensor[batch_indices]
batch_labels = labels_tensor[batch_indices]
# Apply temperature scaling
scaled_logits = batch_logits / temperature
probs = F.softmax(scaled_logits, dim=1)
# Calculate confidence (max probability)
confidences = torch.max(probs, dim=1)[0].detach().numpy()
# Calculate gradients for each loss function
for loss_name, loss_fn in [
("SoftECE", soft_ece),
("ECE", traditional_ece),
("Brier", brier_score),
("CrossEntropy", cross_entropy),
("MSE", mse_loss)
]:
temperature.grad = None
if loss_name == "SoftECE":
loss = loss_fn(scaled_logits, batch_labels)
elif loss_name == "ECE":
loss = loss_fn(scaled_logits, batch_labels)
elif loss_name == "Brier":
loss = loss_fn(scaled_logits, batch_labels)
elif loss_name == "CrossEntropy":
loss = loss_fn(scaled_logits, batch_labels)
elif loss_name == "MSE":
loss = loss_fn(scaled_logits, batch_labels)
loss.backward(retain_graph=True)
# Store gradient magnitude for each sample
if temperature.grad is not None:
grad_magnitude = temperature.grad.item()
# Store gradients by confidence bin
for i, conf in enumerate(confidences):
bin_idx = np.digitize(conf, confidence_bins) - 1
if 0 <= bin_idx < len(confidence_bins):
results[loss_name]["grads"].append(grad_magnitude)
results[loss_name]["conf_bins"].append(confidence_bins[bin_idx])
# Plot gradient magnitudes across confidence levels
plt.figure(figsize=(10, 6))
for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]:
# Group gradients by confidence bin
binned_grads = {}
for grad, bin_val in zip(results[loss_name]["grads"], results[loss_name]["conf_bins"]):
if bin_val not in binned_grads:
binned_grads[bin_val] = []
binned_grads[bin_val].append(grad)
# Calculate mean and std of gradients for each bin
bin_centers = []
mean_grads = []
std_grads = []
for bin_val in sorted(binned_grads.keys()):
if binned_grads[bin_val]: # Ensure there are gradients for this bin
bin_centers.append(bin_val)
mean_grads.append(np.mean(np.abs(binned_grads[bin_val])))
std_grads.append(np.std(np.abs(binned_grads[bin_val])))
# Plot mean gradient magnitude with error bars
plt.errorbar(bin_centers, mean_grads, yerr=std_grads, label=loss_name, marker='o', capsize=4)
plt.xlabel('Confidence Level')
plt.ylabel('Gradient Magnitude')
plt.title('Gradient Stability Across Confidence Levels')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'gradient_stability.png'), dpi=300)
plt.close()
# Save results
with open(os.path.join(output_dir, 'gradient_stability_results.json'), 'w') as f:
# Convert numpy arrays to lists for JSON serialization
serializable_results = {}
for loss_name, data in results.items():
serializable_results[loss_name] = {
"grads": [float(g) for g in data["grads"]],
"conf_bins": [float(c) for c in data["conf_bins"]]
}
json.dump(serializable_results, f, indent=2)
print(f"Gradient stability analysis complete. Results saved to {output_dir}")
# Experiment 2: Gradient information content analysis
def experiment_2_gradient_information(test_logits, test_labels, cache_dir, output_dir="results"):
print("\nExperiment 2: Analyzing Gradient Information Content of Different Calibration Objectives")
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Convert data to PyTorch tensors
logits_tensor = torch.tensor(test_logits, dtype=torch.float32)
labels_tensor = torch.tensor(test_labels, dtype=torch.long)
# Sample a subset of data
num_samples = 2000
indices = np.random.choice(len(test_logits), num_samples, replace=False)
# Initialize different loss functions
soft_ece = SoftECE(n_bins=15, sigma=0.05)
traditional_ece = ECEWrapper(n_bins=15)
brier_score = BrierLoss()
cross_entropy = CrossEntropyLoss()
mse_loss = MSELoss()
# Create synthetic miscalibration by distorting temperatures
# We'll create 5 different scenarios ranging from underconfident to overconfident
temp_scenarios = [0.5, 0.8, 1.0, 1.2, 2.0]
# Store gradient direction consistency and correlation with calibration error
results = {
"temp_scenario": [],
"ece_values": [],
"gradient_consistency": {},
"gradient_correlation": {},
"gradient_entropy": {}
}
for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]:
results["gradient_consistency"][loss_name] = []
results["gradient_correlation"][loss_name] = []
results["gradient_entropy"][loss_name] = []
# Create confidence bins for analysis
confidence_bins = np.linspace(0.1, 1.0, 10)
for temperature_value in temp_scenarios:
print(f"\nAnalyzing scenario with temperature = {temperature_value}")
# Set up temperature parameter for this scenario
temperature = nn.Parameter(torch.ones(1) * temperature_value)
# Generate scaled logits for the whole dataset to calculate overall ECE
with torch.no_grad():
overall_scaled_logits = logits_tensor / temperature
overall_probs = F.softmax(overall_scaled_logits, dim=1)
ece_metric = ECE(n_bins=15)
ece_value = ece_metric(overall_scaled_logits, labels_tensor).item()
results["temp_scenario"].append(temperature_value)
results["ece_values"].append(ece_value)
print(f"Overall ECE for temperature {temperature_value}: {ece_value:.4f}")
# For each loss function, analyze gradient properties
for loss_name, loss_fn in [
("SoftECE", soft_ece),
("ECE", traditional_ece),
("Brier", brier_score),
("CrossEntropy", cross_entropy),
("MSE", mse_loss)
]:
print(f"Analyzing gradients for {loss_name}")
# Calculate gradients for each sample in batches
batch_size = 100
num_batches = (num_samples + batch_size - 1) // batch_size
# Store all gradients and corresponding confidences
all_grads = []
all_confidences = []
all_is_correct = []
for batch_idx in tqdm(range(num_batches)):
start_idx = batch_idx * batch_size
end_idx = min((batch_idx + 1) * batch_size, num_samples)
batch_indices = indices[start_idx:end_idx]
batch_logits = logits_tensor[batch_indices]
batch_labels = labels_tensor[batch_indices]
# Calculate gradients per sample
for i in range(len(batch_logits)):
sample_logits = batch_logits[i:i+1]
sample_label = batch_labels[i:i+1]
# Reset parameter to temperature_value for each sample
temperature = nn.Parameter(torch.ones(1) * temperature_value)
# Apply temperature scaling
scaled_logits = sample_logits / temperature
probs = F.softmax(scaled_logits, dim=1)
# Check if prediction is correct
pred = torch.argmax(probs, dim=1)
is_correct = (pred == sample_label).float().item()
# Calculate confidence
confidence = torch.max(probs).item()
# Calculate loss and gradient
temperature.grad = None
try:
loss = loss_fn(scaled_logits, sample_label)
loss.backward()
# Only store if gradient was successfully calculated
if temperature.grad is not None:
all_grads.append(temperature.grad.item())
all_confidences.append(confidence)
all_is_correct.append(is_correct)
except Exception as e:
# Skip samples that cause errors in gradient calculation
print(f" Skipping sample due to error: {e}")
continue
# Skip further analysis if we don't have enough gradient data
if len(all_grads) < 10:
print(f" Not enough gradient data for {loss_name}, skipping analysis")
continue
# Calculate gradient consistency per confidence bin
# (correlation between gradient direction and correctness)
bin_grad_consistency = []
bin_grad_entropy = []
for i in range(len(confidence_bins) - 1):
bin_start = confidence_bins[i]
bin_end = confidence_bins[i+1]
# Find samples in this bin
bin_indices = []
for j in range(len(all_confidences)):
if bin_start <= all_confidences[j] < bin_end:
bin_indices.append(j)
if len(bin_indices) > 5: # Only consider bins with enough samples
bin_grads = [all_grads[j] for j in bin_indices]
bin_correct = [all_is_correct[j] for j in bin_indices]
# Calculate consistency: avg sign of gradient * (conf - accuracy)
bin_conf = np.mean([all_confidences[j] for j in bin_indices])
bin_acc = np.mean(bin_correct)
calibration_error = bin_conf - bin_acc
# Compute correlation between gradient and calibration error
# A well-behaved gradient should be negative when confidence > accuracy
# and positive when confidence < accuracy
grad_signs = np.sign(bin_grads)
ce_sign = np.sign(calibration_error)
correct_direction = -1 * ce_sign # Gradient should point in opposite direction of error
consistency = np.mean(grad_signs == correct_direction)
bin_grad_consistency.append(consistency)
# Calculate entropy of gradient distribution in this bin
# Normalize gradients for comparison
if len(bin_grads) > 0 and np.std(bin_grads) > 0:
norm_grads = (bin_grads - np.mean(bin_grads)) / np.std(bin_grads)
# Use histogram to estimate entropy
hist, _ = np.histogram(norm_grads, bins=10, density=True)
hist = hist[hist > 0] # Avoid log(0)
entropy = -np.sum(hist * np.log(hist))
bin_grad_entropy.append(entropy)
# Store results
if bin_grad_consistency:
avg_consistency = np.mean(bin_grad_consistency)
results["gradient_consistency"][loss_name].append(avg_consistency)
print(f" {loss_name} gradient consistency: {avg_consistency:.4f}")
if bin_grad_entropy:
avg_entropy = np.mean(bin_grad_entropy)
results["gradient_entropy"][loss_name].append(avg_entropy)
print(f" {loss_name} gradient entropy: {avg_entropy:.4f}")
# Calculate correlation between gradient and calibration error
# For overall dataset
if len(all_grads) > 0:
accuracies = np.array(all_is_correct)
confidences = np.array(all_confidences)
grads = np.array(all_grads)
# Ensure we have valid data
if len(grads) > 0 and not np.all(np.isnan(grads)):
cal_errors = confidences - accuracies
# Correlation should be negative (gradient points opposite to error)
correlation = np.corrcoef(cal_errors, -grads)[0, 1]
if not np.isnan(correlation):
results["gradient_correlation"][loss_name].append(correlation)
print(f" {loss_name} gradient-error correlation: {correlation:.4f}")
# Plot results
# 1. Plot gradient consistency across different calibration scenarios
plt.figure(figsize=(10, 6))
for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]:
if loss_name in results["gradient_consistency"] and len(results["gradient_consistency"][loss_name]) > 0:
plt.plot(results["temp_scenario"], results["gradient_consistency"][loss_name],
marker='o', label=loss_name)
plt.xlabel('Temperature (Lower = More Overconfident)')
plt.ylabel('Gradient Direction Consistency')
plt.title('Gradient Consistency Across Calibration Scenarios')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'gradient_consistency.png'), dpi=300)
plt.close()
# 2. Plot gradient-error correlation
plt.figure(figsize=(10, 6))
for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]:
if loss_name in results["gradient_correlation"] and len(results["gradient_correlation"][loss_name]) > 0:
plt.plot(results["temp_scenario"], results["gradient_correlation"][loss_name],
marker='o', label=loss_name)
plt.xlabel('Temperature (Lower = More Overconfident)')
plt.ylabel('Correlation between Gradient and Calibration Error')
plt.title('Gradient-Error Correlation Across Calibration Scenarios')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'gradient_correlation.png'), dpi=300)
plt.close()
# 3. Plot gradient entropy (information content)
plt.figure(figsize=(10, 6))
for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]:
if loss_name in results["gradient_entropy"] and len(results["gradient_entropy"][loss_name]) > 0:
plt.plot(results["temp_scenario"], results["gradient_entropy"][loss_name],
marker='o', label=loss_name)
plt.xlabel('Temperature (Lower = More Overconfident)')
plt.ylabel('Gradient Distribution Entropy')
plt.title('Gradient Information Content Across Calibration Scenarios')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'gradient_entropy.png'), dpi=300)
plt.close()
# Save results
with open(os.path.join(output_dir, 'gradient_information_results.json'), 'w') as f:
# Ensure all data is serializable
serializable_results = {
"temp_scenario": list(results["temp_scenario"]),
"ece_values": list(results["ece_values"]),
"gradient_consistency": {k: list(v) for k, v in results["gradient_consistency"].items()},
"gradient_correlation": {k: list(v) for k, v in results["gradient_correlation"].items()},
"gradient_entropy": {k: list(v) for k, v in results["gradient_entropy"].items()}
}
json.dump(serializable_results, f, indent=2)
print(f"Gradient information analysis complete. Results saved to {output_dir}")
# Experiment 3: Sample efficiency and overfitting resistance analysis
def experiment_3_sample_efficiency(val_logits, val_labels, test_logits, test_labels, cache_dir, output_dir="results"):
print("\nExperiment 3: Analyzing Sample Efficiency and Overfitting Resistance")
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Convert data to PyTorch tensors
val_logits_tensor = torch.tensor(val_logits, dtype=torch.float32)
val_labels_tensor = torch.tensor(val_labels, dtype=torch.long)
test_logits_tensor = torch.tensor(test_logits, dtype=torch.float32)
test_labels_tensor = torch.tensor(test_labels, dtype=torch.long)
# Define different validation set sizes to test
val_set_sizes = [10, 20, 30, 40,50, 100, 150]
val_set_sizes = [min(size, len(val_logits)) for size in val_set_sizes]
# Define loss functions to compare
loss_functions = [
("SoftECE", lambda: SoftECE(n_bins=15, sigma=0.05)),
("Brier", lambda: CustomBrierLoss()),
("CrossEntropy", lambda: CrossEntropyLoss()),
("MSE", lambda: MSELoss())
]
# Number of training steps to monitor
max_steps = 100
step_interval = 5 # Record metrics every n steps
# Store results
results = {
"val_set_sizes": val_set_sizes,
"training_curves": {size: {} for size in val_set_sizes},
"final_metrics": {size: {} for size in val_set_sizes},
}
# Train on different validation set sizes
for val_size in val_set_sizes:
print(f"\nTraining with validation set size: {val_size}")
# Sample a subset of validation data
indices = np.random.choice(len(val_logits), val_size, replace=False)
subset_logits = val_logits_tensor[indices]
subset_labels = val_labels_tensor[indices]
# For each loss function
for loss_name, loss_fn_creator in loss_functions:
print(f" Training with {loss_name}")
# Initialize results storage for this scenario
if loss_name not in results["training_curves"][val_size]:
results["training_curves"][val_size][loss_name] = {
"steps": [],
"train_loss": [],
"train_ece": [],
"test_ece": [],
"test_acc": []
}
if loss_name not in results["final_metrics"][val_size]:
results["final_metrics"][val_size][loss_name] = {}
# Initialize temperature and optimizer
temperature = nn.Parameter(torch.ones(1))
optimizer = torch.optim.Adam([temperature], lr=0.01)
# Create loss function
loss_fn = loss_fn_creator()
# Training loop with tracking
for step in range(max_steps):
optimizer.zero_grad()
# Apply temperature scaling
scaled_logits = subset_logits / temperature
# Calculate loss
loss = loss_fn(scaled_logits, subset_labels)
# Backpropagation
loss.backward()
optimizer.step()
# Record metrics at specified intervals
if step % step_interval == 0 or step == max_steps - 1:
with torch.no_grad():
# Calculate training metrics
train_ece = ECE(n_bins=15)(scaled_logits, subset_labels).item()
# Calculate test metrics
test_scaled_logits = test_logits_tensor / temperature
test_probs = F.softmax(test_scaled_logits, dim=1)
test_ece = ECE(n_bins=15)(test_scaled_logits, test_labels_tensor).item()
test_acc = (torch.argmax(test_probs, dim=1) == test_labels_tensor).float().mean().item()
# Store metrics
results["training_curves"][val_size][loss_name]["steps"].append(step)
results["training_curves"][val_size][loss_name]["train_loss"].append(loss.item())
results["training_curves"][val_size][loss_name]["train_ece"].append(train_ece)
results["training_curves"][val_size][loss_name]["test_ece"].append(test_ece)
results["training_curves"][val_size][loss_name]["test_acc"].append(test_acc)
# Store final metrics
results["final_metrics"][val_size][loss_name] = {
"temperature": temperature.item(),
"train_ece": train_ece,
"test_ece": test_ece,
"test_acc": test_acc,
"train_test_ece_gap": abs(train_ece - test_ece) # Measure of overfitting
}
print(f" Final temperature: {temperature.item():.4f}, Test ECE: {test_ece:.4f}")
# Plot results
# 1. Plot final test ECE vs validation set size
plt.figure(figsize=(10, 6))
print("\nFinal Test ECE values for plotting:")
for loss_name, _ in loss_functions:
test_eces = [results["final_metrics"][size][loss_name]["test_ece"] for size in val_set_sizes]
print(f" {loss_name}: {test_eces}")
line, = plt.plot(val_set_sizes, test_eces, marker='o', linewidth=2, markersize=8)
plt.annotate(loss_name, (val_set_sizes[-1], test_eces[-1]),
xytext=(5, 0), textcoords='offset points', va='center')
plt.xlabel('Validation Set Size')
plt.ylabel('Test ECE')
plt.title('Sample Efficiency: Test ECE vs. Validation Set Size')
plt.legend([loss_name for loss_name, _ in loss_functions])
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'sample_efficiency_ece.png'), dpi=300)
plt.close()
# 2. Plot train-test ECE gap vs validation set size (measure of overfitting)
plt.figure(figsize=(10, 6))
print("\nTrain-Test ECE Gap values for plotting:")
for loss_name, _ in loss_functions:
gaps = [results["final_metrics"][size][loss_name]["train_test_ece_gap"] for size in val_set_sizes]
print(f" {loss_name}: {gaps}")
line, = plt.plot(val_set_sizes, gaps, marker='o', linewidth=2, markersize=8)
plt.annotate(loss_name, (val_set_sizes[-1], gaps[-1]),
xytext=(5, 0), textcoords='offset points', va='center')
plt.xlabel('Validation Set Size')
plt.ylabel('|Train ECE - Test ECE|')
plt.title('Overfitting Resistance: Train-Test Gap vs. Validation Set Size')
plt.legend([loss_name for loss_name, _ in loss_functions])
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'overfitting_resistance.png'), dpi=300)
plt.close()
# 3. Plot training curves for different loss functions on smallest dataset
smallest_size = val_set_sizes[0]
plt.figure(figsize=(12, 8))
for loss_name, _ in loss_functions:
steps = results["training_curves"][smallest_size][loss_name]["steps"]
test_eces = results["training_curves"][smallest_size][loss_name]["test_ece"]
plt.plot(steps, test_eces, marker='.', label=f"{loss_name}")
plt.xlabel('Training Step')
plt.ylabel('Test ECE')
plt.title(f'Training Stability with Small Dataset (n={smallest_size})')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, f'training_stability_{smallest_size}.png'), dpi=300)
plt.close()
# 4. Plot training curves for SoftECE across different dataset sizes
plt.figure(figsize=(12, 8))
for val_size in val_set_sizes:
steps = results["training_curves"][val_size]["SoftECE"]["steps"]
test_eces = results["training_curves"][val_size]["SoftECE"]["test_ece"]
plt.plot(steps, test_eces, marker='.', label=f"n={val_size}")
plt.xlabel('Training Step')
plt.ylabel('Test ECE')
plt.title('SoftECE Training Curves Across Dataset Sizes')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'softece_across_sizes.png'), dpi=300)
plt.close()
# Save results
with open(os.path.join(output_dir, 'sample_efficiency_results.json'), 'w') as f:
# Ensure all data is serializable
serializable_results = {
"val_set_sizes": results["val_set_sizes"],
"training_curves": {},
"final_metrics": {}
}
# Convert training curves
for size in results["training_curves"]:
serializable_results["training_curves"][str(size)] = {}
for loss_name in results["training_curves"][size]:
serializable_results["training_curves"][str(size)][loss_name] = {
k: [float(v_i) for v_i in v]
for k, v in results["training_curves"][size][loss_name].items()
}
# Convert final metrics
for size in results["final_metrics"]:
serializable_results["final_metrics"][str(size)] = {}
for loss_name in results["final_metrics"][size]:
serializable_results["final_metrics"][str(size)][loss_name] = {
k: float(v) for k, v in results["final_metrics"][size][loss_name].items()
}
json.dump(serializable_results, f, indent=2)
print(f"Sample efficiency analysis complete. Results saved to {output_dir}")
# Experiment 4: Bias-variance tradeoff visualization
def experiment_4_bias_variance_tradeoff(val_logits, val_labels, test_logits, test_labels, cache_dir, output_dir="results"):
print("\nExperiment 4: Visualizing Bias-Variance Tradeoff")
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Convert data to PyTorch tensors
val_logits_tensor = torch.tensor(val_logits, dtype=torch.float32)
val_labels_tensor = torch.tensor(val_labels, dtype=torch.long)
test_logits_tensor = torch.tensor(test_logits, dtype=torch.float32)
test_labels_tensor = torch.tensor(test_labels, dtype=torch.long)
# Define loss functions to compare
loss_functions = [
("SoftECE", lambda: SoftECE(n_bins=15, sigma=0.05)),
("ECE", lambda: ECEWrapper(n_bins=15)),
("Brier", lambda: CustomBrierLoss()),
("CrossEntropy", lambda: CrossEntropyLoss()),
("MSE", lambda: MSELoss())
]
# Bootstrap parameters
n_bootstraps = 20 # Number of bootstrap samples
bootstrap_size = min(500, len(val_logits)) # Size of each bootstrap sample
# Store results
results = {
"bootstrap_metrics": {loss_name: {
"temperatures": [],
"test_eces": [],
"calibrated_confidences": []
} for loss_name, _ in loss_functions},
"aggregated_metrics": {loss_name: {} for loss_name, _ in loss_functions}
}
# Create bootstrap samples
print(f"Creating {n_bootstraps} bootstrap samples of size {bootstrap_size}")
bootstrap_indices = []
for i in range(n_bootstraps):
# Sample with replacement
indices = np.random.choice(len(val_logits), bootstrap_size, replace=True)
bootstrap_indices.append(indices)
# Train on each bootstrap sample
for bootstrap_idx, indices in enumerate(bootstrap_indices):
print(f"\nTraining on bootstrap sample {bootstrap_idx+1}/{n_bootstraps}")
# Get bootstrap sample
bootstrap_logits = val_logits_tensor[indices]
bootstrap_labels = val_labels_tensor[indices]
# Train each loss function on this bootstrap sample
for loss_name, loss_fn_creator in loss_functions:
# Initialize temperature and optimizer
temperature = nn.Parameter(torch.ones(1))
optimizer = torch.optim.Adam([temperature], lr=0.01)
# Create loss function
loss_fn = loss_fn_creator()
# Train for a fixed number of epochs
epochs = 100
for epoch in range(epochs):
optimizer.zero_grad()
# Apply temperature scaling
scaled_logits = bootstrap_logits / temperature
# Calculate loss
loss = loss_fn(scaled_logits, bootstrap_labels)
# Backpropagation
loss.backward()
optimizer.step()
# Evaluate on test set
with torch.no_grad():
# Apply learned temperature
scaled_test_logits = test_logits_tensor / temperature
test_probs = F.softmax(scaled_test_logits, dim=1)
# Calculate metrics
test_ece = ECE(n_bins=15)(scaled_test_logits, test_labels_tensor).item()
# Store max confidences from a random subset for visualization
subset_size = min(1000, len(test_logits))
subset_indices = np.random.choice(len(test_logits), subset_size, replace=False)
subset_confs = torch.max(test_probs[subset_indices], dim=1)[0].cpu().numpy()
# Store results for this bootstrap run
results["bootstrap_metrics"][loss_name]["temperatures"].append(temperature.item())
results["bootstrap_metrics"][loss_name]["test_eces"].append(test_ece)
results["bootstrap_metrics"][loss_name]["calibrated_confidences"].append(subset_confs)
print(f" {loss_name}: Temperature = {temperature.item():.4f}, Test ECE = {test_ece:.4f}")
# Calculate aggregated metrics
for loss_name, _ in loss_functions:
temps = results["bootstrap_metrics"][loss_name]["temperatures"]
eces = results["bootstrap_metrics"][loss_name]["test_eces"]
# Calculate statistics
results["aggregated_metrics"][loss_name] = {
"temperature_mean": np.mean(temps),
"temperature_std": np.std(temps),
"temperature_cv": np.std(temps) / np.mean(temps) if np.mean(temps) > 0 else 0, # Coefficient of variation
"ece_mean": np.mean(eces),
"ece_std": np.std(eces),
"ece_cv": np.std(eces) / np.mean(eces) if np.mean(eces) > 0 else 0
}
# Prepare plots
# 1. Box plots of learned temperatures
plt.figure(figsize=(10, 6))
temp_data = [results["bootstrap_metrics"][loss_name]["temperatures"] for loss_name, _ in loss_functions]
plt.boxplot(temp_data, labels=[loss_name for loss_name, _ in loss_functions])
plt.ylabel('Temperature Value')
plt.title('Distribution of Learned Temperatures Across Bootstrap Samples')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'temperature_distribution.png'), dpi=300)
plt.close()
# 2. Box plots of test ECEs
plt.figure(figsize=(10, 6))
ece_data = [results["bootstrap_metrics"][loss_name]["test_eces"] for loss_name, _ in loss_functions]
plt.boxplot(ece_data, labels=[loss_name for loss_name, _ in loss_functions])
plt.ylabel('Test ECE')
plt.title('Distribution of Test ECE Across Bootstrap Samples')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'ece_distribution.png'), dpi=300)
plt.close()
# 3. Scatter plot of temperature variance vs ECE mean
plt.figure(figsize=(10, 6))
temp_vars = [results["aggregated_metrics"][loss_name]["temperature_cv"] for loss_name, _ in loss_functions]
ece_means = [results["aggregated_metrics"][loss_name]["ece_mean"] for loss_name, _ in loss_functions]
plt.scatter(temp_vars, ece_means, s=100)
# Add labels to points
for i, (loss_name, _) in enumerate(loss_functions):
plt.annotate(loss_name, (temp_vars[i], ece_means[i]),
textcoords="offset points", xytext=(0,10), ha='center')
plt.xlabel('Temperature Coefficient of Variation')
plt.ylabel('Mean Test ECE')
plt.title('Bias-Variance Tradeoff: Parameter Stability vs. Calibration Performance')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'bias_variance_tradeoff.png'), dpi=300)
plt.close()
# 4. Histograms of calibrated confidences for each method
# We'll use the last bootstrap sample for visualization
plt.figure(figsize=(15, 10))
for i, (loss_name, _) in enumerate(loss_functions):
plt.subplot(2, 3, i+1)
confidences = results["bootstrap_metrics"][loss_name]["calibrated_confidences"][-1]
plt.hist(confidences, bins=20, alpha=0.7)
plt.title(f'{loss_name} Calibrated Confidences')
plt.xlabel('Confidence')
plt.ylabel('Count')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'calibrated_confidence_distribution.png'), dpi=300)
plt.close()
# 5. Violin plots of ECE distribution
plt.figure(figsize=(12, 6))
# Create violin plot
plt.violinplot(ece_data, showmeans=True, showmedians=True)
# Add labels
plt.xticks(range(1, len(loss_functions) + 1), [loss_name for loss_name, _ in loss_functions])
plt.ylabel('Test ECE')
plt.title('Density Distribution of Test ECE Across Bootstrap Samples')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'ece_density_distribution.png'), dpi=300)
plt.close()
# Save results
with open(os.path.join(output_dir, 'bias_variance_results.json'), 'w') as f:
# Ensure all data is serializable
serializable_results = {
"bootstrap_metrics": {},
"aggregated_metrics": {}
}
# Convert bootstrap metrics
for loss_name in results["bootstrap_metrics"]:
serializable_results["bootstrap_metrics"][loss_name] = {
"temperatures": [float(t) for t in results["bootstrap_metrics"][loss_name]["temperatures"]],
"test_eces": [float(e) for e in results["bootstrap_metrics"][loss_name]["test_eces"]],
# Don't save all confidences as it's too much data
"temperature_mean": float(np.mean(results["bootstrap_metrics"][loss_name]["temperatures"])),
"temperature_std": float(np.std(results["bootstrap_metrics"][loss_name]["temperatures"])),
"ece_mean": float(np.mean(results["bootstrap_metrics"][loss_name]["test_eces"])),
"ece_std": float(np.std(results["bootstrap_metrics"][loss_name]["test_eces"]))
}
# Convert aggregated metrics
for loss_name in results["aggregated_metrics"]:
serializable_results["aggregated_metrics"][loss_name] = {
k: float(v) for k, v in results["aggregated_metrics"][loss_name].items()
}
json.dump(serializable_results, f, indent=2)
print(f"Bias-variance tradeoff analysis complete. Results saved to {output_dir}")
def main():
# Set random seed
set_seed(42)
# Define cache directory containing logits and labels
cache_dir = "/hdd/haolan/shats/PureLogits/cache/imagenet_vit_b_16_seed1_vs0.2"
# cache_dir = "/hdd/haolan/shats/PureLogits/cache/cifar100_resnet50_cross_entropy_seed1"
# cache_dir = "/hdd/haolan/shats/PureLogits/cache/imagenet_resnet50_seed1_vs0.2"
# cache_dir = "/hdd/haolan/shats/PureLogits/cache/cifar10_resnet50_cross_entropy_seed1"
# Load data
val_logits, val_labels, test_logits, test_labels = load_data(cache_dir)
# Create output directory
output_dir = "experiment_results/softece_validation"
os.makedirs(output_dir, exist_ok=True)
# Run experiments
# experiment_1_gradient_stability(test_logits, test_labels, cache_dir, output_dir)
# experiment_2_gradient_information(test_logits, test_labels, cache_dir, output_dir)
experiment_3_sample_efficiency(val_logits, val_labels, test_logits, test_labels, cache_dir, output_dir)
# experiment_4_bias_variance_tradeoff(val_logits, val_labels, test_logits, test_labels, cache_dir, output_dir)
if __name__ == "__main__":
start_time = time.time()
main()
elapsed_time = time.time() - start_time
print(f"Experiments completed in {elapsed_time/60:.2f} minutes") |