This repository was archived by the owner on Sep 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathcodec.py
More file actions
341 lines (263 loc) · 10.6 KB
/
codec.py
File metadata and controls
341 lines (263 loc) · 10.6 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
# Copyright 2018 Google, Inc.,
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Modules for encoding and decoding observations."""
import sonnet as snt
import tensorflow as tf
from . import batch_dist
from . import dist_module
from . import util
class EncoderSequence(snt.Sequential):
"""A wrapper arount snt.Sequential that also implements output_size."""
@property
def output_size(self):
return self.layers[-1].output_size
class FlattenEncoder(snt.AbstractModule):
"""Forwards the flattened input."""
def __init__(self, input_size=None, name=None):
super(FlattenEncoder, self).__init__(name=name)
self._input_size = None
if input_size is not None:
self._merge_input_sizes(input_size)
def _merge_input_sizes(self, input_size):
if self._input_size is None:
self._input_size = snt.nest.map(tf.TensorShape, input_size)
return
self._input_size = snt.nest.map(
lambda cur_size, inp_size: cur_size.merge_with(inp_size),
self._input_size,
input_size)
@property
def output_size(self):
"""Returns the output Tensor shapes."""
if self._input_size is None:
return tf.TensorShape([None])
flattened_size = 0
for inp_size in snt.nest.flatten(self._input_size):
num_elements = inp_size.num_elements()
if num_elements is None:
return tf.TensorShape([None])
flattened_size += num_elements
return tf.TensorShape([flattened_size])
def _build(self, inp):
input_sizes = snt.nest.map(lambda inp_i: inp_i.get_shape()[1:], inp)
self._merge_input_sizes(input_sizes)
flatten = snt.BatchFlatten(preserve_dims=1)
flat_inp = snt.nest.map(lambda inp_i: tf.to_float(flatten(inp_i)), inp)
ret = util.concat_features(flat_inp)
util.set_tensor_shapes(ret, self.output_size, add_batch_dims=1)
return ret
def MLPObsEncoder(hparams, name=None):
"""Observation -> encoded, flat observation."""
name = name or "mlp_obs_encoder"
mlp = util.make_mlp(hparams, hparams.obs_encoder_fc_layers,
name=name + "/mlp")
return EncoderSequence([FlattenEncoder(), mlp], name=name)
class DecoderSequence(dist_module.DistModule):
"""A sequence of zero or more AbstractModules, followed by a DistModule."""
def __init__(self, input_encoders, decoder, name=None):
super(DecoderSequence, self).__init__(name=name)
self._input_encoders = input_encoders
self._decoder = decoder
@property
def event_dtype(self):
return self._decoder.event_dtype
@property
def event_size(self):
return self._decoder.event_size
def dist(self, params, name=None):
return self._decoder.dist(params, name=name)
def _build(self, inputs):
if self._input_encoders:
inputs = snt.Sequential(self._input_encoders)(inputs)
return self._decoder(inputs)
def MLPObsDecoder(hparams, decoder, param_size, name=None):
"""Inputs -> decoder(obs; mlp(inputs))."""
name = name or "mlp_" + decoder.module_name
layers = hparams.obs_decoder_fc_hidden_layers + [param_size]
mlp = util.make_mlp(hparams, layers, name=name + "/mlp")
return DecoderSequence([util.concat_features, mlp], decoder, name=name)
class BernoulliDecoder(dist_module.DistModule):
"""Inputs -> Bernoulli(obs; logits=inputs)."""
def __init__(self, dtype=tf.int32, squeeze_input=False, name=None):
self._dtype = dtype
self._squeeze_input = squeeze_input
super(BernoulliDecoder, self).__init__(name=name)
@property
def event_dtype(self):
return self._dtype
@property
def event_size(self):
return tf.TensorShape([])
def _build(self, inputs):
if self._squeeze_input:
inputs = tf.squeeze(inputs, axis=-1)
return inputs
def dist(self, params, name=None):
return tf.distributions.Bernoulli(
logits=params,
dtype=self._dtype,
name=name or self.module_name + "_dist")
class BetaDecoder(dist_module.DistModule):
"""Inputs -> Beta(obs; conc1, conc0)."""
def __init__(self,
positive_projection=None,
squeeze_input=False,
name=None):
self._positive_projection = positive_projection
self._squeeze_input = squeeze_input
super(BetaDecoder, self).__init__(name=name)
@property
def event_dtype(self):
return tf.float32
@property
def event_size(self):
return tf.TensorShape([])
def _build(self, inputs):
conc1, conc0 = tf.split(inputs, 2, axis=-1)
if self._positive_projection is not None:
conc1 = self._positive_projection(conc1)
conc0 = self._positive_projection(conc0)
if self._squeeze_input:
conc1 = tf.squeeze(conc1, axis=-1)
conc0 = tf.squeeze(conc0, axis=-1)
return (conc1, conc0)
def dist(self, params, name=None):
conc1, conc0 = params
return tf.distributions.Beta(
conc1, conc0,
name=name or self.module_name + "_dist")
class _BinomialDist(tf.contrib.distributions.Binomial):
"""Work around missing functionality in Binomial."""
def __init__(self, total_count, logits=None, probs=None, name=None):
self._total_count = total_count
super(_BinomialDist, self).__init__(
total_count=tf.to_float(total_count),
logits=logits, probs=probs,
name=name or "Binomial")
def _log_prob(self, counts):
return super(_BinomialDist, self)._log_prob(tf.to_float(counts))
def _sample_n(self, n, seed=None):
all_counts = tf.to_float(tf.range(self._total_count + 1))
for batch_dim in range(self.batch_shape.ndims):
all_counts = tf.expand_dims(all_counts, axis=-1)
all_cdfs = tf.map_fn(self.cdf, all_counts)
shape = tf.concat([[n], self.batch_shape_tensor()], 0)
uniform = tf.random_uniform(shape, seed=seed)
return tf.foldl(
lambda acc, cdfs: tf.where(uniform > cdfs, acc + 1, acc),
all_cdfs,
initializer=tf.zeros(shape, dtype=tf.int32))
class BinomialDecoder(dist_module.DistModule):
"""Inputs -> Binomial(obs; total_count, logits)."""
def __init__(self, total_count=None, squeeze_input=False, name=None):
self._total_count = total_count
self._squeeze_input = squeeze_input
super(BinomialDecoder, self).__init__(name=name)
@property
def event_dtype(self):
return tf.int32
@property
def event_size(self):
return tf.TensorShape([])
def _build(self, inputs):
if self._squeeze_input:
inputs = tf.squeeze(inputs, axis=-1)
return inputs
def dist(self, params, name=None):
return _BinomialDist(
self._total_count,
logits=params,
name=name or self.module_name + "_dist")
class CategoricalDecoder(dist_module.DistModule):
"""Inputs -> Categorical(obs; logits=inputs)."""
def __init__(self, dtype=tf.int32, name=None):
self._dtype = dtype
super(CategoricalDecoder, self).__init__(name=name)
@property
def event_dtype(self):
return self._dtype
@property
def event_size(self):
return tf.TensorShape([])
def _build(self, inputs):
return inputs
def dist(self, params, name=None):
return tf.distributions.Categorical(
logits=params,
dtype=self._dtype,
name=name or self.module_name + "_dist")
class NormalDecoder(dist_module.DistModule):
"""Inputs -> Normal(obs; loc=half(inputs), scale=project(half(inputs)))"""
def __init__(self, positive_projection=None, name=None):
self._positive_projection = positive_projection
super(NormalDecoder, self).__init__(name=name)
@property
def event_dtype(self):
return tf.float32
@property
def event_size(self):
return tf.TensorShape([])
def _build(self, inputs):
loc, scale = tf.split(inputs, 2, axis=-1)
if self._positive_projection is not None:
scale = self._positive_projection(scale)
return loc, scale
def dist(self, params, name=None):
loc, scale = params
return tf.distributions.Normal(
loc=loc,
scale=scale,
name=name or self.module_name + "_dist")
class BatchDecoder(dist_module.DistModule):
"""Wrap a decoder to model batches of events."""
def __init__(self, decoder, event_size, name=None):
self._decoder = decoder
self._event_size = tf.TensorShape(event_size)
super(BatchDecoder, self).__init__(name=name)
@property
def event_dtype(self):
return self._decoder.event_dtype
@property
def event_size(self):
return self._event_size
def _build(self, inputs):
return self._decoder(inputs)
def dist(self, params, name=None):
return batch_dist.BatchDistribution(
self._decoder.dist(params, name=name),
ndims=self._event_size.ndims)
class GroupDecoder(dist_module.DistModule):
"""Group up decoders to model a set of independent of events."""
def __init__(self, decoders, name=None):
self._decoders = decoders
super(GroupDecoder, self).__init__(name=name)
@property
def event_dtype(self):
return snt.nest.map(lambda dec: dec.event_dtype, self._decoders)
@property
def event_size(self):
return snt.nest.map(lambda dec: dec.event_size, self._decoders)
def _build(self, inputs):
return snt.nest.map_up_to(
self._decoders,
lambda dec, input_: dec(input_),
self._decoders, inputs)
def dist(self, params, name=None):
with self._enter_variable_scope():
with tf.name_scope(name or "group"):
dists = snt.nest.map_up_to(
self._decoders,
lambda dec, param: dec.dist(param),
self._decoders, params)
return batch_dist.GroupDistribution(dists, name=name)