Beispiel #1
0
    def test_skipped_ops(self):
        with context.eager_mode():
            x = constant_op.constant(np.ones((1, 1, 1, 1)).astype(np.float32))

            # Cast is on the hardcoded list of ops to skip
            gen_math_ops.cast(x, dtypes.float64)
            self.assertEmpty(self._get_new_node_defs())

            gen_nn_ops.conv2d(x, x, [1, 1, 1, 1], 'SAME')
            y = constant_op.constant(np.zeros((1, 1, 1, 1)).astype(np.float32))
            # Duplicate ops are skipped, even if input values are different
            gen_nn_ops.conv2d(x, y, [1, 1, 1, 1], 'SAME')
            if not IsMklEnabled():
                self.assertLen(self._get_new_node_defs(), 1)
            else:
                ndefs = self._get_new_node_defs()
                if (len(ndefs) >= 1 and ndefs[0].op != ndefs[1].op):
                    # One of the ops got rewritten by oneDNN optimization pass
                    self.assertLen(ndefs, 2)
                else:
                    self.assertLen(ndefs, 1)

            x = constant_op.constant(
                np.ones((1, 1, 1, 1, 1, 1)).astype(np.float32))
            paddings = constant_op.constant(np.ones((6, 2)).astype(np.int32))
            constant_values = constant_op.constant(0.)
            # If an host int32 input has more than 10 elements, the op is skipped
            gen_array_ops.pad_v2(x, paddings, constant_values)
            self.assertEmpty(self._get_new_node_defs())
Beispiel #2
0
def _Conv2DBackpropInputGrad(op, grad):
    """The derivatives for deconvolution.

  Args:
    op: the Deconvolution op.
    grad: the tensor representing the gradient w.r.t. the output

  Returns:
    the gradients w.r.t. the input and the filter
  """
    # We call the gen_nn_ops backprop functions instead of nn_ops backprop
    # functions for performance reasons in Eager mode. See _Conv2DGrad.
    return [
        None,
        gen_nn_ops.conv2d_backprop_filter(
            grad,
            array_ops.shape(op.inputs[1]),
            op.inputs[2],
            dilations=op.get_attr("dilations"),
            strides=op.get_attr("strides"),
            padding=op.get_attr("padding"),
            explicit_paddings=op.get_attr("explicit_paddings"),
            use_cudnn_on_gpu=op.get_attr("use_cudnn_on_gpu"),
            data_format=op.get_attr("data_format").decode()),
        gen_nn_ops.conv2d(grad,
                          op.inputs[1],
                          dilations=op.get_attr("dilations"),
                          strides=op.get_attr("strides"),
                          padding=op.get_attr("padding"),
                          explicit_paddings=op.get_attr("explicit_paddings"),
                          use_cudnn_on_gpu=op.get_attr("use_cudnn_on_gpu"),
                          data_format=op.get_attr("data_format").decode())
    ]
Beispiel #3
0
def conv2d_layer(inputs,
                 filters,
                 kernel_size,
                 strides=(1, 1),
                 padding="valid",
                 data_format="channels_last",
                 dilation_rate=(1, 1),
                 name=None):
    dtype = inputs.dtype
    c_axis = -1 if data_format == "channels_last" else 1
    nchan = inputs.shape[c_axis]
    weights_shape = (kernel_size[0], kernel_size[1], nchan, filters)
    weights = constant_op.constant(np.random.randn(*weights_shape),
                                   dtype=dtype)
    padding = padding.upper()
    if data_format == "channels_last":
        strides = [1] + list(strides) + [1]
        dilations = [1] + list(dilation_rate) + [1]
        data_format = "NHWC"
    else:
        strides = [1, 1] + list(strides)
        dilations = [1, 1] + list(dilation_rate)
        data_format = "NCHW"
    return gen_nn_ops.conv2d(inputs,
                             weights,
                             strides=strides,
                             padding=padding,
                             dilations=dilations,
                             data_format=data_format)
Beispiel #4
0
def conv2d_layer(inputs,
                 filters,
                 kernel_size,
                 strides=(1, 1),
                 padding="valid",
                 data_format="channels_last",
                 dilation_rate=(1, 1),
                 name=None):
  dtype = inputs.dtype
  c_axis = -1 if data_format == "channels_last" else 1
  nchan = inputs.shape[c_axis]
  weights_shape = (kernel_size[0], kernel_size[1], nchan, filters)
  weights = constant_op.constant(np.random.randn(*weights_shape), dtype=dtype)
  padding = padding.upper()
  if data_format == "channels_last":
    strides = [1] + list(strides) + [1]
    dilations = [1] + list(dilation_rate) + [1]
    data_format = "NHWC"
  else:
    strides = [1, 1] + list(strides)
    dilations = [1, 1] + list(dilation_rate)
    data_format = "NCHW"
  return gen_nn_ops.conv2d(
      inputs,
      weights,
      strides=strides,
      padding=padding,
      dilations=dilations,
      data_format=data_format)
Beispiel #5
0
 def run(self, inp):
   if self.v is None:
     self.v = variables.Variable([[[[1., 0.5, 4., 6., 0.5, 1.],
                                    [1., 0.5, 1., 1., 0.5, 1.]]]])
   conv = gen_nn_ops.conv2d(
       input=inp, filter=self.v, strides=[1, 2, 2, 1], padding="SAME")
   identity = array_ops.identity(conv)
   return identity
Beispiel #6
0
 def run(self, inp):
   if self.v is None:
     self.v = variables.Variable([[[[1., 0.5, 4., 6., 0.5, 1.],
                                    [1., 0.5, 1., 1., 0.5, 1.]]]])
   conv = gen_nn_ops.conv2d(
       input=inp, filter=self.v, strides=[1, 2, 2, 1], padding="SAME")
   identity = array_ops.identity(conv)
   return identity
Beispiel #7
0
    def test_skipped_ops(self):
        with context.eager_mode():
            x = constant_op.constant(np.ones((1, 1, 1, 1)).astype(np.float32))

            # Cast is on the hardcoded list of ops to skip
            gen_math_ops.cast(x, dtypes.float64)
            self.assertEmpty(self._get_new_node_defs())

            gen_nn_ops.conv2d(x, x, [1, 1, 1, 1], 'SAME')
            y = constant_op.constant(np.zeros((1, 1, 1, 1)).astype(np.float32))
            # Duplicate ops are skipped, even if input values are different
            gen_nn_ops.conv2d(x, y, [1, 1, 1, 1], 'SAME')
            self.assertLen(self._get_new_node_defs(), 1)

            x = constant_op.constant(
                np.ones((1, 1, 1, 1, 1, 1)).astype(np.float32))
            paddings = constant_op.constant(np.ones((6, 2)).astype(np.int32))
            constant_values = constant_op.constant(0.)
            # If an host int32 input has more than 10 elements, the op is skipped
            gen_array_ops.pad_v2(x, paddings, constant_values)
            self.assertEmpty(self._get_new_node_defs())
Beispiel #8
0
def conv1d(value,
           filters,
           stride,
           padding,
           use_cudnn_on_gpu=None,
           data_format=None,
           name=None):
    """Computes a 1-D convolution given 3-D input and filter tensors.

  Given an input tensor of shape [batch, in_width, in_channels]
  and a filter / kernel tensor of shape
  [filter_width, in_channels, out_channels], this op reshapes
  the arguments to pass them to conv2d to perform the equivalent
  convolution operation.

  Internally, this op reshapes the input tensors and invokes
  `tf.nn.conv2d`.  A tensor of shape [batch, in_width, in_channels]
  is reshaped to [batch, 1, in_width, in_channels], and the filter
  is reshaped to [1, filter_width, in_channels, out_channels].
  The result is then reshaped back to [batch, out_width, out_channels]
  (where out_width is a function of the stride and padding as in
  conv2d) and returned to the caller.

  Args:
    value: A 3D `Tensor`.  Must be of type `float32` or `float64`.
    filters: A 3D `Tensor`.  Must have the same type as `input`.
    stride: An `integer`.  The number of entries by which
      the filter is moved right at each step.
    padding: 'SAME' or 'VALID'
    use_cudnn_on_gpu: An optional `bool`.  Defaults to `True`.
    data_format: An optional `string` from `"NHWC", "NCHW"`.  Defaults
      to `"NHWC"`, the data is stored in the order of
      [batch, in_width, in_channels].  The `"NCHW"` format stores
      data as [batch, in_channels, in_width].
    name: A name for the operation (optional).

  Returns:
    A `Tensor`.  Has the same type as input.
  """
    with ops.op_scope([value, filters], name, "conv1d") as name:
        # Reshape the input tensor to [batch, 1, in_width, in_channels]
        value = array_ops.expand_dims(value, 1)
        # And reshape the filter to [1, filter_width, in_channels, out_channels]
        filters = array_ops.expand_dims(filters, 0)
        result = gen_nn_ops.conv2d(value,
                                   filters, [1, 1, stride, 1],
                                   padding,
                                   use_cudnn_on_gpu=use_cudnn_on_gpu,
                                   data_format=data_format)
        return array_ops.squeeze(result, [1])
