-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.py
66 lines (58 loc) · 2.37 KB
/
net.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
import torch.nn as nn
import torch.nn.functional as F
import os
import torch
def saveNetGAN(filename, generator, optimizer_gen, discriminator, optimizer_disc, iterations, train_loss, val_loss):
torch.save({
"gen": generator.state_dict(),
"optimizer_gen": optimizer_gen.state_dict(),
"disc": discriminator.state_dict(),
"optimizer_disc": optimizer_disc.state_dict(),
"iteration": iterations,
"loss": train_loss,
"val_loss": val_loss
}, filename)
def loadNetGAN(filename, generator, optimizer_gen, discriminator, optimizer_disc, device):
try:
checkpoint = torch.load(filename, map_location=device)
generator.load_state_dict(checkpoint["gen"])
optimizer_gen.load_state_dict(checkpoint["optimizer_gen"])
discriminator.load_state_dict(checkpoint["disc"])
optimizer_disc.load_state_dict(checkpoint["optimizer_disc"])
iteration = checkpoint["iteration"]
train_loss = checkpoint["loss"]
val_loss = checkpoint["val_loss"]
print(f"Net loaded from memory! Starting on iteration {iteration[-1]+1} with train-loss {train_loss[-1]}")
return iteration, train_loss, val_loss
except (OSError, FileNotFoundError):
print(f"Couldn't find {filename}, creating new net!")
return [], [], []
def saveNet(filename, net, optimizer, iterations, train_loss, val_loss):
torch.save({
"gen": net.state_dict(),
"optimizer": optimizer.state_dict(),
"iteration": iterations,
"loss": train_loss,
"val_loss": val_loss
}, filename)
def loadNet(filename, net, optimizer, device):
try:
checkpoint = torch.load(filename, map_location=device)
net.load_state_dict(checkpoint["gen"])
optimizer.load_state_dict(checkpoint["optimizer"])
iteration = checkpoint["iteration"]
train_loss = checkpoint["loss"]
val_loss = checkpoint["val_loss"]
print(f"Net loaded from memory! Starting on iteration {iteration[-1]+1} with train-loss {train_loss[-1]}")
return iteration, train_loss, val_loss
except (OSError, FileNotFoundError):
print(f"Couldn't find {filename}, creating new net!")
return [], [], []
def loadNetEval(filename, net, device):
try:
checkpoint = torch.load(filename, map_location=device)
net.load_state_dict(checkpoint["gen"])
net.eval()
print(filename, "successfully loaded in eval mode")
except (OSError, FileNotFoundError):
print(f"Couldn't find {filename}")