-
Notifications
You must be signed in to change notification settings - Fork 1
/
variational_mdp.py
2338 lines (2068 loc) · 112 KB
/
variational_mdp.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
import os
from collections import namedtuple
import enum
from enum import Enum
from typing import Tuple, Optional, Callable, Dict, Iterator, NamedTuple, List
import numpy as np
import psutil
from absl import logging
import threading
from tf_agents.environments.wrappers import TimeLimit
from keras.saving.saved_model import utils
from reinforcement_learning.environments.latent_environment import LatentEmbeddingTFEnvironmentWrapper
from reinforcement_learning.environments.no_reward_shaping import NoRewardShapingWrapper
from reinforcement_learning.environments.perturbed_env import PerturbedEnvironment
from util.io.video import VideoEmbeddingObserver
from verification.model import TransitionFnDecorator
try:
import reverb
except ImportError as ie:
print(ie, "Reverb is not installed on your system, "
"meaning prioritized experience replay cannot be used.")
import time
import datetime
import gc
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow.python.keras import Model
from tensorflow.python.keras.layers import Input, Concatenate, Reshape, Dense, Lambda
from tensorflow.keras.utils import Progbar
import tf_agents.policies.tf_policy
import tf_agents.agents.tf_agent
from tensorflow.keras.layers import TimeDistributed, Flatten, LSTM
from tensorflow.python.keras.models import Sequential
from tf_agents import specs, trajectories
from tf_agents.policies import tf_policy, py_tf_eager_policy, policy_saver
from tf_agents.trajectories import time_step as ts
from tf_agents.drivers import dynamic_step_driver, py_driver
from tf_agents.environments import tf_py_environment, parallel_py_environment, tf_environment, py_environment
from tf_agents.replay_buffers import tf_uniform_replay_buffer, reverb_replay_buffer, reverb_utils
from tf_agents.trajectories import trajectory
from tf_agents.trajectories.policy_step import PolicyStep
from tf_agents.trajectories.trajectory import Trajectory
from policies.latent_policy import LatentPolicyOverRealStateAndActionSpaces
from policies.time_stacked_states import TimeStackedStatesPolicyWrapper
from policies.epsilon_mimic import EpsilonMimicPolicy
from reinforcement_learning.environments import EnvironmentLoader
from util.io import dataset_generator
from util.io.dataset_generator import reset_state, map_rl_trajectory_to_vae_input, ergodic_batched_labeling_function
from util.io.dataset_generator import ErgodicMDPTransitionGenerator
from util.replay_buffer_tools import PriorityBuckets, LossPriority, PriorityHandler
from verification.local_losses import estimate_local_losses_from_samples
import tensorflow_probability.python.distributions as tfd
import tensorflow_probability.python.bijectors as tfb
debug = False
debug_verbosity = -1
debug_gradients = False
check_numerics = False
if check_numerics:
tf.debugging.enable_check_numerics(stack_height_limit=150)
epsilon = 1e-12
class DatasetComponents(NamedTuple):
replay_buffer: tf_agents.replay_buffers.replay_buffer.ReplayBuffer
driver: tf_agents.drivers.py_driver.PyDriver
initial_collect_driver: tf_agents.drivers.py_driver.PyDriver
close_fn: Callable
replay_buffer_num_frames_fn: Callable[[], int]
wrapped_manager: Optional[tf.train.CheckpointManager]
dataset: tf.data.Dataset
dataset_iterator: Iterator
epsilon_greedy: tf.Variable
class EvaluationCriterion(Enum):
MAX = enum.auto()
MEAN = enum.auto()
class VariationalMarkovDecisionProcess(tf.Module):
def __init__(
self,
state_shape: Tuple[int, ...],
action_shape: Tuple[int, ...],
reward_shape: Tuple[int, ...],
label_shape: Tuple[int, ...],
encoder_network: Model,
transition_network: Model,
reward_network: Model,
decoder_network: Model,
label_transition_network: Optional[Model] = None,
latent_policy_network: Optional[Model] = None,
state_encoder_pre_processing_network: Optional[Model] = None,
state_decoder_pre_processing_network: Optional[Model] = None,
time_stacked_states: bool = False,
latent_state_size: int = 12,
encoder_temperature: float = 2. / 3,
prior_temperature: float = 1. / 2,
encoder_temperature_decay_rate: float = 0.,
prior_temperature_decay_rate: float = 0.,
entropy_regularizer_scale_factor: float = 0.,
entropy_regularizer_decay_rate: float = 0.,
entropy_regularizer_scale_factor_min_value: float = 0.,
marginal_entropy_regularizer_ratio: float = 0.,
kl_scale_factor: float = 1.,
kl_annealing_growth_rate: float = 0.,
mixture_components: int = 3,
max_decoder_variance: Optional[float] = None,
multivariate_normal_raw_scale_diag_activation: Callable[[tf.Tensor], tf.Tensor] = tf.nn.softplus,
multivariate_normal_full_covariance: bool = False,
pre_loaded_model: bool = False,
reset_state_label: bool = True,
latent_policy_training_phase: bool = False,
full_optimization: bool = True,
optimizer: Optional = None,
evaluation_window_size: int = 5,
evaluation_criterion: EvaluationCriterion = EvaluationCriterion.MAX,
action_label_transition_network: Optional[Model] = None,
action_transition_network: Optional[Model] = None,
importance_sampling_exponent: Optional[float] = 1.,
importance_sampling_exponent_growth_rate: Optional[float] = 0.,
time_stacked_lstm_units: int = 128,
reward_bounds: Optional[Tuple[float, float]] = None,
deterministic_state_embedding: bool = True,
):
super(VariationalMarkovDecisionProcess, self).__init__()
self.state_shape = state_shape
self.action_shape = action_shape
self.reward_shape = reward_shape
self.latent_state_size = latent_state_size
self.label_shape = label_shape
self.atomic_prop_dims = np.prod(label_shape) + int(reset_state_label)
self.mixture_components = mixture_components
self.full_covariance = multivariate_normal_full_covariance
self.latent_policy_training_phase = latent_policy_training_phase
self.full_optimization = full_optimization
self._optimizer = optimizer
self.time_stacked_states = time_stacked_states
self.time_stacked_lstm_units = time_stacked_lstm_units
self.deterministic_state_embedding = deterministic_state_embedding
# initialize all tf variables
self._entropy_regularizer_scale_factor = None
self._kl_scale_factor = None
self._initial_kl_scale_factor = None
self._kl_scale_factor_decay = None
self._is_exponent = None
self._initial_is_exponent = None
self._is_exponent_decay = None
self._is_exponent_growth_rate = None
self.encoder_temperature = encoder_temperature
self.prior_temperature = prior_temperature
self.entropy_regularizer_scale_factor = (
entropy_regularizer_scale_factor - entropy_regularizer_scale_factor_min_value)
self.kl_scale_factor = kl_scale_factor
self.encoder_temperature_decay_rate = encoder_temperature_decay_rate
self.prior_temperature_decay_rate = prior_temperature_decay_rate
self.entropy_regularizer_decay_rate = entropy_regularizer_decay_rate
self.kl_growth_rate = kl_annealing_growth_rate
self.max_decoder_variance = max_decoder_variance
self.is_exponent = importance_sampling_exponent
self.is_exponent_growth_rate = importance_sampling_exponent_growth_rate
self.scale_activation = multivariate_normal_raw_scale_diag_activation
self.entropy_regularizer_scale_factor_min_value = tf.constant(entropy_regularizer_scale_factor_min_value)
self.marginal_entropy_regularizer_ratio = marginal_entropy_regularizer_ratio
self.number_of_discrete_actions = -1 # only used if a latent policy network is provided
state = Input(shape=state_shape, name="state")
action = Input(shape=action_shape, name="action")
self._encoder_softclip = tfb.SoftClip(low=-10., high=10.) # , hinge_softness=10.)
if reward_bounds is not None:
if len(reward_bounds) != 2 or reward_bounds[0] > reward_bounds[1]:
raise ValueError("Please provide valid reward bounds."
"Values provided: {}".format(str(reward_bounds)))
self._reward_softclip = tfb.SoftClip(low=reward_bounds[0], high=reward_bounds[1])
else:
self._reward_softclip = None
# the evaluation window contains eiter the N max evaluation scores encountered during training if the evaluation
# criterion is MAX, or the N last evaluation scores encountered if the evaluation criterion is MEAN.
self.evaluation_criterion = evaluation_criterion
self._evaluation_window = tf.Variable(
initial_value=-1. * np.inf * tf.ones(shape=(evaluation_window_size,)),
trainable=False,
name='evaluation_window')
self._sample_additional_transition = False
self.priority_handler = None
if not pre_loaded_model:
# Encoder network
if time_stacked_states:
if state_encoder_pre_processing_network is not None:
encoder = TimeDistributed(state_encoder_pre_processing_network)(state)
else:
encoder = state
encoder = LSTM(units=time_stacked_lstm_units)(encoder)
encoder = encoder_network(encoder)
else:
if state_encoder_pre_processing_network is not None:
_state = state_encoder_pre_processing_network(state)
else:
_state = state
encoder = encoder_network(_state)
logits_layer = Dense(
units=latent_state_size - self.atomic_prop_dims,
# allows avoiding exploding logits values and probability errors after applying a sigmoid
activation=lambda x: self._encoder_softclip(x),
name='encoder_latent_distribution_logits'
)(encoder)
self.encoder_network = Model(
inputs=state,
outputs=logits_layer,
name='state_encoder')
# Latent policy network
latent_state = Input(shape=(latent_state_size,), name="latent_state")
if latent_policy_network is not None:
self.latent_policy_network = latent_policy_network(latent_state)
# we assume actions to be discrete and given in one hot when using a latent policy network
assert len(self.action_shape) == 1
self.number_of_discrete_actions = self.action_shape[0]
self.latent_policy_network = Dense(
units=self.number_of_discrete_actions,
activation=None,
name='latent_policy_one_hot_logits'
)(self.latent_policy_network)
self.latent_policy_network = Model(
inputs=latent_state,
outputs=self.latent_policy_network,
name='latent_policy_network')
else:
self.latent_policy_network = None
self.number_of_discrete_actions = -1
# Transition network
# inputs are binary concrete random variables, outputs are locations of logistic distributions
next_label = Input(shape=(self.atomic_prop_dims,), name='next_label')
if self.number_of_discrete_actions != -1:
if label_transition_network is not None:
transition_network_input = Concatenate(name='transition_network_input')(
[latent_state, next_label])
else:
transition_network_input = latent_state
_transition_network = transition_network(transition_network_input)
no_latent_state_logits = latent_state_size - self.atomic_prop_dims
transition_output_layer = Dense(
units=no_latent_state_logits * self.number_of_discrete_actions,
activation=None,
name='transition_network_raw_output_layer'
)(_transition_network)
transition_output_layer = Reshape(
target_shape=(no_latent_state_logits, self.number_of_discrete_actions),
name='transition_network_output_layer_reshape'
)(transition_output_layer)
action_transition_output = transition_output_layer
_action = tf.keras.layers.RepeatVector(
int(no_latent_state_logits), name='transition_output_repeat_action')(action)
transition_output_layer = tf.keras.layers.Multiply(name="multiply_action_transition")(
[_action, transition_output_layer])
transition_output_layer = Lambda(
lambda x: tf.reduce_sum(x, axis=-1),
name='transition_logits_reduce_sum_action_mask_layer'
)(transition_output_layer)
else:
if label_transition_network is not None:
transition_network_input = Concatenate(
name="transition_network_input")([latent_state, action, next_label])
else:
transition_network_input = Concatenate(
name="transition_network_input")([latent_state, action])
_transition_network = transition_network(transition_network_input)
action_transition_output = None
transition_output_layer = Dense(
units=latent_state_size - self.atomic_prop_dims,
activation=None,
name='latent_transition_distribution_logits'
)(_transition_network)
# Label transition network
# Gives logits of a Bernoulli distribution giving the probability of the next label given the
# current latent state and the action chosen
if self.number_of_discrete_actions != -1:
if label_transition_network is not None:
_label_transition_network = label_transition_network(latent_state)
else:
_label_transition_network = _transition_network
_label_transition_network = Dense(
units=self.atomic_prop_dims * self.number_of_discrete_actions,
activation=None,
name="label_transition_network_raw_output_layer"
)(_label_transition_network)
_label_transition_network = Reshape(
target_shape=(self.atomic_prop_dims, self.number_of_discrete_actions),
name='reshape_label_transition_output'
)(_label_transition_network)
self.action_label_transition_network = Model(
inputs=latent_state,
outputs=_label_transition_network,
name='action_label_transition_network')
self.action_transition_network = Model(
inputs=[latent_state, next_label] if label_transition_network is not None else latent_state,
outputs=(action_transition_output if label_transition_network is not None else
[_label_transition_network, action_transition_output]),
name="action_transition_network")
_action = tf.keras.layers.RepeatVector(
int(self.atomic_prop_dims),
name='label_transition_output_repeat_action')(action)
_label_transition_network = tf.keras.layers.Multiply()([_action, _label_transition_network])
_label_transition_network = Lambda(
lambda x: tf.reduce_sum(x, axis=-1),
name='label_transition_reduce_sum_action_mask_layer'
)(_label_transition_network)
else:
if label_transition_network is not None:
label_transition_network_input = Concatenate(
name="label_transition_network_input")([latent_state, action])
_label_transition_network = label_transition_network(label_transition_network_input)
else:
_label_transition_network = _transition_network
_label_transition_network = Dense(
units=self.atomic_prop_dims,
activation=None,
name='next_label_transition_logits'
)(_label_transition_network)
self.label_transition_network = Model(
inputs=[latent_state, action],
outputs=_label_transition_network,
name='label_transition_network')
self.transition_network = Model(
inputs=([latent_state, action, next_label] if label_transition_network is not None else
[latent_state, action]),
outputs=(transition_output_layer if label_transition_network is not None else
[_label_transition_network, transition_output_layer]),
name="transition_network")
# Reward network
next_latent_state = Input(shape=(latent_state_size,), name="next_latent_state")
if self.number_of_discrete_actions != -1:
reward_network_input = Concatenate(name="reward_network_input")(
[latent_state, next_latent_state])
_reward_network = reward_network(reward_network_input)
reward_mean = Dense(
units=np.prod(reward_shape) * self.number_of_discrete_actions,
activation=None if self._reward_softclip is None else lambda x: self._reward_softclip(x),
name='reward_mean_raw_output')(_reward_network)
reward_mean = Reshape(target_shape=(reward_shape + (self.number_of_discrete_actions,)))(reward_mean)
_action = tf.keras.layers.RepeatVector(int(np.prod(reward_shape)))(action)
_action = Reshape(target_shape=(reward_shape + (self.number_of_discrete_actions,)))(_action)
reward_mean = tf.keras.layers.Multiply(name="multiply_action_reward_stack")(
[_action, reward_mean])
reward_mean = Lambda(
lambda x: tf.reduce_sum(x, axis=-1), name='reward_mean_reduce_sum_action_mask_layer'
)(reward_mean)
reward_raw_covar = Dense(
units=np.prod(reward_shape) * self.number_of_discrete_actions,
activation=None,
name='reward_covar_raw_output')(_reward_network)
reward_raw_covar = Reshape(
target_shape=reward_shape + (self.number_of_discrete_actions,))(reward_raw_covar)
reward_raw_covar = tf.keras.layers.Multiply(
name='multiply_action_raw_covar_stack')([_action, reward_raw_covar])
reward_raw_covar = Lambda(
lambda x: tf.reduce_sum(x, axis=-1),
name='reward_raw_covar_reduce_sum_action_mask_layer'
)(reward_raw_covar)
else:
reward_network_input = Concatenate(name="reward_network_input")(
[latent_state, action, next_latent_state])
_reward_network = reward_network(reward_network_input)
reward_mean = Dense(
units=np.prod(reward_shape),
activation=None if self._reward_softclip is None else lambda x: self._reward_softclip(x),
name='reward_mean_0')(_reward_network)
reward_raw_covar = Dense(
units=np.prod(reward_shape),
activation=None,
name='state_reward_raw_diag_covariance_0'
)(_reward_network)
reward_mean = Reshape(reward_shape, name='reward_mean')(reward_mean)
reward_raw_covar = Reshape(
reward_shape, name='reward_raw_diag_covariance')(reward_raw_covar)
self.reward_network = Model(
inputs=[latent_state, action, next_latent_state],
outputs=[reward_mean, reward_raw_covar],
name='reward_network')
# Reconstruction network
decoder = decoder_network(next_latent_state)
if time_stacked_states:
time_dimension = state_shape[0]
_state_shape = state_shape[1:]
if decoder.shape[-1] % time_dimension != 0:
decoder = Dense(
units=decoder.shape[-1] + time_dimension - decoder.shape[-1] % time_dimension)(decoder)
decoder = Reshape(target_shape=(time_dimension, decoder.shape[-1] // time_dimension))(decoder)
decoder = LSTM(units=self.time_stacked_lstm_units, return_sequences=True)(decoder)
if state_decoder_pre_processing_network is not None:
decoder = TimeDistributed(state_decoder_pre_processing_network)(decoder)
else:
if state_decoder_pre_processing_network is not None:
decoder = state_decoder_pre_processing_network(decoder)
_state_shape = state_shape
# 1 mean per dimension, nb Normal Gaussian
decoder_output_mean = Sequential([
Dense(
units=mixture_components * np.prod(_state_shape),
activation=None,
name='state_decoder_GMM_mean_0'),
Reshape(
target_shape=(mixture_components,) + _state_shape,
name="state_decoder_GMM_mean")],
name="state_decoder_mean")
if self.full_covariance and len(_state_shape) == 1:
d = np.prod(_state_shape) * (np.prod(_state_shape) + 1) / 2
decoder_raw_output = Sequential([
Dense(
units=mixture_components * d,
activation=None,
name='state_decoder_GMM_tril_params_0'),
Reshape(
target_shape=(mixture_components, d,),
name='state_decoder_GMM_tril_params_1'),
Lambda(
lambda x: tfb.FillScaleTriL()(x),
name='state_decoder_GMM_scale_tril')],
name='state_decoder_scale_tril')
else:
# n diagonal co-variance matrices
decoder_raw_output = Sequential([
Dense(
units=mixture_components * np.prod(_state_shape),
activation=None,
name='state_decoder_GMM_raw_diag_covariance_0'),
Reshape(
(mixture_components,) + _state_shape,
name="state_decoder_GMM_raw_diag_covar")],
name='state_decoder_raw_diag_covar')
# prior distribution over the mixture components
decoder_prior = Sequential([
Dense(
units=mixture_components,
activation='softmax',
name="state_decoder_GMM_priors")])
if time_stacked_states:
decoder_output_mean = TimeDistributed(decoder_output_mean)(decoder)
decoder_raw_output = TimeDistributed(decoder_raw_output)(decoder)
decoder_prior = TimeDistributed(decoder_prior)(decoder)
else:
decoder_output_mean = decoder_output_mean(decoder)
decoder_raw_output = decoder_raw_output(decoder)
decoder_prior = decoder_prior(decoder)
self.reconstruction_network = Model(
inputs=next_latent_state,
outputs=[decoder_output_mean, decoder_raw_output, decoder_prior],
name='state_reconstruction_network')
else:
self.encoder_network = encoder_network
self.transition_network = transition_network
self.label_transition_network = label_transition_network
self.reward_network = reward_network
self.reconstruction_network = decoder_network
self.latent_policy_network = latent_policy_network
self.number_of_discrete_actions = self.action_shape[0] if self.latent_policy_network is not None else -1
self.action_label_transition_network = action_label_transition_network
self.action_transition_network = action_transition_network
self.loss_metrics = {
'ELBO': tf.keras.metrics.Mean(name='ELBO'),
'state_mse': tf.keras.metrics.MeanSquaredError(name='state_mse'),
'reward_mse': tf.keras.metrics.MeanSquaredError(name='reward_mse'),
'distortion': tf.keras.metrics.Mean(name='distortion'),
'rate': tf.keras.metrics.Mean(name='rate'),
# 'annealed_rate': tf.keras.metrics.Mean(name='annealed_rate'),
'entropy_regularizer': tf.keras.metrics.Mean(name='entropy_regularizer'),
'encoder_entropy': tf.keras.metrics.Mean(name='encoder_entropy'),
'marginal_encoder_entropy': tf.keras.metrics.Mean(name='marginal_encoder_entropy'),
'transition_log_probs': tf.keras.metrics.Mean(name='transition_log_probs'),
# 'decoder_variance': tf.keras.metrics.Mean(name='decoder_variance')
}
self.temperature_metrics = {
't_1': self.encoder_temperature,
't_2': self.prior_temperature}
self._dynamic_reward_scaling = tf.Variable(1., trainable=False)
def reset_metrics(self):
for value in self.loss_metrics.values():
value.reset_states()
# super().reset_metrics()
def attach_optimizer(self, optimizer):
self._optimizer = optimizer
def detach_optimizer(self):
optimizer = self._optimizer
self._optimizer = None
return optimizer
def relaxed_state_encoding(
self, state: tf.Tensor, temperature: float, label: Optional[tf.Tensor] = None, *args, **kwargs
) -> tfd.Distribution:
"""
Embed the input state and its label (if given) into a Binary Concrete probability distribution over
a relaxed binary latent representation of the latent state space.
Note: the Binary Concrete distribution is replaced by a Logistic distribution to avoid underflow issues:
z ~ BinaryConcrete(logits, temperature) = sigmoid(z_logistic)
with z_logistic ~ Logistic(loc=logits/temperature, scale=1./temperature))
"""
logits = self.encoder_network(state)
if label is not None:
logits = tf.concat([(label * 2. - 1.) * 1e2, logits], axis=-1)
return tfd.Independent(
tfd.Logistic(
loc=logits / temperature,
scale=1. / temperature,
allow_nan_stats=False, ))
def binary_encode_state(self, state: tf.Tensor, label: Optional[tf.Tensor] = None) -> tfd.Distribution:
"""
Embed the input state and its label (if given) into a Bernoulli probability distribution over the binary
representation of the latent state space.
"""
logits = self.encoder_network(state)
if label is not None:
logits = tf.concat([(label * 2. - 1.) * 1e2, logits], axis=-1)
return tfd.Independent(
tfd.Bernoulli(
logits=logits,
allow_nan_stats=False))
def decode_state(self, latent_state: tf.Tensor) -> tfd.Distribution:
"""
Decode a binary latent state to a probability distribution over states of the original MDP.
"""
[
reconstruction_mean, reconstruction_raw_covariance, reconstruction_prior_components
] = self.reconstruction_network(latent_state)
if self.max_decoder_variance is None:
reconstruction_raw_covariance = self.scale_activation(reconstruction_raw_covariance)
else:
reconstruction_raw_covariance = tfp.bijectors.SoftClip(
low=epsilon, high=self.max_decoder_variance ** 0.5).forward(reconstruction_raw_covariance)
if self.mixture_components == 1:
reconstruction_mean = (reconstruction_mean[:, 0, ...] if not self.time_stacked_states
else reconstruction_mean[:, :, 0, ...])
reconstruction_raw_covariance = (reconstruction_raw_covariance[:, 0, ...] if not self.time_stacked_states
else reconstruction_raw_covariance[:, :, 0, ...])
if self.full_covariance:
decoder_distribution = tfd.MultivariateNormalTriL(
loc=reconstruction_mean,
scale_tril=reconstruction_raw_covariance,
allow_nan_stats=False, )
else:
decoder_distribution = tfd.MultivariateNormalDiag(
loc=reconstruction_mean,
scale_diag=reconstruction_raw_covariance,
allow_nan_stats=False)
else:
if self.full_covariance:
decoder_distribution = tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(probs=reconstruction_prior_components),
components_distribution=tfd.MultivariateNormalTriL(
loc=reconstruction_mean,
scale_tril=reconstruction_raw_covariance,
allow_nan_stats=False
),
allow_nan_stats=False)
else:
decoder_distribution = tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(probs=reconstruction_prior_components),
components_distribution=tfd.MultivariateNormalDiag(
loc=reconstruction_mean,
scale_diag=reconstruction_raw_covariance,
allow_nan_stats=False
),
allow_nan_stats=False)
if self.time_stacked_states:
return tfd.Independent(decoder_distribution)
else:
return decoder_distribution
def relaxed_markov_chain_latent_transition(
self, latent_state: tf.Tensor, temperature: float = 1e-5) -> tfd.Distribution:
if self._has_dedicated_label_transition_network:
next_label_logits = self.action_label_transition_network(latent_state)
next_state_logits = lambda _next_label: self.action_transition_network([latent_state, _next_label])
else:
next_label_logits, _next_state_logits = self.action_transition_network(latent_state)
next_state_logits = lambda _: _next_state_logits
return tfd.JointDistributionSequential([
tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(logits=self.latent_policy_network(latent_state)),
components_distribution=tfd.Independent(
tfd.Bernoulli(
logits=tf.transpose(next_label_logits, perm=[0, 2, 1]),
allow_nan_stats=False, ),
reinterpreted_batch_ndims=1),
allow_nan_stats=False,
), lambda _next_label: tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(logits=self.latent_policy_network(latent_state)),
components_distribution=tfd.Independent(tfd.Logistic(
loc=tf.transpose(next_state_logits(_next_label), perm=[0, 2, 1]) / temperature,
scale=1. / temperature,
allow_nan_stats=False, ), reinterpreted_batch_ndims=1),
allow_nan_stats=False)])
def relaxed_latent_transition(
self, latent_state: tf.Tensor, action: tf.Tensor, next_label: Optional[tf.Tensor] = None,
temperature: float = 1e-5, *args, **kwargs
) -> tfd.Distribution:
"""
Retrieves a Binary Concrete probability distribution P(z'|z, a) over successor latent states, given a latent
state z given in relaxed binary representation and an action a.
Note: the Binary Concrete distribution is replaced by a Logistic distribution to avoid underflow issues:
z ~ BinaryConcrete(logits, temperature) = sigmoid(z_logistic)
with z_logistic ~ Logistic(loc=logits / temperature, scale=1. / temperature))
"""
if self._has_dedicated_label_transition_network:
next_label_logits = self.label_transition_network([latent_state, action])
next_state_logits = lambda _next_label: self.transition_network([latent_state, action, _next_label])
else:
next_label_logits, _next_state_logits = self.transition_network([latent_state, action])
next_state_logits = lambda _: _next_state_logits
if next_label is not None:
_next_state_logits = next_state_logits(next_label)
return tfd.Independent(
tfd.Logistic(
loc=_next_state_logits / temperature,
scale=1. / temperature,
allow_nan_stats=False),
allow_nan_stats=False, )
else:
return tfd.JointDistributionSequential([
tfd.Independent(
tfd.Bernoulli(
logits=next_label_logits,
allow_nan_stats=False,
name='label_transition_distribution'),
allow_nan_stats=False),
lambda _next_label: tfd.Independent(
tfd.Logistic(
loc=next_state_logits(_next_label) / temperature,
scale=1. / temperature,
allow_nan_stats=False),
allow_nan_stats=False)],
allow_nan_stats=False)
def discrete_markov_chain_latent_transition(
self, latent_state: tf.Tensor) -> tfd.Distribution:
if self._has_dedicated_label_transition_network:
next_label_logits = self.action_label_transition_network(latent_state)
next_state_logits = lambda _next_label: self.action_transition_network([latent_state, _next_label])
else:
next_label_logits, _next_state_logits = self.action_transition_network(latent_state)
next_state_logits = lambda _: _next_state_logits
return tfd.JointDistributionSequential([
tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(logits=self.latent_policy_network(latent_state)),
components_distribution=tfd.Independent(
tfd.Bernoulli(
logits=tf.transpose(next_label_logits, perm=[0, 2, 1]),
dtype=tf.float32,
allow_nan_stats=False),
reinterpreted_batch_ndims=1)
), lambda _next_label: tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(logits=self.latent_policy_network(latent_state)),
components_distribution=tfd.Independent(tfd.Bernoulli(
logits=tf.transpose(next_state_logits(_next_label), perm=[0, 2, 1]),
allow_nan_stats=False), reinterpreted_batch_ndims=1))])
def discrete_latent_transition(
self, latent_state: tf.Tensor, action: tf.Tensor, next_label: Optional[tf.Tensor] = None
) -> tfd.Distribution:
"""
Retrieves a Bernoulli probability distribution P(z'|z, a) over successor latent states, given a binary latent
state z and an action a.
"""
if self._has_dedicated_label_transition_network:
next_label_logits = self.label_transition_network([latent_state, action])
next_state_logits = lambda _next_label: self.transition_network([latent_state, action, _next_label])
else:
next_label_logits, _next_state_logits = self.transition_network([latent_state, action])
next_state_logits = lambda _: _next_state_logits
if next_label is not None:
_next_state_logits = next_state_logits(next_label)
return tfd.Independent(tfd.Bernoulli(logits=_next_state_logits, allow_nan_stats=False))
else:
return tfd.JointDistributionSequential([
tfd.Independent(tfd.Bernoulli(
logits=next_label_logits,
allow_nan_stats=False,
dtype=tf.float32)),
lambda _next_label: tfd.Independent(
tfd.Bernoulli(
logits=next_state_logits(_next_label),
allow_nan_stats=False))])
def reward_distribution(
self, latent_state: tf.Tensor, action: tf.Tensor, next_latent_state: tf.Tensor) -> tfd.Distribution:
"""
Retrieves a probability distribution P(r|z, a, z') over the rewards obtained when the transition z, a, z'
has been performed.
"""
[reward_mean, reward_raw_covariance] = self.reward_network([latent_state, action, next_latent_state])
return tfd.MultivariateNormalDiag(
loc=reward_mean,
scale_diag=self.scale_activation(reward_raw_covariance),
allow_nan_stats=False)
def discrete_latent_policy(self, latent_state: tf.Tensor):
return tfd.OneHotCategorical(
logits=self.latent_policy_network(latent_state),
allow_nan_stats=False)
def state_embedding_function(
self,
state: tf.Tensor,
label: Optional[tf.Tensor] = None,
labeling_function: Optional[Callable[[tf.Tensor], tf.Tensor]] = None,
dtype: tf.dtypes = tf.int32,
) -> tf.Tensor:
if label is not None:
label = tf.cast(label, dtype=tf.float32)
elif labeling_function is not None:
label = labeling_function(state)
if self.deterministic_state_embedding:
latent_state = self.binary_encode_state(state, label).mode()
else:
latent_state = self.binary_encode_state(state, label).sample()
return tf.cast(latent_state, dtype)
def action_embedding_function(
self,
latent_state: tf.Tensor,
latent_action: tf.Tensor,
) -> tf.Tensor:
return latent_action
def anneal(self):
for var, decay_rate in [
(self.encoder_temperature, self.encoder_temperature_decay_rate),
(self.prior_temperature, self.prior_temperature_decay_rate),
(self._entropy_regularizer_scale_factor, self.entropy_regularizer_decay_rate),
(self._kl_scale_factor_decay, self.kl_growth_rate),
(self._is_exponent_decay, self._is_exponent_growth_rate)
]:
if decay_rate.numpy().all() > 0:
var.assign(var * (1. - decay_rate))
for var, var_growth_rate, initial_var_value, decay in [
(self.kl_scale_factor, self.kl_growth_rate, self._initial_kl_scale_factor, self._kl_scale_factor_decay),
(self.is_exponent, self.is_exponent_growth_rate, self._initial_is_exponent, self._is_exponent_decay)
]:
if var_growth_rate > 0:
var.assign(initial_var_value + (1. - initial_var_value) * (1. - decay))
def call(self, inputs, training=None, mask=None, **kwargs):
return self.__call__(*inputs, **kwargs)
def get_config(self):
pass
@tf.function
def __call__(
self,
state: tf.Tensor,
label: tf.Tensor,
action: tf.Tensor,
reward: tf.Tensor,
next_state: tf.Tensor,
next_label: tf.Tensor,
sample_key: Optional[tf.Tensor] = None,
*args, **kwargs
):
if self.latent_policy_training_phase:
return self.latent_policy_training(state, label, action, reward, next_state, next_label)
# Logistic samples
state_encoder_distribution = self.relaxed_state_encoding(state, temperature=self.encoder_temperature)
next_state_encoder_distribution = self.relaxed_state_encoding(next_state, temperature=self.encoder_temperature)
# Sigmoid of Logistic samples with location alpha/t and scale 1/t gives Relaxed Bernoulli
# samples of location alpha and temperature t
latent_state = tf.concat([label, tf.sigmoid(state_encoder_distribution.sample())], axis=-1)
next_logistic_latent_state = next_state_encoder_distribution.sample()
log_q_encoding = next_state_encoder_distribution.log_prob(next_logistic_latent_state)
if self.latent_policy_network is not None and self.full_optimization:
log_p_transition = self.relaxed_markov_chain_latent_transition(
latent_state, temperature=self.prior_temperature
).log_prob(next_label, next_logistic_latent_state)
else:
log_p_transition = self.relaxed_latent_transition(
latent_state, action, temperature=self.prior_temperature
).log_prob(next_label, next_logistic_latent_state)
rate = log_q_encoding - log_p_transition
# retrieve Relaxed Bernoulli samples
next_latent_state = tf.concat([next_label, tf.sigmoid(next_logistic_latent_state)], axis=-1)
if self.latent_policy_network is not None and self.full_optimization:
# log P(a, r, s' | z, z') = log π(a | z) + log P(r | z, a, z') + log P(s' | z')
reconstruction_distribution = tfd.JointDistributionSequential([
self.discrete_latent_policy(latent_state),
lambda _action: self.reward_distribution(latent_state, _action, next_latent_state),
self.decode_state(next_latent_state)
])
distortion = -1. * reconstruction_distribution.log_prob(action, reward, next_state)
else:
# log P(r, s' | z, a, z') = log P(r | z, a, z') + log P(s' | z')
reconstruction_distribution = tfd.JointDistributionSequential([
self.reward_distribution(latent_state, action, next_latent_state),
self.decode_state(next_latent_state)
])
distortion = -1. * reconstruction_distribution.log_prob(reward, next_state)
entropy_regularizer = self.entropy_regularizer(
next_state,
use_marginal_entropy=True,
latent_states=next_latent_state)
# priority support
if self.priority_handler is not None and sample_key is not None:
tf.stop_gradient(
self.priority_handler.update_priority(
keys=sample_key,
latent_states=tf.stop_gradient(tf.cast(tf.round(latent_state), tf.int32)),
loss=tf.stop_gradient(distortion + rate)))
# metrics
self.loss_metrics['ELBO'](tf.stop_gradient(-1 * (distortion + rate)))
reconstruction_sample = reconstruction_distribution.sample()
self.loss_metrics['state_mse'](next_state, reconstruction_sample[-1])
self.loss_metrics['reward_mse'](reward, reconstruction_sample[-2])
self.loss_metrics['distortion'](distortion)
self.loss_metrics['rate'](rate)
# self.loss_metrics['annealed_rate'](tf.stop_gradient(self.kl_scale_factor * rate))
self.loss_metrics['entropy_regularizer'](
tf.stop_gradient(self.entropy_regularizer_scale_factor * entropy_regularizer))
self.loss_metrics['transition_log_probs'](
tf.stop_gradient(
self.discrete_latent_transition(tf.stop_gradient(tf.round(latent_state)),
action).log_prob(
next_label, tf.round(tf.sigmoid(next_logistic_latent_state)))))
if 'action_mse' in self.loss_metrics:
self.loss_metrics['action_mse'](action, reconstruction_sample[0])
if debug:
tf.print(latent_state, "sampled z")
tf.print(next_logistic_latent_state, "sampled (logistic) z'")
tf.print(next_latent_state, "sampled z'")
tf.print(self.encoder_network([state, label]), "log locations[:-1] -- logits[:-1] of Q")
tf.print(log_q_encoding, "Log Q(logistic z'|s', l')")
tf.print(self.transition_network([latent_state, action]), "log-locations P_transition")
tf.print(log_p_transition, "log P(logistic z'|z, a)")
tf.print(self.discrete_latent_transition(
tf.round(latent_state), action
).prob(tf.round(tf.sigmoid(next_logistic_latent_state))), "P(round(z') | round(z), a)")
tf.print(next_latent_state, "sampled z'")
[reconstruction_mean, _, reconstruction_prior_components] = \
self.reconstruction_network(next_latent_state)
tf.print(reconstruction_mean, 'mean(s | z)')
tf.print(reconstruction_prior_components, 'GMM: prior components')
tf.print(log_q_encoding - log_p_transition, "log Q(z') - log P(z')")
return {'distortion': distortion, 'rate': rate, 'entropy_regularizer': entropy_regularizer}
@tf.function
def entropy_regularizer(
self, state: tf.Tensor,
use_marginal_entropy: bool = False,
latent_states: Optional[tf.Tensor] = None,
*args, **kwargs
):
logits = self.encoder_network(state)
for metric_label in ('encoder_entropy', 'state_encoder_entropy'):
if metric_label in self.loss_metrics:
self.loss_metrics[metric_label](
tf.stop_gradient(tfd.Independent(tfd.Bernoulli(logits=logits)).entropy()))
if use_marginal_entropy:
batch_size = tf.shape(logits)[0]
marginal_encoder = tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(
logits=tf.ones(shape=(batch_size, batch_size))),
components_distribution=tfd.Independent(tfd.RelaxedBernoulli(
logits=tf.tile(tf.expand_dims(logits, axis=0), [batch_size, 1, 1]),
temperature=self.encoder_temperature,
# allow_nan_stats=False
), reinterpreted_batch_ndims=1),
reparameterize=(latent_states is None),
# allow_nan_stats=False
)
if latent_states is None:
latent_states = marginal_encoder.sample(batch_size)
else:
latent_states = latent_states[..., self.atomic_prop_dims:]
latent_states = tf.clip_by_value(latent_states, clip_value_min=1e-7, clip_value_max=1. - 1e-7)
marginal_entropy_regularizer = tf.reduce_mean(marginal_encoder.log_prob(latent_states))
if tf.reduce_any(tf.logical_or(
tf.math.is_nan(marginal_entropy_regularizer),
tf.math.is_inf(marginal_entropy_regularizer))):
tf.print("Inf or NaN detected in marginal_encoder_entropy")
return -1. * tfd.Independent(tfd.Bernoulli(logits=logits, allow_nan_stats=False)).entropy()
else:
if 'marginal_encoder_entropy' in self.loss_metrics:
self.loss_metrics['marginal_encoder_entropy'](tf.stop_gradient(-1. * marginal_entropy_regularizer))
return marginal_entropy_regularizer
else:
return -1. * tfd.Independent(tfd.Bernoulli(logits=logits, allow_nan_stats=False)).entropy()
def latent_policy_training(
self,
state: tf.Tensor,
label: tf.Tensor,
action: tf.Tensor,
reward: tf.Tensor,
next_state: tf.Tensor,
next_label: tf.Tensor
):
latent_distribution = self.relaxed_state_encoding(state, label, temperature=self.encoder_temperature)
latent_state = latent_distribution.sample()
latent_policy_distribution = self.discrete_latent_policy(latent_state)
if 'action_mse' in self.loss_metrics:
self.loss_metrics['action_mse'](action, latent_policy_distribution.sample())
return {'distortion': -1. * latent_policy_distribution.log_prob(action), 'rate': 0., 'entropy_regularizer': 0.}
def eval(
self,
state: tf.Tensor,
label: tf.Tensor,
action: tf.Tensor,
reward: tf.Tensor,
next_state: tf.Tensor,
next_label: tf.Tensor
):
"""
Evaluate the ELBO by making use of a discrete latent space.
"""
latent_distribution = self.binary_encode_state(state)
next_latent_distribution = self.binary_encode_state(next_state)
latent_state = tf.concat([label, tf.cast(latent_distribution.sample(), tf.float32)], axis=-1)
next_latent_state_no_label = tf.cast(next_latent_distribution.sample(), tf.float32)
if self.latent_policy_network is not None and self.full_optimization:
transition_distribution = self.discrete_markov_chain_latent_transition(
latent_state)
else:
transition_distribution = self.discrete_latent_transition(latent_state, action)
# rate = next_latent_distribution.kl_divergence(transition_distribution)
rate = next_latent_distribution.log_prob(next_latent_state_no_label) - transition_distribution.log_prob(
next_label, next_latent_state_no_label)