Beispiel #9
0
def conv1d(value, filters, stride, padding,
           use_cudnn_on_gpu=None, data_format=None,
           name=None):
  """Computes a 1-D convolution given 3-D input and filter tensors.

  Given an input tensor of shape [batch, in_width, in_channels]
  and a filter / kernel tensor of shape
  [filter_width, in_channels, out_channels], this op reshapes
  the arguments to pass them to conv2d to perform the equivalent
  convolution operation.

  Internally, this op reshapes the input tensors and invokes
  `tf.nn.conv2d`.  A tensor of shape [batch, in_width, in_channels]
  is reshaped to [batch, 1, in_width, in_channels], and the filter
  is reshaped to [1, filter_width, in_channels, out_channels].
  The result is then reshaped back to [batch, out_width, out_channels]
  (where out_width is a function of the stride and padding as in
  conv2d) and returned to the caller.

  Args:
    value: A 3D `Tensor`.  Must be of type `float32` or `float64`.
    filters: A 3D `Tensor`.  Must have the same type as `input`.
    stride: An `integer`.  The number of entries by which
      the filter is moved right at each step.
    padding: 'SAME' or 'VALID'
    use_cudnn_on_gpu: An optional `bool`.  Defaults to `True`.
    data_format: An optional `string` from `"NHWC", "NCHW"`.  Defaults
      to `"NHWC"`, the data is stored in the order of
      [batch, in_width, in_channels].  The `"NCHW"` format stores
      data as [batch, in_channels, in_width].
    name: A name for the operation (optional).

  Returns:
    A `Tensor`.  Has the same type as input.
  """
  with ops.op_scope([value, filters], name, "conv1d") as name:
    # Reshape the input tensor to [batch, 1, in_width, in_channels]
    value = array_ops.expand_dims(value, 1)
    # And reshape the filter to [1, filter_width, in_channels, out_channels]
    filters = array_ops.expand_dims(filters, 0)
    result = gen_nn_ops.conv2d(value, filters, [1, 1, stride, 1], padding,
                               use_cudnn_on_gpu=use_cudnn_on_gpu,
                               data_format=data_format)
    return array_ops.squeeze(result, [1])
Beispiel #10
0
def _Conv2DBackpropFilterGrad(op, grad):
    # We call the gen_nn_ops backprop functions instead of nn_ops backprop
    # functions for performance reasons in Eager mode. See _Conv2DGrad.
    return [
        gen_nn_ops.conv2d_backprop_input(
            array_ops.shape(op.inputs[0]),
            grad,
            op.inputs[2],
            dilations=op.get_attr("dilations"),
            strides=op.get_attr("strides"),
            padding=op.get_attr("padding"),
            explicit_paddings=op.get_attr("explicit_paddings"),
            use_cudnn_on_gpu=op.get_attr("use_cudnn_on_gpu"),
            data_format=op.get_attr("data_format").decode()), None,
        gen_nn_ops.conv2d(op.inputs[0],
                          grad,
                          dilations=op.get_attr("dilations"),
                          strides=op.get_attr("strides"),
                          padding=op.get_attr("padding"),
                          explicit_paddings=op.get_attr("explicit_paddings"),
                          use_cudnn_on_gpu=op.get_attr("use_cudnn_on_gpu"),
                          data_format=op.get_attr("data_format").decode())
    ]
