models icon indicating copy to clipboard operation
models copied to clipboard

[deeplab] What is the purpose of separable_conv2d_same?

Open hsm207 opened this issue 8 years ago • 6 comments

I am trying to understand the following comments in the separable_conv2d_same function:

Note that

     net = separable_conv2d_same(inputs, num_outputs, 3,
       depth_multiplier=1, stride=stride)

  is equivalent to

     net = slim.separable_conv2d(inputs, num_outputs, 3,
       depth_multiplier=1, stride=1, padding='SAME')
     net = resnet_utils.subsample(net, factor=stride)

  whereas

     net = slim.separable_conv2d(inputs, num_outputs, 3, stride=stride,
       depth_multiplier=1, padding='SAME')

  is different when the input's height or width is even, which is why we add the
  current function.

I don't understand the point about the slim.separable_conv2d giving different results when the input's height or width is even, so I wrote the following code:

print('When input\'s height and width is odd:')
x = tf.random_uniform((1, 5, 5, 1), 1, 10, tf.int32)
x = tf.cast(x, tf.float32)

stride = 2
y1 = slim.separable_conv2d(x, 2, 3, depth_multiplier=1, stride=1, padding='same')
y1 = resnet_utils.subsample(y1, factor=stride)
print(y1.shape)

y2 = separable_conv2d_same(x, 2, 3, depth_multiplier=1, stride=stride, scope='xxx')
print(y2.shape)

y3 = slim.separable_conv2d(x, 2, 3, stride=stride, depth_multiplier=1, padding='same')
print(y3.shape)

print('When input\'s height is even and width is odd:')
x = tf.random_uniform((1, 6, 5, 1), 1, 10, tf.int32)
x = tf.cast(x, tf.float32)

stride = 2
y1 = slim.separable_conv2d(x, 2, 3, depth_multiplier=1, stride=1, padding='same')
y1 = resnet_utils.subsample(y1, factor=stride)
print(y1.shape)

y2 = separable_conv2d_same(x, 2, 3, depth_multiplier=1, stride=stride, scope='xxx')
print(y2.shape)

y3 = slim.separable_conv2d(x, 2, 3, stride=stride, depth_multiplier=1, padding='same')
print(y3.shape)

The output from all 6 print statements is the same: (1, 3, 3, 2). So, it looks to me that the separable_conv2d_same function does the same thing as slim.separable_conv2d in all cases.

Please help me understand the message the comment is meant to convey.

The following is the entire code to reproduce the output I got:

import tensorflow.contrib.eager as tfe
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.slim.nets import resnet_utils


def fixed_padding(inputs, kernel_size, rate=1):
    kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)
    pad_total = kernel_size_effective - 1
    pad_beg = pad_total // 2
    pad_end = pad_total - pad_beg
    padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end],
                                    [pad_beg, pad_end], [0, 0]])
    return padded_inputs


def separable_conv2d_same(inputs,
                          num_outputs,
                          kernel_size,
                          depth_multiplier,
                          stride,
                          rate=1,
                          use_explicit_padding=True,
                          regularize_depthwise=False,
                          scope=None,
                          **kwargs):
    def _separable_conv2d(padding):
        """Wrapper for separable conv2d."""
        return slim.separable_conv2d(inputs,
                                     num_outputs,
                                     kernel_size,
                                     depth_multiplier=depth_multiplier,
                                     stride=stride,
                                     rate=rate,
                                     padding=padding,
                                     scope=scope,
                                     **kwargs)

    def _split_separable_conv2d(padding):
        """Splits separable conv2d into depthwise and pointwise conv2d."""
        outputs = slim.separable_conv2d(inputs,
                                        None,
                                        kernel_size,
                                        depth_multiplier=depth_multiplier,
                                        stride=stride,
                                        rate=rate,
                                        padding=padding,
                                        scope=scope + '_depthwise',
                                        **kwargs)
        return slim.conv2d(outputs,
                           num_outputs,
                           1,
                           scope=scope + '_pointwise',
                           **kwargs)

    if stride == 1 or not use_explicit_padding:
        if regularize_depthwise:
            outputs = _separable_conv2d(padding='SAME')
        else:
            outputs = _split_separable_conv2d(padding='SAME')
    else:
        inputs = fixed_padding(inputs, kernel_size, rate)
        if regularize_depthwise:
            outputs = _separable_conv2d(padding='VALID')
        else:
            outputs = _split_separable_conv2d(padding='VALID')
    return outputs


