How to specify the interpolate layers output shape when export to onnx?

Hi.

When I exporting a model that final layer is an “interpolate layer”.

That model doesn’t have specific output shape.

I tested flowing simple model that has only interpolate layer.

When I print output shape of ort_session its show ['batch_size', 'Resizeoutput_dim_1', 'Resizeoutput_dim_2', 'Resizeoutput_dim_3'].

import onnxruntime
import onnx
import numpy as np

import torch
import torch.nn as nn
import torch.nn.functional as F

class SimpleTest(nn.Module):
    def __init__(self):
        super(SimpleTest, self).__init__()

    def forward(self, x):        
        y = F.interpolate(x, size=(x.shape[2] * 2, x.shape[2] * 2))
        return y

if __name__ == "__main__":    
    model = SimpleTest()
    model.cuda()
    model.eval()

    dummy_input = torch.rand(1, 1, 4, 4).cuda()

    out = model(dummy_input)

    torch.onnx.export(model, dummy_input,"./results/simple_test.onnx",export_params=True,
                            opset_version=11, do_constant_folding=True, 
                            input_names=['input'], output_names=['output'],
                            dynamic_axes={'input':{0: 'batch_size'},
                            'output':{0: 'batch_size'}})


    onnx_model = onnx.load("./results/simple_test.onnx")
    onnx.checker.check_model(onnx_model)

    dummy_input = np.array([[[[1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, 3.0], [4.0, 4.0, 4.0, 4.0]]]], dtype=np.float32)
        
    ort_session = onnxruntime.InferenceSession("./results/simple_test.onnx")
    ort_inputs = {ort_session.get_inputs()[0].name: dummy_input}

    print("Input_Shape: ", ort_session.get_inputs()[0].shape)
    print("Output_Shape: ", ort_session.get_outputs()[0].shape)
    ort_outs = ort_session.run(None, ort_inputs)

    print(ort_outs[0])

"""
>>> Input_Shape:  ['batch_size', 1, 4, 4]
>>> Output_Shape:  ['batch_size', 'Resizeoutput_dim_1', 'Resizeoutput_dim_2', 'Resizeoutput_dim_3']
>>>[[[[1. 1. 1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1. 1. 1.]
   [2. 2. 2. 2. 2. 2. 2. 2.]
   [2. 2. 2. 2. 2. 2. 2. 2.]
   [3. 3. 3. 3. 3. 3. 3. 3.]
   [3. 3. 3. 3. 3. 3. 3. 3.]
   [4. 4. 4. 4. 4. 4. 4. 4.]
   [4. 4. 4. 4. 4. 4. 4. 4.]]]]
"""

How to specify the interpolate layers output shape when export to onnx?

Met the same problem. Did you get a solution?

Hi… Actually, I couldn’t found any solution about this issue…

But. In my case it doesn’t matter to inference.

I just do inference even if last layer doesn’t have specific shape,then reshape the output of model.

I hope you solve the problem :slight_smile:

1 Like