Skip to content

[BUG] BndBox flickers #257

@FFace32

Description

@FFace32

Describe the bug

When using cvcuda.bndbox/cvcuda.bndbox_into in Python multiple times, it flickers.

Example correct (expected) output:

Image

Example flicker (notice how out of the 3 rectangles, only 2 are being properly drawn):

Image

Example flicker (notice how out of the 3 rectangles, only 1 is being properly drawn):

Image

2 more examples of flickering (notice how out of the 3 rectangles, only 1 is being properly drawn; 1 is missing completely & another only has "a few pixels going down"):

Image

Image

In my real project I've also encountered issues where 2 of the 4 sides of a rectangle would be gray instead of the specified color.

I've ran the following code on two machines.

Machine1 is using a NVIDIA GeForce RTX 3060 Laptop GPU bare-metal and on Machine2 I've tested both the Tesla T4 and the NVIDIA A2 inside Docker (a devcontainer).

I've tried using the _into variants of all the methods used in this example code, the behavior is the same. I've also used the default cuda stream (i.e. not passing stream to any of the cvcuda methods and not calling retain_primary_context or anything), the behavior is the same.

If I were to replace the multiple calls to cvcuda.bndbox with a single one, with multiple cvcuda.BndBoxI, the issue wouldn't reproduce, but in my real project, without major refactoring, I have to do it this way.

In my real project I'm using other operations as well (e.g. resize, composite, customcrop, copymakeborder, stack, convert) and they seem to worsen the issue somehow. If I also do inference using the tritonclient with CUDA shared memory (I copy the memory from a cvcuda tensor using tritonclient.utils.cuda_shared_memory.set_shared_memory_region_from_dlpack) I get even worse results, sometimes even black regions of the frames. In my real project I also encode the tensors using PyNvVideoCodec, but I don't think that's a problem, because if I dump the tensors to disk before encoding them (see tensor_to_png inside the code) they also look "corrupted".

EDIT: Ignore what I said about triton, it was an issue on my side.

Steps/Code to reproduce bug

from PIL import Image
import cupy as cp
import cv2
import cvcuda
import numpy as np
import pycuda.driver as cuda
import PyNvVideoCodec as nvc

counter = 0


def tensor_to_png(tensor) -> None:
    global counter

    gpu_mat = cv2.cuda.createGpuMatFromCudaMemory(
        tensor.shape[1],
        tensor.shape[2],
        cv2.CV_8UC3,
        tensor.cuda().__cuda_array_interface__["data"][0],
    )
    rgb_mat = gpu_mat.download()
    bgr_mat = cv2.cvtColor(rgb_mat, cv2.COLOR_RGB2BGR)

    cv2.imwrite(f"frames/{counter}.png", bgr_mat)

    counter += 1

# Use this method if you don't have OpenCV built with CUDA support
def tensor_to_png_cupy(tensor) -> None:
    global counter

    cupy_tensor = cp.asarray(tensor.cuda())
    if cupy_tensor.ndim == 4:
        cupy_tensor = cp.squeeze(cupy_tensor, axis=0)

    np_tensor = cp.asnumpy(cupy_tensor)

    if np_tensor.shape[0] == 3:
        np_tensor = np.transpose(np_tensor, (1, 2, 0))

    img = Image.fromarray(np_tensor.astype(np.uint8), mode="RGB")
    img.save(f"frames/{counter}.png")

    counter += 1

def cvcuda_rectangle(
    img,
    bbox,
    color,
    thickness,
    *,
    stream=None,
) -> None:
    fill_alpha = 0
    if thickness == -1:
        fill_alpha = 255

    return cvcuda.bndbox(
        img,
        cvcuda.BndBoxesI(
            [
                [
                    cvcuda.BndBoxI(
                        bbox,
                        thickness,
                        # RGBA
                        (*color, 255),
                        (*color, fill_alpha),
                    )
                ]
            ]
        ),
        stream=stream,
    )


# On Machine2, I use a different GPU by setting CUDA_VISIBLE_DEVICES
device_id = 0
cuda_device = cuda.Device(device_id)
cuda_ctx = cuda_device.retain_primary_context()
cuda_ctx.push()
cuda_stream = cvcuda.Stream()

# I've also tried it without any of the above lines, the behavior is the same

# You can get the same exact video from https://file-examples.com/index.php/sample-video-files/sample-mp4-files/
demuxer = nvc.CreateDemuxer(filename="file_example_MP4_1920_18MG.mp4")
decoder = nvc.CreateDecoder(
    codec=demuxer.GetNvCodecId(),
    usedevicememory=True,
    cudacontext=cuda_ctx.handle,
    cudastream=cuda_stream.handle,
)

