Opencv cuda convolution extremly slower than bare cuda code convolution on Jetson Nano using unified memory

Hi everyone, I wrote both an image convolution directly using cuda kernel and then I tried using opencv cuda convolution on my Jetson nano (Jetpack 4.3) with cuda and opencv 4.0.0 recompiled after removing Jetpack opencv version. I paste below my opencv code with convolution matrix. I used the same matrix in cuda “handwritten” convolution (just cuda code without opencv). The problem is that in opencv cuda convolution version the convolution process is 200 times slower than the “handwritten” cuda convolution. In opencv convolution I’m trying to use unified memory to access Mat and GpuMat from other opencv function. Have you got any suggestion to speed up this code on Jetson Nano?

cudaSetDeviceFlags(cudaDeviceMapHost); //Support for mapped pinned allocations

int rows = 512;
int cols = 640;
int righekernel=7;
int colonnekernel=7;
float *h_a, *cu_kernel, *h_result;
QTime Timek1, Timek2;
int elaps;
float kernelmatr[righekernel*colonnekernel]= {
         0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
        0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
        0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
        0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
        0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
        0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
        0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04};

//Allocate memory for device pointers
cudaMallocManaged(&h_a, sizeof(float)*rows*cols);
cudaMallocManaged(&h_result, sizeof(float)*rows*cols);
cudaMallocManaged(&cu_kernel, sizeof(float)*righekernel*colonnekernel);
memcpy(cu_kernel,kernelmatr,righekernel*colonnekernel*sizeof(float));

//Mats (declaring them using pointers)
cv::Mat hmat_a(cv::Size(cols, rows), CV_32F, h_a);
cv::Mat hmat_orig(cv::Size(cols, rows), CV_32F, h_a);
cv::Mat hmat_result(cv::Size(cols, rows), CV_32F, h_result);
cv::Mat hmat_kernel(cv::Size(colonnekernel, righekernel), CV_32F, cu_kernel);

//Gpu Mats (declaring with the same pointers!)
cv::cuda::GpuMat dmat_a(cv::Size(cols, rows), CV_32F, h_a);
cv::cuda::GpuMat dmat_result(cv::Size(cols, rows), CV_32F, h_result);
cv::cuda::GpuMat dmat_kernel(cv::Size(colonnekernel, righekernel), CV_32F, cu_kernel);

hmat_orig = cv::imread("img_in.bmp",0);
hmat_orig.convertTo(hmat_a, CV_32FC1);
cv::Ptr<cv::cuda::Convolution> conv= cv::cuda::createConvolution(cv::Size(7, 7));

Timek1 = QTime::currentTime();
conv->convolve(dmat_a, dmat_kernel, dmat_result);
Timek2 = QTime::currentTime();
elaps = Timek1.msecsTo(Timek2);
ui->textEdit_UM->setText(QString::number(elaps));


cv::Mat dst;
dmat_result.download(dst);
cv::imwrite("out.bmp",dst);




cudaFree(&h_a);
cudaFree(&h_result);
cudaFree(&cu_kernel);

Hi,

Have you built OpenCV with cuDNN support?

Not sure how do you build OpenCV on the Jetson.
Here is a good example for your reference:

Thanks.

Yes, I launched exactly the same script when I configured the Jetson. I think the problem is in UNIFIED MEMORY management in the OpenCv cuda configuation. Is there any flag to select in Tegra OpenCV setup/configuration?

I followed this guide to write cuda code:

and this discussion in my code posted before, using OpenCv Cuda implementation:

==> so maybe the problem is OpenCv convolution implementation. Any suggestions?

Be aware that CUDA stuff may be long to set up the first time, up to a few seconds.
Make a loop and you’ll probably find that the next convolutions are much faster.

