-
Notifications
You must be signed in to change notification settings - Fork 2
/
trainstep.py
95 lines (70 loc) · 2.59 KB
/
trainstep.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import random
import numpy as np
import os
import torch
import torch.nn.functional as F
import torchmetrics
import torch.nn as nn
def seed_everything(seed: int = 42):
random.seed(seed)
np.random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed) # type: ignore
torch.backends.cudnn.deterministic = True # type: ignore
torch.backends.cudnn.benchmark = True # type: ignore
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
torch.backends.cudnn.benchmark = True
def accuracy_function(real, pred):
accuracies = torch.eq(real, torch.argmax(pred, dim=1))
#print(torch.argmax(pred,dim=1))
mask = torch.logical_not(torch.eq(real, 0))
accuracies = torch.logical_and(mask, accuracies)
accuracies = accuracies.clone().detach()
mask = mask.clone().detach()
return torch.sum(accuracies)/torch.sum(mask)
def train_step(batch_item, epoch, batch, training, model, optimizer):
loss_fn = nn.MSELoss()
if training is True:
model.train()
optimizer.zero_grad()
label = batch_item['label'].to(device)
#label2 = batch_item['label2'].to(device)
input_seq = batch_item['inputs'].to(device)
#print(label)
with torch.cuda.amp.autocast():
output = model(input_seq)
loss = loss_fn(output, label)
loss.backward()
optimizer.step()
return loss
else:
model.eval()
label = batch_item['label'].to(device)
with torch.no_grad():
output = model(batch_item['inputs'].to(device))
loss = loss_fn(output, label)
return loss
def pretrain_step(batch_item, epoch, batch, training, model, optimizer):
loss_fn = nn.CrossEntropyLoss()
if training is True:
model.train()
optimizer.zero_grad()
label = batch_item['label'].to(device)
#label2 = batch_item['label2'].to(device)
input_seq = batch_item['inputs'].to(device)
#print(label)
with torch.cuda.amp.autocast():
output = model(input_seq)
loss = loss_fn(output, input_seq) #+ loss_fn(secondoutput,label2)
loss.backward()
optimizer.step()
return loss
else:
model.eval()
label = batch_item['label'].to(device)
input_seq = batch_item['inputs'].to(device)
with torch.no_grad():
output = model(input_seq)
loss = loss_fn(output, input_seq) #+ loss_fn(secondoutput,label2)
return loss