color_conversion = (
    cvcuda.ColorConversion.YUV2RGB
    if decoder.GetPixelFormat() == nvc.Pixel_Format.YUV444
    else cvcuda.ColorConversion.YUV2RGB_NV12
)

for packet in demuxer:
    for frame in decoder.Decode(packet):
        tensor = cvcuda.as_tensor(cvcuda.as_image(frame.nvcv_image()))
        nhwc_tensor = cvcuda.reformat(
            tensor, cvcuda.TensorLayout.NHWC, stream=cuda_stream
        )
        rgb_tensor = cvcuda.cvtcolor(nhwc_tensor, color_conversion, stream=cuda_stream)

        # Any coords should do
        for rect in [
            (436, 242, 289, 558),
            (486, 292, 289, 558),
            (616, 907, 423, 172),
        ]:
            rgb_tensor = cvcuda_rectangle(
                rgb_tensor, rect, (0, 255, 0), 3, stream=cuda_stream
            )

        # Or use tensor_to_png_cupy
        tensor_to_png(rgb_tensor)

Expected behavior

The user should be able to call BndBox multiple times on the same tensor, and all calls should result in tensors with complete rectangles.

Environment overview

  • Environment location: Bare-metal on Machine1, Docker (devcontainer) on Machine2
  • Method of cuDF install: not using cuDF; cvcuda was installed with pip

Environment details

Click here to see the environment details of Machine1
     ***OS Information***
     DISTRIB_DESCRIPTION="Ubuntu 20.04.6 LTS"
     Linux 5.15.0-139-generic #149~20.04.1-Ubuntu SMP Wed Apr 16 08:29:56 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
 ***GPU Information***
 Sun Jun 29 21:06:31 2025
 +---------------------------------------------------------------------------------------+
 | NVIDIA-SMI 535.183.01             Driver Version: 535.183.01   CUDA Version: 12.2     |
 |-----------------------------------------+----------------------+----------------------+
 | GPU  Name                 Persistence-M | Bus-Id        Disp.A | Volatile Uncorr. ECC |
 | Fan  Temp   Perf          Pwr:Usage/Cap |         Memory-Usage | GPU-Util  Compute M. |
 |                                         |                      |               MIG M. |
 |=========================================+======================+======================|
 |   0  NVIDIA GeForce RTX 3060 ...    Off | 00000000:01:00.0  On |                  N/A |
 | N/A   55C    P8              16W /  60W |     83MiB /  6144MiB |     35%      Default |
 |                                         |                      |                  N/A |
 +-----------------------------------------+----------------------+----------------------+
 
 +---------------------------------------------------------------------------------------+
 | Processes:                                                                            |
 |  GPU   GI   CI        PID   Type   Process name                            GPU Memory |
 |        ID   ID                                                             Usage      |
 |=======================================================================================|
 |    0   N/A  N/A      1968      G   /usr/lib/xorg/Xorg                           24MiB |
 |    0   N/A  N/A      3720      G   /usr/lib/xorg/Xorg                           53MiB |
 +---------------------------------------------------------------------------------------+
 
 ***CPU***
 Architecture:                         x86_64
 CPU op-mode(s):                       32-bit, 64-bit
 Byte Order:                           Little Endian
 Address sizes:                        48 bits physical, 48 bits virtual
 CPU(s):                               16
 On-line CPU(s) list:                  0-15
 Thread(s) per core:                   2
 Core(s) per socket:                   8
 Socket(s):                            1
 NUMA node(s):                         1
 Vendor ID:                            AuthenticAMD
 CPU family:                           25
 Model:                                80
 Model name:                           AMD Ryzen 9 5900HS with Radeon Graphics
 Stepping:                             0
 Frequency boost:                      enabled
 CPU MHz:                              1300.000
 CPU max MHz:                          3300,0000
 CPU min MHz:                          1200,0000
 BogoMIPS:                             6588.09
 Virtualization:                       AMD-V
 L1d cache:                            256 KiB
 L1i cache:                            256 KiB
 L2 cache:                             4 MiB
 L3 cache:                             16 MiB
 NUMA node0 CPU(s):                    0-15
 Vulnerability Gather data sampling:   Not affected
 Vulnerability Itlb multihit:          Not affected
 Vulnerability L1tf:                   Not affected
 Vulnerability Mds:                    Not affected
 Vulnerability Meltdown:               Not affected
 Vulnerability Mmio stale data:        Not affected
 Vulnerability Reg file data sampling: Not affected
 Vulnerability Retbleed:               Not affected
 Vulnerability Spec rstack overflow:   Mitigation; safe RET, no microcode
 Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl and seccomp
 Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
 Vulnerability Spectre v2:             Mitigation; Retpolines; IBPB conditional; IBRS_FW; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
 Vulnerability Srbds:                  Not affected
 Vulnerability Tsx async abort:        Not affected
 Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm
 
 ***CMake***
 /usr/bin/cmake
 cmake version 3.31.2

 ***g++***
 /usr/bin/g++
 g++ (Ubuntu 13.1.0-8ubuntu1~20.04.2) 13.1.0

 ***nvcc***
 /usr/local/cuda-12.9/bin/nvcc
 nvcc: NVIDIA (R) Cuda compiler driver
 Copyright (c) 2005-2025 NVIDIA Corporation
 Built on Wed_Apr__9_19:24:57_PDT_2025
 Cuda compilation tools, release 12.9, V12.9.41
 Build cuda_12.9.r12.9/compiler.35813241_0
 
 ***Python***
 Python 3.11.12

