-
Notifications
You must be signed in to change notification settings - Fork 161
/
test.py
180 lines (142 loc) · 5.5 KB
/
test.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# Copyright (c) 2022 Huawei Technologies Co., Ltd.
# Licensed under CC BY-NC-SA 4.0 (Attribution-NonCommercial-ShareAlike 4.0 International) (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
#
# The code is released for academic research use only. For commercial use, please contact Huawei Technologies Co., Ltd.
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This repository was forked from https://github.com/openai/guided-diffusion, which is under the MIT license
"""
Like image_sample.py, but use a noisy image classifier to guide the sampling
process towards more realistic images.
"""
import os
import argparse
import torch as th
import torch.nn.functional as F
import time
import conf_mgt
from utils import yamlread
from guided_diffusion import dist_util
# Workaround
try:
import ctypes
libgcc_s = ctypes.CDLL('libgcc_s.so.1')
except:
pass
from guided_diffusion.script_util import (
NUM_CLASSES,
model_and_diffusion_defaults,
classifier_defaults,
create_model_and_diffusion,
create_classifier,
select_args,
) # noqa: E402
def toU8(sample):
if sample is None:
return sample
sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
sample = sample.permute(0, 2, 3, 1)
sample = sample.contiguous()
sample = sample.detach().cpu().numpy()
return sample
def main(conf: conf_mgt.Default_Conf):
print("Start", conf['name'])
device = dist_util.dev(conf.get('device'))
model, diffusion = create_model_and_diffusion(
**select_args(conf, model_and_diffusion_defaults().keys()), conf=conf
)
model.load_state_dict(
dist_util.load_state_dict(os.path.expanduser(
conf.model_path), map_location="cpu")
)
model.to(device)
if conf.use_fp16:
model.convert_to_fp16()
model.eval()
show_progress = conf.show_progress
if conf.classifier_scale > 0 and conf.classifier_path:
print("loading classifier...")
classifier = create_classifier(
**select_args(conf, classifier_defaults().keys()))
classifier.load_state_dict(
dist_util.load_state_dict(os.path.expanduser(
conf.classifier_path), map_location="cpu")
)
classifier.to(device)
if conf.classifier_use_fp16:
classifier.convert_to_fp16()
classifier.eval()
def cond_fn(x, t, y=None, gt=None, **kwargs):
assert y is not None
with th.enable_grad():
x_in = x.detach().requires_grad_(True)
logits = classifier(x_in, t)
log_probs = F.log_softmax(logits, dim=-1)
selected = log_probs[range(len(logits)), y.view(-1)]
return th.autograd.grad(selected.sum(), x_in)[0] * conf.classifier_scale
else:
cond_fn = None
def model_fn(x, t, y=None, gt=None, **kwargs):
assert y is not None
return model(x, t, y if conf.class_cond else None, gt=gt)
print("sampling...")
all_images = []
dset = 'eval'
eval_name = conf.get_default_eval_name()
dl = conf.get_dataloader(dset=dset, dsName=eval_name)
for batch in iter(dl):
for k in batch.keys():
if isinstance(batch[k], th.Tensor):
batch[k] = batch[k].to(device)
model_kwargs = {}
model_kwargs["gt"] = batch['GT']
gt_keep_mask = batch.get('gt_keep_mask')
if gt_keep_mask is not None:
model_kwargs['gt_keep_mask'] = gt_keep_mask
batch_size = model_kwargs["gt"].shape[0]
if conf.cond_y is not None:
classes = th.ones(batch_size, dtype=th.long, device=device)
model_kwargs["y"] = classes * conf.cond_y
else:
classes = th.randint(
low=0, high=NUM_CLASSES, size=(batch_size,), device=device
)
model_kwargs["y"] = classes
sample_fn = (
diffusion.p_sample_loop if not conf.use_ddim else diffusion.ddim_sample_loop
)
result = sample_fn(
model_fn,
(batch_size, 3, conf.image_size, conf.image_size),
clip_denoised=conf.clip_denoised,
model_kwargs=model_kwargs,
cond_fn=cond_fn,
device=device,
progress=show_progress,
return_all=True,
conf=conf
)
srs = toU8(result['sample'])
gts = toU8(result['gt'])
lrs = toU8(result.get('gt') * model_kwargs.get('gt_keep_mask') + (-1) *
th.ones_like(result.get('gt')) * (1 - model_kwargs.get('gt_keep_mask')))
gt_keep_masks = toU8((model_kwargs.get('gt_keep_mask') * 2 - 1))
conf.eval_imswrite(
srs=srs, gts=gts, lrs=lrs, gt_keep_masks=gt_keep_masks,
img_names=batch['GT_name'], dset=dset, name=eval_name, verify_same=False)
print("sampling complete")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--conf_path', type=str, required=False, default=None)
args = vars(parser.parse_args())
conf_arg = conf_mgt.conf_base.Default_Conf()
conf_arg.update(yamlread(args.get('conf_path')))
main(conf_arg)