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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.optim as optim
|
| 4 |
+
from torch.utils.data import Dataset, DataLoader
|
| 5 |
+
import torchvision.transforms as transforms
|
| 6 |
+
import torchvision.models as models
|
| 7 |
+
from torchvision.models import EfficientNet_V2_S_Weights
|
| 8 |
+
from codecarbon import EmissionsTracker
|
| 9 |
+
from carbontracker.tracker import CarbonTracker
|
| 10 |
+
from fvcore.nn import FlopCountAnalysis
|
| 11 |
+
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
import pandas as pd
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pickle
|
| 16 |
+
import os
|
| 17 |
+
import time
|
| 18 |
+
import logging
|
| 19 |
+
import warnings
|
| 20 |
+
import gc
|
| 21 |
+
|
| 22 |
+
# --- Environment Optimization ---
|
| 23 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
| 24 |
+
logging.getLogger("codecarbon").setLevel(logging.ERROR)
|
| 25 |
+
|
| 26 |
+
# --- Configurations ---
|
| 27 |
+
DATA_DIR = r"C:\Users\shanm\Dataset Download\cifar-10-batches-py"
|
| 28 |
+
LOG_FILE = "eden_unfrozen_cifar10_efficientNet.csv"
|
| 29 |
+
MODEL_SAVE_PATH = "eden_unfrozen_efficientnet_v2_cifar10.pth"
|
| 30 |
+
|
| 31 |
+
BATCH_SIZE = 32
|
| 32 |
+
ACCUMULATION_STEPS = 4
|
| 33 |
+
LEARNING_RATE = 1e-3
|
| 34 |
+
NUM_EPOCHS = 20
|
| 35 |
+
UNFREEZE_EPOCH = 5 # Epoch to unlock the full network
|
| 36 |
+
L1_LAMBDA = 1e-5
|
| 37 |
+
|
| 38 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 39 |
+
|
| 40 |
+
# --- Dataset Loader (RAM Cached for 64GB System) ---
|
| 41 |
+
class CIFAR10Binary(Dataset):
|
| 42 |
+
def __init__(self, root, train=True, transform=None):
|
| 43 |
+
self.data = []
|
| 44 |
+
self.labels = []
|
| 45 |
+
self.transform = transform
|
| 46 |
+
|
| 47 |
+
if train:
|
| 48 |
+
for i in range(1, 6):
|
| 49 |
+
file_path = os.path.join(root, f'data_batch_{i}')
|
| 50 |
+
with open(file_path, 'rb') as f:
|
| 51 |
+
entry = pickle.load(f, encoding='latin1')
|
| 52 |
+
self.data.append(entry['data'])
|
| 53 |
+
self.labels.extend(entry['labels'])
|
| 54 |
+
self.data = np.vstack(self.data).reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
|
| 55 |
+
else:
|
| 56 |
+
file_path = os.path.join(root, 'test_batch')
|
| 57 |
+
with open(file_path, 'rb') as f:
|
| 58 |
+
entry = pickle.load(f, encoding='latin1')
|
| 59 |
+
self.data = entry['data'].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
|
| 60 |
+
self.labels = entry['labels']
|
| 61 |
+
|
| 62 |
+
def __len__(self): return len(self.data)
|
| 63 |
+
|
| 64 |
+
def __getitem__(self, idx):
|
| 65 |
+
img, target = self.data[idx], self.labels[idx]
|
| 66 |
+
if self.transform:
|
| 67 |
+
img = self.transform(img)
|
| 68 |
+
return img, target
|
| 69 |
+
|
| 70 |
+
# --- Main Profiling Engine ---
|
| 71 |
+
def run_experiment():
|
| 72 |
+
torch.cuda.empty_cache()
|
| 73 |
+
gc.collect()
|
| 74 |
+
|
| 75 |
+
# 1. Transfer Learning Initialization (Stage 1: Frozen)
|
| 76 |
+
weights = EfficientNet_V2_S_Weights.DEFAULT
|
| 77 |
+
model = models.efficientnet_v2_s(weights=weights)
|
| 78 |
+
|
| 79 |
+
for param in model.features.parameters():
|
| 80 |
+
param.requires_grad = False # Freeze features initially
|
| 81 |
+
|
| 82 |
+
model.classifier[1] = nn.Linear(model.classifier[1].in_features, 10) # 10 Classes for CIFAR-10
|
| 83 |
+
model = model.to(DEVICE)
|
| 84 |
+
|
| 85 |
+
dummy_input = torch.randn(1, 3, 224, 224).to(DEVICE)
|
| 86 |
+
with warnings.catch_warnings():
|
| 87 |
+
warnings.simplefilter("ignore")
|
| 88 |
+
total_flops = FlopCountAnalysis(model, dummy_input).total()
|
| 89 |
+
total_params = sum(p.numel() for p in model.parameters())
|
| 90 |
+
|
| 91 |
+
transform = transforms.Compose([
|
| 92 |
+
transforms.ToPILImage(),
|
| 93 |
+
transforms.Resize(224),
|
| 94 |
+
transforms.ToTensor(),
|
| 95 |
+
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
|
| 96 |
+
])
|
| 97 |
+
|
| 98 |
+
train_set = CIFAR10Binary(DATA_DIR, train=True, transform=transform)
|
| 99 |
+
loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4, pin_memory=True)
|
| 100 |
+
|
| 101 |
+
# Initially only optimize the classifier
|
| 102 |
+
optimizer = optim.Adam(model.classifier.parameters(), lr=LEARNING_RATE)
|
| 103 |
+
criterion = nn.CrossEntropyLoss()
|
| 104 |
+
scaler = torch.cuda.amp.GradScaler()
|
| 105 |
+
|
| 106 |
+
cc_tracker = EmissionsTracker(measure_power_secs=1, save_to_file=False)
|
| 107 |
+
ct_tracker = CarbonTracker(epochs=NUM_EPOCHS, monitor_epochs=NUM_EPOCHS, update_interval=1)
|
| 108 |
+
|
| 109 |
+
cc_tracker.start()
|
| 110 |
+
all_logs = []
|
| 111 |
+
total_iterations_counter = 0
|
| 112 |
+
session_start_time = time.time()
|
| 113 |
+
|
| 114 |
+
prev_cum_gpu_j, prev_cum_cpu_j, prev_cum_ram_j = 0.0, 0.0, 0.0
|
| 115 |
+
prev_acc = 0.0
|
| 116 |
+
|
| 117 |
+
print(f"\nEDEN PROFILING STARTED | DEVICE: {torch.cuda.get_device_name(0)}")
|
| 118 |
+
print(f"Dataset: CIFAR-10 | Params: {total_params:,} | FLOPs: {total_flops:.2e}\n")
|
| 119 |
+
|
| 120 |
+
for epoch in range(NUM_EPOCHS):
|
| 121 |
+
# --- Stage 2: Progressive Unfreezing ---
|
| 122 |
+
if epoch + 1 == UNFREEZE_EPOCH:
|
| 123 |
+
print("\n[STAGE 2 INITIATED] Unfreezing Backbone for Fine-Tuning...")
|
| 124 |
+
for param in model.parameters():
|
| 125 |
+
param.requires_grad = True
|
| 126 |
+
# Re-initialize optimizer with a lower learning rate for the whole model
|
| 127 |
+
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE * 0.1)
|
| 128 |
+
|
| 129 |
+
ct_tracker.epoch_start()
|
| 130 |
+
torch.cuda.reset_peak_memory_stats()
|
| 131 |
+
epoch_start_time = time.time()
|
| 132 |
+
model.train()
|
| 133 |
+
|
| 134 |
+
running_loss = 0.0
|
| 135 |
+
all_preds, all_labels = [], []
|
| 136 |
+
epoch_grad_norms = []
|
| 137 |
+
|
| 138 |
+
optimizer.zero_grad()
|
| 139 |
+
pbar = tqdm(loader, desc=f"Epoch {epoch+1}/{NUM_EPOCHS}", unit="batch", leave=False)
|
| 140 |
+
|
| 141 |
+
for i, (images, labels) in enumerate(pbar):
|
| 142 |
+
images, labels = images.to(DEVICE), labels.to(DEVICE)
|
| 143 |
+
|
| 144 |
+
with torch.cuda.amp.autocast():
|
| 145 |
+
outputs = model(images)
|
| 146 |
+
loss = criterion(outputs, labels)
|
| 147 |
+
|
| 148 |
+
# Active Sparse Training (L1 Penalty) applied to currently trainable parameters
|
| 149 |
+
trainable_params = [p for p in model.parameters() if p.requires_grad]
|
| 150 |
+
l1_penalty = sum(p.abs().sum() for p in trainable_params)
|
| 151 |
+
|
| 152 |
+
# Calculate total loss for backprop, but DO NOT log it
|
| 153 |
+
total_loss = loss + (L1_LAMBDA * l1_penalty)
|
| 154 |
+
scaled_loss = total_loss / ACCUMULATION_STEPS
|
| 155 |
+
|
| 156 |
+
scaler.scale(scaled_loss).backward()
|
| 157 |
+
|
| 158 |
+
grad_norm = 0.0
|
| 159 |
+
for p in model.parameters():
|
| 160 |
+
if p.requires_grad and p.grad is not None:
|
| 161 |
+
grad_norm += p.grad.data.norm(2).item() ** 2
|
| 162 |
+
epoch_grad_norms.append(grad_norm ** 0.5)
|
| 163 |
+
|
| 164 |
+
if (i + 1) % ACCUMULATION_STEPS == 0:
|
| 165 |
+
scaler.step(optimizer)
|
| 166 |
+
scaler.update()
|
| 167 |
+
optimizer.zero_grad()
|
| 168 |
+
|
| 169 |
+
# Track ONLY the clean classification loss for the CSV
|
| 170 |
+
running_loss += loss.item() * ACCUMULATION_STEPS
|
| 171 |
+
|
| 172 |
+
_, preds = torch.max(outputs, 1)
|
| 173 |
+
all_preds.extend(preds.cpu().numpy())
|
| 174 |
+
all_labels.extend(labels.cpu().numpy())
|
| 175 |
+
total_iterations_counter += 1
|
| 176 |
+
|
| 177 |
+
pbar.set_postfix(loss=f"{(loss.item()*ACCUMULATION_STEPS):.4f}")
|
| 178 |
+
|
| 179 |
+
# --- A. Evaluation ---
|
| 180 |
+
ct_tracker.epoch_end()
|
| 181 |
+
epoch_end_time = time.time()
|
| 182 |
+
epoch_duration = epoch_end_time - epoch_start_time
|
| 183 |
+
avg_it_per_sec = len(loader) / epoch_duration
|
| 184 |
+
|
| 185 |
+
acc = accuracy_score(all_labels, all_preds)
|
| 186 |
+
p, r, f1, _ = precision_recall_fscore_support(all_labels, all_preds, average='macro', zero_division=0)
|
| 187 |
+
|
| 188 |
+
# Rigorous Inference Latency (With Warm-up)
|
| 189 |
+
model.eval()
|
| 190 |
+
with torch.no_grad():
|
| 191 |
+
sample_img = torch.randn(1, 3, 224, 224).to(DEVICE)
|
| 192 |
+
_ = model(sample_img)
|
| 193 |
+
torch.cuda.synchronize()
|
| 194 |
+
|
| 195 |
+
starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 196 |
+
starter.record()
|
| 197 |
+
_ = model(sample_img)
|
| 198 |
+
ender.record()
|
| 199 |
+
torch.cuda.synchronize()
|
| 200 |
+
lat_ms = starter.elapsed_time(ender)
|
| 201 |
+
|
| 202 |
+
# --- B. Energy & Power Calculations ---
|
| 203 |
+
emissions_data = cc_tracker._prepare_emissions_data()
|
| 204 |
+
|
| 205 |
+
cum_gpu_j = emissions_data.gpu_energy * 3.6e6
|
| 206 |
+
cum_cpu_j = emissions_data.cpu_energy * 3.6e6
|
| 207 |
+
cum_ram_j = emissions_data.ram_energy * 3.6e6
|
| 208 |
+
cum_total_j = cum_gpu_j + cum_cpu_j + cum_ram_j
|
| 209 |
+
|
| 210 |
+
epoch_gpu_j = cum_gpu_j - prev_cum_gpu_j
|
| 211 |
+
epoch_cpu_j = cum_cpu_j - prev_cum_cpu_j
|
| 212 |
+
epoch_ram_j = cum_ram_j - prev_cum_ram_j
|
| 213 |
+
epoch_total_j = epoch_gpu_j + epoch_cpu_j + epoch_ram_j
|
| 214 |
+
|
| 215 |
+
prev_cum_gpu_j, prev_cum_cpu_j, prev_cum_ram_j = cum_gpu_j, cum_cpu_j, cum_ram_j
|
| 216 |
+
|
| 217 |
+
avg_gpu_w = epoch_gpu_j / epoch_duration if epoch_duration > 0 else 0
|
| 218 |
+
avg_cpu_w = epoch_cpu_j / epoch_duration if epoch_duration > 0 else 0
|
| 219 |
+
avg_ram_w = epoch_ram_j / epoch_duration if epoch_duration > 0 else 0
|
| 220 |
+
|
| 221 |
+
vram_peak = torch.cuda.max_memory_allocated(DEVICE) / (1024**3)
|
| 222 |
+
|
| 223 |
+
acc_gain = acc - prev_acc
|
| 224 |
+
eag = acc_gain / epoch_total_j if epoch_total_j > 0 else 0
|
| 225 |
+
prev_acc = acc
|
| 226 |
+
|
| 227 |
+
# --- C. Terminal Update ---
|
| 228 |
+
print(f"Epoch {epoch+1} Summary:")
|
| 229 |
+
print(f" > Acc: {acc:.4f} | F1: {f1:.4f} | Loss: {running_loss/len(loader):.4f}")
|
| 230 |
+
print(f" > Epoch Energy: {epoch_total_j:.1f}J | EAG: {eag:.8f}")
|
| 231 |
+
print(f" > Avg Power: GPU {avg_gpu_w:.1f}W | VRAM: {vram_peak:.2f}GB | Latency: {lat_ms:.2f}ms")
|
| 232 |
+
print("-" * 65)
|
| 233 |
+
|
| 234 |
+
# --- D. Unified Verified CSV Logging ---
|
| 235 |
+
log_entry = {
|
| 236 |
+
"epoch": epoch + 1,
|
| 237 |
+
"loss": running_loss / len(loader),
|
| 238 |
+
"accuracy": acc, "f1_score": f1, "precision": p, "recall": r,
|
| 239 |
+
"epoch_energy_gpu_j": epoch_gpu_j, "epoch_energy_cpu_j": epoch_cpu_j,
|
| 240 |
+
"epoch_energy_ram_j": epoch_ram_j, "epoch_total_energy_j": epoch_total_j,
|
| 241 |
+
"cumulative_total_energy_j": cum_total_j, "carbon_emissions_kg": emissions_data.emissions,
|
| 242 |
+
"avg_power_gpu_w": avg_gpu_w, "avg_power_cpu_w": avg_cpu_w, "avg_power_ram_w": avg_ram_w,
|
| 243 |
+
"vram_peak_gb": vram_peak, "latency_ms": lat_ms, "avg_grad_norm": np.mean(epoch_grad_norms),
|
| 244 |
+
"eag_metric": eag, "it_per_sec": avg_it_per_sec, "total_iterations": total_iterations_counter,
|
| 245 |
+
"epoch_duration_sec": epoch_duration, "cumulative_time_sec": time.time() - session_start_time
|
| 246 |
+
}
|
| 247 |
+
all_logs.append(log_entry)
|
| 248 |
+
pd.DataFrame(all_logs).to_csv(LOG_FILE, index=False)
|
| 249 |
+
|
| 250 |
+
cc_tracker.stop()
|
| 251 |
+
|
| 252 |
+
# --- E. Save Optimized Model ---
|
| 253 |
+
torch.save(model.state_dict(), MODEL_SAVE_PATH)
|
| 254 |
+
print(f"\n[FINISH] Verified Optimization Complete.")
|
| 255 |
+
|
| 256 |
+
if __name__ == "__main__":
|
| 257 |
+
run_experiment()
|