astrowavenet_model.py 12 KB
Newer Older
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
# Copyright 2018 The TensorFlow 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
#
#     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.

"""A TensorFlow WaveNet model for generative modeling of light curves.

Implementation based on "WaveNet: A Generative Model of Raw Audio":
https://arxiv.org/abs/1609.03499
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
26
import tensorflow_probability as tfp
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


def _shift_right(x):
  """Shifts the input Tensor right by one index along the second dimension.

  Pads the front with zeros and discards the last element.

  Args:
    x: Input three-dimensional tf.Tensor.

  Returns:
    Padded, shifted tensor of same shape as input.
  """
  x_padded = tf.pad(x, [[0, 0], [1, 0], [0, 0]])
  return x_padded[:, :-1, :]


class AstroWaveNet(object):
  """A TensorFlow model for generative modeling of light curves."""

  def __init__(self, features, hparams, mode):
    """Basic setup.

    The actual TensorFlow graph is constructed in build().

    Args:
      features: A dictionary containing "autoregressive_input" and
        "conditioning_stack", each of which is a named input Tensor. All
        features have dtype float32 and shape [batch_size, length, dim].
      hparams: A ConfigDict of hyperparameters for building the model.
      mode: A tf.estimator.ModeKeys to specify whether the graph should be built
        for training, evaluation or prediction.

    Raises:
      ValueError: If mode is invalid.
    """
    valid_modes = [
        tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL,
        tf.estimator.ModeKeys.PREDICT
    ]
    if mode not in valid_modes:
68
      raise ValueError("Expected mode in {}. Got: {}".format(valid_modes, mode))
69
70
71
    self.hparams = hparams
    self.mode = mode

72
73
74
    self.autoregressive_input = features["autoregressive_input"]
    self.conditioning_stack = features["conditioning_stack"]
    self.weights = features.get("weights")
75
76

    self.network_output = None  # Sum of skip connections from dilation stack.
77
    self.dist_params = None  # Dict of predicted distribution parameters.
78
    self.predicted_distributions = None  # Predicted distribution for examples.
79
    self.autoregressive_target = None  # Autoregressive target predictions.
80
81
    self.batch_losses = None  # Loss for each predicted distribution in batch.
    self.per_example_loss = None  # Loss for each example in batch.
82
    self.num_nonzero_weight_examples = None  # Number of examples in batch.
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
    self.total_loss = None  # Overall loss for the batch.
    self.global_step = None  # Global step Tensor.

  def causal_conv_layer(self, x, output_size, kernel_width, dilation_rate=1):
    """Applies a dialated causal convolution to the input.

    Args:
      x: tf.Tensor; Input tensor.
      output_size: int; Number of output filters for the convolution.
      kernel_width: int; Width of the 1D convolution window.
      dilation_rate: int; Dilation rate of the layer.

    Returns:
      Resulting tf.Tensor after applying the convolution.
    """
    causal_conv_op = tf.keras.layers.Conv1D(
        output_size,
        kernel_width,
101
        padding="causal",
102
        dilation_rate=dilation_rate,
103
        name="causal_conv")
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    return causal_conv_op(x)

  def conv_1x1_layer(self, x, output_size, activation=None):
    """Applies a 1x1 convolution to the input.

    Args:
      x: tf.Tensor; Input tensor.
      output_size: int; Number of output filters for the 1x1 convolution.
      activation: Activation function to apply (e.g. 'relu').

    Returns:
      Resulting tf.Tensor after applying the 1x1 convolution.
    """
    conv_1x1_op = tf.keras.layers.Conv1D(
118
        output_size, 1, activation=activation, name="conv1x1")
119
120
121
122
123
124
125
126
127
128
129
130
131
    return conv_1x1_op(x)

  def gated_residual_layer(self, x, dilation_rate):
    """Creates a gated, dilated convolutional layer with a residual connnection.

    Args:
      x: tf.Tensor; Input tensor
      dilation_rate: int; Dilation rate of the layer.

    Returns:
      skip_connection: tf.Tensor; Skip connection to network_output layer.
      residual_connection: tf.Tensor; Sum of learned residual and input tensor.
    """
132
133
134
135
    with tf.variable_scope("filter"):
      x_filter_conv = self.causal_conv_layer(x, x.shape[-1].value,
                                             self.hparams.dilation_kernel_width,
                                             dilation_rate)
136
      cond_filter_conv = self.conv_1x1_layer(self.conditioning_stack,
137
138
139
140
141
                                             x.shape[-1].value)
    with tf.variable_scope("gate"):
      x_gate_conv = self.causal_conv_layer(x, x.shape[-1].value,
                                           self.hparams.dilation_kernel_width,
                                           dilation_rate)
142
      cond_gate_conv = self.conv_1x1_layer(self.conditioning_stack,
143
                                           x.shape[-1].value)
144
145
146
147
148

    gated_activation = (
        tf.tanh(x_filter_conv + cond_filter_conv) *
        tf.sigmoid(x_gate_conv + cond_gate_conv))

149
150
151
    with tf.variable_scope("residual"):
      residual = self.conv_1x1_layer(gated_activation, x.shape[-1].value)
    with tf.variable_scope("skip"):
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
      skip_connection = self.conv_1x1_layer(gated_activation,
                                            self.hparams.skip_output_dim)

    return skip_connection, x + residual

  def build_network(self):
    """Builds WaveNet network.

    This consists of:
      1) An initial causal convolution,
      2) The dialation stack, and
      3) Summing of skip connections

    The network output can then be used to predict various output distributions.

    Inputs:
      self.autoregressive_input
      self.conditioning_stack

    Outputs:
      self.network_output; tf.Tensor
    """
    skip_connections = []
    x = _shift_right(self.autoregressive_input)
176
    with tf.variable_scope("preprocess"):
177
178
179
      x = self.causal_conv_layer(x, self.hparams.preprocess_output_size,
                                 self.hparams.preprocess_kernel_width)
    for i in range(self.hparams.num_residual_blocks):
180
      with tf.variable_scope("block_{}".format(i)):
181
        for dilation_rate in self.hparams.dilation_rates:
182
          with tf.variable_scope("dilation_{}".format(dilation_rate)):
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
            skip_connection, x = self.gated_residual_layer(x, dilation_rate)
            skip_connections.append(skip_connection)

    self.network_output = tf.add_n(skip_connections)

  def dist_params_layer(self, x, outputs_size):
    """Converts x to the correct shape for populating a distribution object.

    Args:
      x: A Tensor of shape [batch_size, time_series_length, num_features].
      outputs_size: The number of parameters needed to specify all the
        distributions in the output. E.g. 5*3=15 to specify 5 distributions with
        3 parameters each.

    Returns:
      The parameters of each distribution, a tensor of shape [batch_size,
        time_series_length, outputs_size].
    """
201
    with tf.variable_scope("dist_params"):
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
      conv_outputs = self.conv_1x1_layer(x, outputs_size)
    return conv_outputs

  def build_predictions(self):
    """Predicts output distribution from network outputs.

    Runs the model through:
      1) ReLU
      2) 1x1 convolution
      3) ReLU
      4) 1x1 convolution

    The result of the last convolution is used as the parameters of the
    specified output distribution (currently either Categorical or Normal).

    Inputs:
      self.network_outputs

    Outputs:
