Repository navigation
Closed
Labels
Milestone
Description
cv::cuda::Filter created by cv::cuda::createGaussianFilter(...) is not thread safe. And I don't mean the classical thread-safety of accessing one instance from multiple cpu threads. It is not safe to create separate instances of the Filter in multiple threads.
system info
- OpenCV version: 3.1.0
- Host OS: Linux (Ubuntu 14.04)
- GPU: GeForce GTX TITAN X
- compiler: g++ 4.8.4
Expected behaviour
Actual behaviour


(not deterministic... each execution outputs slightly different results, but the first image is almost always badly distorted)
Code example to reproduce the issue
#include <iostream>
#include <string>
#include <thread>
#include <opencv2/core/core.hpp>
#include <opencv2/cudafilters.hpp>
#include <opencv2/highgui/highgui.hpp>
void show(const std::string& win_name, const cv::Mat& im) {
cv::Mat to_show;
double min, max;
cv::minMaxIdx(im, &min, &max);
im.convertTo(to_show, CV_8UC1, 255 / (max-min), -min);
cv::namedWindow(win_name, CV_WINDOW_NORMAL);
std::cout << win_name << " - min: " << min << "; max: " << max << std::endl;
cv::imshow(win_name, to_show);
// cv::imwrite(std::string("/tmp/")+win_name+".png", to_show);
}
void filter_it(const cv::cuda::GpuMat& d_src, int ksize, cv::Mat& h_dst) {
cv::cuda::GpuMat d_dst(d_src.rows, d_src.cols, CV_32FC1);
cv::Ptr<cv::cuda::Filter> filter =
cv::cuda::createGaussianFilter(CV_32FC1, CV_32FC1, cv::Size(ksize,ksize), 0, 0);
filter->apply(d_src, d_dst);
h_dst = cv::Mat(d_dst);
}
int main(int argc, char *argv[])
{
cv::Mat dot1;
const int size = 65;
dot1.create(size, size, CV_32FC1);
dot1.at<float>(size/2, size/2) = 1.0f;
cv::Mat dot2;
dot1.copyTo(dot2);
cv::cuda::GpuMat d_src1(dot1);
cv::cuda::GpuMat d_src2(dot2);
cv::Mat h_dst1;
h_dst1.create(size, size, CV_32FC1);
cv::Mat h_dst2;
h_dst2.create(size, size, CV_32FC1);
std::thread thr1(&filter_it, std::ref(d_src1), 31, std::ref(h_dst1));
std::thread thr2(&filter_it, std::ref(d_src2), 3, std::ref(h_dst2));
thr1.join();
thr2.join();
show("filter_1", h_dst1);
show("filter_2", h_dst2);
cv::waitKey(0);
return 0;
}
Reacted by Alex Louden and Richard Veale


