TensorFlow.NET icon indicating copy to clipboard operation
TensorFlow.NET copied to clipboard

Missing API: conv2d_transpose

Open tiredamage42 opened this issue 7 years ago • 5 comments

there's currently no option to use conv2d_transpose for image upsampling with GANs.

https://www.tensorflow.org/api_docs/python/tf/nn/conv2d_transpose

tiredamage42 avatar Sep 30 '19 16:09 tiredamage42

Hi Oceania2018 and folks Thanks for the Amazing library. I've hit a stumbling block trying to implement a VAE because tf.nn.conv2d_transpose is missing. Also noticed that in SiaNet they have simply thrown an exception for Deconvolutions

Tried porting it from the tensorflow python source but inevitably got stuck at nn_ops does not have DeConvolution method and bindings are also missing in GenOps. Below is as far as I got.

` public class Conv2DTranspose : Tensorflow.Keras.Layers.Conv2D { public Conv2DTranspose(Tensor inputs, int filters, int[] kernel_size, int[] strides = null, string padding = "valid", int[] _OutputPadding = null, string data_format = null, int[] dilation_rate = null, bool use_bias = true, IActivation activation = null, IInitializer kernel_initializer = null, IInitializer bias_initializer = null, bool trainable = true, string name = null) : base(filters: filters, kernel_size: kernel_size, strides: strides, padding: padding, data_format: data_format, dilation_rate: dilation_rate, activation: activation, use_bias: use_bias, kernel_initializer: kernel_initializer, bias_initializer: bias_initializer, trainable: trainable, name: name ) { output_padding = _OutputPadding; if (output_padding != null) { output_padding = Tensorflow.Keras.Utils.conv_utils.normalize_tuple(output_padding, 2, @"output_padding"); if (output_padding.Length != strides.Length) { throw new InvalidOperationException(@"Strides must have the same dimensions as Output Padding"); } for (int I= 0; I < output_padding.Length; I++) { if (output_padding[I] > strides[I]) { throw new InvalidOperationException(@"Strides values must be greater than or equal to Output padding values"); } } } } protected int[] output_padding { get; set; } //protected VariableV1 kernel { get; set; } //protected Tensorflow.Keras.Engine.InputSpec input_spec { get; set; }

protected override void build(TensorShape input_shape) { //base.build(input_shape) int channel_axis = data_format == "channels_first" ? 1 : -1; int input_dim = channel_axis < 0 ? input_shape.dims[input_shape.ndim + channel_axis] : input_shape.dims[channel_axis]; if (input_shape.rank != 4) { throw new InvalidOperationException(@"Inputs should have rank 4."); } Dictionary<int, int> AxisDict; AxisDict = new Dictionary<int, int>(); AxisDict.Add(channel_axis, input_dim); base.input_spec = new Tensorflow.Keras.Engine.InputSpec(ndim: 4, axes: AxisDict); int[] kernel_shape; kernel_shape = new int[2] { base.kernel_size[0] + filters, base.kernel_size[1] + input_dim }; kernel = (RefVariable)add_weight(name: @"kernel", shape: kernel_shape, initializer: base.kernel_initializer, trainable: true, dtype: _dtype); if (use_bias) { bias = (RefVariable)add_weight(name: "bias", shape: new int[] { base.filters }, initializer: bias_initializer, trainable: true, dtype: _dtype); } else { bias = null; } built = true; }

protected override Tensor[] call(Tensor inputs, Tensor training = null, Tensor state = null) { //return base.call(inputs, training, state); Tensor inputs_shape = array_ops.shape(inputs); int batch_size = inputs_shape.dims[0]; int h_axis; int w_axis; if (data_format == "channels_first") { h_axis = 2; w_axis = 3; } else { h_axis = 1; w_axis = 2; } int height = inputs_shape.dims[h_axis]; int width = inputs_shape.dims[w_axis]; int kernel_h = kernel_size[0]; int kernel_w = kernel_size[1]; int stride_h = base.strides[0]; int stride_w = base.strides[1]; int? out_pad_h; int? out_pad_w;

if (output_padding == null)
{
    out_pad_h = null;
    out_pad_w = null;
}
else
{
    out_pad_h = output_padding[0];
    out_pad_w = output_padding[1];
}
//Tensorflow.Keras.Utils.conv_utils.deconv_output_length is missing
int out_height = deconv_output_length(height,
    kernel_h,
    padding: base.padding, //Keep it explicit - base classes are python style
    output_padding: out_pad_h,
    stride: stride_h,
    dilation: base.dilation_rate[0] //Keep it explicit - base classes are python style
    );

int out_width = deconv_output_length(width,
    kernel_w,
    padding: base.padding, //Keep it explicit - base classes are python style
    output_padding: out_pad_w,
    stride: stride_w,
    dilation: base.dilation_rate[1] //Keep it explicit - base classes are python style
    );
int[] output_shape;
if (data_format == @"channels_first")
{
    output_shape = new int[4] { batch_size, base.filters, out_height, out_width };
}
else
{
    output_shape = new int[4] { batch_size, out_height, out_width, base.filters };
}
Tensor output_shape_tensor = array_ops.stack(output_shape);

string op_padding;
if (padding == "causal")
    op_padding = "valid";
else
    op_padding = padding;
var df = Tensorflow.Keras.Utils.conv_utils.convert_data_format(data_format, rank + 2);

// This needs DeConvolution in nn_ops. Cannot go any further because I doubt the next line is correct.
_convolution_op = nn_ops.Convolution(output_shape,
kernel.shape,
op_padding.ToUpper(),
strides,
dilation_rate,
data_format: df);


//Not sure how to check if Tensorflow is executing eagerly to skip the next
TensorShape out_shape = compute_output_shape(inputs.shape);

Tensor outputs;
if (base.use_bias)
{
    outputs = tf.nn.bias_add(_convolution_op, base.bias, data_format: Tensorflow.Keras.Utils.conv_utils.convert_data_format(base.data_format, ndim: 4));
}

}

private TensorShape compute_output_shape(TensorShape InputShape) { int[] input_shape = InputShape.as_list(); int[] output_shape = InputShape.as_list(); int c_axis; int h_axis; int w_axis; if (data_format == @"channels_first") { c_axis = 1; h_axis = 2; w_axis = 3; } else { c_axis = 3; h_axis = 1; w_axis = 2; } int kernel_h = kernel_size[0]; int kernel_w = kernel_size[1]; int stride_h = base.strides[0]; int stride_w = base.strides[1]; int? out_pad_h; int? out_pad_w;

if (output_padding == null)
{
    out_pad_h = null;
    out_pad_w = null;
}
else
{
    out_pad_h = output_padding[0];
    out_pad_w = output_padding[1];
}
output_shape[c_axis] = filters;
output_shape[h_axis] = deconv_output_length(
    output_shape[h_axis],
    kernel_h,
    padding: base.padding,
    output_padding: out_pad_h,
    stride: stride_h,
    dilation: base.dilation_rate[0]
    );
output_shape[w_axis] = deconv_output_length(
    output_shape[w_axis],
    kernel_w,
    padding: base.padding,
    output_padding: out_pad_w,
    stride: stride_w,
    dilation: base.dilation_rate[1]
    );
return new TensorShape(output_shape);

}

private int deconv_output_length(int input_length, int filter_size, string padding, int stride) { //if (input_length == null) //{ // return null; //} input_length *= stride; if (padding == @"valid") { input_length += Math.Max(filter_size - stride, 0); } else if (padding == @"full") { input_length -= (stride + filter_size - 2); } return input_length; } private int deconv_output_length(int input_length, int filter_size, string padding, int? output_padding= null, int stride = 0, int dilation = 1) { //if (input_length == null) //{ // return null; //} // Get the dilated kernel size filter_size = filter_size + (filter_size - 1) * (dilation - 1);

//Infer length if output padding is None, else compute the exact length
int length;
//if (!output_padding.HasValue)
if (output_padding == null)
    {
    switch (padding)
    {
        case @"valid":
            length = input_length * stride + Math.Max(filter_size - stride, 0);
            break;
        case @"full":
            length = input_length * stride - (stride + filter_size - 2);
            break;
        case @"same":
            length = input_length * stride;
            break;
        default:
            throw new InvalidOperationException(@"Padding must be one of: valid, full, same");
    }
}
else
{
    int pad;
    switch (padding)
    {
        case @"same":
            pad = filter_size;
            break;
        case @"valid":
            pad = 0;
            break;
        case @"full":
            pad = filter_size - 1;
            break;
        default:
            throw new InvalidOperationException(@"Padding must be one of: valid, full, same");
    }
    length = ((input_length - 1) * stride + filter_size - 2 * pad + output_padding.Value);
}
return length;

} `

tcwicks avatar Feb 05 '20 23:02 tcwicks

@tiredamage42 @tcwicks Could you provide a UnitTest in C#?

Oceania2018 avatar Feb 06 '20 03:02 Oceania2018

I have the same issue as I posted as a bit of a hijack in a Unity post, since I'm also trying to use this in Unity. (I did leave pointers on how to get started with Tensorflow.NET in Unity on the Unity forum.)

For what part of tf.nn.conv2d_transpose not being available would a UnitTest help?

I've also gotten completely stuck trying to work around conv2d_transpose not being available. I tried resizing the input and then applying a kernel, but resize_bilinear doesn't support gradients, resize_nearest_neighbour doesn't allow an arbitrary batch size (first shape dimension undefined) and resize_images is not implemented. I tried replicating a nearest neighbour resize with concat, but that throws a nullpointer exception. A similar try with batch was also a dead end.

jvo3dc avatar May 19 '20 12:05 jvo3dc

Are there new advances on this point ? I also need to use conv2d_transpose.

JulietteV avatar Oct 22 '20 07:10 JulietteV

Closing since conv2d_transpose has been developed, please reopen if you still have question, thanks!

Wanglongzhi2001 avatar Nov 13 '23 16:11 Wanglongzhi2001