221
      self.dist_params
222
223
224
225
226
      self.predicted_distributions

    Raises:
      ValueError: If distribution type is neither 'categorical' nor 'normal'.
    """
227
    with tf.variable_scope("postprocess"):
228
229
230
      network_output = tf.keras.activations.relu(self.network_output)
      network_output = self.conv_1x1_layer(
          network_output,
231
232
233
          output_size=network_output.shape[-1].value,
          activation="relu")
    num_dists = self.autoregressive_input.shape[-1].value
234

235
    if self.hparams.output_distribution.type == "categorical":
236
      num_classes = self.hparams.output_distribution.num_classes
237
238
      logits = self.dist_params_layer(network_output, num_dists * num_classes)
      logits_shape = tf.concat(
239
          [tf.shape(network_output)[:-1], [num_dists, num_classes]], 0)
240
241
242
243
244
245
      logits = tf.reshape(logits, logits_shape)
      dist = tfp.distributions.Categorical(logits=logits)
      dist_params = {"logits": logits}
    elif self.hparams.output_distribution.type == "normal":
      loc_scale = self.dist_params_layer(network_output, num_dists * 2)
      loc, scale = tf.split(loc_scale, 2, axis=-1)
246
247
      # Ensure scale is positive.
      scale = tf.nn.softplus(scale) + self.hparams.output_distribution.min_scale
248
249
      dist = tfp.distributions.Normal(loc, scale)
      dist_params = {"loc": loc, "scale": scale}
250
    else:
251
      raise ValueError("Unsupported distribution type {}".format(
252
          self.hparams.output_distribution.type))
253
254

    self.dist_params = dist_params
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
    self.predicted_distributions = dist

  def build_losses(self):
    """Builds the training losses.

    Inputs:
      self.predicted_distributions

    Outputs:
      self.batch_losses
      self.total_loss
    """
    autoregressive_target = self.autoregressive_input

    # Quantize the target if the output distribution is categorical.
270
    if self.hparams.output_distribution.type == "categorical":
271
272
273
274
275
276
277
278
279
280
281
282
      min_val = self.hparams.output_distribution.min_quantization_value
      max_val = self.hparams.output_distribution.max_quantization_value
      num_classes = self.hparams.output_distribution.num_classes
      clipped_target = tf.keras.backend.clip(autoregressive_target, min_val,
                                             max_val)
      quantized_target = tf.floor(
          (clipped_target - min_val) / (max_val - min_val) * num_classes)
      # Deal with the corner case where clipped_target equals max_val by mapping
      # the label num_classes to num_classes - 1. Essentially, this makes the
      # final quantized bucket a closed interval while all the other quantized
      # buckets are half-open intervals.
      quantized_target = tf.where(
283
          quantized_target >= num_classes,
284
285
286
287
288
289
290
291
292
          tf.ones_like(quantized_target) * (num_classes - 1), quantized_target)
      autoregressive_target = quantized_target

    log_prob = self.predicted_distributions.log_prob(autoregressive_target)

    weights = self.weights
    if weights is None:
      weights = tf.ones_like(log_prob)
    weights_dim = len(weights.shape)
293
294
    per_example_weight = tf.reduce_sum(
        weights, axis=list(range(1, weights_dim)))
295
    per_example_indicator = tf.to_float(tf.greater(per_example_weight, 0))
296
    num_examples = tf.reduce_sum(per_example_indicator)
297
298

    batch_losses = -log_prob * weights
299
    losses_ndims = batch_losses.shape.ndims
300
    per_example_loss_sum = tf.reduce_sum(
301
        batch_losses, axis=list(range(1, losses_ndims)))
302
303
304
305
306
    per_example_loss = tf.where(per_example_weight > 0,
                                per_example_loss_sum / per_example_weight,
                                tf.zeros_like(per_example_weight))
    total_loss = tf.reduce_sum(per_example_loss) / num_examples

307
    self.autoregressive_target = autoregressive_target
308
309
    self.batch_losses = batch_losses
    self.per_example_loss = per_example_loss
310
    self.num_nonzero_weight_examples = num_examples
311
312
313
314
315
316
317
318
319
320
321
    self.total_loss = total_loss

  def build(self):
    """Creates all ops for training, evaluation or inference."""
    self.global_step = tf.train.get_or_create_global_step()

    self.build_network()
    self.build_predictions()

    if self.mode in [tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL]:
      self.build_losses()