Skip to content

opencv_perf_objdetect "OCL_Cascade_*" tests fail since commit ad70ab40 #6293

Open

Description

@sander1234567890

When running opencv_perf_objdetect all haarcascade tests fail with the exception below.
This was introduced in commit ad70ab4, if i checkout 1 commit before that the tests run fine.

Time compensation is 0
CTEST_FULL_OUTPUT
OpenCV version: 3.1.0-dev
OpenCV VCS version: 3.1.0-315-gecf65a0-dirty
Build type: release
Parallel framework: pthreads
CPU features: mmx sse sse2 sse3
OpenCL Platforms:
    Clover
        iGPU: AMD TAHITI (DRM 2.43.0, LLVM 3.7.1) (OpenCL 1.1 MESA 11.1.2)
Current OpenCL device:
    Type = iGPU
    Name = AMD TAHITI (DRM 2.43.0, LLVM 3.7.1)
    Version = OpenCL 1.1 MESA 11.1.2
    Compute units = 28
    Max work group size = 256
    Local memory size = 32 kB
    Max memory allocation size = 256 MB
    Double support = Yes
    Host unified memory = Yes
    Has AMD Blas = No
    Has AMD Fft = No
    Preferred vector width char = 16
    Preferred vector width short = 8
    Preferred vector width int = 4
    Preferred vector width long = 2
    Preferred vector width float = 4
    Preferred vector width double = 2
[==========] Running 28 tests from 2 test cases.
[----------] Global test environment set-up.


[ RUN      ] OCL_Cascade_Image_MinSize_CascadeClassifier.CascadeClassifier/3
OpenCV Error: Assertion failed (u->origdata == data) in deallocate, file /usr/src/opencv/modules/core/src/ocl.cpp, line 4584
/usr/src/opencv/modules/ts/src/ts_perf.cpp:1721: Failure
Failed
Expected: PerfTestBody() doesn't throw an exception.
  Actual: it throws cv::Exception:
  /usr/src/opencv/modules/core/src/ocl.cpp:4584: error: (-215) u->origdata == data in function deallocate

params    = ("cv/cascadeandhog/cascades/haarcascade_frontalface_alt.xml", "cv/cascadeandhog/images/bttf301.png", 30)
termination reason:  unhandled exception
bytesIn   =     240950
bytesOut  =          0
samples   =         10 of 100
outliers  =          0
frequency = 1000000000
min       =   16528436 = 16.53ms
median    =   16943004 = 16.94ms
gmean     =   16932285 = 16.93ms
gstddev   = 0.02050919 = 2.08ms for 97% dispersion interval
mean      =   16935514 = 16.94ms
stddev    =     351309 = 0.35ms
[  FAILED  ] OCL_Cascade_Image_MinSize_CascadeClassifier.CascadeClassifier/3, where GetParam() = ("cv/cascadeandhog/cascades/haarcascade_frontalface_alt.xml", "cv/cascadeandhog/images/bttf301.png", 30) (236 ms)

Activity

  1. alalek commented on Mar 17, 2016

    @alalek
    Member

    Please add: std::cout << cv::getBuildInformation().c_str() << std::endl

    Git commit is "3.1.0-315-gecf65a0-dirty" and it not very good: it is dirty and looks like it is non public.
    Mentioned line is different (doesn't contain assertion, it is below):
    ad70ab4#diff-ff67959a252bb213e2340f8557e16e84R4584

    Please rerun test with added environment parameter OPENCV_OPENCL_RAISE_ERROR=1

    This assertion checks this assumption from specifications:

    The pointer value returned by clEnqueueMapBuffer will be derived from the host_ptr specified when the buffer object is created.

    (https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clEnqueueMapBuffer.html)

    Could you check used flags for created OpenCL buffer?

    • Please hack ocl.cpp and dump flags and returned value for clCreateBuffer calls; also add dumping of u->handle value before this assertion
    • or just dump result of clGetMemObjectInfo with CL_MEM_FLAGS parameter before this assertion.
  2. sander1234567890 commented on Mar 19, 2016

    @sander1234567890
    Author
    Buildinfo:
    General configuration for OpenCV 3.1.0-dev =====================================
      Version control:               3.1.0-316-g4e479d5-dirty
    
      Platform:
        Timestamp:                   2016-03-19T17:45:16Z
        Host:                        Linux 4.4.0-1-amd64 x86_64
        CMake:                       3.5.0
        CMake generator:             Unix Makefiles
        CMake build tool:            /usr/bin/make
        Configuration:               Release
    
      C/C++:
        Built as dynamic libs?:      YES
        C++ Compiler:                /usr/bin/c++  (ver 5.3.1)
        C++ flags (Release):         -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
        C++ flags (Debug):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
        C Compiler:                  /usr/bin/cc
        C flags (Release):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -O3 -DNDEBUG  -DNDEBUG
        C flags (Debug):             -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -g  -O0 -DDEBUG -D_DEBUG
        Linker flags (Release):
        Linker flags (Debug):
        Precompiled headers:         YES
        Extra dependencies:          /usr/lib/x86_64-linux-gnu/libpng.so /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/x86_64-linux-gnu/libjasper.so gthread-2.0 gstvideo-1.0 gstapp-1.0 gstbase-1.0 gstriff-1.0 gstpbutils-1.0 gstreamer-1.0 gobject-2.0 glib-2.0 avcodec-ffmpeg avformat-ffmpeg avutil-ffmpeg swscale-ffmpeg avresample-ffmpeg /lib/x86_64-linux-gnu/libbz2.so.1 dl m pthread rt
        3rdparty dependencies:       libwebp libtiff libjpeg IlmImf
    
      OpenCV modules:
        To be built:                 core flann imgproc ml photo video imgcodecs shape videoio highgui objdetect superres ts features2d calib3d stitching videostab python2 python3
        Disabled:                    world
        Disabled by dependency:      -
        Unavailable:                 cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev java viz
    
      GUI: 
        QT:                          NO
        GTK+:                        NO
        GThread :                    YES (ver 2.46.2)
        GtkGlExt:                    NO
        OpenGL support:              NO
        VTK support:                 NO
    
      Media I/O: 
        ZLib:                        /usr/lib/x86_64-linux-gnu/libz.so (ver 1.2.8)
        JPEG:                        libjpeg (ver 90)
        WEBP:                        build (ver 0.3.1)
        PNG:                         /usr/lib/x86_64-linux-gnu/libpng.so (ver 1.2.54)
        TIFF:                        build (ver 42 - 4.0.2)
        JPEG 2000:                   /usr/lib/x86_64-linux-gnu/libjasper.so (ver 1.900.1)
        OpenEXR:                     build (ver 1.7.1)
        GDAL:                        NO
    
      Video I/O:
        DC1394 1.x:                  NO
        DC1394 2.x:                  NO
        FFMPEG:                      YES
          codec:                     YES (ver 56.60.100)
          format:                    YES (ver 56.40.101)
          util:                      YES (ver 54.31.100)
          swscale:                   YES (ver 3.1.101)
          resample:                  YES (ver 2.1.0)
          gentoo-style:              YES
        GStreamer:                   
          base:                      YES (ver 1.6.3)
          video:                     YES (ver 1.6.3)
          app:                       YES (ver 1.6.3)
          riff:                      YES (ver 1.6.3)
          pbutils:                   YES (ver 1.6.3)
        OpenNI:                      NO
        OpenNI PrimeSensor Modules:  NO
        OpenNI2:                     NO
        PvAPI:                       NO
        GigEVisionSDK:               NO
        UniCap:                      NO
        UniCap ucil:                 NO
        V4L/V4L2:                    NO/YES
        XIMEA:                       NO
        Xine:                        NO
        gPhoto2:                     NO
    
      Parallel framework:            pthreads
    
      Other third-party libraries:
        Use IPP:                     9.0.1 [9.0.1]
             at:                     /usr/src/opencv-vanilla/3rdparty/ippicv/unpack/ippicv_lnx
        Use IPP Async:               NO
        Use VA:                      NO
        Use Intel VA-API/OpenCL:     NO
        Use Eigen:                   YES (ver 3.2.92)
        Use Cuda:                    NO
        Use OpenCL:                  YES
        Use custom HAL:              NO
    
      OpenCL:                        <Dynamic loading of OpenCL library>
        Include path:                /usr/src/opencv-vanilla/3rdparty/include/opencl/1.2
        Use AMDFFT:                  NO
        Use AMDBLAS:                 NO
    
      Python 2:
        Interpreter:                 /usr/bin/python2.7 (ver 2.7.11)
        Libraries:                   /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.11+)
        numpy:                       /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.11.0b3)
        packages path:               lib/python2.7/dist-packages
    
      Python 3:
        Interpreter:                 /usr/bin/python3 (ver 3.5.1)
        Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.5m.so (ver 3.5.1+)
        numpy:                       /usr/lib/python3/dist-packages/numpy/core/include (ver 1.11.0b3)
        packages path:               lib/python3.5/dist-packages
    
      Python (for build):            /usr/bin/python2.7
    
      Java:
        ant:                         NO
        JNI:                         NO
        Java wrappers:               NO
        Java tests:                  NO
    
      Matlab:                        Matlab not found or implicitly disabled
    
      Documentation:
        Doxygen:                     NO
        PlantUML:                    NO
    
      Tests and samples:
        Tests:                       YES
        Performance tests:           YES
        C/C++ Examples:              NO
    
      Install path:                  /usr/local
    
      cvconfig.h is in:              /usr/src/opencv-vanilla/build
    -----------------------------------------------------------------
    
    
    Debug output:
    # ./bin/opencv_perf_objdetect --gtest_filter=OCL_Cascade_Image_MinSize_CascadeClassifier* --gtest_break_on_failure
    Time compensation is 0
    CTEST_FULL_OUTPUT
    OpenCV version: 3.1.0-dev
    OpenCV VCS version: 3.1.0-316-g4e479d5-dirty
    Build type: release
    Parallel framework: pthreads
    CPU features: mmx sse sse2 sse3
    OpenCL Platforms: 
        Clover
            iGPU: AMD TAHITI (DRM 2.43.0, LLVM 3.7.1) (OpenCL 1.1 MESA 11.1.2)
    Current OpenCL device: 
        Type = iGPU
        Name = AMD TAHITI (DRM 2.43.0, LLVM 3.7.1)
        Version = OpenCL 1.1 MESA 11.1.2
        Compute units = 28
        Max work group size = 256
        Local memory size = 32 kB 
        Max memory allocation size = 256 MB 
        Double support = Yes
        Host unified memory = Yes
        Has AMD Blas = No
        Has AMD Fft = No
        Preferred vector width char = 16
        Preferred vector width short = 8
        Preferred vector width int = 4
        Preferred vector width long = 2
        Preferred vector width float = 4
        Preferred vector width double = 2
    Note: Google Test filter = OCL_Cascade_Image_MinSize_CascadeClassifier*
    [==========] Running 27 tests from 1 test case.
    [----------] Global test environment set-up.
    [----------] 27 tests from OCL_Cascade_Image_MinSize_CascadeClassifier
    [ RUN      ] OCL_Cascade_Image_MinSize_CascadeClassifier.CascadeClassifier/0
    ?!?!?: Me here 2  | clCreateBuffer retval:0
    ?!?!?: Me here 4  | u->handle:0x114c8f0 (262144) u->flags:0x28 u->allocatorFlags_:0
    ?!?!?: Me here 1  | u->handle:0x12b8560 (136640) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: Me here 1  | u->handle:0x1348e80 (600) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: Me here 1  | u->handle:0x1937a90 (6116352) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: Me here 1  | u->handle:0x1938590 (120004) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: Me here 1  | u->handle:0x12b8c00 (264) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: Me here 1  | u->handle:0x67aadc0 (34160) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: Me here 1  | u->handle:0x1348a80 (17080) u->flags:0x2 u->allocatorFlags_:0x1
    .
    ?!?!?: Me here 5  | u->handle:0x114c8f0 (262144) u->flags:0x2a u->allocatorFlags_:0
    ?!?!?: Me here 6  | clEnqueueMapBuffer retval:0
    ?!?!?: Me here 7  | ret:0 cl_mem_flags 0x9
    ?!?!?: Me here 8  | u->origdata:0x11d77e0 data:0x7f17cac01000
    OpenCV Error: Assertion failed (u->origdata == data) in deallocate, file /usr/src/opencv-vanilla/modules/core/src/ocl.cpp, line 4603
    /usr/src/opencv-vanilla/modules/ts/src/ts_perf.cpp:1721: Failure
    Failed
    Expected: PerfTestBody() doesn't throw an exception.
      Actual: it throws cv::Exception:
      /usr/src/opencv-vanilla/modules/core/src/ocl.cpp:4603: error: (-215) u->origdata == data in function deallocate
    
    Segmentation fault
    

    debug-patch.txt

    The debug patch i used is attached.

  3. alalek commented on Mar 19, 2016

    @alalek
    Member

    Thanks for update!

    cl_mem_flags 0x9

    This means: 9 = 8 | 1 ~ (CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE)

    Could you please dump near point 2 value of u->origdata?
    if it is equal to value on point 8 then it is unexpected behavior of OpenCL runtime:

    If the buffer object is created with CL_MEM_USE_HOST_PTR set in mem_flags, the host_ptr specified in clCreateBuffer is guaranteed to contain the latest bits in the region being mapped when the clEnqueueMapBuffer command has completed; and the pointer value returned by clEnqueueMapBuffer will be derived from the host_ptr specified when the buffer object is created.

    (https://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/clEnqueueMapBuffer.html , cite from OpenCL 1.1, previous was from OpenCL 1.2 spec, but the problem is same: "derived from the host_ptr")

    I have already guarded some cases with unaligned buffers (there was more worse case - silent memory corruption), but looks like this OpenCL runtime wants more relaxed parameters.
    Currently I have no idea, what condition to place here, because it looks like a bug of OpenCL runtime and probably will be fixed in future OpenCL runtime updates.

    Some workarounds:

  4. sander1234567890 commented on Mar 20, 2016

    @sander1234567890
    Author

    Could you please dump near point 2 value of u->origdata?
    if it is equal to value on point 8 then it is unexpected behavior of OpenCL runtime:

    If the buffer object is created with CL_MEM_USE_HOST_PTR set in mem_flags, the host_ptr specified in clCreateBuffer is guaranteed to contain the latest bits in the region being mapped when the clEnqueueMapBuffer command has completed; and the pointer value returned by clEnqueueMapBuffer will be derived from the host_ptr specified when the buffer object is created.
    

    (https://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/clEnqueueMapBuffer.html , cite from OpenCL 1.1, previous was from OpenCL 1.2 spec, but the problem is same: "derived from the host_ptr")

    Here is the output (debug-patch2.txt attached), it seems you are right:
    [==========] Running 27 tests from 1 test case.
    debug-patch2.txt

    [----------] Global test environment set-up.
    [----------] 27 tests from OCL_Cascade_Image_MinSize_CascadeClassifier
    [ RUN ] OCL_Cascade_Image_MinSize_CascadeClassifier.CascadeClassifier/0
    ?!?!?: Me here 2 | clCreateBuffer retval:0
    ?!?!?: | ret:0 cl_mem_flags 0x9
    ?!?!?: | u->origdata:0xf6a7e0 createFlags:0
    ?!?!?: Me here 4 | u->handle:0xedf8f0 (262144) u->flags:0x28 u->allocatorFlags_:0
    ?!?!?: Me here 1 | u->handle:0x104b560 (136640) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: | ret:0 cl_mem_flags 0x1
    ?!?!?: | u->origdata:(nil) createFlags:0
    ?!?!?: Me here 1 | u->handle:0x10dbe80 (600) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: | ret:0 cl_mem_flags 0x1
    ?!?!?: | u->origdata:(nil) createFlags:0
    ?!?!?: Me here 1 | u->handle:0x16caa90 (6116352) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: | ret:0 cl_mem_flags 0x1
    ?!?!?: | u->origdata:(nil) createFlags:0
    ?!?!?: Me here 1 | u->handle:0x16cb590 (120004) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: | ret:0 cl_mem_flags 0x1
    ?!?!?: | u->origdata:(nil) createFlags:0
    ?!?!?: Me here 1 | u->handle:0x104bc00 (264) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: | ret:0 cl_mem_flags 0x1
    ?!?!?: | u->origdata:(nil) createFlags:0
    ?!?!?: Me here 1 | u->handle:0x1f6ff90 (34160) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: | ret:0 cl_mem_flags 0x1
    ?!?!?: | u->origdata:(nil) createFlags:0
    ?!?!?: Me here 1 | u->handle:0x10dba80 (17080) u->flags:0x2 u->allocatorFlags_:0x1
    ?!?!?: | ret:0 cl_mem_flags 0x1
    ?!?!?: | u->origdata:(nil) createFlags:0
    .
    ?!?!?: Me here 5 | u->handle:0xedf8f0 (262144) u->flags:0x2a u->allocatorFlags_:0
    ?!?!?: Me here 6 | clEnqueueMapBuffer retval:0
    ?!?!?: Me here 7 | ret:0 cl_mem_flags 0x9
    ?!?!?: Me here 8 | u->origdata:0xf6a7e0 data:0x7fc1bff15000
    OpenCV Error: Assertion failed (u->origdata == data) in deallocate, file /usr/src/opencv-vanilla/modules/core/src/ocl.cpp, line 4623
    /usr/src/opencv-vanilla/modules/ts/src/ts_perf.cpp:1721: Failure
    Failed
    Expected: PerfTestBody() doesn't throw an exception.
    Actual: it throws cv::Exception:
    /usr/src/opencv-vanilla/modules/core/src/ocl.cpp:4623: error: (-215) u->origdata == data in function deallocate

    Some workarounds:
    disable OpenCL support

    Since i'm trying to get OpenCL to work that is not the direction i want to go to ;)

    add an option to disable usage of CL_MEM_USE_HOST_PTR and disable it manually (via environment variable)
    if this OpenCL runtime works fine with aligned buffers (by 4k I guess), then you can try to fix alignments in these places: https://github.com/Itseez/opencv/blob/3.1.0/modules/core/src/ocl.cpp#L4452 https://github.com/Itseez/opencv/blob/3.1.0/modules/core/include/opencv2/core/private.hpp#L137 https://github.com/Itseez/opencv/blob/3.1.0/modules/core/include/opencv2/core/private.hpp#L208
    

    Tried something in this direction, by commenting out the code block around point2, so force it to go through point 3, which uses CL_MEM_COPY_HOST_PTR, although that is probably a lot slower since it needs to do extra copying. But if i do that it all works fine.

    Another thing is to try to get another runtime working, though the whole AMD prop. driver is a PITA to install on linux (and a hassle since it breaks every kernel update). It would have been very nice if the OSS clover/mesa stuff did work out :(.

  5. sander1234567890 commented on Mar 20, 2016

    @sander1234567890
    Author

    Hmm CL_MEM_USE_HOST_PTR seems implemented in this patch:
    https://cgit.freedesktop.org/mesa/mesa/commit/?id=f972b223c4cb4ec58a9451cbac5d120ac9deb336

    and has a comment about alignment:

    •  // Page alignment is normally required for this, just try, hope for the
      
    •  // best and fall back if it fails.
      
  6. alalek commented on Mar 20, 2016

    @alalek
    Member

    Thanks for updates!

    is probably a lot slower since it needs to do extra copying.

    Extra copying is actual for most part of implementation with unaligned data (another OpenCL implementations tries to disable CPU cache for boundary pages, but it is hard to say what is worse).

    From MESA patch comment:

    In case the memory cannot be mapped, a fallback similar to CL_MEM_COPY_HOST_PTR is used.

    Actually this fallback to CL_MEM_COPY_HOST_PTR breaks OpenCL specification statements for clEnqueueMapBuffer behavior.
    I believe clCreateBuffer should just fail in this case:

       if (obj.flags() & CL_MEM_USE_HOST_PTR && user_ptr_support) {
          // Page alignment is normally required for this, just try, hope for the
          // best and fall back if it fails.
          pipe = dev.pipe->resource_from_user_memory(dev.pipe, &info, obj.host_ptr());
          if (pipe)
             return;
    +     throw error(CL_MEM_OBJECT_ALLOCATION_FAILURE or other error);
       }
    
  7. alalek commented on Sep 25, 2019

    @alalek
    Member

    Added workaround via runtime flag: #15579

  8. edman007 commented on Jan 29, 2022

    @edman007
    Contributor

    Hi, so I encountered a bug that calls this issue out, and the workaround does not work. Specifically, I am converting an AVFrame (from FFMPEG) to a UMat. So I tried to make a Mat() and get the UMat, and I get this problem:

    OpenCV(4.5.5-dev) Error: Assertion failed (u->origdata == data && "Details: https://github.com/opencv/opencv/issues/6293") in deallocate_, file /tmp/opencv/modules/core/src/ocl.cpp, line 5762
    terminate called after throwing an instance of 'cv::Exception'
      what():  OpenCV(4.5.5-dev) /tmp/opencv/modules/core/src/ocl.cpp:5762: error: (-215:Assertion failed) u->origdata == data && "Details: https://github.com/opencv/opencv/issues/6293" in function 'deallocate_'
    

    My Code is:

            cv::Mat myMat = cv::Mat(input->height, input->width, CV_16UC1, input->data, input->linesize[0]);
            //myMat.getUMat(cv::ACCESS_READ).copyTo(buf);//this line works if uncommented, no problems
            buf = myMat.getUMat(cv::ACCESS_READ);
    

    Also, if I set OPENCV_OPENCL_ENABLE_MEM_USE_HOST_PTR=0 it crashes with FFmpeg appearing to have corrupted allocator. It seems like getting the UMat() causes the destructor to deallocate the host pointer (which shouldn't even be attempted, because the docs say the caller owns the pointer and should deallocate it).

  9. alalek commented on Jan 29, 2022

    @alalek
    Member

    @edman007 Please provide complete minimal reproducer (provided lines doesn't call deallocate, it is done somewhere later). Add dump of opencv_version --opencl output.

    P.S. myMat is created with RAW data pointer. It is not able to manage lifetime of the data, so some limitations may apply. At least you should guarantee that lifetime of myMat is bigger than lifetime of buf.

  10. edman007 commented on Jan 29, 2022

    @edman007
    Contributor

    @alalek It does deallocate on the second line, see the stack trace:

    OpenCV(4.5.5-dev) Error: Assertion failed (u->origdata == data && "Details: https://github.com/opencv/opencv/issues/6293") in deallocate_, file /tmp/opencv/modules/core/src/ocl.cpp, line 5762
    terminate called after throwing an instance of 'cv::Exception'
      what():  OpenCV(4.5.5-dev) /tmp/opencv/modules/core/src/ocl.cpp:5762: error: (-215:Assertion failed) u->origdata == data && "Details: https://github.com/opencv/opencv/issues/6293" in function 'deallocate_'
    
    
    Thread 3 "chiton" received signal SIGABRT, Aborted.
    [Switching to Thread 0x7fffeba23640 (LWP 5194)]
    0x00007ffff3fec868 in raise () from /lib64/libc.so.6
    (gdb) bt
    #0  0x00007ffff3fec868 in raise () at /lib64/libc.so.6
    #1  0x00007ffff3fd3546 in abort () at /lib64/libc.so.6
    #2  0x00007ffff439a89a in  () at /usr/lib64/libstdc++.so.6
    #3  0x00007ffff43a606a in  () at /usr/lib64/libstdc++.so.6
    #4  0x00007ffff43a60d5 in  () at /usr/lib64/libstdc++.so.6
    #5  0x00007ffff43a6368 in  () at /usr/lib64/libstdc++.so.6
    #6  0x00007ffff4584ba6 in cv::error(cv::Exception const&) (exc=...) at /tmp/opencv/modules/core/src/system.cpp:1237
    #7  0x00007ffff476468d in cv::error(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char const*, char const*, int)
        (_code=_code@entry=-215, _err="u->origdata == data && \"Details: https://github.com/opencv/opencv/issues/6293\"", _func=0x7fffeba21230 "\370\206\216\364\377\177", 
        _func@entry=0x7ffff482a873 "deallocate_", _file=_file@entry=0x7ffff4827480 "/tmp/opencv/modules/core/src/ocl.cpp", _line=_line@entry=5762)
        at /tmp/opencv/modules/core/src/system.cpp:1249
    #8  0x00007ffff4705b17 in cv::ocl::OpenCLAllocator::deallocate_(cv::UMatData*) const (this=<optimized out>, u=0x7fffe4256d80) at /usr/include/c++/11.2.0/ext/new_allocator.h:79
    #9  0x00007ffff477119e in cv::UMat::release() (this=this@entry=0x7fffe4424dd8) at /tmp/opencv/modules/core/src/umatrix.cpp:381
    #10 0x00007ffff4771211 in cv::UMat::operator=(cv::UMat&&) (this=0x7fffe4424dd8, m=...) at /tmp/opencv/modules/core/src/umatrix.cpp:430
    #11 0x0000000000491787 in MotionOpenCV::process_frame(AVFrame const*, bool) (this=0x7fffe4424dc0, frame=0x7fffe40097c0, video=true) at motion_opencv.cpp:87
    #12 0x000000000048e48d in MotionController::process_frame(int, AVFrame const*) (this=0x7fffeba21850, index=0, frame=0x7fffe40097c0) at motion_controller.cpp:56
    #13 0x0000000000460e0c in Camera::run() (this=0x521b00) at camera.cpp:201
    #14 0x0000000000452d4d in std::__invoke_impl<void, void (Camera::*)(), Camera*>(std::__invoke_memfun_deref, void (Camera::*&&)(), Camera*&&)
        (__f=@0x5398f0: (void (Camera::*)(Camera * const)) 0x45fb38 <Camera::run()>, __t=@0x5398e8: 0x521b00) at /usr/include/c++/11.2.0/bits/invoke.h:74
    #15 0x0000000000452cab in std::__invoke<void (Camera::*)(), Camera*>(void (Camera::*&&)(), Camera*&&) (__fn=@0x5398f0: (void (Camera::*)(Camera * const)) 0x45fb38 <Camera::run()>)
        at /usr/include/c++/11.2.0/bits/invoke.h:96
    #16 0x0000000000452c1b in std::thread::_Invoker<std::tuple<void (Camera::*)(), Camera*> >::_M_invoke<0ul, 1ul>(std::_Index_tuple<0ul, 1ul>) (this=0x5398e8)
        at /usr/include/c++/11.2.0/bits/std_thread.h:253
    #17 0x0000000000452bd4 in std::thread::_Invoker<std::tuple<void (Camera::*)(), Camera*> >::operator()() (this=0x5398e8) at /usr/include/c++/11.2.0/bits/std_thread.h:260
    #18 0x0000000000452bb8 in std::thread::_State_impl<std::thread::_Invoker<std::tuple<void (Camera::*)(), Camera*> > >::_M_run() (this=0x5398e0)
        at /usr/include/c++/11.2.0/bits/std_thread.h:211
    #19 0x00007ffff43d0884 in  () at /usr/lib64/libstdc++.so.6
    #20 0x00007ffff7f15e45 in start_thread () at /lib64/libpthread.so.0
    #21 0x00007ffff40bc4af in clone () at /lib64/libc.so.6
    (gdb) frame 10
    #10 0x00007ffff4771211 in cv::UMat::operator= (this=0x7fffe4424dd8, m=...) at /tmp/opencv/modules/core/src/umatrix.cpp:430
    430	    release();
    (gdb) l
    425	
    426	UMat& UMat::operator=(UMat&& m)
    427	{
    428	    if (this == &m)
    429	      return *this;
    430	    release();
    431	    flags = m.flags; dims = m.dims; rows = m.rows; cols = m.cols;
    432	    allocator = m.allocator; usageFlags = m.usageFlags;
    433	    u = m.u;
    434	    offset = m.offset;
    (gdb) frame 9
    #9  0x00007ffff477119e in cv::UMat::release (this=this@entry=0x7fffe4424dd8) at /tmp/opencv/modules/core/src/umatrix.cpp:381
    381	        deallocate();
    (gdb) l
    376	}
    377	
    378	void UMat::release()
    379	{
    380	    if( u && CV_XADD(&(u->urefcount), -1) == 1 )
    381	        deallocate();
    382	    for(int i = 0; i < dims; i++)
    383	        size.p[i] = 0;
    384	    u = 0;
    385	}
    
    

    The = operator deallocates the UMat() returned by getUMat() (since that's the last and only place that UMat is referenced). And I changed the myMat to last longer than buf, that did not change the results. The Full function I have is (and the pointer is freed at av_frame_unref(input), which is the second call of this function, and the exception happens on the first call):

    class MotionOpenCV {
    private:
    cv::Mat myMat;
    cv::UMat buf;//the Mat we operate on
    };
    
    bool MotionOpenCV::process_frame(const AVFrame *frame, bool video){
    
            LDEBUG("SW OpenCV Conversion");
            //direct VAAPI conversion not possible
            if (!fmt_filter.send_frame(frame)){
                LWARN("OpenCV Failed to Send Frame");
                return false;
            }
            buf.release();//release the UMat that might reference myMat
            myMat.release();//release the last myMat
            av_frame_unref(input);//and release it's underlying pointer
            if (!fmt_filter.get_frame(input)){
                LWARN("OpenCV Failed to Get Frame");
                return false;
            }
            //CV_16UC1 matches the format in set_video_stream()
            myMat = cv::Mat(input->height, input->width, CV_16UC1, input->data, input->linesize[0]);
            //myMat.getUMat(cv::ACCESS_READ).copyTo(buf);
            buf = myMat.getUMat(cv::ACCESS_READ);
       
    
        return true;
    }
    

    and the opencl_version info:

    4.5.5-dev
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (1186) haveOpenCL Initialize OpenCL runtime...
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (1192) haveOpenCL OpenCL: found 1 platforms
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (984) getInitializedExecutionContext OpenCL: initializing thread execution context
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (994) getInitializedExecutionContext OpenCL: creating new execution context...
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (1012) getInitializedExecutionContext OpenCL: device=AMD PITCAIRN (DRM 2.50.0, 5.15.17, LLVM 13.0.0)
    OpenCL Platforms: 
        Clover
            dGPU: AMD PITCAIRN (DRM 2.50.0, 5.15.17, LLVM 13.0.0) (OpenCL 1.1 Mesa 21.3.5)
    Current OpenCL device: 
        Type = dGPU
        Name = AMD PITCAIRN (DRM 2.50.0, 5.15.17, LLVM 13.0.0)
        Version = OpenCL 1.1 Mesa 21.3.5
        Driver version = 21.3.5
        Address bits = 64
        Compute units = 20
        Max work group size = 256
        Local memory size = 32 KB
        Max memory allocation size = 2 GB 819 MB 204 KB 819 B
        Double support = Yes
        Half support = Yes
        Host unified memory = No
        Device extensions:
            cl_khr_byte_addressable_store
            cl_khr_global_int32_base_atomics
            cl_khr_global_int32_extended_atomics
            cl_khr_local_int32_base_atomics
            cl_khr_local_int32_extended_atomics
            cl_khr_int64_base_atomics
            cl_khr_int64_extended_atomics
            cl_khr_fp64
            cl_khr_extended_versioning
        Has AMD Blas = No
        Has AMD Fft = No
        Preferred vector width char = 16
        Preferred vector width short = 8
        Preferred vector width int = 4
        Preferred vector width long = 2
        Preferred vector width float = 4
        Preferred vector width double = 2
        Preferred vector width half = 0
    
    
  11. alalek commented on Jan 31, 2022

    @alalek
    Member

    It does deallocate on the second line, see the stack trace

    It releases UMat from the previous loop (so just two lines are not enough):

    #9  0x00007ffff477119e in cv::UMat::release() (this=this@entry=0x7fffe4424dd8) at /tmp/opencv/modules/core/src/umatrix.cpp:381
    #10 0x00007ffff4771211 in cv::UMat::operator=(cv::UMat&&) (this=0x7fffe4424dd8, m=...) at /tmp/opencv/modules/core/src/umatrix.cpp:430
    

    No idea why this line doesn't release it:

    buf.release();//release the UMat that might reference myMat
    

    Please provide complete minimal reproducer and ensure that it triggers the original problem.

  12. edman007 commented on Feb 7, 2022

    @edman007
    Contributor

    @alalek Minimal reproducer is: https://gist.github.com/edman007/4191c998b27de381a14c7a6b8f328a1c (Build command and usage instructions are in the comment at the top)

    If I call release() that causes it to deallocate, if I don't then assignment deallocates() the previous, but it doesn't actually matter, deallocation of the UMat fails if it was created from a Mat without using copyTo()

    Also, in my testing, it doesn't actually matter if I use a pointer for the original Mat, or just write the data into the Mat with memcpy(), they both result in the same result. But copyTo() to go from Mat to UMat causes no such issues.

    But my output of that command is:

    $ ./opencv_debug Big_Buck_Bunny_first_23_seconds_1080p.ogv
    [theora @ 0x4af000] 7 bits left in packet 82
    [ogg @ 0x4c0f40] Broken file, keyframe not correctly marked.
    [theora @ 0x63bfc0] 7 bits left in packet 82
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (1186) haveOpenCL Initialize OpenCL runtime...
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (1192) haveOpenCL OpenCL: found 1 platforms
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (984) getInitializedExecutionContext OpenCL: initializing thread execution context
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (994) getInitializedExecutionContext OpenCL: creating new execution context...
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/ocl.cpp (1012) getInitializedExecutionContext OpenCL: device=AMD PITCAIRN (DRM 2.50.0, 5.15.18, LLVM 13.0.0)
    [ INFO:[email protected]] global /tmp/opencv/modules/highgui/src/registry.impl.hpp (114) UIBackendRegistry UI: Enabled backends(3, sorted by priority): GTK(1000); GTK3(990); GTK2(980) + BUILTIN(QT5)
    init done
    opengl support available
    [ INFO:[email protected]] global /tmp/opencv/modules/core/src/parallel/registry_parallel.impl.hpp (96) ParallelBackendRegistry core(parallel): Enabled backends(3, sorted by priority): ONETBB(1000); TBB(990); OPENMP(980)
    OpenCV(4.5.5-dev) Error: Assertion failed (u->origdata == data && "Details: https://github.com/opencv/opencv/issues/6293") in deallocate_, file /tmp/opencv/modules/core/src/ocl.cpp, line 5762
    terminate called after throwing an instance of 'cv::Exception'
      what():  OpenCV(4.5.5-dev) /tmp/opencv/modules/core/src/ocl.cpp:5762: error: (-215:Assertion failed) u->origdata == data && "Details: https://github.com/opencv/opencv/issues/6293" in function 'deallocate_'
    
    Aborted
    
    
  13. alalek commented on Feb 10, 2022

    @alalek
    Member

    "Minimal" reproducer should not have 3rdparty external dependencies, like ffmpeg.

    Reproducer for MESA looks like this:

    cv::Mat mat(Size(640, 480), CV_8UC3, Scalar::all(0));
    cv::UMat umat = mat.getUMat(ACCESS_READ);
    umat.release();  // oops
    mat.release();
    

    With MESA we still need to use OPENCV_OPENCL_ENABLE_MEM_USE_HOST_PTR=0 workaround as mentioned above.

    Provide stacktrace for scenario with workaround.
    Also you could enable OpenCL calls trace here.


    Main difference between .getUMat() and copyTo() is a "map" semantic.
    Releasing of .getUMat() result would try sync back data (even with ACCESS_READ - this parameter is ignored and RW access is forced).


    You could try to play with this code:

    Details
    #define TEST_CASE 2
    #if TEST_CASE == 0
        size_t size = alignSize(640*480*3, 4096);
        // #include <sys/mman.h>
        void* data = mmap(NULL, size, (PROT_READ | PROT_WRITE), MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
        cv::Mat mat(Size(640, 480), CV_8UC3, data);
    #elif TEST_CASE == 1  // memory is garbaged, but still accessinble (use-after-free violation)
        std::vector<uchar> data(640*480*3, 0);
        cv::Mat mat(Size(640, 480), CV_8UC3, (void*)data.data());
    #else
        cv::Mat mat(Size(640, 480), CV_8UC3, Scalar::all(0));
    #endif
        std::cout << "mapping..." << std::endl;
        cv::UMat umat = mat.getUMat(ACCESS_READ);
        std::cout << "releasing Mat..." << std::endl;
        mat.release();  // wrong order
    #if TEST_CASE == 0
        munmap(data, size);
    #elif TEST_CASE == 1
        data.clear();
    #endif
        std::cout << "releasing UMat..." << std::endl;
        umat.release();
    
    mapping...
    OpenCV(OpenCL:0): clCreateBuffer(CL_MEM_COPY_HOST_PTR|CL_MEM_READ_WRITE|createFlags, sz=921600, origdata=0x7fe4099a7040) => 0x28e2a70
    OpenCV(OpenCL:0): clCreateBuffer() => 0x28e2a70
    releasing Mat...
    releasing UMat...
    OpenCV(OpenCL:0): clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, 0, u->size, alignedPtr.getAlignedPtr(), 0, 0, 0)
    OpenCV(OpenCL:0): clReleaseMemObject(ptr=0x28e2a70)
    
    ! OPENCV warning: getUMat()/getMat() call chain possible problem.
    !                 Base object is dead, while nested/derived object is still alive or processed.
    !                 Please check lifetime of UMat/Mat objects!
    
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