[EDIT: Just checked now with this code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#include "cuda_runtime.h"

#include "opencv2/core.hpp"
#include "opencv2/cudaarithm.hpp"
#include "opencv2/imgcodecs.hpp" 
#include "opencv2/highgui.hpp" 
 

int main() {
	/* Convolution kernel in unified memory */
	const int kern_height = 7;
	const int kern_width = 7;
	float * u_kern;
	cudaMallocManaged(&u_kern, sizeof(float) * kern_height * kern_width);
	cv::Mat          h_kernel(kern_height, kern_width, CV_32FC1, u_kern);
	cv::cuda::GpuMat d_kernel(kern_height, kern_width, CV_32FC1, u_kern);
	// Set kernel from CPU. Here flat kernel as example
	h_kernel.setTo(1.0/(kern_height * kern_width));   

	/* Prepare convolution filter */
	cv::Ptr<cv::cuda::Convolution> conv = cv::cuda::createConvolution(cv::Size(kern_height, kern_width));

	/* Read image and get resolution */
	cv::Mat readFrame = cv::imread("/usr/local/cuda/samples/3_Imaging/dct8x8/data/barbara.bmp", cv::IMREAD_GRAYSCALE);
	unsigned int height = readFrame.rows;
	unsigned int width = readFrame.cols;

	cv::imshow("Original", readFrame);
	//cv::waitKey(-1);

	/* Float frame in unified memory */
	float * u_fFrame;
	cudaMallocManaged(&u_fFrame, sizeof(float) * height * width);
	cv::Mat          h_fFrame(height, width, CV_32FC1, u_fFrame);
	cv::cuda::GpuMat d_fFrame(height, width, CV_32FC1, u_fFrame);

	/* Float result in unified memory */
	float * u_fResult;
	unsigned int res_height = height - kern_height + 1;
	unsigned int res_width = width - kern_width + 1;
	cudaMallocManaged(&u_fResult, sizeof(float) * res_height * res_width);
	cv::Mat          h_fResult(res_height, res_width, CV_32FC1, u_fResult);
	cv::cuda::GpuMat d_fResult(res_height, res_width, CV_32FC1, u_fResult);


	/* Process */
	std::cout<<"Starting..." << std::endl;
	readFrame.convertTo(h_fFrame, CV_32FC1);

	int loops = 10;
	while(loops--) {
		double prev = (double) cv::getTickCount();
		conv->convolve(d_fFrame, d_kernel, d_fResult);
		cudaDeviceSynchronize();
		double now = (double) cv::getTickCount();
		double delta = (now - prev) / cv::getTickFrequency();
		std::cout<<"convolution time =" << delta << std::endl;
	}

	cv::Mat h_result(res_height, res_width, CV_8UC1);
	h_fResult.convertTo(h_result, CV_8UC1);
	/* Processing done */


	cv::imshow("Filtered", h_result);
	cv::waitKey(-1);
	cv::imwrite("filtered.bmp", h_result);


	/* Clean up */
	cudaFree(u_fResult);
	cudaFree(u_fFrame);
	cudaFree(u_kern);

	return 0;
}

and got these timings:

Starting...
convolution time =2.04625
convolution time =0.00437133
convolution time =0.00437347
convolution time =0.0041271
convolution time =0.00897517
convolution time =0.00619217
convolution time =0.00867555
convolution time =0.00689813
convolution time =0.00498308
convolution time =0.00404592

Dear Honey_Patouceul, I tried your code but unfortunately the result I get in the convoluaione are images with artifacts (in the attachment you can see origina limage and convoluted image with a large vertical line). This does not happen with the image you used for your example, coming from the cuda examples installed in the Jetson. Do I need to change anything in the image format? I am also attaching the original image in this case.

Original image (I load it as bmp format)

Convoluted image (large black row after convolution)

I wrote CUDA code directly for convolution (in handwritten CUDA I have no artifacts) with unified memory but even in this case I have a very high startup cost and I can’t understand why. Do you have any idea why the first iterations in CUDA are so slow?

The cause may be the improper size given to createConvolution. I did not pay attention and reproduced your original code, that works up to 512 pixels.
Giving the frame size instead should solve your problem:

     ...
     unsigned int height = readFrame.rows;
     unsigned int width = readFrame.cols;

	 /* Prepare convolution filter */
	 cv::Ptr<cv::cuda::Convolution> conv = cv::cuda::createConvolution(cv::Size(height, width));

Someone from NVIDIA may better advise or at least inform about first iteration setup time.
Obviously, next iterations may benefit from cache, but there may be more I’m not aware of.

Thanks, this solved the artifact problem. I just hope someone from NVIDIA can help us figure out how to improve setup time. In fact the setup time is high in opencv but it is also high (albeit of shorter duration) in the code that I wrote directly in CUDA. I hope in the clarification of NVIDIA for OpenCV approach and for CUDA approach. Thanks again Honey Patouceul.

Hi,

Would you mind to share a completely source to reproduce this?
Or we can use the Honey_Patouceul sample directly?

Thanks.

Dear
AastaLLL, I apologize for the delay in replying.
To reproduce my same situation you can use the Honey_Patouceul sample (which is the version tested with GPU-based OpenCv), while for the CUDA code I am attaching an example project with the convolution created directly in CUDA.

From the tests made I found that the code written directly in CUDA is faster than the GPU-based OpenCv one in executing the convolution but is still slow during the setup. How can I speed up the OpenCv version? How can I speed up that CUDA instead?

In the CUDA version I have doubts if this is correct:

  1. Grid and Block sizing to maximize Kernel execution speed (target image size is 640x512 with a 7x7 convolution kernel)

  2. management of unified memory to ensure maximum access speed to image data

Thanks in advanceCUDA_CONV.zip (497.9 KB)