-
Notifications
You must be signed in to change notification settings - Fork 5
/
eval_sample.py
71 lines (55 loc) · 1.94 KB
/
eval_sample.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
import os
import math
import torch
import pickle
import argparse
import torchvision.utils as vutils
# Data
from data.data import get_data, get_data_id, add_data_args
# Model
from model.model import get_model, get_model_id, add_model_args
from survae.distributions import DataParallelDistribution
###########
## Setup ##
###########
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default=None)
parser.add_argument('--samples', type=int, default=64)
parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--double', type=eval, default=False)
eval_args = parser.parse_args()
path_args = '{}/args.pickle'.format(eval_args.model)
path_check = '{}/check/checkpoint.pt'.format(eval_args.model)
torch.manual_seed(eval_args.seed)
###############
## Load args ##
###############
with open(path_args, 'rb') as f:
args = pickle.load(f)
##################
## Specify data ##
##################
train_loader, eval_loader, data_shape, num_classes = get_data(args)
###################
## Specify model ##
###################
model = get_model(args, data_shape=data_shape, num_classes=num_classes)
if args.parallel == 'dp':
model = DataParallelDistribution(model)
checkpoint = torch.load(path_check)
model.load_state_dict(checkpoint['model'])
print('Loaded weights for model at {}/{} epochs'.format(checkpoint['current_epoch'], args.epochs))
############
## Sample ##
############
path_samples = os.path.join(eval_args.model, 'samples/sample_ep{}_s{}.txt'.format(checkpoint['current_epoch'], eval_args.seed))
if not os.path.exists(os.path.dirname(path_samples)):
os.mkdir(os.path.dirname(path_samples))
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = model.to(device)
model = model.eval()
if eval_args.double: model = model.double()
samples = model.sample(eval_args.samples).cpu()
samples_text = train_loader.dataset.tensor2text(samples)
with open(path_samples, 'w') as f:
f.write('\n'.join(samples_text))