Skip to content

Inference speed on GPU is much slower than that on CPU.  #17358

Open

Description

@JTzhuang
System information (version)
  • OpenCV => :4.2 and 4.3
  • Operating System / Platform => :Windows 10 64 Bit
  • Compiler => : VS 2017 and VS 2015
  • GPU => : RTX 2080Ti × 2
Detailed description

When I test my model using OpenCV DNN modules on CUDA backend and OPENCV backend, I find that the inference speed of my model on GPU is much slower than that on CPU.

And my net is just like a Siamese Network, It has two inputs and four outputs. @YashasSamaga finds that one of inputs may makes the model initialize more than once. There may be some bug in initialization ligic.

Steps to reproduce
Issue submission checklist
  • I report the issue, it's not a question
  • I checked the problem with documentation, FAQ, open issues,
    answers.opencv.org, Stack Overflow, etc and have not found solution
  • I updated to latest OpenCV version and the issue is still there
  • There is reproducer code and related data files: videos, images, onnx, etc

code and .pb file.
https://drive.google.com/open?id=1Wsx4JOKvn6Xn2Rr7m0VX2HTXEvUBvWm3

Activity

  1. YashasSamaga commented on May 24, 2020

    @YashasSamaga
    Contributor

    I added getPerfProfile support to the CUDA backend here.

    OCV Time: 193ms, getPerfProfile: 183.962ms
    CUDA Time: 532ms, getPerfProfile: 42.5451ms
    
    Code
    #include <iostream>
    #include <chrono>
    
    #include <opencv2/core/cuda.hpp>
    #include <opencv2/dnn.hpp>
    #include <opencv2/imgproc.hpp>
    #include <opencv2/highgui.hpp>
    
    int main ()
    {
        auto color_input = cv::imread("9-c.png");
    	auto height_input = cv::imread("9-h.png");
    	auto colo_input_blob = cv::dnn::blobFromImage(color_input, 1 / 255, cv::Size(224, 224), cv::Scalar(), true, false);
    	auto height_input_blob = cv::dnn::blobFromImage(height_input, 1 / 255, cv::Size(224, 224), cv::Scalar(), false, false);
        
    	auto net_ocv = cv::dnn::readNetFromTensorflow("DP_concat.pb");
        net_ocv.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
        net_ocv.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
    
        {
            net_ocv.setInput(colo_input_blob, "color_input");
            net_ocv.setInput(height_input_blob, "height_input");
            net_ocv.forward("feature_concat/Softmax");
        }
    
        auto start = std::chrono::steady_clock::now();
        {
            net_ocv.setInput(colo_input_blob, "color_input");
            net_ocv.setInput(height_input_blob, "height_input");
            net_ocv.forward("feature_concat/Softmax");
        }
        auto end = std::chrono::steady_clock::now();
        auto ocv_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    
        std::vector<double> ocvLayerTimings;
        auto ocv_getPerfProfile = net_ocv.getPerfProfile(ocvLayerTimings) / cv::getTickFrequency() * 1000;
        std::cout << "OCV Time: " << ocv_time << "ms, getPerfProfile: " << ocv_getPerfProfile << "ms" << std::endl;
    
        auto net_cuda = cv::dnn::readNetFromTensorflow("DP_concat.pb");
        net_cuda.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
        net_cuda.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
       
        {
            net_cuda.setInput(colo_input_blob, "color_input");
            net_cuda.setInput(height_input_blob, "height_input");
            net_cuda.forward("feature_concat/Softmax");
        }
    
        start = std::chrono::steady_clock::now();
        {
            net_cuda.setInput(colo_input_blob, "color_input");
            net_cuda.setInput(height_input_blob, "height_input");
            net_cuda.forward("feature_concat/Softmax");
        }
        end = std::chrono::steady_clock::now();
        auto cuda_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    
        std::vector<double> cudaLayerTimings;
        auto cuda_getPerfProfile = net_cuda.getPerfProfile(cudaLayerTimings) / cv::getTickFrequency() * 1000;
        std::cout << "CUDA Time: " << cuda_time << "ms, getPerfProfile: " << cuda_getPerfProfile << "ms" << std::endl;
    
        return 0;
    }
    

    The first number in each line is the actual time it took for net.forward() to finish executing. The second number in each line is what the layerwise sum of timings gives.

    It appears like the CUDA backend is taking 42ms to compute the outputs. The remaining ~500ms is coming from initialization. The DNN module is reinitializing the backend even though the input shape is not changing.

  2. YashasSamaga commented on May 24, 2020

    @YashasSamaga
    Contributor

    The reinitialization is happening in OCV CPU backend too. The initialization cost is barely anything on CPU and hence it doesn't show up in the timings. So it's a bug in setInput.

  3. JTzhuang commented on May 25, 2020

    @JTzhuang
    Author

    @YashasSamaga I found that inference time won't increase much if we increase the batch size of input.

  4. JTzhuang commented on Jun 7, 2020

    @JTzhuang
    Author

    @YashasSamaga Do you find any solutions about this issue?

  5. alalek commented on Jun 10, 2020

    @alalek
    Member

    Looks like the input color_input is not connected to any layers in attached model (or there is another bug in DNN TF parser).

    DNN module doesn't handle this properly in TF parser.

    Possible workaround:

    • remove net_ocv.setInput(colo_input_blob, "color_input"); statements.
  6. JTzhuang commented on Jun 11, 2020

    @JTzhuang
    Author

    @alalek So you think the error occured when I froze the model ? But when I test it using tensorflow, the model works well.

  7. alalek commented on Jun 11, 2020

    @alalek
    Member

    when I test it using tensorflow, the model works well.

    Could you try the workaround above (drop setInput call for color_input) and check results (accuracy with TF)?

  8. JTzhuang commented on Jun 12, 2020

    @JTzhuang
    Author

    ``
    output_graph_def = tf.GraphDef()
    with open('DP_concat.pb', "rb") as f:
    output_graph_def.ParseFromString(f.read())
    tensors = tf.import_graph_def(output_graph_def, name="")

    graph = tf.get_default_graph()
    input_color = graph.get_tensor_by_name("color_input:0")
    input_height = graph.get_tensor_by_name("height_input:0")
    concat_softmax = graph.get_tensor_by_name("feature_concat/Softmax:0")
    color_softmax = graph.get_tensor_by_name("color/Softmax:0")
    height_softmax = graph.get_tensor_by_name("height/Softmax:0")

    image = cv2.imread('9-c.png')
    height = cv2.imread('9-h.png')
    image = cv2.resize(image, (224,224))
    height = cv2.resize(height, (224, 224))
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = image.astype(np.float32) / 255.
    height = height.astype(np.float32) /255.
    image = np.expand_dims(image, axis=0)
    height = np.expand_dims(height, axis=0)

    with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    logits_concat, logits_color, logits_height = sess.run([concat_softmax, color_softmax, height_softmax], feed_dict={input_color: image, input_height: height})
    print('color_input ans height_input: ',logits_concat)
    print('color_input: ', logits_color)
    print('height_input: ',logits_height)
    print(np.argmax(logits_concat, axis=-1))
    ``
    @alalek This is my testing code using tensorflow, and the output is as follows:
    color_input ans height_input: [[1.318436e-05 1.318436e-05 9.999604e-01 1.318436e-05]]
    color_input: [[5.8156675e-05 4.3866065e-05 9.9985409e-01 4.3866065e-05]]
    height_input: [[4.5331984e-04 4.5331984e-04 9.9864000e-01 4.5331984e-04]]`

    ocv output:
    color_input and height_input: [1.318402e-05, 1.318402e-05, 0.99996042, 1.318402e-05]
    color_input: [5.815634e-05, 4.3865861e-05, 0.99985409, 4.3865861e-05]
    height_input: [0.00045329696, 0.00045329696, 0.99864012, 0.00045329696]

    They are almost equal.

  9. added
    Hackathon
    on Dec 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Hackathonbugcategory: dnnconfirmedoptimization

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions