Skip to content

Commit c3bed73

Browse files
authored
Add files via upload
1 parent 39579bf commit c3bed73

33 files changed

+1210
-0
lines changed

Adapt_CAAE/ResLearn.py

+919
Large diffs are not rendered by default.

Adapt_CAAE/checkGPU.py

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# check GPU status
2+
from pynvml import *
3+
from time import sleep
4+
from datetime import datetime
5+
6+
7+
def gpu_memory_usage(is_print=True):
8+
try:
9+
nvmlInit()
10+
# version = nvmlSystemGetDriverVersion()
11+
deviceCount = nvmlDeviceGetCount()
12+
GPU = {}
13+
for i in range(deviceCount):
14+
GPU[i] = {}
15+
handle = nvmlDeviceGetHandleByIndex(i)
16+
info = nvmlDeviceGetMemoryInfo(handle)
17+
GPU[i]['total'] = info.total / 1024.0 / 1024.0 / 1024.0
18+
GPU[i]['free'] = info.free / 1024.0 / 1024.0 / 1024.0
19+
if is_print:
20+
print("\nGPU #%d Memory Usage:"
21+
"\n\tTotal:\t%4.2fGB\n\tFree:\t%4.2fGB" %
22+
(i, GPU[i]['total'], GPU[i]['free']))
23+
print datetime.now()
24+
nvmlShutdown()
25+
return GPU
26+
except:
27+
print "Fail to check GPU status!"
28+
exit(0)
29+
30+
31+
def auto_queue(gpu_memory_require=3.2, interval=1, schedule=None):
32+
# input arg: schedule = datetime(year, month, day, hour, minute, second)
33+
if schedule is None:
34+
schedule = datetime.today()
35+
else:
36+
print '\nScheduled time: ', schedule
37+
38+
# wait until the scheduled time
39+
now = datetime.today()
40+
while now.year < schedule.year or now.month < schedule.month or now.day < schedule.day or \
41+
now.hour < schedule.hour or now.minute < schedule.minute or now.second < schedule.second:
42+
now = datetime.today()
43+
sleep(interval)
44+
45+
gpu_stat = gpu_memory_usage()
46+
if gpu_stat[0]['total'] < gpu_memory_require:
47+
print 'Memory requirement is larger than GPU total memory'
48+
exit(1)
49+
while gpu_stat[0]['free'] < gpu_memory_require:
50+
sleep(interval) # second
51+
gpu_stat = gpu_memory_usage()
52+
return gpu_stat
53+
54+
55+
def set_memory_usage(usage=12.0, allow_growth=True):
56+
auto_queue(gpu_memory_require=usage)
57+
try:
58+
import tensorflow as tf
59+
assert type(usage) is int or float
60+
assert usage >= 0
61+
62+
config = tf.ConfigProto()
63+
gpu_stat = gpu_memory_usage()
64+
total_memory = gpu_stat[0]['total']
65+
if usage > total_memory:
66+
usage_percentage = 1.0
67+
else:
68+
usage_percentage = usage / total_memory
69+
config.gpu_options.allow_growth = allow_growth
70+
config.gpu_options.per_process_gpu_memory_fraction = usage_percentage
71+
return config
72+
except:
73+
print 'Failed to set memory usage!'
74+
return None
75+
76+
77+
if __name__ == '__main__':
78+
gpu_memory_usage()
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading

Adapt_CAAE/main.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import tensorflow as tf
2+
from ResLearn import ResLearn
3+
import checkGPU
4+
import numpy as np
5+
6+
7+
flags = tf.app.flags
8+
flags.DEFINE_integer(flag_name='epoch', default_value=50, docstring='number of epochs')
9+
flags.DEFINE_integer(flag_name='batch_size', default_value=25, docstring='batch size')
10+
flags.DEFINE_integer(flag_name='is_train', default_value=1, docstring='training mode')
11+
flags.DEFINE_integer(flag_name='is_bn', default_value=0, docstring='enable batch normalization')
12+
flags.DEFINE_string(flag_name='dataset', default_value='UTKFace', docstring='dataset name')
13+
flags.DEFINE_string(flag_name='savedir', default_value='save', docstring='dir for saving training results')
14+
flags.DEFINE_string(flag_name='testdir', default_value='None', docstring='dir for testing images')
15+
flags.DEFINE_float(flag_name='param0', default_value=1.0, docstring='weight of discriminator loss on fake images')
16+
flags.DEFINE_float(flag_name='param1', default_value=1.0, docstring='weight of reconstruct loss on artifact modeling')
17+
flags.DEFINE_integer(flag_name='is_schedule', default_value=0, docstring='scheduled running')
18+
flags.DEFINE_integer(flag_name='day', default_value=1, docstring='date')
19+
flags.DEFINE_integer(flag_name='hr', default_value=0, docstring='hour')
20+
flags.DEFINE_integer(flag_name='min', default_value=0, docstring='minute')
21+
22+
FLAGS = flags.FLAGS
23+
24+
25+
gpu_memory_require = 7.0
26+
27+
28+
def main(_):
29+
from datetime import datetime
30+
if FLAGS.is_schedule:
31+
today = datetime.today()
32+
checkGPU.auto_queue(
33+
gpu_memory_require=gpu_memory_require,
34+
interval=1,
35+
schedule=datetime(year=today.year, month=today.month, day=FLAGS.day, hour=FLAGS.hr, minute=FLAGS.min)
36+
)
37+
config = checkGPU.set_memory_usage(
38+
usage=gpu_memory_require,
39+
allow_growth=True
40+
)
41+
42+
# print settings
43+
import pprint
44+
pprint.pprint(FLAGS.__flags)
45+
46+
with tf.Session(config=config) as session:
47+
model = ResLearn(
48+
session, # TensorFlow session
49+
is_training=FLAGS.is_train, # flag for training or testing mode
50+
save_dir=FLAGS.savedir, # path to save checkpoints, samples, and summary
51+
dataset_name=FLAGS.dataset, # name of the dataset in the folder ./data
52+
size_batch=FLAGS.batch_size,
53+
enable_bn=FLAGS.is_bn
54+
)
55+
if FLAGS.is_train:
56+
print '\n\tTraining Mode'
57+
model.train(
58+
num_epochs=FLAGS.epoch, # number of epochs
59+
params=[FLAGS.param0, FLAGS.param1]
60+
)
61+
else:
62+
print '\n\tTesting Mode'
63+
model.custom_test(
64+
testing_samples_dir=FLAGS.testdir + '/*jpg'
65+
)
66+
67+
68+
if __name__ == '__main__':
69+
if 0:
70+
print 'Run on CPU'
71+
with tf.device("/cpu:0"):
72+
gpu_memory_require = 0.0
73+
tf.app.run()
74+
75+
tf.app.run()
76+

Adapt_CAAE/ops.py

+137
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
from __future__ import division
2+
import tensorflow as tf
3+
import numpy as np
4+
from scipy.misc import imread, imresize, imsave
5+
6+
7+
class batch_norm(object):
8+
def __init__(self, epsilon=1e-5, momentum=0.9, name="batch_norm"):
9+
with tf.variable_scope(name):
10+
self.epsilon = epsilon
11+
self.momentum = momentum
12+
self.name = name
13+
14+
def __call__(self, x, train=True):
15+
return tf.contrib.layers.batch_norm(x, decay=self.momentum, updates_collections=None, epsilon=self.epsilon,
16+
scale=True, scope=self.name)
17+
18+
19+
def conv2d(input_map, num_output_channels, size_kernel=5, stride=2, name='conv2d'):
20+
with tf.variable_scope(name):
21+
stddev = np.sqrt(2.0 / (np.sqrt(input_map.get_shape()[-1].value * num_output_channels) * size_kernel ** 2))
22+
stddev = 0.02
23+
kernel = tf.get_variable(
24+
name='w',
25+
shape=[size_kernel, size_kernel, input_map.get_shape()[-1], num_output_channels],
26+
dtype=tf.float32,
27+
initializer=tf.truncated_normal_initializer(stddev=stddev)
28+
)
29+
biases = tf.get_variable(
30+
name='b',
31+
shape=[num_output_channels],
32+
dtype=tf.float32,
33+
initializer=tf.constant_initializer(0.0)
34+
)
35+
conv = tf.nn.conv2d(input_map, kernel, strides=[1, stride, stride, 1], padding='SAME')
36+
return tf.nn.bias_add(conv, biases)
37+
38+
39+
def fc(input_vector, num_output_length, name='fc'):
40+
with tf.variable_scope(name):
41+
stddev = np.sqrt(1.0 / (np.sqrt(input_vector.get_shape()[-1].value * num_output_length)))
42+
stddev = 0.02
43+
w = tf.get_variable(
44+
name='w',
45+
shape=[input_vector.get_shape()[1], num_output_length],
46+
dtype=tf.float32,
47+
initializer=tf.random_normal_initializer(stddev=stddev)
48+
)
49+
b = tf.get_variable(
50+
name='b',
51+
shape=[num_output_length],
52+
dtype=tf.float32,
53+
initializer=tf.constant_initializer(0.0)
54+
)
55+
return tf.matmul(input_vector, w) + b
56+
57+
58+
def deconv2d(input_map, output_shape, size_kernel=5, stride=2, stddev=0.02, name='deconv2d'):
59+
with tf.variable_scope(name):
60+
stddev = np.sqrt(1.0 / (np.sqrt(input_map.get_shape()[-1].value * output_shape[-1]) * size_kernel ** 2))
61+
stddev = 0.02
62+
# filter : [height, width, output_channels, in_channels]
63+
kernel = tf.get_variable(
64+
name='w',
65+
shape=[size_kernel, size_kernel, output_shape[-1], input_map.get_shape()[-1]],
66+
dtype=tf.float32,
67+
initializer=tf.random_normal_initializer(stddev=stddev)
68+
)
69+
biases = tf.get_variable(
70+
name='b',
71+
shape=[output_shape[-1]],
72+
dtype=tf.float32,
73+
initializer=tf.constant_initializer(0.0)
74+
)
75+
deconv = tf.nn.conv2d_transpose(input_map, kernel, strides=[1, stride, stride, 1], output_shape=output_shape)
76+
return tf.nn.bias_add(deconv, biases)
77+
78+
79+
def lrelu(logits, leak=0.2):
80+
return tf.maximum(logits, leak*logits)
81+
82+
83+
def concat_label(x, label, duplicate=1):
84+
x_shape = x.get_shape().as_list()
85+
if duplicate < 1:
86+
return x
87+
# duplicate the label to enhance its effect, does it really affect the result?
88+
label = tf.tile(label, [1, duplicate])
89+
label_shape = label.get_shape().as_list()
90+
if len(x_shape) == 2:
91+
return tf.concat(1, [x, label])
92+
elif len(x_shape) == 4:
93+
label = tf.reshape(label, [x_shape[0], 1, 1, label_shape[-1]])
94+
return tf.concat(3, [x, label*tf.ones([x_shape[0], x_shape[1], x_shape[2], label_shape[-1]])])
95+
96+
97+
def load_image(
98+
image_path, # path of a image
99+
image_size=64, # expected size of the image
100+
image_value_range=(-1, 1), # expected pixel value range of the image
101+
is_gray=False, # gray scale or color image
102+
):
103+
if is_gray:
104+
image = imread(image_path, flatten=True).astype(np.float32)
105+
else:
106+
image = imread(image_path).astype(np.float32)
107+
image = imresize(image, [image_size, image_size])
108+
image = image.astype(np.float32) * (image_value_range[-1] - image_value_range[0]) / 255.0 + image_value_range[0]
109+
return image
110+
111+
112+
def save_batch_images(
113+
batch_images, # a batch of images
114+
save_path, # path to save the images
115+
image_value_range=(-1,1), # value range of the input batch images
116+
size_frame=None # size of the image matrix, number of images in each row and column
117+
):
118+
# transform the pixcel value to 0~1
119+
images = (batch_images - image_value_range[0]) / (image_value_range[-1] - image_value_range[0])
120+
if size_frame is None:
121+
auto_size = int(np.ceil(np.sqrt(images.shape[0])))
122+
size_frame = [auto_size, auto_size]
123+
img_h, img_w = batch_images.shape[1], batch_images.shape[2]
124+
frame = np.zeros([img_h * size_frame[0], img_w * size_frame[1], 3])
125+
for ind, image in enumerate(images):
126+
ind_col = ind % size_frame[1]
127+
ind_row = ind // size_frame[1]
128+
frame[(ind_row * img_h):(ind_row * img_h + img_h), (ind_col * img_w):(ind_col * img_w + img_w), :] = image
129+
imsave(save_path, np.clip(frame, 0.0, 1.0)) # imsave(save_path, frame)
130+
131+
132+
133+
134+
135+
136+
137+

0 commit comments

Comments
 (0)