-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
2214 lines (1665 loc) · 82.9 KB
/
train.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
# ==============================================================================
"""Example script to train the DNC on a repeated copy task."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import sonnet as snt
from tensorflow.contrib.layers.python.layers import initializers
from tensorflow.python.ops import array_ops
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import nn
from dnc import dnc
import numpy as np
import cv2
from scipy import ndimage as nd
from PIL import Image
import os, sys
import time
from utility import alrc, auto_name
from scipy.stats import norm
experiment_number = 280
FLAGS = tf.flags.FLAGS
# Model parameters
tf.flags.DEFINE_integer("hidden_size", 256, "Size of LSTM hidden layer.")
tf.flags.DEFINE_integer("memory_size", 16, "The number of memory slots.")
tf.flags.DEFINE_integer("word_size", 64, "The width of each memory slot.")
tf.flags.DEFINE_integer("num_write_heads", 1, "Number of memory write heads.")
tf.flags.DEFINE_integer("num_read_heads", 4, "Number of memory read heads.")
tf.flags.DEFINE_integer("clip_value", 0, "Maximum absolute value of controller and dnc outputs.")
tf.flags.DEFINE_bool("use_batch_norm", True, "Use batch normalization in generator.")
tf.flags.DEFINE_string("model", "LSTM", "LSTM or DNC.")
tf.flags.DEFINE_integer("projection_size", 0, "Size of projection layer. Zero for no projection.")
tf.flags.DEFINE_integer("lstm_depth", 2, "Number of LSTM cells deep.")
tf.flags.DEFINE_bool("is_input_embedder", False, "Embed inputs before they are input.")
tf.flags.DEFINE_bool("is_variable_initial_states", True, "Trainable initial states rather than zero states.")
tf.flags.DEFINE_bool("is_layer_norm", False, "Use layer normalization in recurrent networks.")
# Optimizer parameters.
tf.flags.DEFINE_integer("batch_size", 32, "Batch size for training.")
tf.flags.DEFINE_integer("replay_size", 100_000, "Maximum examples in ring buffer.")
tf.flags.DEFINE_integer("avg_replays", 1, "Mean frequency each experience is used.")
tf.flags.DEFINE_integer("replay_add_frequency", 1, "How often to add expereinces to ring buffer.")
tf.flags.DEFINE_bool("is_cyclic_replay", False, "True to cyclically replace experiences.")
tf.flags.DEFINE_float("max_grad_norm", 50, "Gradient clipping norm limit.")
tf.flags.DEFINE_float("L2_norm", 1.e-5, "Decay rate for L2 regularization. 0 for no regularization.")
tf.flags.DEFINE_float("grad_clip_norm", 0, "Threshold to clip gradient sizes to. Zero for no clipping.")
tf.flags.DEFINE_float("grad_clip_value", 0.000, "Threshold to clip gradient sizes to. Zero for no clipping.")
# Task parameters
tf.flags.DEFINE_integer("img_side", 96, "Number of image pixels for square image")
tf.flags.DEFINE_integer("num_steps", 20, "Number of image pixels for square image")
tf.flags.DEFINE_integer("step_size", 20, "Distance STEM probe moves at each step (in px).")
tf.flags.DEFINE_integer("num_actions", 1, "Number of parameters to describe actions.")
tf.flags.DEFINE_integer("shuffle_size", 2000, "Size of moving buffer to sample data from.")
tf.flags.DEFINE_integer("prefetch_size", 10, "Number of batches to prepare in advance.")
# Training options.
tf.flags.DEFINE_float("actor_lr", 0.0005, "Actor learning rate.")
tf.flags.DEFINE_float("critic_lr", 0.001, "Critic learning rate.")
tf.flags.DEFINE_float("generator_lr", 0.003, "Generator learning rate.")
tf.flags.DEFINE_float("discriminator_lr", 0.003, "Discriminator learning rate.")
tf.flags.DEFINE_float("specificity", 0.0, "Weight specificity loss. Zero for no specificity loss.")
tf.flags.DEFINE_float("loss_norm_decay", 0.997, "Weight for loss normalization. Zero for no normalization.")
tf.flags.DEFINE_float("rnn_norm_decay", 0., "Weight for critic loss normalization. Zero for no normalization.")
tf.flags.DEFINE_bool("is_immediate_critic_loss", False, "True to not backpropagate.")
tf.flags.DEFINE_bool("is_target_actor_feedback", False, "True to use target critic to train actor.")
tf.flags.DEFINE_bool("is_ranked_loss", False, "Loses are indices in sorted arrays.")
tf.flags.DEFINE_float("gamma", 0.97, "Reward/loss decay.")
tf.flags.DEFINE_float("loss_gamma", 1., "Reward/loss decay applied directly to losses.")
tf.flags.DEFINE_float("loss_norm_clip", 0., "Norm to clip losses to.")
tf.flags.DEFINE_bool("is_advantage_actor_critic", False, "Use advantage rather than Q errors for actor.")
tf.flags.DEFINE_bool("is_direct_advantage", False, "Use predicted Q minus exploration Q errors for actor.")
tf.flags.DEFINE_bool("is_cyclic_generator_learning_rate", True, "True for sawtooth oscillations.")
tf.flags.DEFINE_bool("is_decaying_generator_learning_rate", True, "True for decay envelope for sawtooth oscillations.")
tf.flags.DEFINE_integer("supervision_iters", 1, "Starting value for supeversion.")
tf.flags.DEFINE_float("supervision_start", 0., "Starting value for supeversion.")
tf.flags.DEFINE_float("supervision_end", 0., "Starting value for supeversion.")
if FLAGS.supervision_iters:
#Flag will not be used
tf.flags.DEFINE_float("supervision", 0.5, "Weighting for known discounted future reward.")
else:
#Flag will be used
tf.flags.DEFINE_float("supervision", 0.0, "Weighting for known discounted future reward.")
tf.flags.DEFINE_bool("is_target_actor", False and FLAGS.supervision != 1, "True to use target actor.")
tf.flags.DEFINE_bool("is_target_critic", True and FLAGS.supervision != 1, "True to use target critic.")
tf.flags.DEFINE_bool("is_target_generator", False, "True to use target generator.")
tf.flags.DEFINE_integer("update_frequency", 0, "Frequency of hard target network updates. Zero for soft updates.")
tf.flags.DEFINE_float("target_decay", 0.997, "Decay rate for target network soft updates.")
tf.flags.DEFINE_bool("is_generator_batch_norm_tracked", False, "True to track generator batch normalization.")
tf.flags.DEFINE_bool("is_positive_qs", False, "Whether to clip qs to be positive.")
tf.flags.DEFINE_bool("is_norm_q", False, "Whether to set mean of q values.")
tf.flags.DEFINE_bool("is_infilled", False, "True to use infilling rather than generator.")
tf.flags.DEFINE_bool("is_prev_position_input", True, "True to input previous positions.")
tf.flags.DEFINE_bool("is_ornstein_uhlenbeck", True, "True for O-U exploration noise.")
tf.flags.DEFINE_bool("is_noise_decay", True, "Decay noise if true.")
tf.flags.DEFINE_float("ou_theta", 0.1, "Drift back to mean.")
tf.flags.DEFINE_float("ou_sigma", 0.2, "Size of random process.")
tf.flags.DEFINE_float("exploration_loss", 0., "Exploration loss.")
tf.flags.DEFINE_float("uniform_coverage_loss", 0, "Additive uniform coverage loss.")
tf.flags.DEFINE_bool("is_rel_to_truth", False, "True to normalize losses using expected losses.")
tf.flags.DEFINE_bool("is_clipped_reward", True, "True to clip rewards.")
tf.flags.DEFINE_bool("is_clipped_critic", False, "True to clip critic predictions for actor training.")
tf.flags.DEFINE_float("over_edge_penalty", 0.05, "Penalty for action going over edge of image.")
tf.flags.DEFINE_float("end_edge_penalty", 0.0, "Penalty for action going over edge of image.")
tf.flags.DEFINE_bool("is_prioritized_replay", False, "True to prioritize the replay of difficult experiences.")
tf.flags.DEFINE_bool("is_biased_prioritized_replay", False, "Priority sampling without bias correction.")
tf.flags.DEFINE_bool("is_relative_to_spirals", False, "True to compare generator losses against losses for spirals.")
tf.flags.DEFINE_bool("is_self_competition", True, "Oh it is on. True to compete against past versions of itself.")
tf.flags.DEFINE_float("norm_generator_losses_decay", 0., "Divide generator losses by their running mean. Zero for no normalization.")
tf.flags.DEFINE_float("replay_decay", 0.999, "Decay rates to calculate loss moments.")
tf.flags.DEFINE_bool("is_minmax_reward", False, "True to use highest losses for actor loss.")
tf.flags.DEFINE_integer("start_iter", 0, "Starting iteration")
tf.flags.DEFINE_integer("train_iters", 1_000_000, "Training iterations")
tf.flags.DEFINE_integer("val_examples", 20_000, "Number of validation examples")
tf.flags.DEFINE_float("style_loss", 0., "Weighting of style loss. Zero for no style loss.")
tf.flags.DEFINE_float("spike_loss", 0., "Penalize critic for spikey predictions.")
tf.flags.DEFINE_float("step_incr", np.sqrt(2), "Number of pixels per step.")
tf.flags.DEFINE_string("model_dir",
f"//ads.warwick.ac.uk/shared/HCSS6/Shared305/Microscopy/Jeffrey-Ede/models/recurrent_conv-1/{experiment_number}/",
"Working directory.")
tf.flags.DEFINE_string("data_file",
"//Desktop-sa1evjv/h/96x96_stem_crops.npy",
"Datafile containing 19769 96x96 downsampled STEM crops.")
tf.flags.DEFINE_integer("report_freq", 10, "How often to print losses to the console.")
os.chdir(FLAGS.model_dir)
sys.path.insert(0, FLAGS.model_dir)
def l1_batch_norm(x):
mu = tf.reduce_mean(x, axis=0, keepdims=True)
d = np.sqrt(np.pi/2)*tf.reduce_mean(tf.abs(x-mu))
return (x - mu) / d
def sobel_edges(image):
"""Returns a tensor holding Sobel edge maps.
Arguments:
image: Image tensor with shape [batch_size, h, w, d] and type float32 or
float64. The image(s) must be 2x2 or larger.
Returns:
Tensor holding edge maps for each channel. Returns a tensor with shape
[batch_size, h, w, d, 2] where the last two dimensions hold [[dy[0], dx[0]],
[dy[1], dx[1]], ..., [dy[d-1], dx[d-1]]] calculated using the Sobel filter.
"""
# Define vertical and horizontal Sobel filters.
static_image_shape = image.get_shape()
image_shape = array_ops.shape(image)
kernels = [[[-1, -2, -1], [0, 0, 0], [1, 2, 1]],
[[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]]
num_kernels = len(kernels)
kernels = np.transpose(np.asarray(kernels), (1, 2, 0))
kernels = np.expand_dims(kernels, -2)
kernels_tf = constant_op.constant(kernels, dtype=image.dtype)
kernels_tf = array_ops.tile(
kernels_tf, [1, 1, image_shape[-1], 1], name='sobel_filters')
# Use depth-wise convolution to calculate edge maps per channel.
pad_sizes = [[0, 0], [1, 1], [1, 1], [0, 0]]
padded = array_ops.pad(image, pad_sizes, mode='REFLECT')
# Output tensor has shape [batch_size, h, w, d * num_kernels].
strides = [1, 1, 1, 1]
output = nn.depthwise_conv2d(padded, kernels_tf, strides, 'VALID')
# Reshape to [batch_size, h, w, d, num_kernels].
shape = array_ops.concat([image_shape, [num_kernels]], 0)
output = array_ops.reshape(output, shape=shape)
output.set_shape(static_image_shape.concatenate([num_kernels]))
return output
def norm_img(img, min=None, max=None, get_min_and_max=False):
if min == None:
min = np.min(img)
if max == None:
max = np.max(img)
if np.absolute(min-max) < 1.e-6:
img.fill(0.)
else:
a = 0.5*(min+max)
b = 0.5*(max-min)
img = (img-a) / b
if get_min_and_max:
return img.astype(np.float32), (min, max)
else:
return img.astype(np.float32)
def scale0to1(img):
"""Rescale image between 0 and 1"""
img = img.astype(np.float32)
min = np.min(img)
max = np.max(img)
if np.absolute(min-max) < 1.e-6:
img.fill(0.5)
else:
img = (img - min)/(max - min)
return img.astype(np.float32)
def disp(img):
#if len(img.shape) == 3:
# img = np.sum(img, axis=2)
cv2.namedWindow('CV_Window', cv2.WINDOW_NORMAL)
cv2.imshow('CV_Window', scale0to1(img))
cv2.waitKey(0)
return
def run_model(input_sequence, output_size):
"""Runs model on input sequence."""
access_config = {
"memory_size": FLAGS.memory_size,
"word_size": FLAGS.word_size,
"num_reads": FLAGS.num_read_heads,
"num_writes": FLAGS.num_write_heads,
}
controller_config = {
"hidden_size": FLAGS.hidden_size,
"use_layer_norm": FLAGS.is_layer_norm,
}
clip_value = FLAGS.clip_value
dnc_core = dnc.DNC(access_config, controller_config, output_size, clip_value)
initial_state = dnc_core.initial_state(FLAGS.batch_size)
output_sequence, _ = tf.nn.dynamic_rnn(
cell=dnc_core,
inputs=input_sequence,
time_major=True,
initial_state=initial_state)
return output_sequence
def sigmoid(x):
return 1/(1 + np.exp(-x))
class RingBuffer(object):
def __init__(
self,
action_shape,
observation_shape,
full_scan_shape,
batch_size,
buffer_size=1000,
num_past_losses=None,
):
self.buffer_size = buffer_size
self.actions = np.zeros([buffer_size]+list(action_shape)[1:])
self.observations = np.zeros([buffer_size]+list(observation_shape)[1:])
self.full_scans = np.zeros([buffer_size]+list(full_scan_shape)[1:])
self.position = 0
self._batch_size = batch_size
self._input_batch_size = batch_size // FLAGS.avg_replays
if FLAGS.is_prioritized_replay or FLAGS.is_biased_prioritized_replay:
self.accesses = np.zeros([buffer_size])
self.priorities = np.ones([buffer_size])
self.indices = np.arange(buffer_size)
self._is_accessed = False
if FLAGS.is_self_competition:
self.mu1 = 0.5
self.mu2 = 0.5
self.std = np.sqrt(self.mu2 - self.mu1**2 + 1.e-3)
self.d_mu1 = 0.5
self.d_mu2 = 0.5
self.d_std = np.sqrt(self.d_mu2 - self.d_mu1**2 + 1.e-3)
self.past_losses = np.zeros([num_past_losses])
self.next_losses = np.zeros([num_past_losses])
self.labels = np.zeros([buffer_size], np.int32)
def add(self, actions, observations, full_scans, labels=None):
if FLAGS.is_cyclic_replay:
i0 = self.position % self.buffer_size
else:
if self.position < self.buffer_size:
i0 = self.position
else:
i0 = np.random.randint(0, self.buffer_size)
num_before_cycle = min(self.buffer_size-i0, self._input_batch_size)
self.actions[i0:i0+num_before_cycle] = actions[:num_before_cycle]
self.observations[i0:i0+num_before_cycle] = observations[:num_before_cycle]
self.full_scans[i0:i0+num_before_cycle] = full_scans[:num_before_cycle]
num_remaining = self._input_batch_size - num_before_cycle
if num_remaining > 0:
self.actions[0:num_remaining] = actions[num_before_cycle:]
self.observations[:num_remaining] = observations[num_before_cycle:]
self.full_scans[:num_remaining] = full_scans[num_before_cycle:]
if FLAGS.is_prioritized_replay or FLAGS.is_biased_prioritized_replay:
if self._is_accessed:
mean_priority = np.mean(self.priorities[self.accesses > 0])
else:
mean_priority = 1.
self.priorities[i0:i0+num_before_cycle] = mean_priority*np.ones([num_before_cycle])
if num_before_cycle < self._input_batch_size:
self.priorities[0:num_remaining] = mean_priority*np.ones([self._input_batch_size - num_before_cycle])
if FLAGS.is_self_competition:
self.labels[i0:i0+num_before_cycle] = labels[:num_before_cycle]
if num_remaining > 0:
self.labels[0:num_remaining] = labels[num_before_cycle:]
#self.past_losses[labels] = self.next_losses[labels]
#self.next_losses[labels] = losses
#self.mu1 = FLAGS.replay_decay*self.mu1 + (1-FLAGS.replay_decay)*np.mean(losses)
#self.mu2 = FLAGS.replay_decay*self.mu2 + (1-FLAGS.replay_decay)*np.mean(losses**2)
#self.std = np.sqrt(self.mu2 - self.mu1**2 + 1.e-3)
#diffs = losses - self.past_losses[labels]
#self.d_mu1 = FLAGS.replay_decay*self.d_mu1 + (1-FLAGS.replay_decay)*np.mean(diffs)
#self.d_mu2 = FLAGS.replay_decay*self.d_mu2 + (1-FLAGS.replay_decay)*np.mean(diffs**2)
#self.d_std = np.sqrt(self.d_mu2 - self.d_mu1**2 + 1.e-3)
self.position += self._input_batch_size
def loss_fn(self, next_loss, prev_loss):
mse_loss = next_loss#(next_loss - self.mu1) / self.std
#exp_loss = (next_loss - prev_loss - self.d_mu1) / self.d_std
loss = mse_loss#sigmoid(mse_loss) # sigmoid(exp_loss)
return loss
def get(self):
limit = min(self.position, self.buffer_size)
if FLAGS.is_prioritized_replay:
sample_idxs = np.random.choice(
self.indices,
size=self._batch_size,
replace=False,
p=self.priorities/np.sum(self.priorities)
) #alpha=1
beta = 0.5 + 0.5*(FLAGS.train_iters - self.position)/FLAGS.train_iters
sampled_priority_weights = self.priorities[sample_idxs]**( -beta )
sampled_priority_weights /= np.max(sampled_priority_weights)
elif FLAGS.is_biased_prioritized_replay:
alpha = 1#(FLAGS.train_iters - self.position)/FLAGS.train_iters
priorities = self.priorities**alpha
sample_idxs = np.random.choice(
self.indices,
size=self._batch_size,
replace=False,
p=self.priorities/np.sum(self.priorities)
)
else:
sample_idxs = np.random.randint(0, limit, size=self._batch_size)
sampled_actions = np.stack([self.actions[i] for i in sample_idxs])
sampled_observations = np.stack([self.observations[i] for i in sample_idxs])
sampled_full_scans = np.stack([self.full_scans[i] for i in sample_idxs])
if FLAGS.is_prioritized_replay:
return sampled_actions, sampled_observations, sample_idxs, sampled_priority_weights
#elif FLAGS.is_biased_prioritized_replay:
#return sampled_actions, sampled_observations, sample_idxs
elif FLAGS.is_self_competition:
sampled_labels = np.stack([self.labels[i] for i in sample_idxs])
sampled_past_losses = np.stack([self.next_losses[i] for i in sampled_labels])
return sampled_actions, sampled_observations, sample_idxs, sampled_past_losses, sampled_full_scans
else:
return sampled_actions, sampled_observations
def update_priorities(self, idxs, priorities):
"""For prioritized experience replay"""
self._is_accessed = True
self.priorities[idxs] = priorities
self.accesses[idxs] = 1.
class Agent(snt.AbstractModule):
def __init__(
self,
num_outputs,
name,
is_new=False,
noise_decay=None,
is_double_critic=False,
sampled_full_scans=None,
val_full_scans=None
):
super(Agent, self).__init__(name=name)
access_config = {
"memory_size": FLAGS.memory_size,
"word_size": FLAGS.word_size,
"num_reads": FLAGS.num_read_heads,
"num_writes": FLAGS.num_write_heads,
}
controller_config = {
"hidden_size": FLAGS.hidden_size,
#"projection_size": FLAGS.projection_size or None,
}
clip_value = FLAGS.clip_value
self.is_actor = "actor" in name
with self._enter_variable_scope():
components = dnc.Components(access_config, controller_config, num_outputs)
self._dnc_core = dnc.DNC(
components,
num_outputs,
clip_value,
is_new=False,
is_double_critic=is_double_critic,
is_actor=self.is_actor)
if is_new:
self._dnc_core_new = dnc.DNC(
components,
num_outputs,
clip_value,
is_new=True,
noise_decay=noise_decay,
sampled_full_scans=sampled_full_scans,
is_noise=True,
is_actor=self.is_actor
)
if not val_full_scans is None:
self._dnc_core_val = dnc.DNC(
components,
num_outputs,
clip_value,
is_new=True,
sampled_full_scans=val_full_scans,
is_actor=self.is_actor
)
self._initial_state = self._dnc_core.initial_state(FLAGS.batch_size)
self._new_start = self._dnc_core.initial_state(FLAGS.batch_size // FLAGS.avg_replays)
#self._action_embedder = snt.Linear(output_size=64)
#self._observation_embedder = snt.Linear(output_size=64)
def _build(self, observations, actions):
#Tiling here is a hack to make inputs the same size
num_tiles = 2 // (actions.get_shape().as_list()[-1] // FLAGS.num_actions)
tiled_actions = tf.tile(actions, [1, 1, num_tiles])
input_sequence = tf.concat([observations, tiled_actions], axis=-1)
self._dnc_core.first = True
output_sequence, _ = tf.nn.dynamic_rnn(
cell=self._dnc_core,
inputs=input_sequence,
time_major=False,
initial_state=self._initial_state
)
return output_sequence
def get_new_experience(self):
self._dnc_core_new.first = True
output_sequence, _ = tf.nn.dynamic_rnn(
cell=self._dnc_core_new,
inputs=tf.zeros([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, 1]),
time_major=False,
initial_state=self._new_start
)
if hasattr(tf, 'ensure_shape'):
output_sequence = tf.ensure_shape(
output_sequence,
[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size+FLAGS.num_actions])
else:
output_sequence = tf.reshape(
output_sequence,
[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size+FLAGS.num_actions])
observations = output_sequence[:,:,:FLAGS.step_size]
actions = output_sequence[:,:,FLAGS.step_size:]
return observations, actions
def get_val_experience(self):
self._dnc_core_val.first = True
output_sequence, _ = tf.nn.dynamic_rnn(
cell=self._dnc_core_val,
inputs=tf.zeros([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, 1]),
time_major=False,
initial_state=self._new_start
)
if hasattr(tf, 'ensure_shape'):
output_sequence = tf.ensure_shape(
output_sequence,
[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size+FLAGS.num_actions])
else:
output_sequence = tf.reshape(
output_sequence,
[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size+FLAGS.num_actions])
observations = output_sequence[:,:,:FLAGS.step_size]
actions = output_sequence[:,:,FLAGS.step_size:]
return observations, actions
@property
def variables(self):
with self._enter_variable_scope():
return tf.get_collection(
tf.GraphKeys.GLOBAL_VARIABLES,
scope=tf.get_variable_scope().name
)
@property
def trainable_variables(self):
with self._enter_variable_scope():
return tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES,
scope=tf.get_variable_scope().name
)
def spectral_norm(w, iteration=1, in_place_updates=False):
"""Spectral normalization. It imposes Lipschitz continuity by constraining the
spectral norm (maximum singular value) of weight matrices.
Inputs:
w: Weight matrix to spectrally normalize.
iteration: Number of times to apply the power iteration method to
enforce spectral norm.
Returns:
Weight matrix with spectral normalization control dependencies.
"""
w0 = w
w_shape = w.shape.as_list()
w = tf.reshape(w, [-1, w_shape[-1]])
u = tf.get_variable(auto_name("u"),
[1, w_shape[-1]],
initializer=tf.random_normal_initializer(mean=0.,stddev=0.03),
trainable=False)
u_hat = u
v_hat = None
for i in range(iteration):
"""
power iteration
Usually iteration = 1 will be enough
"""
v_ = tf.matmul(u_hat, tf.transpose(w))
v_hat = tf.nn.l2_normalize(v_)
u_ = tf.matmul(v_hat, w)
u_hat = tf.nn.l2_normalize(u_)
u_hat = tf.stop_gradient(u_hat)
v_hat = tf.stop_gradient(v_hat)
sigma = tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat))
if in_place_updates:
#In-place control dependencies bottlenect training
with tf.control_dependencies([u.assign(u_hat)]):
w_norm = w / sigma
w_norm = tf.reshape(w_norm, w_shape)
else:
#Execute control dependency in parallel with other update ops
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, u.assign(u_hat))
w_norm = w / sigma
w_norm = tf.reshape(w_norm, w_shape)
return w_norm
def spectral_norm_conv(
inputs,
num_outputs,
stride=1,
kernel_size=3,
padding='VALID',
biases_initializer=tf.zeros_initializer()
):
"""Convolutional layer with spectrally normalized weights."""
w = tf.get_variable(auto_name("kernel"), shape=[kernel_size, kernel_size, inputs.get_shape()[-1], num_outputs])
x = tf.nn.conv2d(input=inputs, filter=spectral_norm(w),
strides=[1, stride, stride, 1], padding=padding)
if biases_initializer != None:
b = tf.get_variable(auto_name("bias"), [num_outputs], initializer=biases_initializer)
x = tf.nn.bias_add(x, b)
return x
def conv(
inputs,
num_outputs,
kernel_size=3,
stride=1,
padding='SAME',
data_format="NHWC",
actv_fn=tf.nn.relu,
is_batch_norm=True,
is_spectral_norm=False,
is_depthwise_sep=False,
extra_batch_norm=False,
biases_initializer=tf.zeros_initializer,
weights_initializer=initializers.xavier_initializer,
transpose=False,
is_training=True
):
"""Convenience function for a strided convolutional or transpositional
convolutional layer.
Intro: https://towardsdatascience.com/intuitively-understanding-convolutions-for-deep-learning-1f6f42faee1.
The order is: Activation (Optional) -> Batch Normalization (optional) -> Convolutions.
Inputs:
inputs: Tensor of shape `[batch_size, height, width, channels]` to apply
convolutions to.
num_outputs: Number of feature channels to output.
kernel_size: Side lenth of square convolutional kernels.
stride: Distance between convolutional kernel applications.
padding: 'SAME' for zero padding where kernels go over the edge.
'VALID' to discard features where kernels go over the edge.
activ_fn: non-linearity to apply after summing convolutions.
is_batch_norm: If True, add batch normalization after activation.
is_spectral_norm: If True, spectrally normalize weights.
is_depthwise_sep: If True, depthwise separate convolutions into depthwise
spatial convolutions, then 1x1 pointwise convolutions.
extra_batch_norm: If True and convolutions are depthwise separable, implement
batch normalization between depthwise and pointwise convolutions.
biases_initializer: Function to initialize biases with. None for no biases.
weights_initializer: Function to initialize weights with. None for no weights.
transpose: If True, apply convolutional layer transpositionally to the
described convolutional layer.
is_training: If True, use training specific operations e.g. batch normalization
update ops.
Returns:
Output of convolutional layer.
"""
x = inputs
num_spatial_dims = len(x.get_shape().as_list()) - 2
if biases_initializer == None:
biases_initializer = lambda: None
if weights_initializer == None:
weights_initializer = lambda: None
if not is_spectral_norm:
#Convolutional layer without spectral normalization
if transpose:
stride0 = 1
if type(stride) == list or is_depthwise_sep or stride % 1:
#Apparently there is no implementation of transpositional
#depthwise separable convolutions, so bilinearly upsample then
#depthwise separably convolute
if kernel_size != 1:
x = tf.image.resize_bilinear(
images=x,
size=stride if type(stride) == list else \
[int(stride*d) for d in x.get_shape().as_list()[1:3]],
align_corners=True
)
stride0 = stride
stride = 1
if type(stride0) == list and not is_depthwise_sep:
layer = tf.contrib.layers.conv2d
elif is_depthwise_sep:
layer = tf.contrib.layers.separable_conv2d
else:
layer = tf.contrib.layers.conv2d_transpose
x = layer(
inputs=x,
num_outputs=num_outputs,
kernel_size=kernel_size,
stride=stride,
padding=padding,
data_format=data_format,
activation_fn=None,
weights_initializer=weights_initializer(),
biases_initializer=biases_initializer())
if type(stride0) != list:
if (is_depthwise_sep or stride0 % 1) and kernel_size == 1:
x = tf.image.resize_bilinear(
images=x,
size=[int(stride0*d) for d in x.get_shape().as_list()[1:3]],
align_corners=True
)
else:
if num_spatial_dims == 1:
layer = tf.contrib.layers.conv1d
elif num_spatial_dims == 2:
if is_depthwise_sep:
layer = tf.contrib.layers.separable_conv2d
else:
layer = tf.contrib.layers.conv2d
x = layer(
inputs=x,
num_outputs=num_outputs,
kernel_size=kernel_size,
stride=stride,
padding=padding,
data_format=data_format,
activation_fn=None,
weights_initializer=weights_initializer(),
biases_initializer=biases_initializer())
else:
#Weights are spectrally normalized
x = spectral_norm_conv(
inputs=x,
num_outputs=num_outputs,
stride=stride,
kernel_size=kernel_size,
padding=padding,
biases_initializer=biases_initializer())
if actv_fn:
x = actv_fn(x)
if is_batch_norm and FLAGS.use_batch_norm:
x = tf.contrib.layers.batch_norm(x, is_training=is_training)
#x = l1_batch_norm(x)
return x
def residual_block(inputs, skip=3, is_training=True):
"""Residual block whre the input is added to the signal after skipping some
layers. This architecture is good for learning purturbative transformations.
If no layer is provided, it defaults to a convolutional layer.
Deep residual learning: https://arxiv.org/abs/1512.03385.
Inputs:
inputs: Tensor to apply residual block to. Outputs of every layer will
have the same shape.
skip: Number of layers to skip before adding input to layer output.
layer: Layer to apply in residual block. Defaults to convolutional
layer. Custom layers must support `inputs`, `num_outputs` and `is_training`
arguments.
Returns:
Final output of residual block.
"""
x = x0 = inputs
def layer(inputs, num_outputs, is_training, is_batch_norm, actv_fn):
x = conv(
inputs=inputs,
num_outputs=num_outputs,
is_training=is_training,
actv_fn=actv_fn
)
return x
for i in range(skip):
x = layer(
inputs=x,
num_outputs=x.get_shape()[-1],
is_training=is_training,
is_batch_norm=i < skip - 1,
actv_fn=tf.nn.relu
)
x += x0
if FLAGS.use_batch_norm:
x = tf.contrib.layers.batch_norm(x, is_training=is_training)
#x = l1_batch_norm(x)
return x
class Discriminator(snt.AbstractModule):
def __init__(self,
name,
is_training
):
super(Discriminator, self).__init__(name=name)
self._is_training = is_training
def _build(self, inputs):
x = inputs
std_actv = tf.nn.relu#lambda x: tf.nn.leaky_relu(x, alpha=0.1)
is_training = self._is_training
is_depthwise_sep = False
base_size = 32
for i in range(0, 5):
x = conv(
x,
num_outputs=base_size*2**i,
kernel_size=4,
stride=2,
is_depthwise_sep=is_depthwise_sep,
is_training=is_training,
actv_fn=std_actv
)
x = tf.layers.flatten(x)
x = tf.layers.dense(x, 1)
x = tf.contrib.layers.batch_norm(x, is_training=is_training)
return x
@property
def variables(self):
with self._enter_variable_scope():
return tf.get_collection(
tf.GraphKeys.GLOBAL_VARIABLES,
scope=tf.get_variable_scope().name
)
@property
def trainable_variables(self):
with self._enter_variable_scope():
return tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES,
scope=tf.get_variable_scope().name
)
class Generator(snt.AbstractModule):
def __init__(self,
name,
is_training
):
super(Generator, self).__init__(name=name)
self._is_training = is_training
def _build(self, inputs):
x = inputs
std_actv = tf.nn.relu#lambda x: tf.nn.leaky_relu(x, alpha=0.1)
is_training = self._is_training
is_depthwise_sep = False
base_size = 32
#x = tf.contrib.layers.batch_norm(x, is_training=is_training)
x = conv(
x,
num_outputs=32,
is_training=is_training,
actv_fn=std_actv
)
#Encoder
for i in range(1, 3):
x = conv(
x,
num_outputs=base_size*2**i,
stride=2,
is_depthwise_sep=is_depthwise_sep,
is_training=is_training,
actv_fn=std_actv
)
if i == 2:
low_level = x
#Residual blocks
for _ in range(5): #Number of blocks
x = residual_block(
x,
skip=3,
is_training=is_training
)