tfe.enable_eager_execution()

print('When input\'s height and width is odd:')
x = tf.random_uniform((1, 5, 5, 1), 1, 10, tf.int32)
x = tf.cast(x, tf.float32)

stride = 2
y1 = slim.separable_conv2d(x, 2, 3, depth_multiplier=1, stride=1, padding='same')
y1 = resnet_utils.subsample(y1, factor=stride)
print(y1.shape)

y2 = separable_conv2d_same(x, 2, 3, depth_multiplier=1, stride=stride, scope='xxx')
print(y2.shape)

y3 = slim.separable_conv2d(x, 2, 3, stride=stride, depth_multiplier=1, padding='same')
print(y3.shape)

print('When input\'s height is even and width is odd:')
x = tf.random_uniform((1, 6, 5, 1), 1, 10, tf.int32)
x = tf.cast(x, tf.float32)

stride = 2
y1 = slim.separable_conv2d(x, 2, 3, depth_multiplier=1, stride=1, padding='same')
y1 = resnet_utils.subsample(y1, factor=stride)
print(y1.shape)

y2 = separable_conv2d_same(x, 2, 3, depth_multiplier=1, stride=stride, scope='xxx')
print(y2.shape)

y3 = slim.separable_conv2d(x, 2, 3, stride=stride, depth_multiplier=1, padding='same')
print(y3.shape)

hsm207 avatar Apr 11 '18 12:04 hsm207

@YknZhu or @aquariusjay can you please share your thoughts?

hsm207 avatar May 23 '18 03:05 hsm207

Hello, @hsm207 . Sorry for disturbing you. Have you figured this out? I am confused about the "misalignment" as well. Could you share your understanding?

hhwxxx avatar Jul 06 '18 13:07 hhwxxx

@hhwxxx no, I have not figured this out. It's been awhile since I looked at this code. Please give me some time to read through the code again and maybe we can share our understanding while waiting for either of the paper's author to respond?

hsm207 avatar Jul 07 '18 19:07 hsm207

@hsm207 and @hhwxxx . I meet the same question as you. I still can't figure this out. Here is my some opinion. I guess when the input's height or width is even and the stride > 1, the position to convolution is not same, so have the following words: """ Note that

 net = conv2d_same(inputs, num_outputs, 3, stride=stride)

is equivalent to

 net = slim.conv2d(inputs, num_outputs, 3, stride=1, padding='SAME')
 net = subsample(net, factor=stride)

whereas

 net = slim.conv2d(inputs, num_outputs, 3, stride=stride, padding='SAME')

is different when the input's height or width is even, which is why we add the
current function. For more details, see ResnetUtilsTest.testConv2DSameEven().

"""

The following is my source code to valid my guess. But I don't know the reason how to cause this.

""" source link: https://github.com/tensorflow/models/blob/master/research/slim/nets/resnet_v2_test.py """ import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np

def create_test_input(batch_size, height, width, channels): """ Create test input tensor. Args: batch_size: The number of images per batch or None if unknown. height: The height of each image or None if unknown. width: The width of each image or None if unknown. channels: The number of channels per image or None if unknown.

Returns:
Either a placeholder `Tensor` of dimension
  [batch_size, height, width, channels] if any of the inputs are `None` or a
constant `Tensor` with the mesh grid values along the spatial dimensions.
"""
if None in [batch_size, height, width, channels]:
    return tf.placeholder(tf.float32, (batch_size, height, width, channels))
else:
    im = np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(width), [1, width])
    im = np.reshape(
                im,
                [1, height, width, 1])
    return tf.to_float(
        np.tile(
            im,
            [batch_size, 1, 1, channels]))

def subsample(inputs, factor, scope=None): """ Subsamples the input along the spatial dimensions.

Args:
inputs: A `Tensor` of size [batch, height_in, width_in, channels].
factor: The subsampling factor.
scope: Optional variable_scope.

Returns:
output: A `Tensor` of size [batch, height_out, width_out, channels] with the
  input, either intact (if factor == 1) or subsampled (if factor > 1).
"""
if factor == 1:
    return inputs
else:
    return slim.max_pool2d(inputs, [1, 1], stride=factor, scope=scope)

