Skip to content

inputs.size() > 0 in function 'getMemoryShapes' #14290

Closed

Description

@alexionby

Strange error when I am trying to convert model from keras to onnx and run through opencv dnn.

  • OpenCV == 4.1.0
  • Operating System / Platform == Ubuntu 16.04 / 64 Bit
  • Compiler == conda 4.6.11 / libgcc-ng 8.2.0
  • onnxmltools == 1.4.0 / onnx = 1.4.1
  • keras == 2.2.4 / tensorflow == 1.13.1
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import numpy as np

from keras import regularizers
from keras import initializers
from keras import layers
from keras.models import Model

def get_model():
    inp = layers.Input(shape=(48,80,1))
    x = layers.Conv2D(32, 7)(inp)
    x = layers.BatchNormalization()(x)
    out = layers.ReLU()(x)
    return Model(inp, out)

if __name__ == '__main__':
    model = get_model()
    model.compile(optimizer='adam', loss='mse')

    X = np.random.rand(32, 48, 80, 1)
    y = np.random.rand(32, 42, 74, 32)

    model.fit(X, y, epochs=1, validation_data=(X, y))
    model.save('model.h5')
import onnxmltools
from keras.models import load_model

model = load_model('model.h5')
onnx_model = onnxmltools.convert_keras(model)

onnxmltools.utils.save_model(onnx_model, 'model.onnx')
import cv2
cv2.dnn.readNetFromONNX('model.onnx')
    ---------------------------------------------------------------------------
    error                                     Traceback (most recent call last)
    <ipython-input-3-6da663bc3421> in <module>
    ----> 1 cv2.dnn.readNetFromONNX("models/eyegaze_reduced.onnx")

    error: OpenCV(4.1.0) ../modules/dnn/src/layers/permute_layer.cpp:124: error: (-215:Assertion failed) inputs.size() > 0 in function 'getMemoryShapes'

Activity

  1. dkurt commented on Apr 10, 2019

    @dkurt
    Member

    Is it possible to share the model? It may help us to solve it faster.

  2. alexionby commented on Apr 10, 2019

    @alexionby
    Author
  3. dkurt commented on Apr 11, 2019

    @dkurt
    Member

    It looks like ONNX doen't sort graphs in the topological order before conversion. This is how nodes are stored in the model:

    name: adjusted_input
    input: input_1_01
    
    name: convolution_output
    input: adjusted_input
    input: W
    input: B
    
    name: batch_norm_output_buffer
    input: convolution_output
    input: scale
    input: bias
    input: mean
    input: var
    
    name: batch_normalization_1_cond_Merge_0
    input: TFNodes_re_lu_1_Relu_0
    
    name: TFNodes_re_lu_1_Relu_0
    input: batch_norm_output_buffer
    
    name: re_lu_1_Relu_0
    input: batch_normalization_1_cond_Merge_0
    

    As you may see, node batch_normalization_1_cond_Merge_0 uses TFNodes_re_lu_1_Relu_0 before it's definition.

    Please try one of the following ways:

    1. Convert Keras .h5 model to TensorFlow model .pb and try to import it with OpenCV
    2. Sort the graph before ONNX serialization:
    from tensorflow.tools.graph_transforms import TransformGraph
    
    graph_def = TransformGraph(graph_def, inpNodesNames, outNodesNames, ['sort_by_execution_order'])
  4. alexionby commented on Apr 11, 2019

    @alexionby
    Author

    @dkurt

    I converted model to .pb with this repo: keras_to_tensorflow
    And then I tried to infer it in opencv. Inference was succesfull.

    import cv2
    net = cv2.dnn.readNetFromTensorflow('model.pb')
    image = cv2.imread('image.jpg', 0)
    input = cv2.dnn.blobFromImage(image, 1, (48, 80))
    net.setInput(input)
    output = net.forward('re_lu_1/Relu')
    

    So with tool tensorflow-onnx i converted this model.pb to model.onnx. (Command: python -m tf2onnx.convert --input model.pb --inputs input_1:0 --outputs re_lu_1/Relu:0 --output model.onnx --verbose)

    And this model.onnx file work without any "nodes reordering".

    import cv2
    net = cv2.dnn.readNetFromONNX('model.onnx')
    image = cv2.imread('image.jpg', 0)
    input = cv2.dnn.blobFromImage(image, 1, (48, 80))
    net.setInput(input)
    output = net.forward('re_lu_1/Relu:0')
    

    But i wrote a small script to check whether reordering is needed:

    import tensorflow as tf
    from tensorflow.tools.graph_transforms import TransformGraph
    import numpy as np
    
    graph = 'model.pb'
    
    with tf.gfile.GFile(graph, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        print('before sort')
        for n in graph_def.node:
            print(n.name)
    
        graph_def = TransformGraph(graph_def, ['input_1'], ['re_lu_1'], ['sort_by_execution_order'])
    
        print('after sort')
        for n in graph_def.node:
            print(n.name)
    
        with tf.gfile.FastGFile('model_sorted.pb', 'wb') as f:
            f.write(graph_def.SerializeToString())
    

    Output:

    ### before sort
    input_1
    conv2d_1/kernel
    conv2d_1/kernel/read
    conv2d_1/bias
    conv2d_1/bias/read
    conv2d_1/convolution
    conv2d_1/BiasAdd
    batch_normalization_1/gamma
    batch_normalization_1/gamma/read
    batch_normalization_1/beta
    batch_normalization_1/beta/read
    batch_normalization_1/moving_mean
    batch_normalization_1/moving_mean/read
    batch_normalization_1/moving_variance
    batch_normalization_1/moving_variance/read
    batch_normalization_1/FusedBatchNorm_1
    re_lu_1/Relu
    
    ### after sort
    batch_normalization_1/moving_variance
    batch_normalization_1/moving_variance/read
    batch_normalization_1/moving_mean
    batch_normalization_1/moving_mean/read
    batch_normalization_1/beta
    batch_normalization_1/beta/read
    batch_normalization_1/gamma
    batch_normalization_1/gamma/read
    conv2d_1/bias
    conv2d_1/bias/read
    conv2d_1/kernel
    conv2d_1/kernel/read
    input_1
    conv2d_1/convolution
    conv2d_1/BiasAdd
    batch_normalization_1/FusedBatchNorm_1
    re_lu_1/Relu
    

    So, nodes order has changed, but in case of .pb file it works anyway. And when I try to import it directly from keras to onnx it fails.

    Can something else be wrong except the nodes order?

  5. dkurt commented on Apr 11, 2019

    @dkurt
    Member

    @alexionby, Please upload mentioned model which produces error.

  6. alexionby commented on Apr 11, 2019

    @alexionby
    Author

    @dkurt, models.zip
    model.h5 - original keras model
    model.onnx - onnx model from model.h5 ( converted by onnxmltools )
    model.pb - .pb from model.h5 ( converted by keras_to_tensorflow )
    model_pb.onnx - onnx from model.pb (converted by tensorflow-onnx )

    I suppose, that model.onnx and model_pb.onnx should be similar, but first doesn't work and second does work.

  7. dkurt commented on Apr 11, 2019

    @dkurt
    Member

    @alexionby, model_pb.onnx works fine for me. Please try to update OpenCV locally:

    import cv2 as cv
    import numpy as np
    
    net = cv.dnn.readNet('model_pb.onnx')
    inp = np.random.standard_normal([1, 1, 48, 80]).astype(np.float32)
    net.setInput(inp)
    out = net.forward()
    print out.shape
    (1, 42, 74, 32)
    

    Update: So can we close an issue? Yes, model_pb.onnx is similar to model.onnx but with ordered nodes. For now OpenCV can sort graphs only from Keras but not from ONNX so both models from Keras (orderer and unordered) will work but only ordered model from ONNX.

  8. alexionby commented on Apr 11, 2019

    @alexionby
    Author

    @dkurt , yes we can.

    *** I tried to convert both ordered and unordered .pb to .onnx. And they both worked. That's what i was trying to say.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions