-
Notifications
You must be signed in to change notification settings - Fork 225
/
Copy path__init__.py
86 lines (73 loc) · 2.48 KB
/
__init__.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
import os
from importlib import import_module
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, args, ckpt):
super(Model, self).__init__()
print('[INFO] Making model...')
self.device = torch.device('cpu' if args.cpu else 'cuda')
self.nGPU = args.nGPU
self.save_models = args.save_models
module = import_module('model.' + args.model.lower())
self.model = module.make_model(args).to(self.device)
if not args.cpu and args.nGPU > 1:
self.model = nn.DataParallel(self.model, range(args.nGPU))
self.load(
ckpt.dir,
pre_train=args.pre_train,
resume=args.resume,
cpu=args.cpu
)
print(self.model, file=ckpt.log_file)
def forward(self, x):
return self.model(x)
def get_model(self):
if self.nGPU == 1:
return self.model
else:
return self.model.module
def save(self, apath, epoch, is_best=False):
target = self.get_model()
torch.save(
target.state_dict(),
os.path.join(apath, 'model', 'model_latest.pt')
)
if is_best:
torch.save(
target.state_dict(),
os.path.join(apath, 'model', 'model_best.pt')
)
if self.save_models:
torch.save(
target.state_dict(),
os.path.join(apath, 'model', 'model_{}.pt'.format(epoch))
)
def load(self, apath, pre_train='', resume=-1, cpu=False):
if cpu:
kwargs = {'map_location': lambda storage, loc: storage}
else:
kwargs = {}
if resume == -1:
self.get_model().load_state_dict(
torch.load(
os.path.join(apath, 'model', 'model_latest.pt'),
**kwargs
),
strict=False
)
elif resume == 0:
if pre_train != '':
print('Loading model from {}'.format(pre_train))
self.get_model().load_state_dict(
torch.load(pre_train, **kwargs),
strict=False
)
else:
self.get_model().load_state_dict(
torch.load(
'/home/wdd/Work/Pytorch/MGN-pytorch-master/experiment/test815/model/model_100.pt',
**kwargs
),
strict=False
)