Skip to content

[BUG] as_image leaks memory #258

@FFace32

Description

@FFace32

Describe the bug
as_image leaks memory.

Steps/Code to reproduce bug

import cvcuda
import gc
import PyNvVideoCodec as nvc
import tracemalloc

tracemalloc.start()


# You can get the same exact video from https://file-examples.com/index.php/sample-video-files/sample-mp4-files/
# But the video doesn't matter
demuxer = nvc.CreateDemuxer(filename="file_example_MP4_1920_18MG.mp4")
decoder = nvc.CreateDecoder(codec=demuxer.GetNvCodecId(), usedevicememory=True)

as_image_line = f"{__file__}:26:"

for packet in demuxer:
    for frame in decoder.Decode(packet):
        image = frame.nvcv_image()

        i = 0
        while True:
            i += 1
            snapshot1 = tracemalloc.take_snapshot()

            # Don't modify anything above this line as the check below is done based on the line number
            cvcuda_image = cvcuda.as_image(image)

            if i % 100 == 0:
                # Calling `gc.collect()` here will worsen the results!
                # gc.collect()

                snapshot2 = tracemalloc.take_snapshot()
                stats = snapshot2.compare_to(snapshot1, "lineno")
                for stat in stats:
                    stat_str = str(stat)
                    if not stat_str.startswith(as_image_line):
                        continue

                    print(stat_str)

This will print how much memory the line cvcuda_image = cvcuda.as_image(image) has allocated.

At first it will increase rapidly, then it will still increase, but very slowly.

Calling gc.collect seemingly makes it worse.

This code shouldn't touch the cache, since it's a wrapped object, but calling cvcuda.clear_cache(cvcuda.ThreadScope.GLOBAL) seemingly makes it better, but the memory usage still increases.

In my real project, I have a long running service and this ends up using too much memory.

I've ran the 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).

Expected behavior
as_image shouldn't leak memory OR calling cvcuda.clear_cache(cvcuda.ThreadScope.GLOBAL)/something_else() should free it.

Environment overview (please complete the following information)

  • 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

? - needs triagebugSomething isn't working as expected (software, install, documentation)

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions