Video dataloading¶
This example uses SPDL to decode and batch video frames, then send them to GPU.
The structure of the pipeline is identical to that of
image_dataloading.
Basic Usage¶
Running this example requires a dataset consists of videos.
For example, to run this example with Kinetics dataset.
Download Kinetics dataset. https://github.com/cvdfoundation/kinetics-dataset provides scripts to facilitate this.
Create a list containing the downloaded videos.
cd /data/users/moto/kinetics-dataset/k400/ find train -name '*.mp4' > ~/imagenet.train.flist
Run the script.
python examples/video_dataloading.py --input-flist ~/kinetics400.train.flist --prefix /data/users/moto/kinetics-dataset/k400/ --num-threads 8
Using GPU video decoder¶
When SPDL is built with NVDEC integration enabled, and the GPUs support NVDEC,
providing --nvdec option switches the video decoder to NVDEC, using
spdl.io.decode_packets_nvdec(). When using this option, adjust the
number of threads (the number of concurrent decoding) to accommodate
the number of hardware video decoder available on GPUs.
For the details, please refer to https://developer.nvidia.com/video-encode-and-decode-gpu-support-matrix-new
Note
This example decodes videos from the beginning to the end, so using NVDEC speeds up the whole decoding speed. But in cases where framees are sampled, CPU decoding with higher concurrency often yields higher throughput.
Source¶
Source
Click here to see the source.
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the BSD-style license found in the
5# LICENSE file in the root directory of this source tree.
6
7"""This example uses SPDL to decode and batch video frames, then send them to GPU.
8
9The structure of the pipeline is identical to that of
10:py:mod:`image_dataloading`.
11
12Basic Usage
13-----------
14
15Running this example requires a dataset consists of videos.
16
17For example, to run this example with Kinetics dataset.
18
191. Download Kinetics dataset.
20 https://github.com/cvdfoundation/kinetics-dataset provides scripts to facilitate this.
212. Create a list containing the downloaded videos.
22
23 .. code-block::
24
25 cd /data/users/moto/kinetics-dataset/k400/
26 find train -name '*.mp4' > ~/imagenet.train.flist
27
283. Run the script.
29
30 .. code-block:: shell
31
32 python examples/video_dataloading.py
33 --input-flist ~/kinetics400.train.flist
34 --prefix /data/users/moto/kinetics-dataset/k400/
35 --num-threads 8
36
37Using GPU video decoder
38-----------------------
39
40When SPDL is built with NVDEC integration enabled, and the GPUs support NVDEC,
41providing ``--nvdec`` option switches the video decoder to NVDEC, using
42:py:func:`spdl.io.decode_packets_nvdec`. When using this option, adjust the
43number of threads (the number of concurrent decoding) to accommodate
44the number of hardware video decoder available on GPUs.
45For the details, please refer to https://developer.nvidia.com/video-encode-and-decode-gpu-support-matrix-new
46
47.. note::
48
49 This example decodes videos from the beginning to the end, so using NVDEC
50 speeds up the whole decoding speed. But in cases where framees are sampled,
51 CPU decoding with higher concurrency often yields higher throughput.
52"""
53
54import argparse
55import logging
56import signal
57import time
58from argparse import Namespace
59from collections.abc import Callable, Iterable
60from dataclasses import dataclass
61from pathlib import Path
62from threading import Event
63from types import FrameType
64from typing import cast
65
66import spdl.io
67import spdl.io.utils
68import torch
69from spdl.pipeline import Pipeline, PipelineBuilder
70from torch import Tensor
71
72_LG: logging.Logger = logging.getLogger(__name__)
73
74__all__ = [
75 "entrypoint",
76 "worker_entrypoint",
77 "benchmark",
78 "source",
79 "decode_video",
80 "decode_video_nvdec",
81 "get_pipeline",
82 "PerfResult",
83]
84
85
86def _parse_args(args: list[str]) -> Namespace:
87 parser = argparse.ArgumentParser(
88 description=__doc__,
89 )
90 parser.add_argument("--debug", action="store_true")
91 parser.add_argument("--input-flist", type=Path, required=True)
92 parser.add_argument("--max-samples", type=int, default=float("inf"))
93 parser.add_argument("--prefix", default="")
94 parser.add_argument("--trace", type=Path)
95 parser.add_argument("--queue-size", type=int, default=16)
96 parser.add_argument("--num-threads", type=int, required=True)
97 parser.add_argument("--worker-id", type=int, required=True)
98 parser.add_argument("--num-workers", type=int, required=True)
99 parser.add_argument("--nvdec", action="store_true")
100 ns = parser.parse_args(args)
101 if ns.trace:
102 ns.max_samples = 320
103 return ns
104
105
106def source(
107 input_flist: str,
108 prefix: str,
109 max_samples: int,
110 split_size: int = 1,
111 split_id: int = 0,
112) -> Iterable[str]:
113 """Iterate a file containing a list of paths, while optionally skipping some.
114
115 Args:
116 input_flist: A file contains list of video paths.
117 prefix: Prepended to the paths in the list.
118 max_samples: The maximum number of items to yield.
119 split_size: Split the paths in to this number of subsets.
120 split_id: The index of this split. Paths at ``line_number % split_size == split_id`` are returned.
121
122 Yields:
123 The paths of the specified split.
124 """
125 with open(input_flist, "r") as f:
126 num_yielded = 0
127 for i, line in enumerate(f):
128 if i % split_size != split_id:
129 continue
130 if line := line.strip():
131 yield prefix + line
132
133 if (num_yielded := num_yielded + 1) >= max_samples:
134 return
135
136
137@spdl.io.fuse
138def decode_video(
139 src: str | bytes,
140 width: int,
141 height: int,
142 device_index: int,
143) -> Tensor:
144 """Decode video and send decoded frames to GPU.
145
146 The decorator :py:func:`spdl.io.fuse` makes demuxing, decoding and
147 conversion execute in one native call.
148
149 Args:
150 src: Data source. Passed to :py:func:`spdl.io.demux_video`.
151 width, height: The target resolution.
152 device_index: The index of the target GPU.
153
154 Returns:
155 A GPU tensor represents decoded video frames.
156 The dtype is uint8, the shape is ``[N, C, H, W]``, where ``N`` is the number
157 of frames in the video, ``C`` is RGB channels.
158 """
159 packets = spdl.io.demux_video(src)
160 frames = spdl.io.decode_packets(
161 packets,
162 filter_desc=spdl.io.get_filter_desc(
163 packets,
164 scale_width=width,
165 scale_height=height,
166 pix_fmt="rgb24",
167 ),
168 )
169 buffer: spdl.io.CPUBuffer | spdl.io.CUDABuffer = spdl.io.convert_frames(frames)
170 buffer = spdl.io.transfer_buffer(
171 cast(spdl.io.CPUBuffer, buffer),
172 device_config=spdl.io.cuda_config(
173 device_index=device_index,
174 allocator=(
175 torch.cuda.caching_allocator_alloc,
176 torch.cuda.caching_allocator_delete,
177 ),
178 ),
179 )
180 return spdl.io.to_torch(buffer).permute(0, 2, 3, 1)
181
182
183def decode_video_nvdec(
184 src: str,
185 device_index: int,
186 width: int,
187 height: int,
188) -> Tensor:
189 """Decode video using NVDEC.
190
191 Args:
192 src: Data source. Passed to :py:func:`spdl.io.demux_video`.
193 device_index: The index of the target GPU.
194 width, height: The target resolution.
195
196 Returns:
197 A GPU tensor represents decoded video frames.
198 The dtype is uint8, the shape is ``[N, C, H, W]``, where ``N`` is the number
199 of frames in the video, ``C`` is RGB channels.
200 """
201 packets = spdl.io.demux_video(src)
202 buffer = spdl.io.decode_packets_nvdec(
203 packets,
204 device_config=spdl.io.cuda_config(
205 device_index=device_index,
206 allocator=(
207 torch.cuda.caching_allocator_alloc,
208 torch.cuda.caching_allocator_delete,
209 ),
210 ),
211 scale_width=width,
212 scale_height=height,
213 pix_fmt="rgb",
214 )
215 return spdl.io.to_torch(buffer)[..., :3].permute(0, 2, 3, 1)
216
217
218def _get_decode_fn(
219 device_index: int, use_nvdec: bool, width: int = 222, height: int = 222
220) -> Callable[[str], Tensor]:
221 if use_nvdec:
222
223 def _decode_func(src: str) -> Tensor:
224 return decode_video_nvdec(src, device_index, width, height)
225
226 else:
227
228 def _decode_func(src: str) -> Tensor:
229 return decode_video(src, width, height, device_index)
230
231 return _decode_func
232
233
234def get_pipeline(
235 src: Iterable[str],
236 decode_fn: Callable[[str], Tensor],
237 decode_concurrency: int,
238 num_threads: int,
239 buffer_size: int = 3,
240) -> Pipeline:
241 """Construct the video loading pipeline.
242
243 Args:
244 src: Pipeline source. Generator that yields image paths. See :py:func:`source`.
245 decode_fn: Function that decode the given image and send the decoded frames to GPU.
246 decode_concurrency: The maximum number of decoding scheduled concurrently.
247 num_threads: The number of threads in the pipeline.
248 buffer_size: The size of buffer for the resulting batch image Tensor.
249 """
250 return (
251 PipelineBuilder()
252 .add_source(src)
253 .pipe(decode_fn, concurrency=decode_concurrency)
254 .add_sink(buffer_size)
255 .build(num_threads=num_threads, report_stats_interval=15)
256 )
257
258
259def _get_pipeline(args: Namespace) -> Pipeline:
260 src = source(
261 input_flist=args.input_flist,
262 prefix=args.prefix,
263 max_samples=args.max_samples,
264 split_id=args.worker_id,
265 split_size=args.num_workers,
266 )
267
268 decode_fn = _get_decode_fn(args.worker_id, args.nvdec)
269 pipeline = get_pipeline(
270 src,
271 decode_fn,
272 decode_concurrency=args.num_threads,
273 num_threads=args.num_threads + 3,
274 buffer_size=args.queue_size,
275 )
276 print(pipeline)
277 return pipeline
278
279
280@dataclass
281class PerfResult:
282 """Used to report the worker performance to the main process."""
283
284 elapsed: float
285 """The time it took to process all the inputs."""
286
287 num_batches: int
288 """The number of batches processed."""
289
290 num_frames: int
291 """The number of frames processed."""
292
293
294def benchmark(
295 dataloader: Iterable[Tensor],
296 stop_requested: Event,
297) -> PerfResult:
298 """The main loop that measures the performance of dataloading.
299
300 Args:
301 dataloader: The dataloader to benchmark.
302 stop_requested: Used to interrupt the benchmark loop.
303
304 Returns:
305 The performance result.
306 """
307 t0 = time.monotonic()
308 num_frames = num_batches = 0
309 try:
310 for batches in dataloader:
311 for batch in batches:
312 num_frames += batch.shape[0]
313 num_batches += 1
314
315 if stop_requested.is_set():
316 break
317
318 finally:
319 elapsed = time.monotonic() - t0
320 fps = num_frames / elapsed
321 _LG.info(f"FPS={fps:.2f} ({num_frames} / {elapsed:.2f}), (Done {num_frames})")
322
323 return PerfResult(elapsed, num_batches, num_frames)
324
325
326def worker_entrypoint(args_: list[str]) -> PerfResult:
327 """Entrypoint for worker process. Load images to a GPU and measure its performance.
328
329 It builds a Pipeline object using :py:func:`get_pipeline` function and run it with
330 :py:func:`benchmark` function.
331 """
332 args = _parse_args(args_)
333 _init(args.debug, args.worker_id)
334
335 _LG.info(args)
336
337 pipeline = _get_pipeline(args)
338
339 device = torch.device(f"cuda:{args.worker_id}")
340
341 ev: Event = Event()
342
343 def handler_stop_signals(_signum: int, _frame: FrameType | None) -> None:
344 ev.set()
345
346 signal.signal(signal.SIGTERM, handler_stop_signals)
347
348 # Warm up
349 torch.zeros([1, 1], device=device)
350
351 trace_path = f"{args.trace}.{args.worker_id}"
352 with (
353 pipeline.auto_stop(),
354 spdl.io.utils.tracing(trace_path, enable=args.trace is not None),
355 ):
356 return benchmark(pipeline.get_iterator(), ev)
357
358
359def _init_logging(debug: bool = False, worker_id: int | None = None) -> None:
360 fmt = "%(asctime)s [%(levelname)s] %(message)s"
361 if worker_id is not None:
362 fmt = f"[{worker_id}:%(thread)d] {fmt}"
363 level = logging.DEBUG if debug else logging.INFO
364 logging.basicConfig(format=fmt, level=level)
365
366
367def _init(debug: bool, worker_id: int) -> None:
368 _init_logging(debug, worker_id)
369
370
371def _parse_process_args(args: list[str] | None) -> tuple[Namespace, list[str]]:
372 parser = argparse.ArgumentParser(
373 description=__doc__,
374 )
375 parser.add_argument("--num-workers", type=int, default=8)
376 return parser.parse_known_args(args)
377
378
379def entrypoint(args: list[str] | None = None) -> None:
380 """CLI entrypoint. Launch the worker processes, each of which load videos and send them to GPU."""
381 ns, args = _parse_process_args(args)
382
383 args_set = [
384 [*args, f"--worker-id={i}", f"--num-workers={ns.num_workers}"]
385 for i in range(ns.num_workers)
386 ]
387
388 from multiprocessing import Pool
389
390 with Pool(processes=ns.num_workers) as pool:
391 _init_logging()
392 _LG.info("Spawned: %d workers", ns.num_workers)
393
394 vals = pool.map(worker_entrypoint, args_set)
395
396 ave_time = sum(v.elapsed for v in vals) / len(vals)
397 total_frames = sum(v.num_frames for v in vals)
398 total_batches = sum(v.num_batches for v in vals)
399
400 _LG.info(f"{ave_time=:.2f}, {total_frames=}, {total_batches=}")
401
402 FPS = total_frames / ave_time
403 BPS = total_batches / ave_time
404 _LG.info(f"Aggregated {FPS=:.2f}, {BPS=:.2f}")
405
406
407if __name__ == "__main__":
408 entrypoint()
API Reference¶
Functions
- entrypoint(args: list[str] | None = None) None[source]¶
CLI entrypoint. Launch the worker processes, each of which load videos and send them to GPU.
- worker_entrypoint(args_: list[str]) PerfResult[source]¶
Entrypoint for worker process. Load images to a GPU and measure its performance.
It builds a Pipeline object using
get_pipeline()function and run it withbenchmark()function.
- benchmark(dataloader: Iterable[Tensor], stop_requested: Event) PerfResult[source]¶
The main loop that measures the performance of dataloading.
- Parameters:
dataloader – The dataloader to benchmark.
stop_requested – Used to interrupt the benchmark loop.
- Returns:
The performance result.
- source(input_flist: str, prefix: str, max_samples: int, split_size: int = 1, split_id: int = 0) Iterable[str][source]¶
Iterate a file containing a list of paths, while optionally skipping some.
- Parameters:
input_flist – A file contains list of video paths.
prefix – Prepended to the paths in the list.
max_samples – The maximum number of items to yield.
split_size – Split the paths in to this number of subsets.
split_id – The index of this split. Paths at
line_number % split_size == split_idare returned.
- Yields:
The paths of the specified split.
- decode_video(src: str | bytes, width: int, height: int, device_index: int) Tensor[source]¶
Decode video and send decoded frames to GPU.
The decorator
spdl.io.fuse()makes demuxing, decoding and conversion execute in one native call.- Parameters:
src – Data source. Passed to
spdl.io.demux_video().width – The target resolution.
height – The target resolution.
device_index – The index of the target GPU.
- Returns:
A GPU tensor represents decoded video frames. The dtype is uint8, the shape is
[N, C, H, W], whereNis the number of frames in the video,Cis RGB channels.
- decode_video_nvdec(src: str, device_index: int, width: int, height: int) Tensor[source]¶
Decode video using NVDEC.
- Parameters:
src – Data source. Passed to
spdl.io.demux_video().device_index – The index of the target GPU.
width – The target resolution.
height – The target resolution.
- Returns:
A GPU tensor represents decoded video frames. The dtype is uint8, the shape is
[N, C, H, W], whereNis the number of frames in the video,Cis RGB channels.
- get_pipeline(src: Iterable[str], decode_fn: Callable[[str], Tensor], decode_concurrency: int, num_threads: int, buffer_size: int = 3) Pipeline[source]¶
Construct the video loading pipeline.
- Parameters:
src – Pipeline source. Generator that yields image paths. See
source().decode_fn – Function that decode the given image and send the decoded frames to GPU.
decode_concurrency – The maximum number of decoding scheduled concurrently.
num_threads – The number of threads in the pipeline.
buffer_size – The size of buffer for the resulting batch image Tensor.
Classes