Click here to see the environment details of Machine2
     DISTRIB_DESCRIPTION="Ubuntu 22.04.5 LTS"
     Linux 5da4e91c4f64 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
 ***GPU Information***
 Sun Jun 29 18:15:45 2025
 +---------------------------------------------------------------------------------------+
 | NVIDIA-SMI 535.230.02             Driver Version: 535.230.02   CUDA Version: 12.2     |
 |-----------------------------------------+----------------------+----------------------+
 | GPU  Name                 Persistence-M | Bus-Id        Disp.A | Volatile Uncorr. ECC |
 | Fan  Temp   Perf          Pwr:Usage/Cap |         Memory-Usage | GPU-Util  Compute M. |
 |                                         |                      |               MIG M. |
 |=========================================+======================+======================|
 |   0  Tesla T4                       Off | 00000000:5E:00.0 Off |                    0 |
 | N/A   57C    P0              30W /  70W |    624MiB / 15360MiB |      0%      Default |
 |                                         |                      |                  N/A |
 +-----------------------------------------+----------------------+----------------------+
 |   1  NVIDIA A2                      Off | 00000000:AF:00.0 Off |                    0 |
 |  0%   59C    P0              27W /  60W |   6640MiB / 15356MiB |      0%      Default |
 |                                         |                      |                  N/A |
 +-----------------------------------------+----------------------+----------------------+
 
 +---------------------------------------------------------------------------------------+
 | Processes:                                                                            |
 |  GPU   GI   CI        PID   Type   Process name                            GPU Memory |
 |        ID   ID                                                             Usage      |
 |=======================================================================================|
 +---------------------------------------------------------------------------------------+
 
 ***CPU***
 Architecture:                       x86_64
 CPU op-mode(s):                     32-bit, 64-bit
 Address sizes:                      46 bits physical, 48 bits virtual
 Byte Order:                         Little Endian
 CPU(s):                             112
 On-line CPU(s) list:                0-111
 Vendor ID:                          GenuineIntel
 Model name:                         Intel(R) Xeon(R) Gold 6238R CPU @ 2.20GHz
 CPU family:                         6
 Model:                              85
 Thread(s) per core:                 2
 Core(s) per socket:                 28
 Socket(s):                          2
 Stepping:                           7
 BogoMIPS:                           4400.00
 Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
 Virtualization:                     VT-x
 L1d cache:                          1.8 MiB (56 instances)
 L1i cache:                          1.8 MiB (56 instances)
 L2 cache:                           56 MiB (56 instances)
 L3 cache:                           77 MiB (2 instances)
 NUMA node(s):                       2
 NUMA node0 CPU(s):                  0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110
 NUMA node1 CPU(s):                  1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111
 Vulnerability Gather data sampling: Mitigation; Microcode
 Vulnerability Itlb multihit:        KVM: Mitigation: Split huge pages
 Vulnerability L1tf:                 Not affected
 Vulnerability Mds:                  Not affected
 Vulnerability Meltdown:             Not affected
 Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
 Vulnerability Retbleed:             Mitigation; Enhanced IBRS
 Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl and seccomp
 Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
 Vulnerability Spectre v2:           Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
 Vulnerability Srbds:                Not affected
 Vulnerability Tsx async abort:      Mitigation; TSX disabled
 
 ***CMake***
 
 ***g++***
 /usr/bin/g++
 g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
 
 
 ***nvcc***
 /usr/local/cuda/bin/nvcc
 nvcc: NVIDIA (R) Cuda compiler driver
 Copyright (c) 2005-2023 NVIDIA Corporation
 Built on Tue_Aug_15_22:02:13_PDT_2023
 Cuda compilation tools, release 12.2, V12.2.140
 Build cuda_12.2.r12.2/compiler.33191640_0
 
 ***Python***
 Python 3.11.13

Metadata

Metadata

Labels

bugSomething isn't working as expected (software, install, documentation)need more infoWaiting for more information from user

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions