/
common.py
1444 lines (1157 loc) · 49.8 KB
/
common.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
# coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# 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
#
# https://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.
"""Common utilities for TF-Agents."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections as cs
import contextlib
import distutils.version
import functools
import importlib
import os
from typing import Dict, Optional, Text
from absl import logging
import numpy as np
import tensorflow as tf
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step as ts
from tf_agents.typing import types
from tf_agents.utils import nest_utils
from tf_agents.utils import object_identity
# pylint:disable=g-direct-tensorflow-import
from tensorflow.core.protobuf import struct_pb2 # TF internal
from tensorflow.python import tf2 as tf2_checker # TF internal
from tensorflow.python.eager import monitoring # TF internal
from tensorflow.python.saved_model import nested_structure_coder # TF internal
# pylint:enable=g-direct-tensorflow-import
try:
importlib.import_module('tf_agents.utils.allow_tf1')
except ImportError:
_TF1_MODE_ALLOWED = False
else:
_TF1_MODE_ALLOWED = True
tf_agents_gauge = monitoring.BoolGauge('/tensorflow/agents/agents',
'TF-Agents usage', 'method')
MISSING_RESOURCE_VARIABLES_ERROR = """
Resource variables are not enabled. Please enable them by adding the following
code to your main() method:
tf.compat.v1.enable_resource_variables()
For unit tests, subclass `tf_agents.utils.test_utils.TestCase`.
"""
def check_tf1_allowed():
"""Raises an error if running in TF1 (non-eager) mode and this is disabled."""
if _TF1_MODE_ALLOWED:
return
if not tf2_checker.enabled():
raise RuntimeError(
'You are using TF1 or running TF with eager mode disabled. '
'TF-Agents no longer supports TF1 mode (except for a shrinking list of '
'internal allowed users). If this negatively affects you, please '
'reach out to the TF-Agents team. Otherwise please use TF2.')
def resource_variables_enabled():
return tf.compat.v1.resource_variables_enabled()
_IN_LEGACY_TF1 = (
tf.__git_version__ != 'unknown'
and tf.__version__ != '1.15.0'
and (distutils.version.LooseVersion(tf.__version__) <=
distutils.version.LooseVersion('1.15.0.dev20190821')))
def in_legacy_tf1():
return _IN_LEGACY_TF1
def set_default_tf_function_parameters(*args, **kwargs):
"""Generates a decorator that sets default parameters for `tf.function`.
Args:
*args: default arguments for the `tf.function`.
**kwargs: default keyword arguments for the `tf.function`.
Returns:
Function decorator with preconfigured defaults for `tf.function`.
"""
def maybe_wrap(fn):
"""Helper function."""
wrapped = [None]
@functools.wraps(fn)
def preconfigured_function(*fn_args, **fn_kwargs):
if tf.executing_eagerly():
return fn(*fn_args, **fn_kwargs)
if wrapped[0] is None:
wrapped[0] = function(*((fn,) + args), **kwargs)
return wrapped[0](*fn_args, **fn_kwargs) # pylint: disable=not-callable
return preconfigured_function
return maybe_wrap
def function(*args, **kwargs):
"""Wrapper for tf.function with TF Agents-specific customizations.
Example:
```python
@common.function()
def my_eager_code(x, y):
...
```
Args:
*args: Args for tf.function.
**kwargs: Keyword args for tf.function.
Returns:
A tf.function wrapper.
"""
autograph = kwargs.pop('autograph', False)
reduce_retracing = kwargs.pop('reduce_retracing', True)
return tf.function( # allow-tf-function
*args,
autograph=autograph,
reduce_retracing=reduce_retracing,
**kwargs)
def has_eager_been_enabled():
"""Returns true iff in TF2 or in TF1 with eager execution enabled."""
with tf.init_scope():
return tf.executing_eagerly()
def function_in_tf1(*args, **kwargs):
"""Wrapper that returns common.function if using TF1.
This allows for code that assumes autodeps is available to be written once,
in the same way, for both TF1 and TF2.
Usage:
```python
train = function_in_tf1()(agent.train)
loss = train(experience)
```
Args:
*args: Arguments for common.function.
**kwargs: Keyword arguments for common.function.
Returns:
A callable that wraps a function.
"""
def maybe_wrap(fn):
"""Helper function."""
# We're in TF1 mode and want to wrap in common.function to get autodeps.
wrapped = [None]
@functools.wraps(fn)
def with_check_resource_vars(*fn_args, **fn_kwargs):
"""Helper function for calling common.function."""
check_tf1_allowed()
if has_eager_been_enabled():
# We're either in eager mode or in tf.function mode (no in-between); so
# autodep-like behavior is already expected of fn.
return fn(*fn_args, **fn_kwargs)
if not resource_variables_enabled():
raise RuntimeError(MISSING_RESOURCE_VARIABLES_ERROR)
if wrapped[0] is None:
wrapped[0] = function(*((fn,) + args), **kwargs)
return wrapped[0](*fn_args, **fn_kwargs) # pylint: disable=not-callable
return with_check_resource_vars
return maybe_wrap
def create_variable(name,
initial_value=0,
shape=(),
dtype=tf.int64,
use_local_variable=False,
trainable=False,
initializer=None,
unique_name=True):
"""Create a variable."""
check_tf1_allowed()
if has_eager_been_enabled():
if initializer is None:
if shape:
initial_value = tf.constant(initial_value, shape=shape, dtype=dtype)
else:
initial_value = tf.convert_to_tensor(initial_value, dtype=dtype)
else:
if callable(initializer):
initial_value = lambda: initializer(shape, dtype)
else:
initial_value = initializer
return tf.compat.v2.Variable(
initial_value, trainable=trainable, dtype=dtype, name=name)
collections = [tf.compat.v1.GraphKeys.GLOBAL_VARIABLES]
if use_local_variable:
collections = [tf.compat.v1.GraphKeys.LOCAL_VARIABLES]
if initializer is None:
initializer = tf.compat.v1.initializers.constant(initial_value, dtype=dtype)
if shape is None:
shape = tf.convert_to_tensor(initial_value).shape
if unique_name:
name = tf.compat.v1.get_default_graph().unique_name(name)
return tf.compat.v1.get_variable(
name=name,
shape=shape,
dtype=dtype,
initializer=initializer,
collections=collections,
use_resource=True,
trainable=trainable)
def soft_variables_update(source_variables,
target_variables,
tau=1.0,
tau_non_trainable=None,
sort_variables_by_name=False):
"""Performs a soft/hard update of variables from the source to the target.
Note: **when using this function with TF DistributionStrategy**, the
`strategy.extended.update` call (below) needs to be done in a cross-replica
context, i.e. inside a merge_call. Please use the Periodically class above
that provides this wrapper for you.
For each variable v_t in target variables and its corresponding variable v_s
in source variables, a soft update is:
v_t = (1 - tau) * v_t + tau * v_s
When tau is 1.0 (the default), then it does a hard update:
v_t = v_s
Args:
source_variables: list of source variables.
target_variables: list of target variables.
tau: A float scalar in [0, 1]. When tau is 1.0 (the default), we do a hard
update. This is used for trainable variables.
tau_non_trainable: A float scalar in [0, 1] for non_trainable variables. If
None, will copy from tau.
sort_variables_by_name: A bool, when True would sort the variables by name
before doing the update.
Returns:
An operation that updates target variables from source variables.
Raises:
ValueError: if `tau not in [0, 1]`.
ValueError: if `len(source_variables) != len(target_variables)`.
ValueError: "Method requires being in cross-replica context,
use get_replica_context().merge_call()" if used inside replica context.
"""
if tau < 0 or tau > 1:
raise ValueError('Input `tau` should be in [0, 1].')
if tau_non_trainable is None:
tau_non_trainable = tau
if tau_non_trainable < 0 or tau_non_trainable > 1:
raise ValueError('Input `tau_non_trainable` should be in [0, 1].')
updates = []
op_name = 'soft_variables_update'
if tau == 0.0 or not source_variables or not target_variables:
return tf.no_op(name=op_name)
if len(source_variables) != len(target_variables):
raise ValueError(
'Source and target variable lists have different lengths: '
'{} vs. {}'.format(len(source_variables), len(target_variables)))
if sort_variables_by_name:
source_variables = sorted(source_variables, key=lambda x: x.name)
target_variables = sorted(target_variables, key=lambda x: x.name)
strategy = tf.distribute.get_strategy()
for (v_s, v_t) in zip(source_variables, target_variables):
v_t.shape.assert_is_compatible_with(v_s.shape)
def update_fn(v1, v2):
"""Update variables."""
# For not trainable variables do hard updates.
# This helps stabilaze BatchNorm moving averagees TODO(b/144455039)
if not v1.trainable:
current_tau = tau_non_trainable
else:
current_tau = tau
if current_tau == 1.0:
return v1.assign(v2)
else:
return v1.assign((1 - current_tau) * v1 + current_tau * v2)
# TODO(b/142508640): remove this when b/142802462 is fixed.
# Workaround for b/142508640, only use extended.update for
# MirroredVariable variables (which are trainable variables).
# For other types of variables (i.e. SyncOnReadVariables, for example
# batch norm stats) do a regular assign, which will cause a sync and
# broadcast from replica 0, so will have slower performance but will be
# correct and not cause a failure.
if tf.distribute.has_strategy() and v_t.trainable:
# Assignment happens independently on each replica,
# see b/140690837 #46.
update = strategy.extended.update(v_t, update_fn, args=(v_s,))
else:
update = update_fn(v_t, v_s)
updates.append(update)
return tf.group(*updates, name=op_name)
def join_scope(parent_scope, child_scope):
"""Joins a parent and child scope using `/`, checking for empty/none.
Args:
parent_scope: (string) parent/prefix scope.
child_scope: (string) child/suffix scope.
Returns:
joined scope: (string) parent and child scopes joined by /.
"""
if not parent_scope:
return child_scope
if not child_scope:
return parent_scope
return '/'.join([parent_scope, child_scope])
# TODO(b/138322868): Add an optional action_spec for validation.
def index_with_actions(q_values, actions, multi_dim_actions=False):
"""Index into q_values using actions.
Note: this supports multiple outer dimensions (e.g. time, batch etc).
Args:
q_values: A float tensor of shape [outer_dim1, ... outer_dimK, action_dim1,
..., action_dimJ].
actions: An int tensor of shape [outer_dim1, ... outer_dimK] if
multi_dim_actions=False [outer_dim1, ... outer_dimK, J] if
multi_dim_actions=True I.e. in the multidimensional case,
actions[outer_dim1, ... outer_dimK] is a vector [actions_1, ...,
actions_J] where each element actions_j is an action in the range [0,
num_actions_j). While in the single dimensional case, actions[outer_dim1,
... outer_dimK] is a scalar.
multi_dim_actions: whether the actions are multidimensional.
Returns:
A [outer_dim1, ... outer_dimK] tensor of q_values for the given actions.
Raises:
ValueError: If actions have unknown rank.
"""
if actions.shape.rank is None:
raise ValueError('actions should have known rank.')
batch_dims = actions.shape.rank
if multi_dim_actions:
# In the multidimensional case, the last dimension of actions indexes the
# vector of actions for each batch, so exclude it from the batch dimensions.
batch_dims -= 1
outer_shape = tf.shape(input=actions)
batch_indices = tf.meshgrid(
*[tf.range(outer_shape[i]) for i in range(batch_dims)], indexing='ij')
batch_indices = [tf.cast(tf.expand_dims(batch_index, -1), dtype=tf.int32)
for batch_index in batch_indices]
if not multi_dim_actions:
actions = tf.expand_dims(actions, -1)
# Cast actions to tf.int32 in order to avoid a TypeError in tf.concat.
actions = tf.cast(actions, dtype=tf.int32)
action_indices = tf.concat(batch_indices + [actions], -1)
return tf.gather_nd(q_values, action_indices)
def periodically(body, period, name='periodically'):
"""Periodically performs the tensorflow op in `body`.
The body tensorflow op will be executed every `period` times the periodically
op is executed. More specifically, with `n` the number of times the op has
been executed, the body will be executed when `n` is a non zero positive
multiple of `period` (i.e. there exist an integer `k > 0` such that
`k * period == n`).
If `period` is `None`, it will not perform any op and will return a
`tf.no_op()`.
If `period` is 1, it will just execute the body, and not create any counters
or conditionals.
Args:
body: callable that returns the tensorflow op to be performed every time an
internal counter is divisible by the period. The op must have no output
(for example, a tf.group()).
period: inverse frequency with which to perform the op.
name: name of the variable_scope.
Raises:
TypeError: if body is not a callable.
Returns:
An op that periodically performs the specified op.
"""
if tf.executing_eagerly():
if isinstance(period, tf.Variable):
return Periodically(body, period, name)
return EagerPeriodically(body, period)
else:
return Periodically(body, period, name)()
class Periodically(tf.Module):
"""Periodically performs the ops defined in `body`."""
def __init__(self, body, period, name='periodically'):
"""Periodically performs the ops defined in `body`.
The body tensorflow op will be executed every `period` times the
periodically op is executed. More specifically, with `n` the number of times
the op has been executed, the body will be executed when `n` is a non zero
positive multiple of `period` (i.e. there exist an integer `k > 0` such that
`k * period == n`).
If `period` is `None`, it will not perform any op and will return a
`tf.no_op()`.
If `period` is 1, it will just execute the body, and not create any counters
or conditionals.
Args:
body: callable that returns the tensorflow op to be performed every time
an internal counter is divisible by the period. The op must have no
output (for example, a tf.group()).
period: inverse frequency with which to perform the op. It can be a Tensor
or a Variable.
name: name of the object.
Raises:
TypeError: if body is not a callable.
Returns:
An op that periodically performs the specified op.
"""
super(Periodically, self).__init__(name=name)
if not callable(body):
raise TypeError('body must be callable.')
self._body = body
self._period = period
self._counter = create_variable(self.name + '/counter', 0)
def __call__(self):
def call(strategy=None):
del strategy # unused
if self._period is None:
return tf.no_op()
if self._period == 1:
return self._body()
period = tf.cast(self._period, self._counter.dtype)
remainder = tf.math.mod(self._counter.assign_add(1), period)
return tf.cond(
pred=tf.equal(remainder, 0), true_fn=self._body, false_fn=tf.no_op)
# TODO(b/129083817) add an explicit unit test to ensure correct behavior
ctx = tf.distribute.get_replica_context()
if ctx:
return tf.distribute.get_replica_context().merge_call(call)
else:
return call()
class EagerPeriodically(object):
"""EagerPeriodically performs the ops defined in `body`.
Only works in Eager mode.
"""
def __init__(self, body, period):
"""EagerPeriodically performs the ops defined in `body`.
Args:
body: callable that returns the tensorflow op to be performed every time
an internal counter is divisible by the period. The op must have no
output (for example, a tf.group()).
period: inverse frequency with which to perform the op. Must be a simple
python int/long.
Raises:
TypeError: if body is not a callable.
Returns:
An op that periodically performs the specified op.
"""
if not callable(body):
raise TypeError('body must be callable.')
self._body = body
self._period = period
self._counter = 0
def __call__(self):
if self._period is None:
return tf.no_op()
if self._period == 1:
return self._body()
self._counter += 1
if self._counter % self._period == 0:
self._body()
def clip_to_spec(value, spec):
"""Clips value to a given bounded tensor spec.
Args:
value: (tensor) value to be clipped.
spec: (BoundedTensorSpec) spec containing min. and max. values for clipping.
Returns:
clipped_value: (tensor) `value` clipped to be compatible with `spec`.
"""
return tf.clip_by_value(value, spec.minimum, spec.maximum)
def spec_means_and_magnitudes(action_spec):
"""Get the center and magnitude of the ranges in action spec."""
action_means = tf.nest.map_structure(
lambda spec: (spec.maximum + spec.minimum) / 2.0, action_spec)
action_magnitudes = tf.nest.map_structure(
lambda spec: (spec.maximum - spec.minimum) / 2.0, action_spec)
return np.array(
action_means, dtype=np.float32), np.array(
action_magnitudes, dtype=np.float32)
def scale_to_spec(tensor, spec):
"""Shapes and scales a batch into the given spec bounds.
Args:
tensor: A [batch x n] tensor with values in the range of [-1, 1].
spec: (BoundedTensorSpec) to use for scaling the action.
Returns:
A batch scaled the given spec bounds.
"""
tensor = tf.reshape(tensor, [-1] + spec.shape.as_list())
# Scale the tensor.
means, magnitudes = spec_means_and_magnitudes(spec)
tensor = means + magnitudes * tensor
# Set type.
return tf.cast(tensor, spec.dtype)
def ornstein_uhlenbeck_process(initial_value,
damping=0.15,
stddev=0.2,
seed=None,
scope='ornstein_uhlenbeck_noise'):
"""An op for generating noise from a zero-mean Ornstein-Uhlenbeck process.
The Ornstein-Uhlenbeck process is a process that generates temporally
correlated noise via a random walk with damping. This process describes
the velocity of a particle undergoing brownian motion in the presence of
friction. This can be useful for exploration in continuous action environments
with momentum.
The temporal update equation is:
`x_next = (1 - damping) * x + N(0, std_dev)`
Args:
initial_value: Initial value of the process.
damping: The rate at which the noise trajectory is damped towards the mean.
We must have 0 <= damping <= 1, where a value of 0 gives an undamped
random walk and a value of 1 gives uncorrelated Gaussian noise. Hence in
most applications a small non-zero value is appropriate.
stddev: Standard deviation of the Gaussian component.
seed: Seed for random number generation.
scope: Scope of the variables.
Returns:
An op that generates noise.
"""
if tf.executing_eagerly():
return OUProcess(initial_value, damping, stddev, seed, scope)
else:
return OUProcess(initial_value, damping, stddev, seed, scope)()
class OUProcess(tf.Module):
"""A zero-mean Ornstein-Uhlenbeck process."""
def __init__(self,
initial_value,
damping=0.15,
stddev=0.2,
seed=None,
scope='ornstein_uhlenbeck_noise'):
"""A Class for generating noise from a zero-mean Ornstein-Uhlenbeck process.
The Ornstein-Uhlenbeck process is a process that generates temporally
correlated noise via a random walk with damping. This process describes
the velocity of a particle undergoing brownian motion in the presence of
friction. This can be useful for exploration in continuous action
environments with momentum.
The temporal update equation is:
`x_next = (1 - damping) * x + N(0, std_dev)`
Args:
initial_value: Initial value of the process.
damping: The rate at which the noise trajectory is damped towards the
mean. We must have 0 <= damping <= 1, where a value of 0 gives an
undamped random walk and a value of 1 gives uncorrelated Gaussian noise.
Hence in most applications a small non-zero value is appropriate.
stddev: Standard deviation of the Gaussian component.
seed: Seed for random number generation.
scope: Scope of the variables.
"""
super(OUProcess, self).__init__()
self._damping = damping
self._stddev = stddev
self._seed = seed
with tf.name_scope(scope):
self._x = tf.compat.v2.Variable(
initial_value=initial_value, trainable=False)
def __call__(self):
noise = tf.random.normal(
shape=self._x.shape,
stddev=self._stddev,
dtype=self._x.dtype,
seed=self._seed)
return self._x.assign((1. - self._damping) * self._x + noise)
def log_probability(distributions, actions, action_spec):
"""Computes log probability of actions given distribution.
Args:
distributions: A possibly batched tuple of distributions.
actions: A possibly batched action tuple.
action_spec: A nested tuple representing the action spec.
Returns:
A Tensor representing the log probability of each action in the batch.
"""
outer_rank = nest_utils.get_outer_rank(actions, action_spec)
def _compute_log_prob(single_distribution, single_action):
# sum log-probs over everything but the batch
single_log_prob = single_distribution.log_prob(single_action)
rank = single_log_prob.shape.rank
reduce_dims = list(range(outer_rank, rank))
return tf.reduce_sum(
input_tensor=single_log_prob,
axis=reduce_dims)
nest_utils.assert_same_structure(distributions, actions)
log_probs = [
_compute_log_prob(dist, action)
for (dist, action
) in zip(tf.nest.flatten(distributions), tf.nest.flatten(actions))
]
# sum log-probs over action tuple
total_log_probs = tf.add_n(log_probs)
return total_log_probs
# TODO(ofirnachum): Move to distribution utils.
def entropy(distributions, action_spec, outer_rank=None):
"""Computes total entropy of distribution.
Args:
distributions: A possibly batched tuple of distributions.
action_spec: A nested tuple representing the action spec.
outer_rank: Optional outer rank of the distributions. If not provided use
distribution.mode() to compute it.
Returns:
A Tensor representing the entropy of each distribution in the batch.
Assumes actions are independent, so that marginal entropies of each action
may be summed.
"""
if outer_rank is None:
nested_modes = tf.nest.map_structure(lambda d: d.mode(), distributions)
outer_rank = nest_utils.get_outer_rank(nested_modes, action_spec)
def _compute_entropy(single_distribution):
try:
entropies = single_distribution.entropy()
# Sum entropies over everything but the batch.
rank = entropies.shape.rank
reduce_dims = list(range(outer_rank, rank))
return tf.reduce_sum(input_tensor=entropies, axis=reduce_dims)
except NotImplementedError:
return None
entropies = []
for dist in tf.nest.flatten(distributions):
entropy_dist = _compute_entropy(dist)
if entropy_dist is not None:
entropies.append(entropy_dist)
# Sum entropies over action tuple.
if not entropies:
return None
return tf.add_n(entropies)
def discounted_future_sum(values, gamma, num_steps):
"""Discounted future sum of batch-major values.
Args:
values: A Tensor of shape [batch_size, total_steps] and dtype float32.
gamma: A float discount value.
num_steps: A positive integer number of future steps to sum.
Returns:
A Tensor of shape [batch_size, total_steps], where each entry `(i, j)` is
the result of summing the entries of values starting from
`gamma^0 * values[i, j]` to
`gamma^(num_steps - 1) * values[i, j + num_steps - 1]`,
with zeros padded to values.
For example, values=[5, 6, 7], gamma=0.9, will result in sequence:
```python
[(5 * 0.9^0 + 6 * 0.9^1 + 7 * 0.9^2), (6 * 0.9^0 + 7 * 0.9^1), 7 * 0.9^0]
```
Raises:
ValueError: If values is not of rank 2.
"""
if values.get_shape().rank != 2:
raise ValueError('Input must be rank 2 tensor. Got %d.' %
values.get_shape().rank)
(batch_size, total_steps) = values.get_shape().as_list()
num_steps = tf.minimum(num_steps, total_steps)
discount_filter = tf.reshape(gamma**tf.cast(tf.range(num_steps), tf.float32),
[-1, 1, 1])
padded_values = tf.concat([values, tf.zeros([batch_size, num_steps - 1])], 1)
convolved_values = tf.squeeze(
tf.nn.conv1d(
input=tf.expand_dims(padded_values, -1),
filters=discount_filter,
stride=1,
padding='VALID'), -1)
return convolved_values
def discounted_future_sum_masked(values, gamma, num_steps, episode_lengths):
"""Discounted future sum of batch-major values.
Args:
values: A Tensor of shape [batch_size, total_steps] and dtype float32.
gamma: A float discount value.
num_steps: A positive integer number of future steps to sum.
episode_lengths: A vector shape [batch_size] with num_steps per episode.
Returns:
A Tensor of shape [batch_size, total_steps], where each entry is the
discounted sum as in discounted_future_sum, except with values after
the end of episode_lengths masked to 0.
Raises:
ValueError: If values is not of rank 2, or if total_steps is not defined.
"""
if values.shape.rank != 2:
raise ValueError('Input must be a rank 2 tensor. Got %d.' % values.shape)
total_steps = tf.compat.dimension_value(values.shape[1])
if total_steps is None:
raise ValueError('total_steps dimension in input '
'values[batch_size, total_steps] must be fully defined.')
episode_mask = tf.cast(
tf.sequence_mask(episode_lengths, total_steps), tf.float32)
values *= episode_mask
return discounted_future_sum(values, gamma, num_steps)
def shift_values(values, gamma, num_steps, final_values=None):
"""Shifts batch-major values in time by some amount.
Args:
values: A Tensor of shape [batch_size, total_steps] and dtype float32.
gamma: A float discount value.
num_steps: A nonnegative integer amount to shift values by.
final_values: A float32 Tensor of shape [batch_size] corresponding to the
values at step num_steps + 1. Defaults to None (all zeros).
Returns:
A Tensor of shape [batch_size, total_steps], where each entry (i, j) is
gamma^num_steps * values[i, j + num_steps] if j + num_steps < total_steps;
gamma^(total_steps - j) * final_values[i] otherwise.
Raises:
ValueError: If values is not of rank 2.
"""
if values.get_shape().rank != 2:
raise ValueError('Input must be rank 2 tensor. Got %d.' %
values.get_shape().rank)
(batch_size, total_steps) = values.get_shape().as_list()
num_steps = tf.minimum(num_steps, total_steps)
if final_values is None:
final_values = tf.zeros([batch_size])
padding_exponent = tf.expand_dims(
tf.cast(tf.range(num_steps, 0, -1), tf.float32), 0)
final_pad = tf.expand_dims(final_values, 1) * gamma**padding_exponent
return tf.concat([
gamma**tf.cast(num_steps, tf.float32) * values[:, num_steps:], final_pad
], 1)
def get_episode_mask(time_steps):
"""Create a mask that is 0.0 for all final steps, 1.0 elsewhere.
Args:
time_steps: A TimeStep namedtuple representing a batch of steps.
Returns:
A float32 Tensor with 0s where step_type == LAST and 1s otherwise.
"""
episode_mask = tf.cast(
tf.not_equal(time_steps.step_type, ts.StepType.LAST), tf.float32)
return episode_mask
def get_contiguous_sub_episodes(next_time_steps_discount):
"""Computes mask on sub-episodes which includes only contiguous components.
Args:
next_time_steps_discount: Tensor of shape [batch_size, total_steps]
corresponding to environment discounts on next time steps (i.e.
next_time_steps.discount).
Returns:
A float Tensor of shape [batch_size, total_steps] specifying mask including
only contiguous components. Each row will be of the form
[1.0] * a + [0.0] * b, where a >= 1 and b >= 0, and in which the initial
sequence of ones corresponds to a contiguous sub-episode.
"""
episode_end = tf.equal(next_time_steps_discount,
tf.constant(0, dtype=next_time_steps_discount.dtype))
mask = tf.math.cumprod(
1.0 - tf.cast(episode_end, tf.float32), axis=1, exclusive=True)
return mask
def convert_q_logits_to_values(logits, support):
"""Converts a set of Q-value logits into Q-values using the provided support.
Args:
logits: A Tensor representing the Q-value logits.
support: The support of the underlying distribution.
Returns:
A Tensor containing the expected Q-values.
"""
probabilities = tf.nn.softmax(logits)
return tf.reduce_sum(input_tensor=support * probabilities, axis=-1)
def generate_tensor_summaries(tag, tensor, step):
"""Generates various summaries of `tensor` such as histogram, max, min, etc.
Args:
tag: A namescope tag for the summaries.
tensor: The tensor to generate summaries of.
step: Variable to use for summaries.
"""
with tf.name_scope(tag):
tf.compat.v2.summary.histogram(name='histogram', data=tensor, step=step)
tf.compat.v2.summary.scalar(
name='mean', data=tf.reduce_mean(input_tensor=tensor), step=step)
tf.compat.v2.summary.scalar(
name='mean_abs',
data=tf.reduce_mean(input_tensor=tf.abs(tensor)),
step=step)
tf.compat.v2.summary.scalar(
name='max', data=tf.reduce_max(input_tensor=tensor), step=step)
tf.compat.v2.summary.scalar(
name='min', data=tf.reduce_min(input_tensor=tensor), step=step)
tf.compat.v2.summary.scalar(
name='std', data=tf.math.reduce_std(input_tensor=tensor), step=step)
def summarize_tensor_dict(tensor_dict: Dict[Text, types.Tensor],
step: Optional[types.Tensor]):
"""Generates summaries of all tensors in `tensor_dict`.
Args:
tensor_dict: A dictionary {name, tensor} to summarize.
step: The global step
"""
for tag in tensor_dict:
generate_tensor_summaries(tag, tensor_dict[tag], step)
def compute_returns(rewards: types.Tensor,
discounts: types.Tensor,
time_major: bool = False):
"""Compute the return from each index in an episode.
Args:
rewards: Tensor `[T]`, `[B, T]`, `[T, B]` of per-timestep reward.
discounts: Tensor `[T]`, `[B, T]`, `[T, B]` of per-timestep discount factor.
Should be `0`. for final step of each episode.
time_major: Bool, when batched inputs setting it to `True`, inputs are
expected to be time-major: `[T, B]` otherwise, batch-major: `[B, T]`.
Returns:
Tensor of per-timestep cumulative returns.
"""
rewards.shape.assert_is_compatible_with(discounts.shape)
if (not rewards.shape.is_fully_defined() or
not discounts.shape.is_fully_defined()):
tf.debugging.assert_equal(tf.shape(input=rewards),
tf.shape(input=discounts))
def discounted_accumulate_rewards(next_step_return, reward_and_discount):
reward, discount = reward_and_discount
return next_step_return * discount + reward
# Support batched rewards and discount via transpose.
if rewards.shape.rank > 1 and not time_major:
rewards = tf.transpose(rewards, perm=[1, 0])
discounts = tf.transpose(discounts, perm=[1, 0])
# Cumulatively sum discounted reward R_t.
# R_t = r_t + discount * (r_t+1 + discount * (r_t+2 * discount( ...
# As discount is 0 for terminal states, ends of episode will not include
# reward from subsequent timesteps.
returns = tf.scan(
discounted_accumulate_rewards, [rewards, discounts],
initializer=tf.zeros_like(rewards[0]),
reverse=True)
# Reverse transpose if needed.
if returns.shape.rank > 1 and not time_major:
returns = tf.transpose(returns, perm=[1, 0])
return returns
def initialize_uninitialized_variables(session, var_list=None):
"""Initialize any pending variables that are uninitialized."""
if var_list is None:
var_list = tf.compat.v1.global_variables() + tf.compat.v1.local_variables()
is_initialized = session.run(
[tf.compat.v1.is_variable_initialized(v) for v in var_list])
uninitialized_vars = []
for flag, v in zip(is_initialized, var_list):
if not flag:
uninitialized_vars.append(v)
if uninitialized_vars:
logging.info('uninitialized_vars: %s',
', '.join([str(x) for x in uninitialized_vars]))
session.run(tf.compat.v1.variables_initializer(uninitialized_vars))
class Checkpointer(object):
"""Checkpoints training state, policy state, and replay_buffer state."""
def __init__(self, ckpt_dir, max_to_keep=20, **kwargs):
"""A class for making checkpoints.
If ckpt_dir doesn't exists it creates it.
Args: