Spaces:
Sleeping
Sleeping
File size: 2,450 Bytes
ceee644 |
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 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
# Import the DCLR optimizer from the local file
from dclr_optimizer import DCLR
# === Simple CNN Model Definition ===
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(64 * 8 * 8, 512)
self.fc2 = nn.Linear(512, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 64 * 8 * 8)
x = F.relu(self.fc1(x))
return self.fc2(x)
# === CIFAR-10 Data Loading ===
transform = transforms.Compose([transforms.ToTensor()])
train_set = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
train_loader = DataLoader(train_set, batch_size=128, shuffle=True)
# === Training Configuration ===
model = SimpleCNN()
# Instantiate DCLR with best-tuned hyperparameters
best_lr = 0.1
best_lambda = 0.1
optimizer = DCLR(model.parameters(), lr=best_lr, lambda_=best_lambda, verbose=False)
criterion = nn.CrossEntropyLoss()
extended_epochs = 20
print(f"Starting training for SimpleCNN with DCLR (lr={best_lr}, lambda_={best_lambda}) for {extended_epochs} epochs...")
# === Training Loop ===
for epoch in range(extended_epochs):
model.train()
running_loss = 0.0
correct = 0
total = 0
for batch_idx, (inputs, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
# DCLR requires output_activations for its step method
optimizer.step(output_activations=outputs)
running_loss += loss.item()
_, predicted = outputs.max(1)
total += labels.size(0)
correct += predicted.eq(labels).sum().item()
epoch_loss = running_loss / len(train_loader)
epoch_acc = 100.0 * correct / total
print(f"Epoch {epoch+1}/{extended_epochs} - Loss: {epoch_loss:.4f}, Accuracy: {epoch_acc:.2f}%")
print("Training complete.")
# === Save the Trained Model ===
torch.save(model.state_dict(), 'simple_cnn_dclr_tuned.pth')
print("Model saved to simple_cnn_dclr_tuned.pth") |