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as optim
|
| 4 |
+
import torchvision
|
| 5 |
+
import torchvision.transforms as transforms
|
| 6 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 7 |
+
from sklearn.metrics import f1_score, precision_score, recall_score
|
| 8 |
+
from codecarbon import EmissionsTracker
|
| 9 |
+
from thop import profile
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
import time, pandas as pd, numpy as np, os, warnings, copy, gc
|
| 12 |
+
|
| 13 |
+
# --- Configuration ---
|
| 14 |
+
MODEL_NAME = "vgg16_EDEN"
|
| 15 |
+
DATASET_NAME = "CIFAR10"
|
| 16 |
+
DATA_PATH = r'C:\Users\shanm\Dataset Download\CIFAR10'
|
| 17 |
+
BATCH_SIZE = 64
|
| 18 |
+
ACCUMULATION_STEPS = 8 # Effective Batch Size = 512
|
| 19 |
+
EPOCHS = 50
|
| 20 |
+
E_UNFREEZE = 10
|
| 21 |
+
LAMBDA_L1 = 1e-5
|
| 22 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 23 |
+
|
| 24 |
+
SAVE_DIR = "saved_models"
|
| 25 |
+
os.makedirs(SAVE_DIR, exist_ok=True)
|
| 26 |
+
CSV_FILENAME = f"{MODEL_NAME}_{DATASET_NAME}_stats.csv"
|
| 27 |
+
|
| 28 |
+
warnings.filterwarnings("ignore")
|
| 29 |
+
os.environ["CODECARBON_LOG_LEVEL"] = "error"
|
| 30 |
+
|
| 31 |
+
def main():
|
| 32 |
+
# --- Phase 1: Zero-Overhead RAM Caching ---
|
| 33 |
+
transform = transforms.Compose([
|
| 34 |
+
transforms.Resize(224), # VGG16 pre-trained expects 224x224
|
| 35 |
+
transforms.ToTensor(),
|
| 36 |
+
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
|
| 37 |
+
])
|
| 38 |
+
|
| 39 |
+
print(f"[*] Caching {DATASET_NAME} to System RAM for zero-I/O overhead...")
|
| 40 |
+
full_dataset = torchvision.datasets.CIFAR10(root=DATA_PATH, train=True, download=False, transform=transform)
|
| 41 |
+
|
| 42 |
+
all_data, all_targets = [], []
|
| 43 |
+
for i, (img, target) in enumerate(full_dataset):
|
| 44 |
+
all_data.append(img)
|
| 45 |
+
all_targets.append(target)
|
| 46 |
+
if i % 10000 == 0: print(f" Loaded {i}/50000 images...")
|
| 47 |
+
|
| 48 |
+
cached_trainset = TensorDataset(torch.stack(all_data), torch.tensor(all_targets))
|
| 49 |
+
trainloader = DataLoader(cached_trainset, batch_size=BATCH_SIZE, shuffle=True, pin_memory=True)
|
| 50 |
+
|
| 51 |
+
# --- Model Setup (EDEN Phase 1) ---
|
| 52 |
+
model = torchvision.models.vgg16(weights='IMAGENET1K_V1')
|
| 53 |
+
# Update for 10 classes
|
| 54 |
+
model.classifier[6] = nn.Linear(4096, 10)
|
| 55 |
+
|
| 56 |
+
# 1. Profile on clone
|
| 57 |
+
print("[*] Calculating hardware metrics...")
|
| 58 |
+
model_for_profile = copy.deepcopy(model).to(DEVICE)
|
| 59 |
+
dummy_input = torch.randn(1, 3, 224, 224).to(DEVICE)
|
| 60 |
+
flops, params = profile(model_for_profile, inputs=(dummy_input, ), verbose=False)
|
| 61 |
+
del model_for_profile
|
| 62 |
+
|
| 63 |
+
# 2. Initially freeze backbone
|
| 64 |
+
for param in model.features.parameters():
|
| 65 |
+
param.requires_grad = False
|
| 66 |
+
|
| 67 |
+
model.to(DEVICE)
|
| 68 |
+
|
| 69 |
+
criterion = nn.CrossEntropyLoss()
|
| 70 |
+
optimizer = optim.AdamW(model.parameters(), lr=1e-3)
|
| 71 |
+
scaler = torch.cuda.amp.GradScaler()
|
| 72 |
+
tracker = EmissionsTracker(measure_power_secs=1, save_to_file=False, log_level='error')
|
| 73 |
+
|
| 74 |
+
results = []
|
| 75 |
+
cumulative_total_energy = 0
|
| 76 |
+
best_acc = 0.0
|
| 77 |
+
|
| 78 |
+
print(f"\n[MODEL INFO] FLOPs: {flops/1e9:.2f} G | Parameters: {params/1e6:.2f} M")
|
| 79 |
+
print(f"{'='*140}")
|
| 80 |
+
print(f"{'Epoch':<6} | {'Loss':<7} | {'Acc':<7} | {'Total(J)':<9} | {'VRAM(GB)':<9} | {'EAG':<8} | {'Status'}")
|
| 81 |
+
print(f"{'-'*140}")
|
| 82 |
+
|
| 83 |
+
for epoch in range(1, EPOCHS + 1):
|
| 84 |
+
if epoch == E_UNFREEZE:
|
| 85 |
+
for param in model.parameters(): param.requires_grad = True
|
| 86 |
+
for pg in optimizer.param_groups: pg['lr'] = 1e-5
|
| 87 |
+
status_msg = "UNFROZEN"
|
| 88 |
+
else:
|
| 89 |
+
status_msg = "FROZEN" if epoch < E_UNFREEZE else "FINE-TUNING"
|
| 90 |
+
|
| 91 |
+
model.train()
|
| 92 |
+
tracker.start()
|
| 93 |
+
epoch_start = time.time()
|
| 94 |
+
running_loss, all_preds, all_labels = 0.0, [], []
|
| 95 |
+
|
| 96 |
+
pbar = tqdm(enumerate(trainloader), total=len(trainloader), desc=f"Epoch {epoch:02d}", leave=False)
|
| 97 |
+
|
| 98 |
+
optimizer.zero_grad()
|
| 99 |
+
for i, (inputs, labels) in pbar:
|
| 100 |
+
inputs, labels = inputs.to(DEVICE), labels.to(DEVICE)
|
| 101 |
+
with torch.cuda.amp.autocast():
|
| 102 |
+
outputs = model(inputs)
|
| 103 |
+
cls_loss = criterion(outputs, labels)
|
| 104 |
+
l1_penalty = sum(p.abs().sum() for p in model.parameters() if p.requires_grad)
|
| 105 |
+
loss = (cls_loss + LAMBDA_L1 * l1_penalty) / ACCUMULATION_STEPS
|
| 106 |
+
|
| 107 |
+
scaler.scale(loss).backward()
|
| 108 |
+
if (i + 1) % ACCUMULATION_STEPS == 0:
|
| 109 |
+
scaler.unscale_(optimizer)
|
| 110 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 111 |
+
scaler.step(optimizer); scaler.update(); optimizer.zero_grad()
|
| 112 |
+
|
| 113 |
+
running_loss += cls_loss.item()
|
| 114 |
+
_, predicted = torch.max(outputs.data, 1)
|
| 115 |
+
all_preds.extend(predicted.cpu().numpy()); all_labels.extend(labels.cpu().numpy())
|
| 116 |
+
pbar.set_postfix({'loss': f"{cls_loss.item():.4f}"})
|
| 117 |
+
|
| 118 |
+
emissions_kg = tracker.stop()
|
| 119 |
+
duration = time.time() - epoch_start
|
| 120 |
+
e_tot = (tracker.final_emissions_data.gpu_energy + tracker.final_emissions_data.cpu_energy + tracker.final_emissions_data.ram_energy) * 3600000
|
| 121 |
+
cumulative_total_energy += e_tot
|
| 122 |
+
acc = (np.array(all_preds) == np.array(all_labels)).mean()
|
| 123 |
+
vram_peak = torch.cuda.max_memory_allocated(DEVICE) / (1024**3)
|
| 124 |
+
eag = acc / (e_tot / 1000) if e_tot > 0 else 0
|
| 125 |
+
|
| 126 |
+
stats = {
|
| 127 |
+
"epoch": epoch, "status": status_msg, "loss": running_loss / len(trainloader),
|
| 128 |
+
"accuracy": acc, "total_energy_j": e_tot, "cumulative_energy_j": cumulative_total_energy,
|
| 129 |
+
"vram_gb": vram_peak, "eag_metric": eag, "carbon_kg": emissions_kg,
|
| 130 |
+
"model_flops": flops, "model_params": params
|
| 131 |
+
}
|
| 132 |
+
results.append(stats)
|
| 133 |
+
pd.DataFrame(results).to_csv(CSV_FILENAME, index=False)
|
| 134 |
+
|
| 135 |
+
best_tag = "*" if acc > best_acc else ""
|
| 136 |
+
if acc > best_acc: best_acc = acc; torch.save(model.state_dict(), os.path.join(SAVE_DIR, f"BEST_{MODEL_NAME}_{DATASET_NAME}.pth"))
|
| 137 |
+
print(f"{epoch:02d}/50 | {stats['loss']:.4f} | {acc:.2%} | {e_tot:<9.2f} | {vram_peak:<9.3f} | {eag:<8.4f} | {status_msg}{best_tag}")
|
| 138 |
+
|
| 139 |
+
# Memory Flush
|
| 140 |
+
del model, trainloader, cached_trainset
|
| 141 |
+
torch.cuda.empty_cache(); gc.collect()
|
| 142 |
+
|
| 143 |
+
if __name__ == '__main__':
|
| 144 |
+
main()
|