-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathengine.py
65 lines (47 loc) · 1.83 KB
/
engine.py
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
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
import math
import sys
import tqdm
from models import utils
def train_one_epoch(model, criterion, data_loader,
optimizer, device, epoch, max_norm):
model.train()
criterion.train()
epoch_loss = 0.0
total = len(data_loader)
with tqdm.tqdm(total=total) as pbar:
for images, masks, caps, cap_masks in data_loader:
samples = utils.NestedTensor(images, masks).to(device)
caps = caps.to(device)
cap_masks = cap_masks.to(device)
outputs = model(samples, caps[:, :-1], cap_masks[:, :-1])
loss = criterion(outputs.permute(0, 2, 1), caps[:, 1:])
loss_value = loss.item()
epoch_loss += loss_value
if not math.isfinite(loss_value):
print(f'Loss is {loss_value}, stopping training')
sys.exit(1)
optimizer.zero_grad()
loss.backward()
if max_norm > 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
optimizer.step()
pbar.update(1)
return epoch_loss / total
@torch.no_grad()
def evaluate(model, criterion, data_loader, device):
model.eval()
criterion.eval()
validation_loss = 0.0
total = len(data_loader)
with tqdm.tqdm(total=total) as pbar:
for images, masks, caps, cap_masks in data_loader:
samples = utils.NestedTensor(images, masks).to(device)
caps = caps.to(device)
cap_masks = cap_masks.to(device)
outputs = model(samples, caps[:, :-1], cap_masks[:, :-1])
loss = criterion(outputs.permute(0, 2, 1), caps[:, 1:])
validation_loss += loss.item()
pbar.update(1)
return validation_loss / total