pytorch / vision

Datasets, Transforms and Models specific to Computer Vision
https://pytorch.org/vision
BSD 3-Clause "New" or "Revised" License
16.13k stars 6.94k forks source link

GPU decoder with 'cuda' backend not working as expected (shape / color / seek) #7745

Open elmuz opened 1 year ago

elmuz commented 1 year ago

πŸ› Describe the bug

I want to exploit the CUDA backend for the new VideoReader object. However, I believe it doesn't work as expected. In particular, I noticed the following:

You can try to reproduce these results using the following script:

def test_VideoReader():
    video_path = "tests/files/lagarde.mp4"
    torchvision.set_video_backend("cuda")
    video = torchvision.io.VideoReader(video_path, "video")
    length = video.get_metadata()["video"]["duration"]

    # These are 100 random indices (in seconds) to test speed of decoders.
    indices = [random.random() * length for _ in range(100)]

    cuda_frames = []
    t_0 = time.perf_counter()
    video = torchvision.io.VideoReader(video_path, "video")
    for i, idx in enumerate(indices):
        # For each random frame try to read 5 consecutive frames
        for j, frame in enumerate(itertools.islice(video.seek(idx), 5)):
            if i == 99:
                print(frame["data"].shape, frame["data"].device, frame["data"].dtype)
                cuda_frames.append(frame["data"])
                torchvision.io.write_png(
                    frame["data"].cpu().permute(2, 0, 1),
                    f"tests/frames/cuda-{j}.png",
                )
    t_1 = time.perf_counter()
    print(f"CUDA backend: {t_1 - t_0:.2f} sec.")

    torchvision.set_video_backend("video_reader")
    cpu_frames = []
    t_0 = time.perf_counter()
    video = torchvision.io.VideoReader(video_path, "video")
    for i, idx in enumerate(indices):
        # For each random frame try to read 5 consecutive frames
        for j, frame in enumerate(itertools.islice(video.seek(idx), 5)):
            if i == 99:
                print(frame["data"].shape, frame["data"].device, frame["data"].dtype)
                cpu_frames.append(frame["data"])
                torchvision.io.write_png(frame["data"], f"tests/frames/cpu-{j}.png")
    t_1 = time.perf_counter()
    print(f"video_reader backend: {t_1 - t_0:.2f} sec.")

    for frame_cuda, frame_cpu in zip(cuda_frames, cpu_frames):
        print(f"All close: {torch.allclose(frame_cuda.cpu().permute(2, 0, 1), frame_cpu)}")

As a side note I can comment that torchaudio.io.StreamReader using the cuvid decoder as per this tutorial.

Versions

Collecting environment information...
PyTorch version: 2.0.0a0+gite9ebda2
Is debug build: False
CUDA used to build PyTorch: 11.5
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.26.4
Libc version: glibc-2.31

Python version: 3.8.17 (default, Jul 12 2023, 13:27:24)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.4.0-149-generic-x86_64-with-glibc2.29
Is CUDA available: True
CUDA runtime version: 11.5.119
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 2080 Ti
Nvidia driver version: 495.29.05
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.3.3
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.3.3
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.3.3
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.3.3
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.3.3
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.3.3
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.3.3
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 48 bits virtual
CPU(s):                          80
On-line CPU(s) list:             0-79
Thread(s) per core:              2
Core(s) per socket:              20
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) Gold 6248 CPU @ 2.50GHz
Stepping:                        7
CPU MHz:                         1000.101
CPU max MHz:                     3900.0000
CPU min MHz:                     1000.0000
BogoMIPS:                        5000.00
Virtualization:                  VT-x
L1d cache:                       1.3 MiB
L1i cache:                       1.3 MiB
L2 cache:                        40 MiB
L3 cache:                        55 MiB
NUMA node0 CPU(s):               0-19,40-59
NUMA node1 CPU(s):               20-39,60-79
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 IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Mitigation; TSX disabled
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

Versions of relevant libraries:
[pip3] numpy==1.24.4
[pip3] pytorch-lightning==2.0.5
[pip3] torch==2.0.0a0+gite9ebda2
[pip3] torch-fidelity==0.3.0
[pip3] torchaudio==2.0.2+31de77d
[pip3] torchmetrics==1.0.0
[pip3] torchvision==0.15.2a0+fa99a53
[pip3] triton==2.0.0.post1
[conda] Could not collect
elmuz commented 1 year ago

These are the specifics of the video retrieved by FFprobe

ffprobe version 5.1.3 Copyright (c) 2007-2022 the FFmpeg developers
  built with gcc 9 (Ubuntu 9.4.0-1ubuntu1~20.04.1)
  configuration: --prefix=/usr/local/ --extra-cflags=-I/usr/local/cuda/include --extra-ldflags=-L/usr/local/cuda/lib64 --nvccflags='-gencode arch=compute_75,code=sm_75 -O2' --disable-doc --disable-static --enable-gnutls --enable-shared --enable-gpl --enable-nonfree --enable-libfdk-aac --enable-libmp3lame --enable-libopus --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-cuda-nvcc --enable-nvenc --enable-cuvid --enable-libnpp --enable-nvdec
  libavutil      57. 28.100 / 57. 28.100
  libavcodec     59. 37.100 / 59. 37.100
  libavformat    59. 27.100 / 59. 27.100
  libavdevice    59.  7.100 / 59.  7.100
  libavfilter     8. 44.100 /  8. 44.100
  libswscale      6.  7.100 /  6.  7.100
  libswresample   4.  7.100 /  4.  7.100
  libpostproc    56.  6.100 / 56.  6.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'tests/files/lagarde.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf59.27.100
  Duration: 00:13:36.00, start: 0.000000, bitrate: 883 kb/s
  Stream #0:0[0x1](und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709, progressive), 480x480 [SAR 1:1 DAR 1:1], 750 kb/s, 25 fps, 25 tbr, 12800 tbn (default)
    Metadata:
      handler_name    : VideoHandler
      vendor_id       : [0][0][0][0]
      encoder         : Lavc59.37.100 libx264
  Stream #0:1[0x2](eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 127 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
      vendor_id       : [0][0][0][0]
elmuz commented 1 year ago

Another inconsistency:

NicolasHug commented 1 year ago

Hi @elmuz , Thanks for the reports. To be completely transparent, the video decoder (and in particular the GPU video decoder) are still in Beta stage, and we acknowledge that there are a bunch of bugs and edge cases that aren't completely covered yet. We're still trying to figure out the level of support we can provide for these, and hopefully we'll be able to provide a suitable alternative soon.

elmuz commented 1 year ago

Hey, thanks. I understand video decoding is a hard topic, especially since there's a lack of reference/de-facto way of doing things like it is on the audio counter-part. However, on this topic I see many points of contact between torchvision, torchaudio or even Nvidia DALI. Unfortunately, at the moment unpacking a video catalog into frames is still the smoothest option (as long as you have enough memory to hold). Otherwise, it's a pain...