GPU Video Decoding: ``CudaDecoders`` and ``RocmDecoders`` ========================================================= SPDL decodes video on the hardware video decoders of NVIDIA GPUs (NVDEC) and AMD GPUs (VCN), and keeps the frames on the GPU. The two backends expose the same model: a long-lived object per GPU, ``spdl.io.cuda_decoders(...)`` and ``spdl.io.rocm_decoders(...)``, that accepts the packets of many clips and decodes them as fast as the hardware allows. This note explains how the decoders use the hardware, why they are designed this way, and where the two vendors differ. Most of it is common to both vendors, so it is written in terms of an abstract GPU first. The workload we optimize for ---------------------------- GPU video decoders are built for low-latency playback of one long stream: create a decoder for the stream, decode it frame by frame, destroy the decoder. Training data looks different: - Many short clips (a few to tens of seconds), each demuxed and decoded independently. - Mixed codecs (H.264, HEVC 8/10-bit, VP9, AV1) and many resolutions in both orientations. A Kinetics-400 copy, for example, has 251 distinct sizes. - Throughput matters, latency does not. What counts is clips (or frames) per second per GPU, sustained over an epoch. - The frames are consumed on the same GPU by the model, so they should never travel to host memory. - The training loop owns the Python interpreter. Decoding must not compete with it for the GIL. So the priorities, in order: 1. **Keep every decode engine busy.** The decode engines are a fixed, small resource on each GPU. Throughput is the number of engines times how much of the time each one is decoding. 2. **Remove per-clip setup.** With short clips, creating and destroying decoder state costs as much as decoding. It must be amortized across clips of different sizes and codecs. 3. **Stay off the Python thread.** Bitstream parsing, waiting for the hardware and completion all happen on native threads that never take the GIL. 4. **Bounded GPU memory.** Decoder state is cached, but under a configurable budget. 5. **Easy distribution.** One ``spdl-io`` wheel per platform. The vendor libraries come at run time from the driver, the CUDA/ROCm installation or PyTorch, and are never redistributed. How a hardware video decoder works ---------------------------------- A GPU has a few fixed-function **decode engines**, separate from the compute units that run kernels. They are shared by every process on the GPU. Decoding one clip involves four parties: .. image:: ../_static/data/gpu_decoding_hardware.png :width: 1046px :alt: Packets of one clip go to the parser on the CPU, which queues the pictures on the GPU's decode engine; the engine decodes them one at a time. The engine reads reference pictures from the decoder session's decode surfaces and writes the decoded picture there; an asynchronous copy or color conversion moves each picture, in display order, into the clip's output buffer. - **Parser** (CPU): reads the bitstream, tracks reference frames and reordering, and produces the parameters of each picture: slice data, reference list, quantization matrices. - **Decoder session** (the vendor object that holds decoder state): owns a set of **decode surfaces**, the reference and output picture memory, sized for a maximum resolution and bit depth. The engine writes decoded pictures into them. - **Decode engine**: decodes the pictures queued by a session one at a time, asynchronously. The parser queues pictures without waiting for each to finish, so the engine always has the next one. - **Hand-off**: when a picture is ready for display (in presentation order), it is copied (or color-converted) from the decode surface into the clip's output buffer. This is an asynchronous copy on a stream. The surface is reused once the copy finishes. Three costs dominate bulk decoding: .. list-table:: :header-rows: 1 * - Cost - When - Why it matters * - Creating a session (allocating its surfaces) - each new size/format, naively each clip - tens of ms on some drivers * - Destroying a session - when it is no longer needed - up to hundreds of ms, and can stall other work * - Waiting on the host for each frame - if the hand-off is synchronous - caps throughput far below the engine's What we measured before designing --------------------------------- Before designing either backend, we timed each step of the vendors' decoder APIs in isolation, on one GPU of each vendor, and measured how these steps interfere with decoding on other threads. The design follows from a few of these numbers. .. note:: **Compare within a vendor.** The GPUs differ in vendor, generation and number of decode engines (7 on the NVIDIA GPUs measured, 4 on the AMD GPU), each was measured on one host, and the AMD path (VA-API through Mesa) is new and untuned. The columns of the table are the steps each design actually performs, not equivalent API calls. Per-step costs, in ms, median (p90 where it differs much), with nothing else running on the GPU. NVIDIA rows are for H.264, HEVC 8/10-bit and VP9 with 20 decode and 2 output surfaces (as :py:class:`~spdl.io.CudaDecoders` creates them), at size buckets from 720p to 2160p; AMD rows are for :py:class:`~spdl.io.RocmDecoders`' own VA-API path. .. list-table:: :header-rows: 1 :widths: 30 20 20 30 * - Step - NVIDIA H100 - NVIDIA GB300 - AMD MI300X * - Parser create - 0.02–0.06 - 0.01–0.02 - 0.002 (H.264), 0.06 (HEVC) * - Create decoder state - **42–58** (VP9 58–64) - **34–41** - surface set (once per lane and bucket): 0.4–1.0; VA context (per clip): 0.03–0.06, plus 0.3–1.4 at its first picture * - Switch to another size - reconfigure: 0.33 (p90 0.7) - reconfigure: 0.01 (p90 0.09) - new VA context, as above * - Destroy, other decoders alive - 22–27 - 29–36 - VA context: 0.001; surface set: 1.7–2.4 (up to 6–14 at 2160p 10-bit) * - Destroy the last decoder of the process (immediately after creating it; see the follow-up below) - **216–235** - **246–249** - (no equivalent) * - Frame map (after decoding) / unmap - 0.046 / ≈0 - 0.046 / ≈0 - ``vaSyncSurface``: ≈0 (display delay 2) * - NV12 copy, 1080p frame - 0.013 - 0.013 - 0.011 * - *Reference only: decode, 1080p H.264, one stream (content dependent)* - *about 2 per frame* - *about 1 per frame* - *1.16 per frame* What these numbers taught us: 1. **Destroying a decoder costs more than creating one, on NVIDIA.** Destroying the last decoder of the process takes up to 0.25 s, up to seven times a create (the follow-up below explains why). With another decoder alive in the process it takes 22–36 ms. So :py:class:`~spdl.io.CudaDecoders` keeps at least one decoder alive until shutdown, and destroys evicted decoders on a background thread. A per-thread cache like :py:class:`~spdl.io.NvDecDecoder`'s pays both costs on the decoding threads. 2. **Creating and destroying a decoder stalls every other session on the GPU.** With 4 or 14 lanes decoding while another thread created and destroyed decoders, every lane stopped outputting frames for the whole duration of each create (the lanes' frame rate fell to 0–30% of normal) and slowed during each destroy (25–65%), on both NVIDIA GPUs. A workload that creates a decoder per clip is therefore capped by these calls, not by the engines: about 11 clips/s on the H100 and 14 on the GB300, with 7 or 14 lanes alike. Destroying in the background removed the destroying lane's own wait (70–115 ms per clip) but not the stall on the others, so total throughput did not improve (9.4 to 10.6 clips/s with 7 lanes, unchanged with 14). The fix is to avoid creating and destroying decoders at all: hence the shared pool and reconfiguration below. The background thread only keeps the unavoidable evictions off the lane that triggers them. 3. **Changing size is nearly free within a decoder's maximum size, on NVIDIA.** ``cuvidReconfigureDecoder`` takes 0.01–0.7 ms. So decoders are created at size buckets and leased by any clip they cover; a lease reconfigures the decoder. 4. **Decoder memory grows with the maximum size and the number of surfaces.** An NVIDIA decoder with a 1080p maximum holds 45–145 MB, one at the codec's hardware maximum up to 4 GB (HEVC). An AMD surface set holds 10–224 MB (448 MB at 2160p 10-bit). So sizes are bucketed rather than set to the hardware maximum, and idle decoder state is kept under ``max_memory_bytes``. 5. **The hand-off is cheap next to decoding.** Mapping and copying a 1080p frame takes about 0.06 ms on NVIDIA and 0.01 ms on AMD, against 1–2 ms to decode it. The engines set the pace; the copy strategy does not matter for throughput, so frames are copied asynchronously and released when an event says the copy finished, which keeps the host out of the way. 6. **On AMD, an engine is bound per VA display.** The kernel pins each display to one engine at its first submission: four decoders on one display decoded at 212–226 frames/s each, against 826 each with a display of their own. So :py:class:`~spdl.io.RocmDecoders` has one display per lane and one lane per engine; four lanes scale linearly (about 3,450 frames/s at 1080p H.264). 7. **On AMD, rocDecode's decoder lifecycle is the expensive part, and it gets ten times worse under load.** Its destroy after use and every reconfigure take 4–7 ms with the GPU idle and 40–50 ms while other decoders run, because a reconfigure frees and re-imports every surface. VA contexts, in contrast, are nearly free, and surfaces cost memory, not time. So :py:class:`~spdl.io.RocmDecoders` drives VA-API directly with cached surface sets and a new context per clip, and uses only rocDecode's parser. 8. **On AMD, releasing decoder state does not disturb other lanes.** Releasing a surface set and a context costs the releasing thread about 3 ms (p90 3.8), and the other lanes' throughput and frame intervals stayed within run-to-run noise. The background release only saves the evicting lane about 3 ms, much less than on NVIDIA; it is kept because it costs nothing. Follow-up: why destroying the last decoder is slow, on NVIDIA ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After the first implementation, a follow-up probe looked into the last-decoder cost on both NVIDIA GPUs (the two behave the same): .. list-table:: :header-rows: 1 * - Another decoder alive in... - Destroy, H100 (ms) - Destroy, GB300 (ms) * - nothing - 232 - 248 * - the same context (same or another ``vidLock``) - 22–24 - 28–31 * - another context of the same process - 21–24 - 28–31 * - another process, on the same GPU - 232 - 248 - **The cost is per process.** Any decoder alive in the same process keeps destroys cheap, whatever its context; a decoder in another process does not. - **It is a wait, not work.** The first decoder of a process starts 8 driver threads, and destroying the last one stops them. During that destroy the calling thread sleeps on a futex for about 90% of the call, and its CPU time is the same as an ordinary destroy (23 ms on the H100, 30 ms on the GB300). No other thread runs meanwhile. - **The wait follows a 250 ms timer.** Destroying the last decoder at increasing delays after creating it gives a saw-tooth with a 250 ms period: the driver threads notice that they should exit only at their next 250 ms tick, counted from their start. So the last destroy costs an ordinary destroy plus 0–250 ms, depending on when it happens; the table above measures the worst case, right after creation. .. image:: ../_static/data/gpu_decoding_last_destroy.png :width: 840px :alt: Destroy time of the last decoder against the time between creating and destroying it, on the H100 and GB300. Both fall linearly from about 230 to 250 ms down to the cost of an ordinary destroy, then jump back up, every 250 ms. - **Creating and destroying stall other sessions only in the same process.** A decoder decoding in another process kept its frame rate and frame intervals during every create and destroy here, the last destroy included. Within one process, both calls stall every other session (insight 2 above). The stall therefore comes from a lock in the driver that is per process, not from the engines. What this means for the design: - Keeping one decoder alive works per process: any decoder of the process (another :py:class:`~spdl.io.CudaDecoders`, or an :py:class:`~spdl.io.NvDecDecoder` cache) keeps destroys cheap. In practice the last-decoder cost is paid once, when the process's last decoder goes. - Background teardown hides that cost completely: it is a sleep, which costs no CPU or GPU time. Only ``shutdown(wait=True)`` waits for it. - Creating decoders for the expected codecs and size buckets before decoding starts would keep those creates, which stall every lane of the process, out of the cold start (see possible future work). - Not measured yet: whether the driver threads are per process or per GPU when one process drives several GPUs. Design ------ One object per GPU, used like an executor ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code-block:: python with spdl.io.cuda_decoders(spdl.io.cuda_config(device_index=0)) as decoders: # or rocm_decoders / rocm_config buffer = decoders.decode(packets) # blocks in C++ with the GIL released future = decoders.decode_future(packets) # returns a future immediately buffer = future.result() # waits with the GIL released buffer = await decoders.decode_async(packets) # completed on the running event loop frames = torch.from_dlpack(buffer) # stream-ordered, no host sync There are three ways to decode one clip: block until it is done (:py:meth:`~spdl.io.CudaDecoders.decode`), get a future (:py:meth:`~spdl.io.CudaDecoders.decode_future`), or await it on an event loop (:py:meth:`~spdl.io.CudaDecoders.decode_async`). A later API for long media, which returns frames chunk by chunk, is meant to follow the same naming with a ``streaming_`` prefix (``streaming_decode``, ``streaming_decode_async``). The object hides all hardware resources (worker threads, sessions, surfaces) and decodes submitted clips as fast as the device allows, like an executor with smart decoder selection. The docs give a guideline for the threads and memory it uses. The decoding methods belong to this long-lived object rather than a free function, so creating and discarding decoders per clip is not the easy path. Construction is cheap. The device side is initialized at ``__enter__``, or at the first decode call if the object is not used as a context manager. Lanes ~~~~~ Inside, worker threads called **lanes** take clips from a shared FIFO queue and decode one clip at a time each. A lane runs the parser, submits pictures to its session, waits for the hardware, and issues the asynchronous copies. With several lanes, a single Python thread that keeps a few clips in flight drives every engine. The SPDL pipeline stage only needs enough concurrency to keep the queue non-empty. .. image:: ../_static/data/gpu_decoding_lanes.png :width: 1122px :alt: decode, decode_future and decode_async, from any number of threads or event loops, submit clips to a FIFO clip queue in the CudaDecoders or RocmDecoders object. A fixed pool of lanes takes clips from the queue, leases decoder state from a pool kept per size bucket and returns it; evicted state goes to a destroyer thread. The lanes send pictures to the GPU's decode engines, which are shared with other processes, and copy the frames into one output buffer per clip on the GPU. The lanes form a fixed thread pool: the number of lanes, not the number of threads that call the decoding methods, sets how many clips are decoded at once. Lanes lease decoder state for each clip and return it afterwards; state that is evicted is destroyed on a separate thread, so no lane waits for it. The decode engines are hardware, shared with other processes. The default number of lanes comes from a capacity query of the device's decode engines. ``num_lanes`` overrides it, for example to oversubscribe or to leave engines to another process. How lanes map onto engines differs between vendors (see below). Reusing decoder state across sizes and codecs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Every clip needs a session for its codec, chroma format and bit depth, at least as large as its coded size. Instead of creating one per clip, sessions or surface sets are created at **size buckets** and reused: - A new session gets the smallest-area bucket that covers the clip, both orientations included: 720p, 1080p (1088 rows) and 2160p by default, plus 480p on AMD. A clip larger than every bucket gets its exact (16-aligned) size. - A later clip reuses the smallest idle compatible session that is large enough. Decoding a smaller stream on larger surfaces is bit-exact; it costs memory, not speed. - Sizing every session at the hardware maximum instead would cost gigabytes per session (for example 8192×4352 for HEVC), and is not needed. - Idle state is cached in a least-recently-used list under ``max_memory_bytes``. Evicted state is destroyed on a background thread, so slow destroys never stall decoding. How a session switches from one clip's size to the next is vendor-specific, and is the main reason the two backends use different APIs. Hand-off without host synchronization ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - The output of each clip is one buffer, allocated when the decode call is made, on the calling thread, by the user's allocator (for example PyTorch's caching allocator). Lanes never call into Python. - Each displayed frame is copied asynchronously on the lane's own stream into its slot of the buffer. A per-surface event guards reuse of the decode surface; the host never waits for individual copies. - ``frames_in_flight`` sets how many decoded frames may wait to be copied out while the engine keeps decoding. It is a runtime knob, because the best value depends on the workload. - The buffer carries an event recorded after the last copy. ``__dlpack__(stream=...)`` makes the consumer stream wait on it, so ``torch.from_dlpack`` is ordered without a host synchronization. Completion without the GIL ~~~~~~~~~~~~~~~~~~~~~~~~~~ Futures are completed natively. A lane records the result in a C++ future, which wakes the threads waiting in :py:meth:`~spdl.io.CudaDecoders.decode` and ``result()``, and, for :py:meth:`~spdl.io.CudaDecoders.decode_async`, pushes the clip's ID to a per-event-loop completion queue whose file descriptor the asyncio loop watches; the loop thread drains the IDs of all completed clips at each wakeup and completes their asyncio futures. Both backends use the same future and completion queue (``libspdl/core/future.h``) and implement the same interface (the ``spdl::core::AsyncDecoders`` concept). Only the waiting thread takes the GIL. A Python ``concurrent.futures.Future`` would cost only microseconds per clip, but completing it requires the GIL. A lane could then wait up to the interpreter's switch interval (5 ms by default) behind the training loop, with its engine idle. Errors ~~~~~~ Each clip fails only its own future. Streams the hardware cannot decode (for example 4:2:2, 4:4:4, 12-bit, or sizes above the engine limit) fail with a dedicated error (:py:class:`~spdl.io.NvDecUnsupportedStreamError` / :py:class:`~spdl.io.RocDecUnsupportedStreamError`) before any decoding. The pipeline can then route those clips to CPU decoding. H.264/HEVC packets must be in Annex B format; demux them with ``bsf="h264_mp4toannexb"`` or ``"hevc_mp4toannexb"``. What we decided against, and why ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - **A decoder per clip:** setup costs as much as decoding a short clip. - **A decoder cache per Python thread** (the earlier NVDEC API): each thread builds its own set of decoders and destroys them inline, so creation and teardown repeat on every thread, on the decoding path. It also gives no control over how many sessions compete for the engines. See :ref:`cudadecoders-compared-with-nvdecdecoder` for what this means in practice. - **Sessions at the hardware maximum size:** gigabytes per session. - **A free function, or a streaming API, in the first version:** a free function makes create-and-discard the easy path, and streaming is not needed for clips. Long videos can be decoded window by window with :py:func:`spdl.io.demux_video` with ``timestamp=...``. NVIDIA (NVDEC) and AMD (VCN): the differences --------------------------------------------- .. list-table:: :header-rows: 1 * - - NVIDIA: :py:class:`~spdl.io.CudaDecoders` - AMD: :py:class:`~spdl.io.RocmDecoders` * - Decoder API - NVDEC (``cuviddec.h``/``nvcuvid.h``), in the driver's ``libnvcuvid`` - VA-API (``libva`` + Mesa's ``radeonsi`` VA driver), used directly * - Parser - NVIDIA's parser in ``libnvcuvid`` - rocDecode's bitstream parser (``librocdecode``, loaded at run time); the rest of rocDecode is not used * - Engine count query - ``cuvidGetDecoderCaps``: ``nNumNVDECs`` - ``DRM_IOCTL_AMDGPU_INFO`` / ``AMDGPU_INFO_HW_IP_COUNT`` for ``AMDGPU_HW_IP_VCN_DEC``, on the device's render node (per partition in DPX/CPX modes) * - Engines on the data-center GPUs we measured - 7 - 4 * - How work reaches an engine - The driver spreads pictures from all sessions over all engines dynamically - The kernel binds each VA display to one engine at its first submission; all contexts on that display share it * - Lanes - One pool of sessions shared by all lanes; default 2 lanes per engine - One VA display per lane; default 1 lane per engine * - Switching sizes - ``cuvidReconfigureDecoder`` (0.01–0.7 ms) within the session's maximum size - New VA context at the exact coded size over the bucket's surfaces (0.03–0.06 ms, plus 0.3–1.4 ms at its first picture); AV1/VP9 use one at the bucket size * - Session state cached across clips - Decoders (with their surfaces), keyed by codec, chroma format and bit depth - Surface sets per lane and size bucket, DRM-PRIME-exported and imported into HIP once * - Create / destroy cost - 34–64 ms / 22–36 ms per decoder (up to 0.25 s for the last one in the process); both stall other sessions - ``vaInitialize`` about 1.5 ms per lane (once); surface sets allocated (about 1 ms) and released (2–3 ms) once per bucket * - Output - NV12, or RGB/BGR from one conversion kernel, chosen per call; 10/12-bit converted to 8-bit NV12 - NV12 (P016 for 10-bit), or RGB/BGR from one conversion kernel, chosen per call * - Runtime libraries - Driver (``libnvcuvid``, ``libcuda``) and the CUDA runtime - The HIP runtime, linked by soname so that it binds to the copy the process loaded (PyTorch's); libva, the VA driver and rocDecode loaded at run time How lanes reach the engines: .. image:: ../_static/data/gpu_decoding_engines.png :width: 870px :alt: On NVIDIA, lanes 1 to 2E lease decoders from one shared pool, keyed by codec, chroma format and bit depth, and the NVDEC driver spreads their pictures over all engines. On AMD, each lane N has its own VA display with its surface sets, and the display is bound to one decode engine at its first submission; a VA context is created on it per clip. On NVIDIA, a lane leases any suitable decoder from the shared pool for each clip, and the driver decides which engine decodes each picture. On AMD, each lane owns a VA display that the kernel binds to one engine, and keeps its own surface sets; a VA context is created on that display for each clip. NVIDIA: one shared pool, cheap reconfiguration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An NVDEC decoder can decode any stream of its codec, chroma format and bit depth up to the maximum size it was created with. Switching to another size is ``cuvidReconfigureDecoder``, which takes well under a millisecond. Creating a decoder takes tens of milliseconds and stalls the other sessions meanwhile, and destroying the last one of the process up to a quarter of a second (see above). So :py:class:`~spdl.io.CudaDecoders` keeps one pool of decoders per GPU, shared by all lanes: 1. The lane feeds the clip's packets to its parser for that codec (one parser per lane and codec, kept across clips). 2. When the parser reports the stream format, the lane leases the smallest idle decoder with the same codec, chroma format, bit depth and output surface format whose maximum size covers the stream. 3. It reconfigures the decoder if the coded size or surface count differs from the previous clip. 4. If no decoder fits, it creates one at the stream's size bucket. 5. At the end of the clip the decoder goes back to the pool, ready for any lane. Decoders are created with enough decode surfaces (20 for H.264/HEVC, 12 for VP9/AV1) that consecutive clips rarely need a reconfiguration to add surfaces. The driver balances pictures from all sessions over all engines. A probe with one more session than engines showed every session decoding at the same rate. So lanes are a concurrency limit, not an engine binding, and a single shared pool is correct. Each lane also spends host time per clip (parsing, waiting for mapped frames, setup), so the default oversubscribes with two lanes per engine to keep the engines fed. A decoded picture is mapped (``cuvidMapVideoFrame``) and copied asynchronously. It is unmapped only after an event confirms the copy finished; NVIDIA does not document unmapping earlier as safe. AMD: VA-API directly, one display per engine ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AMD's rocDecode library wraps VA-API. Its decoder creates the VA context and the surfaces together and recreates both to change size (tens of milliseconds under load), and decoding a smaller H.264/HEVC stream in a larger rocDecode decoder corrupts the output (see below). So it cannot reuse decoder state across sizes the way bulk decoding needs. :py:class:`~spdl.io.RocmDecoders` therefore uses VA-API directly and uses only rocDecode's bitstream parser, which calls no HIP. Two properties of the AMD stack shape the design: - **Engine binding per display.** The kernel schedules each VA display's submissions on one decode engine, chosen at the display's first submission. Contexts created on the same display share that engine: four contexts on one display together decoded about as fast as a single context with a display of its own. So each lane owns one VA display, and the default number of lanes equals the number of engines. Unlike NVIDIA, extra lanes share an engine instead of adding throughput; a fifth lane makes two lanes share one engine at half speed each. - **Decode size comes from the context.** For H.264 and HEVC, the Mesa driver does not send the picture size to the hardware; it uses the size of the VA context. Decoding a smaller H.264/HEVC stream on a larger context corrupts the output. But a VA context is cheap to create (0.03–0.06 ms, plus 0.3–1.4 ms at its first picture) over existing surfaces, and decoding a stream on larger surfaces through a context of the exact size is bit-exact. AV1 and VP9 carry the size in their picture parameters, so one context at the bucket size works for them. So each lane keeps **surface sets** per size bucket: VA surfaces allocated once, exported as DRM PRIME and imported into HIP once. For each clip, the lane: 1. Creates a VA context at the clip's exact coded size over the bucket's surfaces. 2. Decodes the clip. 3. Destroys the context. Contexts are not cached; a context cache caused stalls of about one second on some clips, while recreating one costs a fraction of a millisecond. The lane prefers clips whose bucket it already holds, with a bounded look-ahead into the queue so that the order stays roughly first in, first out and no clip starves. Other AMD-specific details: - **Parser per clip.** A rocDecode parser reused across clips misses a new sequence when only the bit depth changes, so each clip gets a fresh parser. That costs microseconds. - **Slice data padding.** H.264/HEVC slice data is submitted after 32 leading zero bytes, which the Annex B byte stream allows. Without them, some clips with an emulation-prevention byte (``00 00 03``) near the start of the slice data had their first picture left unwritten by the hardware. - **Run-time loading.** - HIP: linked by soname, so it binds to the runtime the process already uses (PyTorch's). Two HIP runtimes in one process crash. - libva and the VA driver: the copies that TheRock's Python packages ship under renamed sonames, with a VA driver built without LLVM, are preferred, then the system's. The VA driver of AMD's Mesa packages links its own LLVM, which clashes with a process that already has another LLVM loaded. - rocDecode (for its parser): a copy already loaded, then TheRock's Python packages, then the library path. ROCm's own copy links the host's ``libva``, which hosts often do not have. - **Copies.** After ``vaSyncSurface``, planes are copied with ``hipMemcpy2DAsync``, or converted to RGB/BGR by a HIP kernel, on the lane's non-blocking stream. .. _cudadecoders-compared-with-nvdecdecoder: ``CudaDecoders`` compared with ``NvDecDecoder`` ----------------------------------------------- :py:class:`~spdl.io.NvDecDecoder` (with :py:func:`spdl.io.nvdec_decoder` and :py:func:`spdl.io.decode_packets_nvdec`) is the earlier NVDEC API: each Python thread owns a decoder object, cached in thread-local storage, with its own small cache of decoders. :py:class:`~spdl.io.CudaDecoders` keeps the decoders of one GPU in one object and decodes on its own threads. Since 0.9.0 both reuse decoders across sizes through reconfiguration, so on a steady workload they decode at the same speed. Their differences come from who owns the decoders and which thread pays for managing them: .. list-table:: :header-rows: 1 * - - :py:class:`~spdl.io.NvDecDecoder` (one per Python thread) - :py:class:`~spdl.io.CudaDecoders` (one per GPU) * - Who decodes - The calling Python thread, inside the call (with the GIL released) - Lanes owned by the object (2 per engine by default); callers only submit and wait * - Concurrency - One Python thread per clip being decoded - Any number of threads calling :py:meth:`~spdl.io.CudaDecoders.decode`, or one thread keeping many clips in flight with :py:meth:`~spdl.io.CudaDecoders.decode_future` / :py:meth:`~spdl.io.CudaDecoders.decode_async` * - Decoder cache - Per thread, least recently used, up to ``max_cached_decoders`` (4) per thread - One pool per GPU, shared by all lanes, least recently used under ``max_memory_bytes`` * - Creating decoders - Every thread builds its own set, so creation repeats per thread - Once per pool; decoders are created at size buckets and reused by every lane * - Destroying decoders - Inline, on the decoding thread, when its cache evicts one (about 0.2 s) or when the thread exits - On a background thread; lanes never wait for it * - Output buffer - Allocated when the clip starts decoding - Allocated when the clip is submitted, so queued clips already hold theirs * - Tuning and diagnosis - Number of threads - ``num_lanes``, ``max_memory_bytes``, ``size_buckets``, ``frames_in_flight``; :py:meth:`~spdl.io.CudaDecoders.stats` tells starvation, saturation and engine-bound apart What this means in practice (measured on one GPU with 7 decode engines, comparing the same number of decoder threads, all kept busy: threads that each own an :py:class:`~spdl.io.NvDecDecoder`, or :py:class:`~spdl.io.CudaDecoders` lanes): - **Easier to use.** One object decodes for the whole process. The caller does not size a thread pool to the engines, manage per-thread decoder caches, or pay for decoder teardown; :py:class:`~spdl.io.CudaDecoders` does that work behind the scenes, and its lanes never take the GIL. - **Same steady-state throughput.** With warm decoders, both reach the same clips per second (on 200 mixed clips of H.264, HEVC 8/10-bit and VP9 at 240p–1080p: 87 vs 85 clips/s with 14 decoder threads). On Kinetics clips (H.264 up to 720p), both are limited by the decode engines (about 60 clips/s). - **Faster when decoders must be created.** On the first pass over the mixed clips, :py:class:`~spdl.io.CudaDecoders` decoded 55 clips/s with 14 lanes against 36 with 14 threads, and 50 against 24 with 28. Per-thread caches create and destroy decoders on every thread, inline; the shared pool creates fewer and destroys them in the background. This matters at startup, for short-lived processes, and when clips vary more than per-thread caches can hold. - **Teardown off the hot path.** Evicting a decoder costs 22–36 ms on the thread that does it, and destroying the last decoder of the process up to 0.25 s. With :py:class:`~spdl.io.NvDecDecoder` that is a decoding thread; with :py:class:`~spdl.io.CudaDecoders` it is a background thread. Either way the other sessions slow down during the call, so the larger gain is the shared pool creating and destroying fewer decoders. - **Same memory with as many clips in flight as lanes.** With one submitting thread per lane, the peak GPU memory matched the same number of :py:class:`~spdl.io.NvDecDecoder` threads (on the mixed clips, 7.4 against 7.2 GB with 14 decoder threads and 10.4 against 11.6 GB with 28; on Kinetics, 6.0 against 5.7 GB with 14), at the same throughput. The shared pool holds fewer decoders when clips vary (3.9 against 5.5 GB of decoders with 28) and slightly more when they are uniform (1.4 against 0.8 GB, because new decoders get the 720p bucket and 20 surfaces). Queued clips hold their outputs, so more clips in flight than lanes add memory: feeding each lane from two threads raised the peak by up to 4 GB (mixed clips) and 6 GB (Kinetics) with 28 lanes, without adding throughput. :py:class:`~spdl.io.NvDecDecoder` remains the API for incremental (streaming) decoding of one stream, and for cropping and scaling in the decoder, which :py:class:`~spdl.io.CudaDecoders` does not support yet. Measured behavior (summary) --------------------------- These numbers come from one GPU of each vendor, on one host each. They describe these implementations on those GPUs, not the vendors' hardware in general. The two GPUs differ in generation and in the number of decode engines, and :py:class:`~spdl.io.RocmDecoders` has not been tuned yet, while the NVDEC driver path is mature. Compare per engine and per codec, not per GPU. - **Decoder reuse is the main gain.** On a mixed corpus of 1–5 s clips, per-clip decoder setup dropped from about 150 ms to near zero on NVIDIA, and to 0.1–0.2 ms on AMD. That took one NVDEC thread from 5 to over 17 clips/s. - **Engine bound, with similar per-engine throughput.** On identical H.264 clips up to 720p, both backends saturate their engines, at about the same rate per engine (within about 6%). Per-GPU totals differ mostly by the number of engines. - **Codec-dependent per-stream speed.** On the two GPUs measured, the AMD GPU decoded one H.264 stream at 720p and above 12–30% faster than the NVIDIA GPU, and one HEVC or VP9 stream at roughly half its speed. Which backend looks faster on a corpus therefore depends on its codec mix. - **Bit-exact output.** Output is bit-exact against FFmpeg's software decoders, and identical between the two backends for 8-bit streams. - **End-to-end training.** Whether faster decoding speeds up training depends on whether the model leaves room for it. A GPU-bound model gains nothing from any decoder. Post-processing that runs as GPU kernels (color conversion, resize) then competes with training. Possible future work -------------------- - Crop and scale on AMD. - Moving the rest of the shared executor machinery (lanes) into ``libspdl_core``; the native futures, the completion queue and the ``AsyncDecoders`` concept already live there. - Reimplementing :py:func:`spdl.io.decode_packets_nvdec` on top of :py:class:`~spdl.io.CudaDecoders` once it supports everything that function does. - Creating decoders for expected codecs and size buckets up front, so that cold-start creates do not stall the lanes of the same process. - A device-neutral layer on top of both, if a use case needs one.