Beispiel #11
0
def atrous_conv2d(value, filters, rate, padding, name=None):
  """Atrous convolution (a.k.a. convolution with holes or dilated convolution).

  Computes a 2-D atrous convolution, also known as convolution with holes or
  dilated convolution, given 4-D `value` and `filters` tensors. If the `rate`
  parameter is equal to one, it performs regular 2-D convolution. If the `rate`
  parameter is greater than one, it performs convolution with holes, sampling
  the input values every `rate` pixels in the `height` and `width` dimensions.
  This is equivalent to convolving the input with a set of upsampled filters,
  produced by inserting `rate - 1` zeros between two consecutive values of the
  filters along the `height` and `width` dimensions, hence the name atrous
  convolution or convolution with holes (the French word trous means holes in
  English).

  More specifically:

      output[b, i, j, k] = sum_{di, dj, q} filters[di, dj, q, k] *
            value[b, i + rate * di, j + rate * dj, q]

  Atrous convolution allows us to explicitly control how densely to compute
  feature responses in fully convolutional networks. Used in conjunction with
  bilinear interpolation, it offers an alternative to `conv2d_transpose` in
  dense prediction tasks such as semantic image segmentation, optical flow
  computation, or depth estimation. It also allows us to effectively enlarge
  the field of view of filters without increasing the number of parameters or
  the amount of computation.

  For a description of atrous convolution and how it can be used for dense
  feature extraction, please see: [Semantic Image Segmentation with Deep
  Convolutional Nets and Fully Connected CRFs](http://arxiv.org/abs/1412.7062).
  The same operation is investigated further in [Multi-Scale Context Aggregation
  by Dilated Convolutions](http://arxiv.org/abs/1511.07122). Previous works
  that effectively use atrous convolution in different ways are, among others,
  [OverFeat: Integrated Recognition, Localization and Detection using
  Convolutional Networks](http://arxiv.org/abs/1312.6229) and [Fast Image
  Scanning with Deep Max-Pooling Convolutional Neural Networks]
  (http://arxiv.org/abs/1302.1700). Atrous convolution is also closely related
  to the so-called noble identities in multi-rate signal processing.

  There are many different ways to implement atrous convolution (see the refs
  above). The implementation here reduces

      atrous_conv2d(value, filters, rate, padding=padding)

  to the following three operations:

      paddings = ...
      net = space_to_batch(value, paddings, block_size=rate)
      net = conv2d(net, filters, strides=[1, 1, 1, 1], padding="VALID")
      crops = ...
      net = batch_to_space(net, crops, block_size=rate)

  Advanced usage. Note the following optimization: A sequence of `atrous_conv2d`
  operations with identical `rate` parameters, 'SAME' `padding`, and filters
  with odd heights/ widths:

      net = atrous_conv2d(net, filters1, rate, padding="SAME")
      net = atrous_conv2d(net, filters2, rate, padding="SAME")
      ...
      net = atrous_conv2d(net, filtersK, rate, padding="SAME")

  can be equivalently performed cheaper in terms of computation and memory as:

      pad = ...  # padding so that the input dims are multiples of rate
      net = space_to_batch(net, paddings=pad, block_size=rate)
      net = conv2d(net, filters1, strides=[1, 1, 1, 1], padding="SAME")
      net = conv2d(net, filters2, strides=[1, 1, 1, 1], padding="SAME")
      ...
      net = conv2d(net, filtersK, strides=[1, 1, 1, 1], padding="SAME")
      net = batch_to_space(net, crops=pad, block_size=rate)

  because a pair of consecutive `space_to_batch` and `batch_to_space` ops with
  the same `block_size` cancel out when their respective `paddings` and `crops`
  inputs are identical.

  Args:
    value: A 4-D `Tensor` of type `float`. It needs to be in the default "NHWC"
      format. Its shape is `[batch, in_height, in_width, in_channels]`.
    filters: A 4-D `Tensor` with the same type as `value` and shape
      `[filter_height, filter_width, in_channels, out_channels]`. `filters`'
      `in_channels` dimension must match that of `value`. Atrous convolution is
      equivalent to standard convolution with upsampled filters with effective
      height `filter_height + (filter_height - 1) * (rate - 1)` and effective
      width `filter_width + (filter_width - 1) * (rate - 1)`, produced by
      inserting `rate - 1` zeros along consecutive elements across the
      `filters`' spatial dimensions.
    rate: A positive int32. The stride with which we sample input values across
      the `height` and `width` dimensions. Equivalently, the rate by which we
      upsample the filter values by inserting zeros across the `height` and
      `width` dimensions. In the literature, the same parameter is sometimes
      called `input stride` or `dilation`.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
    name: Optional name for the returned tensor.

  Returns:
    A `Tensor` with the same type as `value`.

  Raises:
    ValueError: If input/output depth does not match `filters`' shape, or if
      padding is other than `'VALID'` or `'SAME'`.
  """
  with ops.op_scope([value, filters], name, "atrous_conv2d") as name:
    value = ops.convert_to_tensor(value, name="value")
    filters = ops.convert_to_tensor(filters, name="filters")
    value_shape = value.get_shape()
    filter_shape = filters.get_shape()
    if not value_shape[3].is_compatible_with(filter_shape[2]):
      raise ValueError(
          "value's input channels does not match filters' input channels, "
          "{} != {}".format(value_shape[3], filter_shape[2]))
    if rate < 1:
      raise ValueError("rate {} cannot be less than one".format(rate))

    if rate == 1:
      value = gen_nn_ops.conv2d(input=value,
                                filter=filters,
                                strides=[1, 1, 1, 1],
                                padding=padding)
      return value

    # We have two padding contributions. The first is used for converting "SAME"
    # to "VALID". The second is required so that the height and width of the
    # zero-padded value tensor are multiples of rate.

    # Spatial dimensions of original input
    value_shape = array_ops.shape(value)
    in_height = value_shape[1]
    in_width = value_shape[2]

    # Spatial dimensions of the filters and the upsampled filters in which we
    # introduce (rate - 1) zeros between consecutive filter values.
    filter_height = int(filter_shape[0])
    filter_width = int(filter_shape[1])
    filter_height_up = filter_height + (filter_height - 1) * (rate - 1)
    filter_width_up = filter_width + (filter_width - 1) * (rate - 1)

    # Padding required to reduce to "VALID" convolution
    if padding == "SAME":
      pad_height = filter_height_up - 1
      pad_width = filter_width_up - 1
    elif padding == "VALID":
      pad_height = 0
      pad_width = 0
    else:
      raise ValueError("Invalid padding")
    # When padding is "SAME" and the pad_height (pad_width) is odd, we pad more
    # to bottom (right), following the same convention as conv2d().
    pad_top = math_ops.floordiv(pad_height, 2)
    pad_bottom = pad_height - pad_top
    pad_left = math_ops.floordiv(pad_width, 2)
    pad_right = pad_width - pad_left

    # More padding so that rate divides the height and width of the input value
    in_height = in_height + pad_top + pad_bottom
    in_width = in_width + pad_left + pad_right

    mod_height = math_ops.mod(in_height, rate)
    mod_width = math_ops.mod(in_width, rate)
    null = constant_op.constant(0)
    pad_bottom_extra = control_flow_ops.cond(gen_math_ops.equal(mod_height, 0), lambda: null, lambda: rate - mod_height)
    pad_right_extra = control_flow_ops.cond(gen_math_ops.equal(mod_width, 0), lambda: null, lambda: rate - mod_width)

    # The paddings argument to space_to_batch includes both padding components
    pad_bottom = pad_bottom + pad_bottom_extra
    pad_right = pad_right + pad_right_extra

    space_to_batch_pad = [[pad_top, pad_bottom], [pad_left, pad_right]]

    value = array_ops.space_to_batch(input=value,
                                     paddings=space_to_batch_pad,
                                     block_size=rate)
        
    value = gen_nn_ops.conv2d(input=value,
                              filter=filters,
                              strides=[1, 1, 1, 1],
                              padding="VALID",
                              name=name)

    # The crops argument to batch_to_space is just the extra padding component
    batch_to_space_crop = [[0, pad_bottom_extra], [0, pad_right_extra]]
    value = array_ops.batch_to_space(input=value,
                                     crops=batch_to_space_crop,
                                     block_size=rate)

    return value
