-
Notifications
You must be signed in to change notification settings - Fork 752
Expand file tree
/
Copy pathtf_metrics.py
More file actions
474 lines (384 loc) · 14.1 KB
/
tf_metrics.py
File metadata and controls
474 lines (384 loc) · 14.1 KB
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
# 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.
"""TF metrics."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import logging
import gin
import numpy as np
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.metrics import tf_metric
from tf_agents.replay_buffers import table
from tf_agents.utils import common
from tf_agents.utils import nest_utils
class TFDeque(object):
"""Deque backed by tf.Variable storage."""
def __init__(self, max_len, dtype, shape=(), name='TFDeque'):
self._max_len = tf.convert_to_tensor(max_len, dtype=tf.int32)
self._spec = tf.TensorSpec(shape, dtype, name='Buffer')
self._buffer = table.Table(self._spec, capacity=max_len)
self._head = common.create_variable(
initial_value=0, dtype=tf.int32, shape=(), name=name + 'Head'
)
@property
def data(self):
return self._buffer.read(tf.range(self.length))
@common.function(autograph=True)
def extend(self, value):
for v in value:
self.add(v)
@common.function(autograph=True)
def add(self, value):
position = tf.math.mod(self._head, self._max_len)
self._buffer.write(position, value)
self._head.assign_add(1)
@property
def length(self):
return tf.minimum(self._head, self._max_len)
@common.function
def clear(self):
self._head.assign(0)
@common.function(autograph=True)
def mean(self):
if tf.equal(self._head, 0):
return tf.zeros(self._spec.shape, self._spec.dtype)
return tf.math.reduce_mean(self.data, axis=0)
@common.function(autograph=True)
def max(self):
if tf.equal(self._head, 0):
return tf.fill(self._spec.shape, self._spec.dtype.min)
return tf.math.reduce_max(self.data, axis=0)
@common.function(autograph=True)
def min(self):
if tf.equal(self._head, 0):
return tf.fill(self._spec.shape, self._spec.dtype.max)
return tf.math.reduce_min(self.data, axis=0)
@gin.configurable(module='tf_agents')
class EnvironmentSteps(tf_metric.TFStepMetric):
"""Counts the number of steps taken in the environment."""
def __init__(self, name='EnvironmentSteps', prefix='Metrics', dtype=tf.int64):
super(EnvironmentSteps, self).__init__(name=name, prefix=prefix)
self.dtype = dtype
self.environment_steps = common.create_variable(
initial_value=0, dtype=self.dtype, shape=(), name='environment_steps'
)
def call(self, trajectory):
"""Increase the number of environment_steps according to trajectory.
Step count is not increased on trajectory.boundary() since that step
is not part of any episode.
Args:
trajectory: A tf_agents.trajectory.Trajectory
Returns:
The arguments, for easy chaining.
"""
# The __call__ will execute this.
num_steps = tf.cast(~trajectory.is_boundary(), self.dtype)
num_steps = tf.reduce_sum(input_tensor=num_steps)
self.environment_steps.assign_add(num_steps)
return trajectory
def result(self):
return tf.identity(self.environment_steps, name=self.name)
@common.function
def reset(self):
self.environment_steps.assign(0)
@gin.configurable(module='tf_agents')
class NumberOfEpisodes(tf_metric.TFStepMetric):
"""Counts the number of episodes in the environment."""
def __init__(self, name='NumberOfEpisodes', prefix='Metrics', dtype=tf.int64):
super(NumberOfEpisodes, self).__init__(name=name, prefix=prefix)
self.dtype = dtype
self.number_episodes = common.create_variable(
initial_value=0, dtype=self.dtype, shape=(), name='number_episodes'
)
def call(self, trajectory):
"""Increase the number of number_episodes according to trajectory.
It would increase for all trajectory.is_last().
Args:
trajectory: A tf_agents.trajectory.Trajectory
Returns:
The arguments, for easy chaining.
"""
# The __call__ will execute this.
num_episodes = tf.cast(trajectory.is_last(), self.dtype)
num_episodes = tf.reduce_sum(input_tensor=num_episodes)
self.number_episodes.assign_add(num_episodes)
return trajectory
def result(self):
return tf.identity(self.number_episodes, name=self.name)
@common.function
def reset(self):
self.number_episodes.assign(0)
@gin.configurable(module='tf_agents')
class AverageReturnMetric(tf_metric.TFStepMetric):
"""Metric to compute the average return."""
def __init__(
self,
name='AverageReturn',
prefix='Metrics',
dtype=tf.float32,
batch_size=1,
buffer_size=10,
):
super(AverageReturnMetric, self).__init__(name=name, prefix=prefix)
self._buffer = TFDeque(buffer_size, dtype)
self._dtype = dtype
self._return_accumulator = common.create_variable(
initial_value=0, dtype=dtype, shape=(batch_size,), name='Accumulator'
)
@common.function(autograph=True)
def call(self, trajectory):
# Zero out batch indices where a new episode is starting.
self._return_accumulator.assign(
tf.where(
trajectory.is_first(),
tf.zeros_like(self._return_accumulator),
self._return_accumulator,
)
)
# Update accumulator with received rewards. We are summing over all
# non-batch dimensions in case the reward is a vector.
self._return_accumulator.assign_add(
tf.reduce_sum(
trajectory.reward, axis=range(1, len(trajectory.reward.shape))
)
)
# Add final returns to buffer.
last_episode_indices = tf.squeeze(tf.where(trajectory.is_last()), axis=-1)
for indx in last_episode_indices:
self._buffer.add(self._return_accumulator[indx])
return trajectory
def result(self):
return self._buffer.mean()
@common.function
def reset(self):
self._buffer.clear()
self._return_accumulator.assign(tf.zeros_like(self._return_accumulator))
@gin.configurable(module='tf_agents')
class MaxReturnMetric(tf_metric.TFStepMetric):
"""Metric to compute the max return."""
def __init__(
self,
name='MaxReturn',
prefix='Metrics',
dtype=tf.float32,
batch_size=1,
buffer_size=10,
):
super(MaxReturnMetric, self).__init__(name=name, prefix=prefix)
self._buffer = TFDeque(buffer_size, dtype)
self._dtype = dtype
self._return_accumulator = common.create_variable(
initial_value=0, dtype=dtype, shape=(batch_size,), name='Accumulator'
)
@common.function(autograph=True)
def call(self, trajectory):
# Zero out batch indices where a new episode is starting.
self._return_accumulator.assign(
tf.where(
trajectory.is_first(),
tf.zeros_like(self._return_accumulator),
self._return_accumulator,
)
)
# Update accumulator with received rewards.
self._return_accumulator.assign_add(trajectory.reward)
# Add final returns to buffer.
last_episode_indices = tf.squeeze(tf.where(trajectory.is_last()), axis=-1)
for indx in last_episode_indices:
self._buffer.add(self._return_accumulator[indx])
return trajectory
def result(self):
return self._buffer.max()
@common.function
def reset(self):
self._buffer.clear()
self._return_accumulator.assign(tf.zeros_like(self._return_accumulator))
@gin.configurable(module='tf_agents')
class MinReturnMetric(tf_metric.TFStepMetric):
"""Metric to compute the min return."""
def __init__(
self,
name='MinReturn',
prefix='Metrics',
dtype=tf.float32,
batch_size=1,
buffer_size=10,
):
super(MinReturnMetric, self).__init__(name=name, prefix=prefix)
self._buffer = TFDeque(buffer_size, dtype)
self._dtype = dtype
self._return_accumulator = common.create_variable(
initial_value=0, dtype=dtype, shape=(batch_size,), name='Accumulator'
)
@common.function(autograph=True)
def call(self, trajectory):
# Zero out batch indices where a new episode is starting.
self._return_accumulator.assign(
tf.where(
trajectory.is_first(),
tf.zeros_like(self._return_accumulator),
self._return_accumulator,
)
)
# Update accumulator with received rewards.
self._return_accumulator.assign_add(trajectory.reward)
# Add final returns to buffer.
last_episode_indices = tf.squeeze(tf.where(trajectory.is_last()), axis=-1)
for indx in last_episode_indices:
self._buffer.add(self._return_accumulator[indx])
return trajectory
def result(self):
return self._buffer.min()
@common.function
def reset(self):
self._buffer.clear()
self._return_accumulator.assign(tf.zeros_like(self._return_accumulator))
@gin.configurable(module='tf_agents')
class AverageEpisodeLengthMetric(tf_metric.TFStepMetric):
"""Metric to compute the average episode length."""
def __init__(
self,
name='AverageEpisodeLength',
prefix='Metrics',
dtype=tf.float32,
batch_size=1,
buffer_size=10,
):
super(AverageEpisodeLengthMetric, self).__init__(name=name, prefix=prefix)
self._buffer = TFDeque(buffer_size, dtype)
self._dtype = dtype
self._length_accumulator = common.create_variable(
initial_value=0, dtype=dtype, shape=(batch_size,), name='Accumulator'
)
@common.function(autograph=True)
def call(self, trajectory):
# Each non-boundary trajectory (first, mid or last) represents a step.
non_boundary_indices = tf.squeeze(
tf.where(tf.logical_not(trajectory.is_boundary())), axis=-1
)
self._length_accumulator.scatter_add(
tf.IndexedSlices(
tf.ones_like(
non_boundary_indices, dtype=self._length_accumulator.dtype
),
non_boundary_indices,
)
)
# Add lengths to buffer when we hit end of episode
last_indices = tf.squeeze(tf.where(trajectory.is_last()), axis=-1)
for indx in last_indices:
self._buffer.add(self._length_accumulator[indx])
# Clear length accumulator at the end of episodes.
self._length_accumulator.scatter_update(
tf.IndexedSlices(
tf.zeros_like(last_indices, dtype=self._dtype), last_indices
)
)
return trajectory
def result(self):
return self._buffer.mean()
@common.function
def reset(self):
self._buffer.clear()
self._length_accumulator.assign(tf.zeros_like(self._length_accumulator))
@gin.configurable(module='tf_agents')
class ChosenActionHistogram(tf_metric.TFHistogramStepMetric):
"""Metric to compute the frequency of each action chosen."""
def __init__(
self, name='ChosenActionHistogram', dtype=tf.int32, buffer_size=100
):
super(ChosenActionHistogram, self).__init__(name=name)
self._buffer = TFDeque(buffer_size, dtype)
self._dtype = dtype
@common.function
def call(self, trajectory):
self._buffer.extend(trajectory.action)
return trajectory
@common.function
def result(self):
return self._buffer.data
@common.function
def reset(self):
self._buffer.clear()
@gin.configurable(module='tf_agents')
class AverageReturnMultiMetric(tf_metric.TFMultiMetricStepMetric):
"""Metric to compute the average return for multiple metrics."""
def __init__(
self,
reward_spec,
name='AverageReturnMultiMetric',
prefix='Metrics',
dtype=tf.float32,
batch_size=1,
buffer_size=10,
):
self._batch_size = batch_size
self._buffer = tf.nest.map_structure(
lambda r: TFDeque(buffer_size, r.dtype, r.shape), reward_spec
)
metric_names = _get_metric_names_from_spec(reward_spec)
self._dtype = dtype
def create_acc(spec):
return common.create_variable(
initial_value=np.zeros((batch_size,) + spec.shape),
shape=(batch_size,) + spec.shape,
dtype=spec.dtype,
name='Accumulator/' + spec.name,
)
self._return_accumulator = tf.nest.map_structure(create_acc, reward_spec)
self._reward_spec = reward_spec
super(AverageReturnMultiMetric, self).__init__(
name=name, prefix=prefix, metric_names=metric_names
)
@common.function(autograph=True)
def call(self, trajectory):
nest_utils.assert_same_structure(trajectory.reward, self._reward_spec)
for buf, return_acc, reward in zip(
tf.nest.flatten(self._buffer),
tf.nest.flatten(self._return_accumulator),
tf.nest.flatten(trajectory.reward),
):
# Zero out batch indices where a new episode is starting.
is_start = trajectory.is_first()
if reward.shape.rank > 1:
is_start = tf.broadcast_to(
tf.reshape(trajectory.is_first(), [-1, 1]), tf.shape(return_acc)
)
return_acc.assign(
tf.where(is_start, tf.zeros_like(return_acc), return_acc)
)
# Update accumulator with received rewards.
return_acc.assign_add(reward)
# Add final returns to buffer.
last_episode_indices = tf.squeeze(tf.where(trajectory.is_last()), axis=-1)
for indx in last_episode_indices:
buf.add(return_acc[indx])
return trajectory
def result(self):
return tf.nest.map_structure(lambda b: b.mean(), self._buffer)
@common.function
def reset(self):
tf.nest.map_structure(lambda b: b.clear(), self._buffer)
tf.nest.map_structure(
lambda acc: acc.assign(tf.zeros_like(acc)), self._return_accumulator
)
def log_metrics(metrics, prefix=''):
log = ['{0} = {1}'.format(m.name, m.log().numpy()) for m in metrics]
logging.info('%s', '{0} \n\t\t {1}'.format(prefix, '\n\t\t '.join(log)))
def _get_metric_names_from_spec(reward_spec):
reward_spec_flat = tf.nest.flatten(reward_spec)
metric_names_list = tf.nest.map_structure(lambda r: r.name, reward_spec_flat)
return metric_names_list