Spaces:
Running
Running
Will Phoenix commited on
Commit ·
ef2e99f
1
Parent(s): 3a8c01c
Add training script: scripts/train_resnet18.py
Browse files- scripts/train_resnet18.py +90 -0
scripts/train_resnet18.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch import nn, optim
|
| 3 |
+
from torch.utils.data import DataLoader
|
| 4 |
+
from torchvision import datasets, transforms
|
| 5 |
+
from torchvision.models import resnet18
|
| 6 |
+
import argparse
|
| 7 |
+
import random
|
| 8 |
+
|
| 9 |
+
def get_device(device_index=0):
|
| 10 |
+
if torch.cuda.is_available():
|
| 11 |
+
return torch.device(f"cuda:{device_index}")
|
| 12 |
+
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
| 13 |
+
return torch.device("mps")
|
| 14 |
+
else:
|
| 15 |
+
return torch.device("cpu")
|
| 16 |
+
|
| 17 |
+
def set_seed(seed):
|
| 18 |
+
torch.manual_seed(seed)
|
| 19 |
+
torch.cuda.manual_seed_all(seed)
|
| 20 |
+
|
| 21 |
+
@torch.no_grad()
|
| 22 |
+
def evaluate(model, test_loader, device, criterion):
|
| 23 |
+
model.eval()
|
| 24 |
+
correct = total = 0
|
| 25 |
+
loss_sum = 0.0
|
| 26 |
+
for x, y in test_loader:
|
| 27 |
+
x, y = x.to(device), y.to(device)
|
| 28 |
+
out = model(x)
|
| 29 |
+
loss_sum += criterion(out, y).item() * y.size(0)
|
| 30 |
+
pred = out.argmax(1)
|
| 31 |
+
correct += (pred == y).sum().item()
|
| 32 |
+
total += y.size(0)
|
| 33 |
+
return loss_sum / total, correct / total
|
| 34 |
+
|
| 35 |
+
def main(args):
|
| 36 |
+
|
| 37 |
+
device = get_device(args.device)
|
| 38 |
+
|
| 39 |
+
set_seed(args.seed)
|
| 40 |
+
g = torch.Generator()
|
| 41 |
+
g.manual_seed(args.seed)
|
| 42 |
+
|
| 43 |
+
train_ds = datasets.CIFAR10("./data", train=True, download=True, transform=transforms.ToTensor())
|
| 44 |
+
test_ds = datasets.CIFAR10("./data", train=False, download=True, transform=transforms.ToTensor())
|
| 45 |
+
|
| 46 |
+
use_pin = (device.type == "cuda")
|
| 47 |
+
train_loader = DataLoader(train_ds, batch_size=args.train_batch_size, shuffle=True, num_workers=2, pin_memory=use_pin, generator=g)
|
| 48 |
+
test_loader = DataLoader(test_ds, batch_size=args.eval_batch_size, shuffle=False, num_workers=2, pin_memory=use_pin)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
model = resnet18(weights=None, num_classes=10).to(device)
|
| 52 |
+
criterion = nn.CrossEntropyLoss()
|
| 53 |
+
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=0.9)
|
| 54 |
+
|
| 55 |
+
epochs = args.epochs
|
| 56 |
+
|
| 57 |
+
print("Training with the following parameters:\n",
|
| 58 |
+
f"Epochs = {args.epochs}\n",
|
| 59 |
+
f"Train Batch Size = {args.train_batch_size}\n",
|
| 60 |
+
f"Evaluation Batch Size = {args.eval_batch_size}\n",
|
| 61 |
+
f"Learning Rate = {args.lr}\n",
|
| 62 |
+
f"Seed = {args.seed}\n",
|
| 63 |
+
f"Output Path = {args.output_path}\n",
|
| 64 |
+
f"Device = {args.device}\n")
|
| 65 |
+
|
| 66 |
+
for epoch in range(epochs):
|
| 67 |
+
model.train()
|
| 68 |
+
for x, y in train_loader:
|
| 69 |
+
x, y = x.to(device), y.to(device)
|
| 70 |
+
optimizer.zero_grad(set_to_none=True)
|
| 71 |
+
loss = criterion(model(x), y)
|
| 72 |
+
loss.backward()
|
| 73 |
+
optimizer.step()
|
| 74 |
+
val_loss, val_acc = evaluate(model, test_loader, device, criterion)
|
| 75 |
+
print(f"Epoch {epoch+1}/{epochs} - val_loss: {val_loss:.4f} val_acc: {val_acc:.3f}")
|
| 76 |
+
|
| 77 |
+
torch.save(model.state_dict(), args.output_path)
|
| 78 |
+
print(f"Saved to {args.output_path}")
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
parser = argparse.ArgumentParser()
|
| 82 |
+
parser.add_argument("--epochs", help="# of epochs to iterate through", type=int, default=60)
|
| 83 |
+
parser.add_argument("--train_batch_size", help="batch size during training (higher memory usage)", type=int, default=128)
|
| 84 |
+
parser.add_argument("--eval_batch_size", help="batch size during evaluation (lower memory usage)", type=int, default=256)
|
| 85 |
+
parser.add_argument("--lr", help="learning rate for optimizer", default=0.1, type=float)
|
| 86 |
+
parser.add_argument("--seed", help="global RNG seed for pytorch", default=1, type=int)
|
| 87 |
+
parser.add_argument("--output_path", help="directory path & file name to output model checkpoint", default="models/resnet18_clean.pth", type=str)
|
| 88 |
+
parser.add_argument("--device", help="cuda device #, default is 0", default=0, type=int)
|
| 89 |
+
args = parser.parse_args()
|
| 90 |
+
main(args)
|