Beispiel #12
0
def atrous_conv2d(value, filters, rate, padding, name=None):
    """Atrous convolution (a.k.a. convolution with holes or dilated convolution).

  Computes a 2-D atrous convolution, also known as convolution with holes or
  dilated convolution, given 4-D `value` and `filters` tensors. If the `rate`
  parameter is equal to one, it performs regular 2-D convolution. If the `rate`
  parameter is greater than one, it performs convolution with holes, sampling
  the input values every `rate` pixels in the `height` and `width` dimensions.
  This is equivalent to convolving the input with a set of upsampled filters,
  produced by inserting `rate - 1` zeros between two consecutive values of the
  filters along the `height` and `width` dimensions, hence the name atrous
  convolution or convolution with holes (the French word trous means holes in
  English).

  More specifically:

      output[b, i, j, k] = sum_{di, dj, q} filters[di, dj, q, k] *
            value[b, i + rate * di, j + rate * dj, q]

  Atrous convolution allows us to explicitly control how densely to compute
  feature responses in fully convolutional networks. Used in conjunction with
  bilinear interpolation, it offers an alternative to `conv2d_transpose` in
  dense prediction tasks such as semantic image segmentation, optical flow
  computation, or depth estimation. It also allows us to effectively enlarge
  the field of view of filters without increasing the number of parameters or
  the amount of computation.

  For a description of atrous convolution and how it can be used for dense
  feature extraction, please see: [Semantic Image Segmentation with Deep
  Convolutional Nets and Fully Connected CRFs](http://arxiv.org/abs/1412.7062).
  The same operation is investigated further in [Multi-Scale Context Aggregation
  by Dilated Convolutions](http://arxiv.org/abs/1511.07122). Previous works
  that effectively use atrous convolution in different ways are, among others,
  [OverFeat: Integrated Recognition, Localization and Detection using
  Convolutional Networks](http://arxiv.org/abs/1312.6229) and [Fast Image
  Scanning with Deep Max-Pooling Convolutional Neural Networks]
  (http://arxiv.org/abs/1302.1700). Atrous convolution is also closely related
  to the so-called noble identities in multi-rate signal processing.

  There are many different ways to implement atrous convolution (see the refs
  above). The implementation here reduces

      atrous_conv2d(value, filters, rate, padding=padding)

  to the following three operations:

      paddings = ...
      net = space_to_batch(value, paddings, block_size=rate)
      net = conv2d(net, filters, strides=[1, 1, 1, 1], padding="VALID")
      crops = ...
      net = batch_to_space(net, crops, block_size=rate)

  Advanced usage. Note the following optimization: A sequence of `atrous_conv2d`
  operations with identical `rate` parameters, 'SAME' `padding`, and filters
  with odd heights/ widths:

      net = atrous_conv2d(net, filters1, rate, padding="SAME")
      net = atrous_conv2d(net, filters2, rate, padding="SAME")
      ...
      net = atrous_conv2d(net, filtersK, rate, padding="SAME")

  can be equivalently performed cheaper in terms of computation and memory as:

      pad = ...  # padding so that the input dims are multiples of rate
      net = space_to_batch(net, paddings=pad, block_size=rate)
      net = conv2d(net, filters1, strides=[1, 1, 1, 1], padding="SAME")
      net = conv2d(net, filters2, strides=[1, 1, 1, 1], padding="SAME")
      ...
      net = conv2d(net, filtersK, strides=[1, 1, 1, 1], padding="SAME")
      net = batch_to_space(net, crops=pad, block_size=rate)

  because a pair of consecutive `space_to_batch` and `batch_to_space` ops with
  the same `block_size` cancel out when their respective `paddings` and `crops`
  inputs are identical.

  Args:
    value: A 4-D `Tensor` of type `float`. It needs to be in the default "NHWC"
      format. Its shape is `[batch, in_height, in_width, in_channels]`.
    filters: A 4-D `Tensor` with the same type as `value` and shape
      `[filter_height, filter_width, in_channels, out_channels]`. `filters`'
      `in_channels` dimension must match that of `value`. Atrous convolution is
      equivalent to standard convolution with upsampled filters with effective
      height `filter_height + (filter_height - 1) * (rate - 1)` and effective
      width `filter_width + (filter_width - 1) * (rate - 1)`, produced by
      inserting `rate - 1` zeros along consecutive elements across the
      `filters`' spatial dimensions.
    rate: A positive int32. The stride with which we sample input values across
      the `height` and `width` dimensions. Equivalently, the rate by which we
      upsample the filter values by inserting zeros across the `height` and
      `width` dimensions. In the literature, the same parameter is sometimes
      called `input stride` or `dilation`.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
    name: Optional name for the returned tensor.

  Returns:
    A `Tensor` with the same type as `value`.

  Raises:
    ValueError: If input/output depth does not match `filters`' shape, or if
      padding is other than `'VALID'` or `'SAME'`.
  """
    with ops.op_scope([value, filters], name, "atrous_conv2d") as name:
        value = ops.convert_to_tensor(value, name="value")
        filters = ops.convert_to_tensor(filters, name="filters")
        value_shape = value.get_shape()
        filter_shape = filters.get_shape()
        if not value_shape[3].is_compatible_with(filter_shape[2]):
            raise ValueError(
                "value's input channels does not match filters' input channels, "
                "{} != {}".format(value_shape[3], filter_shape[2]))
        if rate < 1:
            raise ValueError("rate {} cannot be less than one".format(rate))

        if rate == 1:
            value = gen_nn_ops.conv2d(input=value,
                                      filter=filters,
                                      strides=[1, 1, 1, 1],
                                      padding=padding)
            return value

        # We have two padding contributions. The first is used for converting "SAME"
        # to "VALID". The second is required so that the height and width of the
        # zero-padded value tensor are multiples of rate.

        # Spatial dimensions of original input
        in_height = int(value_shape[1])
        in_width = int(value_shape[2])

        # Spatial dimensions of the filters and the upsampled filters in which we
        # introduce (rate - 1) zeros between consecutive filter values.
        filter_height = int(filter_shape[0])
        filter_width = int(filter_shape[1])
        filter_height_up = filter_height + (filter_height - 1) * (rate - 1)
        filter_width_up = filter_width + (filter_width - 1) * (rate - 1)

        # Padding required to reduce to "VALID" convolution
        if padding == "SAME":
            pad_height = filter_height_up - 1
            pad_width = filter_width_up - 1
        elif padding == "VALID":
            pad_height = 0
            pad_width = 0
        else:
            raise ValueError("Invalid padding")
        # When padding is "SAME" and the pad_height (pad_width) is odd, we pad more
        # to bottom (right), following the same convention as conv2d().
        pad_top = pad_height // 2
        pad_bottom = pad_height - pad_top
        pad_left = pad_width // 2
        pad_right = pad_width - pad_left

        # More padding so that rate divides the height and width of the input value
        in_height = in_height + pad_top + pad_bottom
        in_width = in_width + pad_left + pad_right
        pad_bottom_extra = 0 if in_height % rate == 0 else rate - in_height % rate
        pad_right_extra = 0 if in_width % rate == 0 else rate - in_width % rate

        # The paddings argument to space_to_batch includes both padding components
        space_to_batch_pad = [[pad_top, pad_bottom + pad_bottom_extra],
                              [pad_left, pad_right + pad_right_extra]]
        value = array_ops.space_to_batch(input=value,
                                         paddings=space_to_batch_pad,
                                         block_size=rate)

        value = gen_nn_ops.conv2d(input=value,
                                  filter=filters,
                                  strides=[1, 1, 1, 1],
                                  padding="VALID",
                                  name=name)

        # The crops argument to batch_to_space is just the extra padding component
        batch_to_space_crop = [[0, pad_bottom_extra], [0, pad_right_extra]]
        value = array_ops.batch_to_space(input=value,
                                         crops=batch_to_space_crop,
                                         block_size=rate)

        return value
Beispiel #13
0
def atrous_conv2d(value, filters, rate, padding, name=None):
  with ops.op_scope([value, filters], name, "atrous_conv2d") as name:
    value = ops.convert_to_tensor(value, name="value")
    filters = ops.convert_to_tensor(filters, name="filters")
    value_shape = value.get_shape()
    filter_shape = filters.get_shape()
    if not value_shape[3].is_compatible_with(filter_shape[2]):
      raise ValueError(
          "value's input channels does not match filters' input channels, "
          "{} != {}".format(value_shape[3], filter_shape[2]))
    if rate < 1:
      raise ValueError("rate {} cannot be less than one".format(rate))

    if rate == 1:
      value = gen_nn_ops.conv2d(input=value,
                                filter=filters,
                                strides=[1, 1, 1, 1],
                                padding=padding)
      return value

    # We have two padding contributions. The first is used for converting "SAME"
    # to "VALID". The second is required so that the height and width of the
    # zero-padded value tensor are multiples of rate.

    # Spatial dimensions of original input
    value_shape = array_ops.shape(value)
    in_height = value_shape[1]
    in_width = value_shape[2]

    # Spatial dimensions of the filters and the upsampled filters in which we
    # introduce (rate - 1) zeros between consecutive filter values.
    filter_shape = array_ops.shape(filters)
    filter_height = filter_shape[0]
    filter_width = filter_shape[1]
    filter_height_up = filter_height + (filter_height - 1) * (rate - 1)
    filter_width_up = filter_width + (filter_width - 1) * (rate - 1)

    # Padding required to reduce to "VALID" convolution
    if padding == "SAME":
      pad_height = filter_height_up - 1
      pad_width = filter_width_up - 1
    elif padding == "VALID":
      pad_height = 0
      pad_width = 0
    else:
      raise ValueError("Invalid padding")
    # When padding is "SAME" and the pad_height (pad_width) is odd, we pad more
    # to bottom (right), following the same convention as conv2d().
    pad_top = math_ops.floordiv(pad_height, 2)
    pad_bottom = pad_height - pad_top
    pad_left = math_ops.floordiv(pad_width, 2)
    pad_right = pad_width - pad_left

    # More padding so that rate divides the height and width of the input value
    in_height = in_height + pad_top + pad_bottom
    in_width = in_width + pad_left + pad_right

    mod_height = math_ops.mod(in_height, rate)
    mod_width = math_ops.mod(in_width, rate)
    null = constant_op.constant(0)
    pad_bottom_extra = control_flow_ops.cond(gen_math_ops.equal(mod_height, 0), lambda: null, lambda: rate - mod_height)
    pad_right_extra = control_flow_ops.cond(gen_math_ops.equal(mod_width, 0), lambda: null, lambda: rate - mod_width)

    # The paddings argument to space_to_batch includes both padding components
    pad_bottom = pad_bottom + pad_bottom_extra
    pad_right = pad_right + pad_right_extra
    print 'hahahaha'
    v = array_ops.expand_dims(array_ops.pack([pad_top, pad_bottom]),1)
    h = array_ops.expand_dims(array_ops.pack([pad_left, pad_right]),1)
    space_to_batch_pad = array_ops.concat(1, [v,h])
    space_to_batch_pad = [[pad_top, pad_bottom],
                          [pad_left, pad_right]]

    value = array_ops.space_to_batch(input=value,
                                     paddings=space_to_batch_pad,
                                     block_size=rate)

    value = gen_nn_ops.conv2d(input=value,
                              filter=filters,
                              strides=[1, 1, 1, 1],
                              padding="VALID",
                              name=name)

    # The crops argument to batch_to_space is just the extra padding component
    v = array_ops.expand_dims(array_ops.pack([0, pad_bottom_extra]),1)
    h = array_ops.expand_dims(array_ops.pack([0, pad_right_extra]),1)
    batch_to_space_crop = array_ops.concat(1, [v,h])
    batch_to_space_crop = [[0, pad_bottom_extra], [0, pad_right_extra]]
    value = array_ops.batch_to_space(input=value,
                                     crops=batch_to_space_crop,
                                     block_size=rate)

    return value