-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
67 lines (56 loc) · 2.18 KB
/
Copy pathtrain.py
File metadata and controls
67 lines (56 loc) · 2.18 KB
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
import torch
from torch import nn
from model import VisionTransformer
import torch.optim as optim
from torchvision import datasets, transforms
import itertools
from util import throb
device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor()
])
train_data = datasets.CelebA(root='~/training_data/', target_type="landmarks", download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
model = VisionTransformer()
model = model.to(device)
model = torch.compile(model)
torch.set_float32_matmul_precision('high')
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=1e-4)
useAMP = True
scaler=torch.amp.GradScaler("cuda", enabled=useAMP)
print("started training")
# Training loop
try:
last_loss = float("inf")
model.train()
for epoch in itertools.count(0):
running_loss = 0.0
for batch,(inputs, labels) in enumerate(train_loader):
inputs = inputs.to(device)
optimizer.zero_grad()
with torch.autocast(device_type=device, dtype=torch.float16, enabled=useAMP):
pred = model(inputs)
loss = criterion(pred, inputs)
if loss.isnan().any():
raise RuntimeError("numerican instability")
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
running_loss += loss.item()
if batch % 30 == 0:
loss, current = loss.item(), (batch + 1)
print(f"loss: {loss:>7f} [{current:>5d}] ")
throb()
print(f"Epoch [{epoch+1}], Loss: {running_loss/len(train_loader)}")
if last_loss < running_loss:
print("early stopping triggered")
break;
last_loss = running_loss
except KeyboardInterrupt:
print("exiting early")
finally:
torch.save(model.state_dict(), "model.pth")
# torch.save(model.state_dict(), f"model-{datetime.now().strftime("%Y%m%d_%H%M%S")}.pth")
print("Saved PyTorch Model State to model.pth")