Activity
serycjon commentedon Jul 2, 2016
The issue is caused by cuda constant memory being used for the filter (modules/cudafilters/src/cuda/row_filter.hpp:55 - constant float c_kernel[MAX_KERNEL_SIZE];)
I see two possible fixes for this bug:
Is there any other possibility? Or which of these two solutions is prefered for OpenCV? (So that I could try and create a fix and a pull request)
cgsexton commentedon Dec 21, 2017
It looks like the proposed/attached fix of changing from constant to global was only made in the row_filter - seems like it would have been needed to be made in the col_filter as well. I've run into this thread safety issue in the 2.4.x release as well.
flyingfalling commentedon Jan 25, 2019
After some examination of the source code I think I figured out the cause of this issue.
Specifically the code in opencv_contrib/modules/cudafilters/src/cuda/filter2d.cu is the cause.
In the macro
#define IMPLEMENT_FILTER2D_TEX_READER(type)the variable
texture< type, cudaTextureType2D, cudaReadModeElementType> tex_filter2D_ ## typeis declared at global scope.
Then, in the call function, this same global scope variable is bound to the input matrix
bindTexture(&tex_filter2D_ ## type, srcWhole);In this of course means that if this call() function is simultaneously called from multiple threads, it is possible that the global tex_filter2D_ ## type would be bound to a different area of global memory by two or more threads (and specifically it could be changed partway through a computation), leading to the observed instability.
Probably the reason it was written this way is that texture can not be easily put as a member of a struct, so a "quick and dirty" fix that I wrote simply used the PtrStepSz of srcWhole directly and accessed via operator(y,x), instead of binding to a texture and then using the tex2D function to access things. This probably leads to not-great memory performance, but I don't have the time to figure out how to hack a texture (pointer?) into a struct member right now.
As for the reason this happened, I guess it is the separation between filter object creation and then calling. In other code in opencv::cuda, where filters/functions are called directly with streams, the code checks whether the passed stream reference is NULL, and if it is, it uses optimized single thread versions e.g. using const memory, otherwise it uses less optimized but thread-safe examples.
With filter pointers, at creation of the filter there is no way to know whether it is going to be called with non-default stream or not. So there is not really a good way to indicate to the creation function whether it should encapsulate memory or not.
Anyways, if anyone has input on this please say so.
I will try to make a pull request but I don't know if it is appropriate since as I said I am not sure what the impact this will have on performance. As it is the current function works fine in single thread, it is only when there are two of the same function called at the same time that it causes corrupted output.
flyingfalling commentedon Jan 25, 2019
I've prepared a patch and verified that it works, the corruption issues are gone when linking to the patched code:
In the file modules/cudafilters/src/cuda/filter2d.cu (in opencv_contrib in >=4.0, and in opencv in <4.0)
Replace:
with this:
alalek commentedon Jan 25, 2019
Feel free to prepare a patch into 3.4 branch of "opencv" repository.
We will merge changes into "opencv_contrib" during regular merging of 3.4 branch into master (weekly / bi-weekly).
@nglee @tomoaki0705 Could you take a look on this fix?
flyingfalling commentedon Jan 25, 2019
This patch should work on 3.4 and 4.0, and in 2.4 the corresponding code is in modules/gpu/src/cuda/imgproc.cu
flyingfalling commentedon Jan 25, 2019
Thanks @alalek, I tested on both 3.4 and 4.0, I don't feel like downloading and compiling 2.4 since I don't use it anymore but the code is identical, it looks like it was just rearranged at some point.
alalek commentedon Jan 25, 2019
We can backport patch onto 2.4 later after validation onto 3.4/master branches.
serycjon commentedon Jan 25, 2019
I think we should test the performance of the patched version thoroughly before merging it. Since it has been over two years of nobody really caring about this bug, I think that any significant performance drop for single-threaded use would not be worth it.
flyingfalling commentedon Jan 25, 2019
@serycjon Sounds good, do you have performance metrics? In my code, I run linear filters about 1000 times per second, and I don't see any performance drop that is noticable.
flyingfalling commentedon Jan 25, 2019
And the bug has existed since at least 2013 (when the initial commit happened). Note that in all the rest of the code, performance sacrifices have been made (e.g. changing constant to global memory) in order to make the functions "thread safe". In general using secret global variables seems bad practice, but then opencv does all sorts of weird stuff with multithreading so I guess it depends on what you think the main purpose is. It should clearly say that the function is not thread-safe, at any rate.
serycjon commentedon Jan 25, 2019
@flyingfalling I don't have the metrics and I don't work with the code causing the bug anymore, so I won't be able to help with that now. Sure, if it seems that it runs ok and if this "thread safe" strategy is common in opencv, then I have no objections to this patch. Thank you for solving this.
I was just off-put by complete lack of any feedback on the proposed fixes back in 2016, so I wanted to discuss the correctness for multi-threading vs speed for single-threading sacrifices now.
Agree that the documentation should be improved anyway.
flyingfalling commentedon Jan 25, 2019
@serycjon, Thank you for the feedback. Yea, the fixes proposed on 2016 didn't fix this bug (as you can see from the comments above). The fixes were aimed at making the functions thread-safe but they seem to have missed this important part of the code.
In general, if I am to do a pull request, should I do it off of master, or the 3.4 branch...? Or do one for each? Seems like a lot.
nglee commentedon Jan 25, 2019
@flyingfalling Your PR should go to the 3.4 branch. Reading this document written by the maintainers may be helpful when deciding which branch a PR should be merged to.
There was a PR (#11483) that tried to solve similar issue about Canny filter being not thread-safe. It might be helpful to look over it. Beside from fixing the filter code itself, the PR also tried to add some test cases to check for multi thread safety.
flyingfalling commentedon Jan 25, 2019
@nglee, OK thank you. I don't think I have the time to make test cases right now but perhaps later.
A note to posterity: the old code used (global) textures which could only be declared at static global scope, which is the reason for the old implementation I assume. After kepler (cuda 5.0), they introduced ability to make "texture objects" (https://devblogs.nvidia.com/cuda-pro-tip-kepler-texture-objects-improve-performance-and-flexibility/) which would enable the use of textures as in the original implementation but with thread safety as well. Since this would require a version check and some code complexities, I just abandoned the texture access and directly access the global device memory holding the input image. This may have some downsides when it comes to 2D locality since it is accessing in 16x16 chunks, but on newer devices this downside will probably be negligible. In the future someone with more interest in optimization may change to using texture objects and compare performance more carefully.
alalek commentedon Jan 25, 2019
There are some performance tests for CUDA filters module. At least they should cover "single thread" case (check regressions on CUDA device which you have).