def conv2d_same(inputs, num_outputs, kernel_size, stride, rate=1, scope=None): """ Strided 2-D convolution with 'SAME' padding.

When stride > 1, then we do explicit zero-padding, followed by conv2d with
'VALID' padding.

Note that

 net = conv2d_same(inputs, num_outputs, 3, stride=stride)

is equivalent to

 net = slim.conv2d(inputs, num_outputs, 3, stride=1, padding='SAME')
 net = subsample(net, factor=stride)

whereas

 net = slim.conv2d(inputs, num_outputs, 3, stride=stride, padding='SAME')

is different when the input's height or width is even, which is why we add the
current function. For more details, see ResnetUtilsTest.testConv2DSameEven().

Args:
inputs: A 4-D tensor of size [batch, height_in, width_in, channels].
num_outputs: An integer, the number of output filters.
kernel_size: An int with the kernel_size of the filters.
stride: An integer, the output stride.
rate: An integer, rate for atrous convolution.
scope: Scope.

Returns:
output: A 4-D tensor of size [batch, height_out, width_out, channels] with
  the convolution output.
"""
if stride == 1:
    return slim.conv2d(inputs, num_outputs, kernel_size, stride=1, rate=rate,
                   padding='SAME', scope=scope)
else:
    kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)
    pad_total = kernel_size_effective - 1
    pad_beg = pad_total // 2
    pad_end = pad_total - pad_beg
    inputs = tf.pad(inputs,
                [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]])
    return slim.conv2d(inputs, num_outputs, kernel_size, stride=stride,
                   rate=rate, padding='VALID', scope=scope)

def Conv2DSameEven(): n, n2 = 4, 2

# Input image.
x = create_test_input(1, n, n, 1)

# Convolution kernel.
w = create_test_input(1, 3, 3, 1)
w = tf.reshape(w, [3, 3, 1, 1])

tf.get_variable('Conv/weights', initializer=w)
tf.get_variable('Conv/biases', initializer=tf.zeros([1]))
tf.get_variable_scope().reuse_variables()

y1 = slim.conv2d(x, 1, [3, 3], stride=1, scope='Conv')
y1_expected = tf.to_float([[14, 28, 43, 26],
                           [28, 48, 66, 37],
                           [43, 66, 84, 46],
                           [26, 37, 46, 22]])
# y1_expected = tf.reshape(y1_expected, [1, n, n, 1])

y2 = subsample(y1, 2)
y2_expected = tf.to_float([[14, 43],
                           [43, 84]])
# y2_expected = tf.reshape(y2_expected, [1, n2, n2, 1])

y3 = conv2d_same(x, 1, 3, stride=2, scope='Conv')
y3_expected = y2_expected

y4 = slim.conv2d(x, 1, [3, 3], stride=2, scope='Conv')
y4_expected = tf.to_float([[48, 37],
                           [37, 22]])
# y4_expected = tf.reshape(y4_expected, [1, n2, n2, 1])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    y1 = tf.squeeze(y1)
    y2 = tf.squeeze(y2)
    y3 = tf.squeeze(y3)
    y4 = tf.squeeze(y4)
    y1_eval, y1_expect_eval = y1.eval(), y1_expected.eval()
    y2_eval, y2_expect_eval = y2.eval(), y2_expected.eval()
    y3_eval, y3_expect_eval = y3.eval(), y3_expected.eval()
    y4_eval, y4_expect_eval = y4.eval(), y4_expected.eval()

Conv2DSameEven()

Ander-H avatar Aug 14 '18 03:08 Ander-H

@hsm207 @hhwxxx Perhaps I have known the reason why there is difference.

Suppose the input is X. After padded, the input is marked by padded-X.

When we do slim.conv2d() and set the padding='SAME', there should do the padding operation first. How many zeros to pad at the begin and end of X is affected by input_size, kernel_size, and stride. After padded, then do convolution operation which padding='VALID' and stride operetion.

The padding operation cause the difference.

Ander-H avatar Aug 14 '18 04:08 Ander-H

Hi There, We are checking to see if you still need help on this, as this seems to be considerably old issue. Please update this issue with the latest information, code snippet to reproduce your issue and error you are seeing. If we don't hear from you in the next 7 days, this issue will be closed automatically. If you don't need help on this issue any more, please consider closing this.

tensorflowbutler avatar Jan 29 '20 23:01 tensorflowbutler