Benchmark video training¶
End-to-end benchmark: video model training with CPU and GPU video decoding.
Trains a video classification model with
torch.nn.parallel.DistributedDataParallel (one process per GPU,
launched with torchrun) on Kinetics-style clips, with one data-loading arm
per run, and measures what each arm delivers to the training loop:
arm |
loader subprocess (CPU) |
trainer process |
|---|---|---|
|
read, demux, decode with FFmpeg ( |
batch, host-to-device copy |
|
read, demux |
|
|
read, demux to Annex B |
one |
|
none |
one random batch, reused: the model’s own speed |
Every arm reads the same clips in the same order, decodes the same time window
of each clip, selects the same frames, resizes and crops them to the same size,
and feeds float32 [B, 3, T, H, W] in [0, 1] to the same model with the
same seed. The loader runs as an SPDL Pipeline split
across a subprocess (CPU stages, with
run_pipeline_in_subprocess()) and the trainer process
(GPU stages). The CPU arm’s host-to-device copy runs on a side CUDA stream,
and each batch carries an event the training step waits for.
Models and input recipes (--model)
videomae: VideoMAE ViT-B/16 video classification (transformersVideoMAEForVideoClassificationwith the configuration ofMCG-NJU/videomae-base-finetuned-kinetics: 16 frames, tubelet 2, patch 16, 224x224, 400 classes), randomly initialized, with PyTorch’s scaled dot product attention. Input: VideoMAE’s Kinetics fine-tuning recipe, 16 frames at stride 4 from a random start (drawn per clip from a seeded generator), short side resized to 256, center crop 224, ImageNet normalization. Each sample decodes about 145 frames (from the key frame before the 64-frame window). AdamW (lr 1e-4, weight decay 0.05), BF16 autocast, batch 16 per GPU.r3d18: R3D-18 (torchvision), asspdl.examples.video_classification: 16 frames spread over the first 0.5 s, resized to 112x112. AdamW (lr 1e-3), BF16 autocast, batch 16 per GPU.
Results
One host with 8 NVIDIA H100 GPUs, Kinetics-400 clips (H.264, up to 720p) on
local disk, 600 measured steps after 100 warmup steps per run, arms
alternating within a job, mean ± standard deviation over runs. % of
model-only is the throughput as a fraction of the synthetic arm’s. A
model that is the bottleneck cannot show a gain from any loader.
VideoMAE ViT-B/16:
arm samples/s % of model-only CPU %
no loader (model only) 1,398 ± 4 100% 3.6
cpu (64 decode threads/rank) 338 ± 2 24% 77.2
nvdec (7 threads/rank) 359 ± 0 26% 6.5
nvdec (28 threads/rank) 444 ± 1 32% 12.3
cuda_decoders (32 threads) 553 ± 6 40% 20.7
CPU % is the CPU time of the trainer and loader processes as a percentage
of the host’s CPUs. With VideoMAE’s input, data loading is the bottleneck. The
NVDEC arm with enough threads is 31% faster than the CPU arm, at a sixth of its
CPU. With R3D-18 (a light model, 0.5 s windows), the CPU arm reaches 1,629
samples/s (47% of model-only) and the NVDEC arm 1,807 with 14 threads per rank.
With cuda_decoders (32 decoding threads per rank), training reaches
553 samples/s, 40% of model-only and 25% more than the NVDEC arm, at a quarter
of the CPU arm’s CPU. It is limited by the NVDEC engines and by the decoders’
interference with the training step in the same process (see below). With
R3D-18, cuda_decoders reaches 2,244 samples/s, 64% of model-only and 38%
more than the CPU arm.
Where to run cuda_decoders
With cuda_decoders in the trainer process, a training step on the H100
host takes about 175 ms even when its batch is ready, against 91 ms for the
model alone. The decoders map, convert and copy every frame of the 64-frame
window on their worker threads, and these CUDA calls, made in the trainer’s
CUDA context, slow down the kernel launches of the training threads (from
about 5 us to 17-43 us on average, with stalls of up to tens of
milliseconds): the step becomes bound by kernel launches, and
DistributedDataParallel makes every rank wait for the slowest one.
Dropping the decoded frames does not help, nor do fewer frames in flight or
more hardware queues (CUDA_DEVICE_MAX_CONNECTIONS); the same decoders in
another process on the same GPU leave the step at 105-135 ms. Two options
remove most of it:
--gpu-decode-in-subprocessdecodes and post-processes the clips in the loader subprocess (on the rank’s GPU) and hands them to the trainer with CUDA IPC (torch.multiprocessing).--gpu-select-framespasses the sampled frame indices to the decoder, which then outputs only those 16 frames instead of the 64 of the window (needs a decoder whosedecodeacceptsframe_indices).
VideoMAE ViT-B/16, NVIDIA H100 host, cuda_decoders with 14 lanes (the
default) and 32 decoding threads per rank, 300 measured steps per run:
placement samples/s % of model-only step, data ready CPU %
trainer process 567 ± 15 41% 174 ms 20.3
trainer process, frame selection 690 ± 2 49% 115 ms 14.4
loader subprocess 689 ± 24 49% 150 ms 24.8
loader subprocess, frame selection 719 ± 13 51% 141 ms 13.4
Both options, alone or together, reach about half of model-only, against 41% in the trainer process and 24% with CPU decoding. The rest of the gap is the hardware: at 14 lanes (the default) the NVDEC engines are about 90% busy, as each sample decodes about 145 frames. Fewer lanes leave the engines idle (33-35% of model-only with 7), and more lanes add conversion work on the GPU without adding decoding (40-46% with 21-28).
Measurement scopes
samples_per_s: training samples per second over the measured steps (all ranks);step_time_msthe mean step;data_wait_fractionthe fraction of each step spent waiting for the next batch (mean over ranks, and the rank that waited most).sys: sampled once per second on the host of local rank 0: GPU and NVDEC utilization (NVML) or GPU busy (amdgpu sysfs), GPU memory, host CPU, the container’s CPU (cgroupcpu.stat), and the CPU time and memory of the trainer processes and of their descendants (the loader subprocesses).stages: SPDL pipeline statistics of every rank within the measured window (average task time and output queue occupancy per stage).loss: the first steps’ loss, to check that every arm trains on the same input.--profiletraces 30 steps of rank 0 withtorch.profilerand reports where the step’s time goes on the GPU and on the training thread.
Notes
Keep the loader subprocesses free of libraries that install a global FFmpeg log callback which takes the GIL (
--block-pyavmakes PyAV unimportable;torchvisionimports it when available). With such a callback, SPDL’s demuxing and decoding threads queue on the GIL and stop scaling.Ranks launched without
torchrunneedOMP_NUM_THREADS=1.
Example
$ torchrun --nproc-per-node 8 benchmark_video_training.py \
--manifest kinetics400.csv --model videomae --arm nvdec \
--decode-threads 28 --output results.jsonl
$ python benchmark_video_training_plot.py \
--input "H100=results.jsonl" --output plots/
The manifest is a CSV file with the columns path and label, and
optionally fps, duration_s, width and height (otherwise probed
from the files).
Source¶
Source
Click here to see the source.
1#!/usr/bin/env python3
2# Copyright (c) Meta Platforms, Inc. and affiliates.
3# All rights reserved.
4#
5# This source code is licensed under the BSD-style license found in the
6# LICENSE file in the root directory of this source tree.
7
8
9"""End-to-end benchmark: video model training with CPU and GPU video decoding.
10
11Trains a video classification model with
12:py:class:`torch.nn.parallel.DistributedDataParallel` (one process per GPU,
13launched with ``torchrun``) on Kinetics-style clips, with one data-loading arm
14per run, and measures what each arm delivers to the training loop:
15
16.. list-table::
17 :header-rows: 1
18
19 * - arm
20 - loader subprocess (CPU)
21 - trainer process
22 * - ``cpu``
23 - read, demux, decode with FFmpeg (:py:func:`spdl.io.decode_packets`), then
24 convert (BT.709 limited-range YUV to full-range RGB), resize and crop the
25 selected frames in one filter graph
26 - batch, host-to-device copy
27 * - ``nvdec``
28 - read, demux
29 - :py:func:`spdl.io.decode_packets_nvdec` (NVDEC resizes and converts to
30 RGB), frame selection and crop
31 * - ``cuda_decoders``
32 - read, demux to Annex B
33 - one ``spdl.io.cuda_decoders`` per GPU (RGB output), frame selection,
34 resize and crop on the GPU, on a side CUDA stream
35 * - ``synthetic``
36 - none
37 - one random batch, reused: the model's own speed
38
39Every arm reads the same clips in the same order, decodes the same time window
40of each clip, selects the same frames, resizes and crops them to the same size,
41and feeds ``float32 [B, 3, T, H, W]`` in ``[0, 1]`` to the same model with the
42same seed. The loader runs as an SPDL :py:class:`~spdl.pipeline.Pipeline` split
43across a subprocess (CPU stages, with
44:py:func:`~spdl.pipeline.run_pipeline_in_subprocess`) and the trainer process
45(GPU stages). The CPU arm's host-to-device copy runs on a side CUDA stream,
46and each batch carries an event the training step waits for.
47
48**Models and input recipes** (``--model``)
49
50- ``videomae``: VideoMAE ViT-B/16 video classification (``transformers``
51 ``VideoMAEForVideoClassification`` with the configuration of
52 ``MCG-NJU/videomae-base-finetuned-kinetics``: 16 frames, tubelet 2, patch 16,
53 224x224, 400 classes), randomly initialized, with PyTorch's scaled dot product
54 attention. Input: VideoMAE's Kinetics fine-tuning recipe, 16 frames at stride
55 4 from a random start (drawn per clip from a seeded generator), short side
56 resized to 256, center crop 224, ImageNet normalization. Each sample decodes
57 about 145 frames (from the key frame before the 64-frame window). AdamW
58 (lr 1e-4, weight decay 0.05), BF16 autocast, batch 16 per GPU.
59- ``r3d18``: R3D-18 (``torchvision``), as
60 :py:mod:`spdl.examples.video_classification`: 16 frames spread over the first
61 0.5 s, resized to 112x112. AdamW (lr 1e-3), BF16 autocast, batch 16 per GPU.
62
63**Results**
64
65One host with 8 NVIDIA H100 GPUs, Kinetics-400 clips (H.264, up to 720p) on
66local disk, 600 measured steps after 100 warmup steps per run, arms
67alternating within a job, mean ± standard deviation over runs. ``% of
68model-only`` is the throughput as a fraction of the ``synthetic`` arm's. A
69model that is the bottleneck cannot show a gain from any loader.
70
71VideoMAE ViT-B/16:
72
73.. code-block:: text
74
75 arm samples/s % of model-only CPU %
76 no loader (model only) 1,398 ± 4 100% 3.6
77 cpu (64 decode threads/rank) 338 ± 2 24% 77.2
78 nvdec (7 threads/rank) 359 ± 0 26% 6.5
79 nvdec (28 threads/rank) 444 ± 1 32% 12.3
80 cuda_decoders (32 threads) 553 ± 6 40% 20.7
81
82``CPU %`` is the CPU time of the trainer and loader processes as a percentage
83of the host's CPUs. With VideoMAE's input, data loading is the bottleneck. The
84NVDEC arm with enough threads is 31% faster than the CPU arm, at a sixth of its
85CPU. With R3D-18 (a light model, 0.5 s windows), the CPU arm reaches 1,629
86samples/s (47% of model-only) and the NVDEC arm 1,807 with 14 threads per rank.
87
88With ``cuda_decoders`` (32 decoding threads per rank), training reaches
89553 samples/s, 40% of model-only and 25% more than the NVDEC arm, at a quarter
90of the CPU arm's CPU. It is limited by the NVDEC engines and by the decoders'
91interference with the training step in the same process (see below). With
92R3D-18, ``cuda_decoders`` reaches 2,244 samples/s, 64% of model-only and 38%
93more than the CPU arm.
94
95.. image:: ../../_static/data/example_benchmark_video_training_h100.png
96
97**Where to run** ``cuda_decoders``
98
99With ``cuda_decoders`` in the trainer process, a training step on the H100
100host takes about 175 ms even when its batch is ready, against 91 ms for the
101model alone. The decoders map, convert and copy every frame of the 64-frame
102window on their worker threads, and these CUDA calls, made in the trainer's
103CUDA context, slow down the kernel launches of the training threads (from
104about 5 us to 17-43 us on average, with stalls of up to tens of
105milliseconds): the step becomes bound by kernel launches, and
106``DistributedDataParallel`` makes every rank wait for the slowest one.
107Dropping the decoded frames does not help, nor do fewer frames in flight or
108more hardware queues (``CUDA_DEVICE_MAX_CONNECTIONS``); the same decoders in
109another process on the same GPU leave the step at 105-135 ms. Two options
110remove most of it:
111
112- ``--gpu-decode-in-subprocess`` decodes and post-processes the clips in the
113 loader subprocess (on the rank's GPU) and hands them to the trainer with
114 CUDA IPC (:py:mod:`torch.multiprocessing`).
115- ``--gpu-select-frames`` passes the sampled frame indices to the decoder,
116 which then outputs only those 16 frames instead of the 64 of the window
117 (needs a decoder whose ``decode`` accepts ``frame_indices``).
118
119VideoMAE ViT-B/16, NVIDIA H100 host, ``cuda_decoders`` with 14 lanes (the
120default) and 32 decoding threads per rank, 300 measured steps per run:
121
122.. code-block:: text
123
124 placement samples/s % of model-only step, data ready CPU %
125 trainer process 567 ± 15 41% 174 ms 20.3
126 trainer process, frame selection 690 ± 2 49% 115 ms 14.4
127 loader subprocess 689 ± 24 49% 150 ms 24.8
128 loader subprocess, frame selection 719 ± 13 51% 141 ms 13.4
129
130Both options, alone or together, reach about half of model-only, against 41%
131in the trainer process and 24% with CPU decoding. The rest of the gap is the
132hardware: at 14 lanes (the default) the NVDEC engines are about 90% busy, as
133each sample decodes about 145 frames. Fewer lanes leave the engines idle (33-35%
134of model-only with 7), and more lanes add conversion work on the GPU without
135adding decoding (40-46% with 21-28).
136
137**Measurement scopes**
138
139- ``samples_per_s``: training samples per second over the measured steps (all
140 ranks); ``step_time_ms`` the mean step; ``data_wait_fraction`` the fraction of
141 each step spent waiting for the next batch (mean over ranks, and the rank
142 that waited most).
143- ``sys``: sampled once per second on the host of local rank 0: GPU and NVDEC
144 utilization (NVML) or GPU busy (amdgpu sysfs), GPU memory, host CPU, the
145 container's CPU (cgroup ``cpu.stat``), and the CPU time and memory of the
146 trainer processes and of their descendants (the loader subprocesses).
147- ``stages``: SPDL pipeline statistics of every rank within the measured window
148 (average task time and output queue occupancy per stage).
149- ``loss``: the first steps' loss, to check that every arm trains on the same
150 input.
151- ``--profile`` traces 30 steps of rank 0 with :py:mod:`torch.profiler` and
152 reports where the step's time goes on the GPU and on the training thread.
153
154**Notes**
155
156- Keep the loader subprocesses free of libraries that install a global FFmpeg
157 log callback which takes the GIL (``--block-pyav`` makes PyAV unimportable;
158 ``torchvision`` imports it when available). With such a callback, SPDL's
159 demuxing and decoding threads queue on the GIL and stop scaling.
160- Ranks launched without ``torchrun`` need ``OMP_NUM_THREADS=1``.
161
162**Example**
163
164.. code-block:: shell
165
166 $ torchrun --nproc-per-node 8 benchmark_video_training.py \\
167 --manifest kinetics400.csv --model videomae --arm nvdec \\
168 --decode-threads 28 --output results.jsonl
169 $ python benchmark_video_training_plot.py \\
170 --input "H100=results.jsonl" --output plots/
171
172The manifest is a CSV file with the columns ``path`` and ``label``, and
173optionally ``fps``, ``duration_s``, ``width`` and ``height`` (otherwise probed
174from the files).
175"""
176
177from __future__ import annotations
178
179__all__ = [
180 "BenchmarkConfig",
181 "Clip",
182 "Loader",
183 "build_loader",
184 "build_model",
185 "crop_trace",
186 "load_clips",
187 "main",
188 "parse_args",
189 "run",
190]
191
192import argparse
193import contextlib
194import csv
195import ctypes
196import dataclasses
197import gc
198import glob
199import json
200import logging
201import multiprocessing
202import os
203import random
204import re
205import statistics
206import sys
207import tempfile
208import threading
209import time
210from collections import defaultdict
211from collections.abc import Callable, Iterator, Sequence
212from concurrent.futures import ThreadPoolExecutor
213from dataclasses import asdict, dataclass
214from datetime import datetime, timedelta
215from functools import partial
216from typing import Any
217
218import spdl.io
219import spdl.pipeline
220import spdl.source.utils
221import torch
222import torch.distributed as dist
223import torch.nn.functional as F
224from spdl.pipeline import PipelineBuilder
225from spdl.source import DistributedRandomSampler
226from torch.nn.parallel import DistributedDataParallel as DDP
227
228_LG: logging.Logger = logging.getLogger(__name__)
229
230ARMS: tuple[str, ...] = ("synthetic", "cpu", "nvdec", "cuda_decoders")
231"""The data-loading arms."""
232
233RECIPES: dict[str, dict[str, Any]] = {
234 "r3d18": {
235 "num_frames": 16,
236 "height": 112,
237 "width": 112,
238 "frame_stride": 0,
239 "span_frames": 0,
240 "short_side": 0,
241 "batch_size": 16,
242 "lr": 1e-3,
243 "weight_decay": 0.01,
244 },
245 "videomae": {
246 "num_frames": 16,
247 "height": 224,
248 "width": 224,
249 "frame_stride": 4,
250 "span_frames": 64,
251 "short_side": 256,
252 "batch_size": 16,
253 "lr": 1e-4,
254 "weight_decay": 0.05,
255 },
256}
257"""Input recipe and optimizer of each model.
258
259``frame_stride`` 0 spreads the frames evenly over the first 0.5 s; otherwise
260every ``frame_stride``-th frame of a ``span_frames`` window from a random start.
261``short_side`` 0 resizes to the output size; otherwise the short side is resized
262to it before the center crop."""
263
264# BT.709 limited range to full range RGB, as SPDL's NVDEC kernels. Rows: R, G,
265# B; columns: Y-16, U-128, V-128.
266_BT709 = (
267 (1.1644, 0.0, 1.8337),
268 (1.1644, -0.2181, -0.5451),
269 (1.1644, 2.1606, 0.0),
270)
271_CPU_FILTER = (
272 "{src},scale=w={w}:h={h}:flags=bilinear:in_color_matrix=bt709:in_range=tv:"
273 "out_range=pc,crop=w={cw}:h={ch},format=pix_fmts=rgb24,buffersink"
274)
275_IMAGENET_MEAN = (0.485, 0.456, 0.406)
276_IMAGENET_STD = (0.229, 0.224, 0.225)
277_STEP_ANNOTATION = "benchmark_train_step"
278_POST_ANNOTATION = "benchmark_decode_post"
279
280Batch = dict[str, Any]
281
282
283@dataclass(frozen=True)
284class Clip:
285 """Clip()
286
287 One training sample: a video file, its label, and the part of it to use."""
288
289 path: str
290 """Path of the video file."""
291 label: int
292 """Class index."""
293 start: float = 0.0
294 """Start of the decoded time window [s]."""
295 end: float = 0.5
296 """End of the decoded time window [s]."""
297 resize: tuple[int, int] | None = None
298 """``(height, width)`` before the center crop; ``None`` resizes to the
299 output size."""
300
301
302@dataclass(frozen=True)
303class BenchmarkConfig:
304 """BenchmarkConfig()
305
306 Configuration of one run (one arm)."""
307
308 arm: str = "cpu"
309 """One of :py:data:`ARMS`."""
310 model: str = "videomae"
311 """``"videomae"`` or ``"r3d18"`` (see :py:data:`RECIPES`)."""
312 batch_size: int = 16
313 """Per GPU."""
314 num_frames: int = 16
315 height: int = 224
316 width: int = 224
317 frame_stride: int = 4
318 num_classes: int = 400
319 lr: float = 1e-4
320 weight_decay: float = 0.05
321 max_grad_norm: float = 1.0
322 warmup_steps: int = 100
323 measure_steps: int = 600
324 loss_steps: int = 300
325 """The first steps whose loss is reported."""
326 num_fetch_threads: int = 8
327 num_demux_threads: int = 3
328 num_decode_threads: int = 32
329 """``cpu``: decode concurrency in the loader subprocess; GPU arms:
330 concurrency of the decode stage."""
331 num_lanes: int | None = None
332 """``cuda_decoders``: lanes (``None``: the default)."""
333 frames_in_flight: int = 2
334 gpu_decoder_mode: str = "thread"
335 """``"thread"`` (blocking calls in a thread pool) or ``"async"``."""
336 gpu_pix_fmt: str = "rgb"
337 """``cuda_decoders`` output: ``"rgb"`` or ``"nv12"``."""
338 gpu_select_frames: bool = False
339 """``cuda_decoders``: pass the sampled frame indices to
340 the decoder, so that it outputs only those frames (needs a ``decode`` that
341 accepts ``frame_indices``)."""
342 gpu_decode_in_subprocess: bool = False
343 """``cuda_decoders``: decode and post-process in the
344 loader subprocess (on the rank's GPU) instead of the trainer process; the
345 clips are handed to the trainer with CUDA IPC."""
346 block_pyav: bool = True
347 """Make PyAV unimportable in the trainer and loader processes."""
348 train_on_synthetic: bool = False
349 """Diagnostic: load batches as usual, but train on one fixed batch."""
350 profile: bool = False
351 """Trace 30 steps of rank 0 with the PyTorch profiler."""
352 decoder_gpu_offset: int = 0
353 """Diagnostic: run the GPU decoders on GPU ``(rank + offset) % n``."""
354 drop_outputs: bool = False
355 """Diagnostic: drop the decoded frames (no post-processing)."""
356 post_only: bool = False
357 """Diagnostic: post-process a synthetic decoded clip, without decoding."""
358 decoder_process: bool = False
359 """Diagnostic: decode in a separate process on the rank's GPU (dropping the
360 frames) while the trainer trains on a fixed batch."""
361 cuda_max_connections: int = 0
362 """Set ``CUDA_DEVICE_MAX_CONNECTIONS`` (0: CUDA's default)."""
363 report_stats_interval: float = 20.0
364 seed: int = 0
365 tag: str = ""
366 """Free text, reported with the results (e.g. the build)."""
367 output: str = ""
368 """JSON lines file the result is appended to (rank 0)."""
369 log_dir: str = ""
370 """Directory of the per-rank logs (default: a temporary directory)."""
371
372
373# ---------------------------------------------------------------------------
374# Clips
375# ---------------------------------------------------------------------------
376
377
378def _even(x: float) -> int:
379 return max(2, int(round(x / 2)) * 2)
380
381
382def _probe(path: str) -> dict[str, str]:
383 packets = spdl.io.demux_video(path)
384 codec = packets.codec
385 ts = packets.get_timestamps()
386 num, den = codec.frame_rate if codec is not None else (30, 1)
387 return {
388 "fps": str(num / den),
389 "duration_s": str(max(ts) if ts else 0.0),
390 "width": str(codec.width if codec is not None else 0),
391 "height": str(codec.height if codec is not None else 0),
392 }
393
394
395def load_clips(
396 manifest: str, model: str, data_dir: str = "", seed: int = 0
397) -> tuple[list[Clip], int]:
398 """Read a manifest and assign each clip its window and resize.
399
400 Args:
401 manifest: CSV file with the columns ``path`` and ``label``, and
402 optionally ``fps``, ``duration_s``, ``width`` and ``height``
403 (otherwise probed from the files).
404 model: The model whose input recipe applies (:py:data:`RECIPES`).
405 data_dir: Directory relative paths are resolved against (default: the
406 manifest's directory).
407 seed: Seed of the window starts. Every rank and every arm gets the same
408 windows.
409
410 Returns:
411 The clips and the number of classes.
412 """
413 recipe = RECIPES[model]
414 with open(manifest, newline="") as f:
415 rows = list(csv.DictReader(f))
416 base = data_dir or os.path.dirname(os.path.abspath(manifest))
417 for r in rows:
418 r["path"] = os.path.join(base, r["path"])
419 missing = [
420 r
421 for r in rows
422 if not all(r.get(k) for k in ("fps", "duration_s", "width", "height"))
423 ]
424 if missing and (recipe["span_frames"] or recipe["short_side"]):
425 with ThreadPoolExecutor(32) as pool:
426 for r, info in zip(
427 missing, pool.map(_probe, [r["path"] for r in missing]), strict=True
428 ):
429 r.update(info)
430 labels = sorted({r["label"] for r in rows})
431 index = {label: i for i, label in enumerate(labels)}
432 rng = random.Random(seed)
433 clips = []
434 for r in rows:
435 start, end, resize = 0.0, 0.5, None
436 if span := recipe["span_frames"]:
437 length = span / (float(r["fps"]) or 30.0)
438 start = rng.random() * max(float(r["duration_s"]) - length, 0.0)
439 end = start + length
440 if short := recipe["short_side"]:
441 w, h = int(r["width"]), int(r["height"])
442 scale = short / min(w, h)
443 resize = (_even(h * scale), _even(w * scale))
444 clips.append(Clip(r["path"], index[r["label"]], start, end, resize))
445 return clips, len(labels)
446
447
448# ---------------------------------------------------------------------------
449# Preprocessing shared by the arms
450# ---------------------------------------------------------------------------
451
452
453def _frame_indices(num_decoded: int, num_frames: int, stride: int) -> list[int]:
454 if stride > 0:
455 return [min(i * stride, num_decoded - 1) for i in range(num_frames)]
456 if num_decoded >= num_frames:
457 return torch.linspace(0, num_decoded - 1, num_frames).long().tolist()
458 return list(range(num_decoded)) + [num_decoded - 1] * (num_frames - num_decoded)
459
460
461def _resize_size(clip: Clip, cfg: BenchmarkConfig) -> tuple[int, int]:
462 return clip.resize or (cfg.height, cfg.width)
463
464
465def _crop_box(clip: Clip, cfg: BenchmarkConfig) -> tuple[int, int]:
466 h, w = _resize_size(clip, cfg)
467 return (h - cfg.height) // 2, (w - cfg.width) // 2
468
469
470def _select(
471 frames: torch.Tensor, cfg: BenchmarkConfig, idx: list[int] | None = None
472) -> torch.Tensor:
473 # Stacked from views: no host-to-device copy of an index tensor, which
474 # would block the calling thread.
475 if idx is None:
476 idx = _frame_indices(len(frames), cfg.num_frames, cfg.frame_stride)
477 return torch.stack([frames[i] for i in idx])
478
479
480def _finish_rgb(
481 frames: torch.Tensor, cfg: BenchmarkConfig, clip: Clip, idx: list[int] | None = None
482) -> torch.Tensor:
483 """[T, 3, H, W] uint8 -> [3, num_frames, h, w] float in [0, 1]."""
484 x = _select(frames, cfg, idx).float()
485 size = _resize_size(clip, cfg)
486 if x.shape[-2:] != size:
487 x = F.interpolate(x, size=size, mode="bilinear", antialias=True)
488 x = x.round_().clamp_(0, 255)
489 top, left = _crop_box(clip, cfg)
490 x = x[..., top : top + cfg.height, left : left + cfg.width]
491 return x.permute(1, 0, 2, 3).div_(255.0)
492
493
494def _finish_nv12(
495 frames: torch.Tensor, cfg: BenchmarkConfig, clip: Clip, idx: list[int] | None = None
496) -> torch.Tensor:
497 """[T, H*3/2, W] NV12 (uint8) or P016 (uint16) -> [3, num_frames, h, w]
498 float in [0, 1]: resize the planes, crop, then convert (BT.709)."""
499 x = _select(frames, cfg, idx)
500 if x.dtype == torch.uint16:
501 x = (x.to(torch.int32) >> 8).to(torch.uint8)
502 t, h3, w = x.shape
503 h = h3 * 2 // 3
504 size = _resize_size(clip, cfg)
505 top, left = _crop_box(clip, cfg)
506 rows, cols = slice(top, top + cfg.height), slice(left, left + cfg.width)
507 y = x[:, None, :h, :].float()
508 uv = x[:, h:, :].reshape(t, h // 2, w // 2, 2).permute(0, 3, 1, 2).float()
509 y = F.interpolate(y, size=size, mode="bilinear", antialias=True)[:, 0, rows, cols]
510 uv = F.interpolate(uv, size=size, mode="bilinear", antialias=True)[..., rows, cols]
511 y, u, v = y - 16.0, uv[:, 0] - 128.0, uv[:, 1] - 128.0
512 m = _BT709
513 rgb = torch.stack([m[c][0] * y + m[c][1] * u + m[c][2] * v for c in range(3)])
514 return rgb.clamp_(0, 255).round_().div_(255.0)
515
516
517# ---------------------------------------------------------------------------
518# Loader subprocess stages (module-level functions, for pickling)
519# ---------------------------------------------------------------------------
520
521
522def _block_pyav() -> None:
523 sys.modules["av"] = None # type: ignore[assignment]
524
525
526def _init_worker(rank: int, log_path: str, block_pyav: bool) -> None:
527 torch.set_num_threads(1)
528 if block_pyav:
529 _block_pyav()
530 logging.basicConfig(
531 level=logging.INFO,
532 format=f"%(asctime)s [%(levelname).1s] [Rank{rank}/loader] %(name)s: %(message)s",
533 handlers=[logging.FileHandler(log_path)],
534 force=True,
535 )
536
537
538def _fetch(index: int, *, clips: Sequence[Clip]) -> tuple[bytes, Clip]:
539 clip = clips[index]
540 with open(clip.path, "rb") as f:
541 return f.read(), clip
542
543
544def _demux(item: tuple[bytes, Clip], *, bsf: str | None) -> tuple[Any, Clip]:
545 data, clip = item
546 return spdl.io.demux_video(data, timestamp=(clip.start, clip.end), bsf=bsf), clip
547
548
549def _cpu_decode(
550 item: tuple[bytes, Clip], *, cfg: BenchmarkConfig
551) -> tuple[torch.Tensor, int]:
552 data, clip = item
553 packets = spdl.io.demux_video(data, timestamp=(clip.start, clip.end))
554 if (codec := packets.codec) is None:
555 raise ValueError(f"{clip.path}: no video stream")
556 # A pass-through filter keeps the frames' timestamps for the time window.
557 frames = spdl.io.decode_packets(packets, filter_desc="null")
558 frames = frames[_frame_indices(len(frames), cfg.num_frames, cfg.frame_stride)]
559 h, w = _resize_size(clip, cfg)
560 graph = spdl.io.FilterGraph(
561 _CPU_FILTER.format(
562 src=spdl.io.get_buffer_desc(codec), w=w, h=h, cw=cfg.width, ch=cfg.height
563 )
564 )
565 graph.add_frames(frames)
566 graph.flush()
567 if (out := graph.get_frames()) is None:
568 raise ValueError(f"{clip.path}: no frames in the window")
569 hwc = spdl.io.to_torch(spdl.io.convert_frames(out)) # [T, h, w, 3]
570 return hwc.permute(3, 0, 1, 2).contiguous(), clip.label
571
572
573# ---------------------------------------------------------------------------
574# Trainer-process stages
575# ---------------------------------------------------------------------------
576
577
578class _NvdecDecode:
579 def __init__(self, cfg: BenchmarkConfig, device: torch.device) -> None:
580 self.cfg = cfg
581 self.device = device
582 self.cuda_cfg = spdl.io.cuda_config(
583 device_index=device.index or 0,
584 allocator=(
585 torch.cuda.caching_allocator_alloc,
586 torch.cuda.caching_allocator_delete,
587 ),
588 )
589
590 def __call__(self, item: tuple[Any, Clip]) -> dict[str, torch.Tensor]:
591 packets, clip = item
592 h, w = _resize_size(clip, self.cfg)
593 buffer = spdl.io.decode_packets_nvdec(
594 packets,
595 device_config=self.cuda_cfg,
596 scale_width=w,
597 scale_height=h,
598 pix_fmt="rgb",
599 )
600 frames = spdl.io.to_torch(buffer) # [T, 3, h, w]
601 cfg = self.cfg
602 idx = torch.tensor(
603 _frame_indices(len(frames), cfg.num_frames, cfg.frame_stride)
604 )
605 top, left = _crop_box(clip, cfg)
606 frames = frames[idx][..., top : top + cfg.height, left : left + cfg.width]
607 return {
608 "video": frames.permute(1, 0, 2, 3).float() / 255.0,
609 "label": torch.tensor(clip.label, dtype=torch.long, device=self.device),
610 }
611
612
613class _GpuDecoders:
614 """One ``CudaDecoders`` per GPU, shared by the decode
615 stage's concurrent tasks; outputs are post-processed on a side stream."""
616
617 def __init__(self, cfg: BenchmarkConfig, device: torch.device) -> None:
618 self.cfg = cfg
619 self.train_device = device
620 if cfg.decoder_gpu_offset:
621 n = torch.cuda.device_count()
622 device = torch.device(
623 f"cuda:{((device.index or 0) + cfg.decoder_gpu_offset) % n}"
624 )
625 self.device = device
626 self.side_stream = torch.cuda.Stream(device)
627 self.decoders: Any = None
628 self._fake: torch.Tensor | None = None
629 self._kwargs: dict[str, Any] = {}
630 self._finish: Callable[..., torch.Tensor] = _finish_nv12
631 if cfg.post_only:
632 # A decoded clip of a typical size: 64 RGB frames of 480x360.
633 self._fake = torch.randint(
634 0, 256, (64, 3, 360, 480), dtype=torch.uint8, device=device
635 )
636 self._finish = _finish_rgb
637 return
638 stream = self.side_stream.cuda_stream
639 allocator = (
640 torch.cuda.caching_allocator_alloc,
641 torch.cuda.caching_allocator_delete,
642 )
643 dev_cfg = spdl.io.cuda_config(
644 device_index=device.index or 0, stream=stream, allocator=allocator
645 )
646 decoders = spdl.io.cuda_decoders(
647 dev_cfg, frames_in_flight=cfg.frames_in_flight, num_lanes=cfg.num_lanes
648 )
649 self._kwargs = {"pix_fmt": cfg.gpu_pix_fmt}
650 if cfg.gpu_pix_fmt == "rgb":
651 self._finish = _finish_rgb
652 decoders.__enter__()
653 self.decoders = decoders
654
655 def _selection(
656 self, packets: Any, clip: Clip
657 ) -> tuple[dict[str, Any], list[int] | None]:
658 """With ``gpu_select_frames``, the frames the decoder outputs and their
659 positions in the clip."""
660 if not self.cfg.gpu_select_frames:
661 return self._kwargs, None
662 start, end = clip.start, clip.end
663 n = sum(start <= t < end for t in packets.get_timestamps())
664 idx = _frame_indices(max(n, 1), self.cfg.num_frames, self.cfg.frame_stride)
665 unique = sorted(set(idx))
666 pos = {i: p for p, i in enumerate(unique)}
667 return {**self._kwargs, "frame_indices": unique}, [pos[i] for i in idx]
668
669 def _output(
670 self, frames: Any, clip: Clip, idx: list[int] | None = None
671 ) -> tuple[torch.Tensor, int]:
672 if self.cfg.drop_outputs:
673 return torch.zeros(0, device=self.train_device), clip.label
674 with torch.cuda.device(self.device), torch.cuda.stream(self.side_stream):
675 with torch.profiler.record_function(_POST_ANNOTATION):
676 if not isinstance(frames, torch.Tensor):
677 frames = torch.from_dlpack(frames)
678 video = self._finish(frames, self.cfg, clip, idx)
679 if self.device != self.train_device:
680 # Diagnostic path (``decoder_gpu_offset``): the copy runs on
681 # ``side_stream`` and is finished before the clip is returned,
682 # so the collate stream can read it.
683 self.side_stream.synchronize()
684 video = video.to(self.train_device)
685 self.side_stream.synchronize()
686 return video, clip.label
687
688 async def decode_async(self, item: tuple[Any, Clip]) -> tuple[torch.Tensor, int]:
689 packets, clip = item
690 if self._fake is not None:
691 return self._output(self._fake, clip)
692 kwargs, idx = self._selection(packets, clip)
693 return self._output(
694 await self.decoders.decode_async(packets, **kwargs), clip, idx
695 )
696
697 def decode(self, item: tuple[Any, Clip]) -> tuple[torch.Tensor, int]:
698 packets, clip = item
699 if self._fake is not None:
700 return self._output(self._fake, clip)
701 kwargs, idx = self._selection(packets, clip)
702 return self._output(self.decoders.decode(packets, **kwargs), clip, idx)
703
704 def stats(self) -> dict[str, int]:
705 if self.decoders is None:
706 return {}
707 s = self.decoders.stats()
708 if isinstance(s, dict):
709 return dict(s)
710 # `spdl.io.DecodersStats` exposes the counters as attributes.
711 return {k: getattr(s, k) for k in dir(s) if not k.startswith("_")}
712
713 def close(self) -> None:
714 if self.decoders is not None:
715 self.decoders.shutdown(wait=False)
716
717
718_SUBPROCESS_INIT = threading.Lock()
719
720
721class _SubprocessDecode:
722 """The GPU decode stage of the loader subprocess (created on first use)."""
723
724 def __init__(self, cfg: BenchmarkConfig, device_index: int) -> None:
725 self.cfg = cfg
726 self.device_index = device_index
727 self.gpu: _GpuDecoders | None = None
728
729 def __call__(self, item: tuple[Any, Clip]) -> tuple[torch.Tensor, int]:
730 if self.gpu is None:
731 with _SUBPROCESS_INIT:
732 if self.gpu is None:
733 torch.cuda.set_device(self.device_index)
734 self.gpu = _GpuDecoders(
735 self.cfg, torch.device(f"cuda:{self.device_index}")
736 )
737 video, label = self.gpu.decode(item)
738 # CUDA IPC orders the receiver after the sender's current stream when
739 # the clip is pickled, not after the side stream: finish it here.
740 self.gpu.side_stream.synchronize()
741 return video, label
742
743
744def _collate_ipc(
745 items: list[tuple[torch.Tensor, int]],
746 *,
747 device: torch.device,
748 stream: torch.cuda.Stream,
749) -> Batch:
750 """Batch clips received with CUDA IPC (ordered on the default stream when
751 unpickled), and wait for the copy before the clips are released."""
752 label = torch.tensor([lbl for _, lbl in items], dtype=torch.long).pin_memory()
753 stream.wait_stream(torch.cuda.default_stream(device))
754 with torch.cuda.stream(stream):
755 batch: Batch = {
756 "video": torch.stack([v for v, _ in items]),
757 "label": label.to(device, non_blocking=True),
758 }
759 stream.synchronize()
760 return batch
761
762
763def _collate(items: list[dict[str, torch.Tensor]]) -> Batch:
764 return {
765 "video": torch.stack([it["video"] for it in items]),
766 "label": torch.stack([it["label"] for it in items]),
767 }
768
769
770def _collate_on_stream(
771 items: list[tuple[torch.Tensor, int]],
772 *,
773 device: torch.device,
774 stream: torch.cuda.Stream,
775 to_device: bool,
776) -> Batch:
777 """Batch on ``stream``; the batch carries the event to wait for."""
778 label = torch.tensor([lbl for _, lbl in items], dtype=torch.long).pin_memory()
779 with torch.cuda.stream(stream):
780 # GPU clips were made on ``stream``, or finished before they were
781 # returned. Their memory must not be reused before the stack runs.
782 for v, _ in items:
783 if v.is_cuda:
784 v.record_stream(stream)
785 video = torch.stack([v for v, _ in items])
786 if to_device:
787 video = video.pin_memory().to(device, non_blocking=True).float().div_(255.0)
788 batch: Batch = {"video": video, "label": label.to(device, non_blocking=True)}
789 ready = torch.cuda.Event()
790 ready.record(stream)
791 batch["ready"] = ready
792 return batch
793
794
795# ---------------------------------------------------------------------------
796# Loader
797# ---------------------------------------------------------------------------
798
799
800@dataclass
801class Loader:
802 """Loader()
803
804 The batches of one rank, and what to report and close."""
805
806 iterator: Iterator[Batch]
807 """Batches, across epochs."""
808 pipeline: Any = None
809 gpu_decoders: Any = None
810 decoder_process: Any = None
811
812 def stats(self) -> dict[str, int] | None:
813 """Counters of the GPU decoders, if any."""
814 if self.decoder_process is not None:
815 _, count, _, started = self.decoder_process
816 elapsed = time.time() - started.value
817 return {
818 "clips": count.value,
819 "clips_per_s_x1000": int(1000 * count.value / elapsed)
820 if started.value
821 else 0,
822 }
823 return self.gpu_decoders.stats() if self.gpu_decoders else None
824
825 def close(self) -> None:
826 """Stop the pipeline and the decoders."""
827 if self.pipeline is not None:
828 # Stopping also waits for the loader subprocess to exit, which can
829 # take more than 30 seconds before it is terminated.
830 self.pipeline.stop(timeout=60)
831 if self.gpu_decoders is not None:
832 self.gpu_decoders.close()
833 if self.decoder_process is not None:
834 proc, _, stop, _ = self.decoder_process
835 stop.set()
836 proc.join(30)
837 if proc.is_alive():
838 proc.kill()
839
840
841def _synthetic(cfg: BenchmarkConfig, device: torch.device) -> Iterator[Batch]:
842 gen = torch.Generator(device=device).manual_seed(cfg.seed)
843 shape = (cfg.batch_size, 3, cfg.num_frames, cfg.height, cfg.width)
844 batch = {
845 "video": torch.rand(shape, device=device, generator=gen),
846 "label": torch.randint(
847 0, cfg.num_classes, (cfg.batch_size,), device=device, generator=gen
848 ),
849 }
850 while True:
851 yield batch
852
853
854def _epochs(pipeline: Any) -> Iterator[Batch]:
855 while True:
856 yield from pipeline.get_iterator(timeout=600)
857
858
859def _decode_process(
860 cfg: BenchmarkConfig,
861 clips: Sequence[Clip],
862 rank: int,
863 world_size: int,
864 device_index: int,
865 count: Any,
866 stop: Any,
867 started: Any,
868) -> None:
869 """Diagnostic: fetch, demux and decode with ``CudaDecoders`` on
870 the rank's GPU, dropping the frames, until ``stop`` is set. ``rank`` is the
871 global rank, which selects the shard of clips."""
872 torch.set_num_threads(1)
873 device = torch.device(f"cuda:{device_index}")
874 torch.cuda.set_device(device)
875 cfg = dataclasses.replace(cfg, drop_outputs=True)
876 gpu = _GpuDecoders(cfg, device)
877 source = spdl.source.utils.embed_shuffle(
878 DistributedRandomSampler(len(clips), rank=rank, world_size=world_size)
879 )
880 pipeline = (
881 PipelineBuilder()
882 .add_source(source, continuous=True)
883 .pipe(partial(_fetch, clips=clips), concurrency=cfg.num_fetch_threads)
884 .pipe(
885 partial(_demux, bsf="h264_mp4toannexb"), concurrency=cfg.num_demux_threads
886 )
887 .pipe(
888 gpu.decode,
889 concurrency=cfg.num_decode_threads,
890 executor=ThreadPoolExecutor(max_workers=cfg.num_decode_threads),
891 )
892 .add_sink(buffer_size=8)
893 .build(num_threads=4)
894 )
895 with pipeline.auto_stop():
896 while not stop.is_set():
897 for _ in pipeline.get_iterator(timeout=600):
898 if not started.value:
899 started.value = time.time()
900 count.value += 1
901 if stop.is_set():
902 break
903 gpu.close()
904
905
906def build_loader(
907 cfg: BenchmarkConfig,
908 clips: Sequence[Clip],
909 *,
910 rank: int,
911 world_size: int,
912 device: torch.device,
913 log_path: str,
914) -> Loader:
915 """Build the data loader of one rank for ``cfg.arm``.
916
917 Args:
918 cfg: The run's configuration.
919 clips: All clips; each rank reads its shard
920 (:py:class:`~spdl.source.DistributedRandomSampler`).
921 rank, world_size: The rank and the number of ranks.
922 device: The rank's GPU.
923 log_path: The log file of the loader subprocess (stage statistics).
924 """
925 if cfg.arm == "synthetic":
926 return Loader(_synthetic(cfg, device))
927 if cfg.decoder_process:
928 ctx = multiprocessing.get_context("spawn")
929 count, stop, started = ctx.Value("q", 0), ctx.Event(), ctx.Value("d", 0.0)
930 proc = ctx.Process(
931 target=_decode_process,
932 args=(
933 cfg,
934 clips,
935 rank,
936 world_size,
937 device.index or 0,
938 count,
939 stop,
940 started,
941 ),
942 daemon=True,
943 )
944 proc.start()
945 return Loader(
946 _synthetic(cfg, device), decoder_process=(proc, count, stop, started)
947 )
948 source = spdl.source.utils.embed_shuffle(
949 DistributedRandomSampler(len(clips), rank=rank, world_size=world_size)
950 )
951 backend = (
952 PipelineBuilder()
953 .add_source(source, continuous=True)
954 .pipe(
955 partial(_fetch, clips=clips),
956 concurrency=cfg.num_fetch_threads,
957 output_order="input",
958 name="fetch",
959 )
960 )
961 if cfg.arm == "cpu":
962 backend = backend.pipe(
963 partial(_cpu_decode, cfg=cfg),
964 concurrency=cfg.num_decode_threads,
965 output_order="input",
966 name="cpu_decode",
967 ).add_sink(buffer_size=cfg.batch_size * 2)
968 threads = max(cfg.num_fetch_threads, cfg.num_decode_threads)
969 else:
970 bsf = None if cfg.arm == "nvdec" else "h264_mp4toannexb"
971 backend = backend.pipe(
972 partial(_demux, bsf=bsf),
973 concurrency=cfg.num_demux_threads,
974 output_order="input",
975 name="demux",
976 )
977 threads = max(cfg.num_fetch_threads, cfg.num_demux_threads)
978 if cfg.gpu_decode_in_subprocess and cfg.arm == "cuda_decoders":
979 backend = backend.pipe(
980 _SubprocessDecode(cfg, device.index or 0),
981 concurrency=cfg.num_decode_threads,
982 output_order="input",
983 name=f"{cfg.arm}_decode",
984 )
985 threads = (
986 cfg.num_fetch_threads + cfg.num_demux_threads + cfg.num_decode_threads
987 )
988 backend = backend.add_sink(
989 buffer_size=cfg.batch_size if cfg.gpu_decode_in_subprocess else 3
990 )
991 src = spdl.pipeline.run_pipeline_in_subprocess(
992 backend.get_config(),
993 num_threads=threads,
994 mp_context="forkserver",
995 report_stats_interval=cfg.report_stats_interval,
996 initializer=partial(_init_worker, rank, log_path, cfg.block_pyav),
997 )
998 frontend = PipelineBuilder().add_source(src, continuous=True)
999 gpu = None
1000 if cfg.arm == "cpu":
1001 frontend = frontend.aggregate(cfg.batch_size, drop_last=True).pipe(
1002 partial(
1003 _collate_on_stream,
1004 device=device,
1005 stream=torch.cuda.Stream(device),
1006 to_device=True,
1007 ),
1008 name="collate_h2d",
1009 )
1010 elif cfg.arm == "nvdec":
1011 frontend = (
1012 frontend.pipe(
1013 _NvdecDecode(cfg, device),
1014 concurrency=cfg.num_decode_threads,
1015 executor=ThreadPoolExecutor(max_workers=cfg.num_decode_threads),
1016 output_order="input",
1017 name="nvdec_decode",
1018 )
1019 .aggregate(cfg.batch_size, drop_last=True)
1020 .pipe(_collate, name="collate")
1021 )
1022 elif cfg.gpu_decode_in_subprocess:
1023 frontend = frontend.aggregate(cfg.batch_size, drop_last=True).pipe(
1024 partial(_collate_ipc, device=device, stream=torch.cuda.Stream(device)),
1025 name="collate",
1026 )
1027 else:
1028 gpu = _GpuDecoders(cfg, device)
1029 if cfg.gpu_decoder_mode == "async":
1030 frontend = frontend.pipe(
1031 gpu.decode_async,
1032 concurrency=cfg.num_decode_threads,
1033 output_order="input",
1034 name=f"{cfg.arm}_decode",
1035 )
1036 else:
1037 frontend = frontend.pipe(
1038 gpu.decode,
1039 concurrency=cfg.num_decode_threads,
1040 executor=ThreadPoolExecutor(max_workers=cfg.num_decode_threads),
1041 output_order="input",
1042 name=f"{cfg.arm}_decode",
1043 )
1044 stream = gpu.side_stream if gpu.device == device else torch.cuda.Stream(device)
1045 frontend = frontend.aggregate(cfg.batch_size, drop_last=True).pipe(
1046 partial(_collate_on_stream, device=device, stream=stream, to_device=False),
1047 name="collate",
1048 )
1049 pipeline = frontend.add_sink(buffer_size=5).build(
1050 num_threads=2, report_stats_interval=cfg.report_stats_interval
1051 )
1052 return Loader(_epochs(pipeline), pipeline, gpu)
1053
1054
1055# ---------------------------------------------------------------------------
1056# Models
1057# ---------------------------------------------------------------------------
1058
1059
1060class _VideoMAE(torch.nn.Module):
1061 def __init__(self, num_classes: int) -> None:
1062 super().__init__()
1063 # Optional dependency, imported only for this model.
1064 from transformers import VideoMAEConfig, VideoMAEForVideoClassification
1065
1066 config = VideoMAEConfig(
1067 image_size=224,
1068 patch_size=16,
1069 num_channels=3,
1070 num_frames=16,
1071 tubelet_size=2,
1072 hidden_size=768,
1073 num_hidden_layers=12,
1074 num_attention_heads=12,
1075 intermediate_size=3072,
1076 qkv_bias=True,
1077 use_mean_pooling=True,
1078 num_labels=num_classes,
1079 attn_implementation="sdpa",
1080 )
1081 self.model = VideoMAEForVideoClassification(config)
1082 self.register_buffer(
1083 "mean", torch.tensor(_IMAGENET_MEAN).view(1, 3, 1, 1, 1), persistent=False
1084 )
1085 self.register_buffer(
1086 "std", torch.tensor(_IMAGENET_STD).view(1, 3, 1, 1, 1), persistent=False
1087 )
1088
1089 def forward(self, video: torch.Tensor) -> torch.Tensor:
1090 x = ((video - self.mean) / self.std).permute(0, 2, 1, 3, 4) # [B, T, 3, H, W]
1091 return self.model(pixel_values=x).logits
1092
1093
1094def build_model(name: str, num_classes: int) -> torch.nn.Module:
1095 """The model: ``"videomae"`` (VideoMAE ViT-B/16, randomly initialized, SDPA
1096 attention; needs ``transformers``) or ``"r3d18"`` (needs ``torchvision``).
1097
1098 Imported lazily: the loader subprocesses import the main module, and the
1099 model libraries must not be loaded there."""
1100 if name == "videomae":
1101 return _VideoMAE(num_classes)
1102 from torchvision.models.video import r3d_18
1103
1104 return r3d_18(num_classes=num_classes)
1105
1106
1107# ---------------------------------------------------------------------------
1108# Host sampling (local rank 0)
1109# ---------------------------------------------------------------------------
1110
1111_CLK_TCK: int = os.sysconf("SC_CLK_TCK")
1112_PAGE: int = os.sysconf("SC_PAGE_SIZE")
1113
1114
1115def _read(path: str) -> str | None:
1116 try:
1117 with open(path) as f:
1118 return f.read()
1119 except OSError:
1120 return None
1121
1122
1123class _Nvml:
1124 def __init__(self) -> None:
1125 self.lib = ctypes.CDLL("libnvidia-ml.so.1")
1126 if self.lib.nvmlInit_v2() != 0:
1127 raise RuntimeError("nvmlInit failed")
1128 count = ctypes.c_uint()
1129 self.lib.nvmlDeviceGetCount_v2(ctypes.byref(count))
1130 self.handles = []
1131 for i in range(count.value):
1132 h = ctypes.c_void_p()
1133 self.lib.nvmlDeviceGetHandleByIndex_v2(i, ctypes.byref(h))
1134 self.handles.append(h)
1135
1136 def sample(self) -> list[tuple[float, float, float]]:
1137 out = []
1138 for h in self.handles:
1139 util = (ctypes.c_uint * 2)()
1140 mem = (ctypes.c_ulonglong * 3)()
1141 dec, period = ctypes.c_uint(), ctypes.c_uint()
1142 self.lib.nvmlDeviceGetUtilizationRates(h, util)
1143 self.lib.nvmlDeviceGetDecoderUtilization(
1144 h, ctypes.byref(dec), ctypes.byref(period)
1145 )
1146 self.lib.nvmlDeviceGetMemoryInfo(h, mem)
1147 out.append((float(util[0]), float(dec.value), mem[2] / 2**20))
1148 return out
1149
1150
1151class _HostSampler:
1152 """Samples the host once per second: GPUs, host and container CPU, and the
1153 CPU time and memory of the trainer processes and their descendants."""
1154
1155 def __init__(self, trainer_pids: Sequence[int]) -> None:
1156 self.trainer_pids = set(trainer_pids)
1157 self.samples: list[dict[str, Any]] = []
1158 self._stop = threading.Event()
1159 self._thread = threading.Thread(target=self._loop, daemon=True)
1160 cg = next(
1161 (
1162 line[3:].strip()
1163 for line in (_read("/proc/self/cgroup") or "").splitlines()
1164 if line.startswith("0::")
1165 ),
1166 "",
1167 )
1168 self._cgroup = "/sys/fs/cgroup" + cg
1169 self._amd = sorted(glob.glob("/sys/class/drm/card*/device/gpu_busy_percent"))
1170 self._nvml: _Nvml | None = None
1171 if not self._amd:
1172 try:
1173 self._nvml = _Nvml()
1174 except (OSError, RuntimeError):
1175 _LG.warning("NVML is not available; no GPU samples")
1176
1177 def __enter__(self) -> _HostSampler:
1178 self._thread.start()
1179 return self
1180
1181 def __exit__(self, *_: object) -> None:
1182 self._stop.set()
1183 self._thread.join()
1184
1185 def _loop(self) -> None:
1186 while not self._stop.is_set():
1187 self.samples.append(self._sample())
1188 self._stop.wait(1.0)
1189
1190 def _procs(self) -> tuple[float, float, int, int]:
1191 table: dict[int, tuple[int, float, int]] = {}
1192 for d in os.listdir("/proc"):
1193 if d.isdigit() and (stat := _read(f"/proc/{d}/stat")):
1194 rest = stat[stat.rfind(")") + 2 :].split()
1195 table[int(d)] = (
1196 int(rest[1]),
1197 (int(rest[11]) + int(rest[12])) / _CLK_TCK,
1198 int(rest[21]) * _PAGE,
1199 )
1200 children: dict[int, list[int]] = defaultdict(list)
1201 for pid, (ppid, _, _) in table.items():
1202 children[ppid].append(pid)
1203 t_cpu = l_cpu = 0.0
1204 t_rss = l_rss = 0
1205 stack = [p for p in self.trainer_pids if p in table]
1206 while stack:
1207 pid = stack.pop()
1208 _, cpu, rss = table[pid]
1209 if pid in self.trainer_pids:
1210 t_cpu, t_rss = t_cpu + cpu, t_rss + rss
1211 else:
1212 l_cpu, l_rss = l_cpu + cpu, l_rss + rss
1213 stack.extend(children[pid])
1214 return t_cpu, l_cpu, t_rss, l_rss
1215
1216 def _sample(self) -> dict[str, Any]:
1217 s: dict[str, Any] = {"t": time.time(), "gpu": [], "dec": [], "mem": []}
1218 if self._nvml is not None:
1219 for g, d, m in self._nvml.sample():
1220 s["gpu"].append(g)
1221 s["dec"].append(d)
1222 s["mem"].append(m)
1223 for busy in self._amd:
1224 s["gpu"].append(float((_read(busy) or "nan").strip()))
1225 used = _read(os.path.join(os.path.dirname(busy), "mem_info_vram_used"))
1226 s["mem"].append(int(used) / 2**20 if used else float("nan"))
1227 s["trainer_cpu"], s["loader_cpu"], s["trainer_rss"], s["loader_rss"] = (
1228 self._procs()
1229 )
1230 for line in (_read(os.path.join(self._cgroup, "cpu.stat")) or "").splitlines():
1231 if line.startswith("usage_usec"):
1232 s["cgroup_cpu"] = int(line.split()[1]) / 1e6
1233 if stat := _read("/proc/stat"):
1234 f = [int(x) for x in stat.splitlines()[0].split()[1:]]
1235 s["host_cpu"] = (f[0] + f[1] + f[2] + f[5] + f[6] + f[7]) / _CLK_TCK
1236 if mem := _read(os.path.join(self._cgroup, "memory.current")):
1237 s["cgroup_mem"] = int(mem)
1238 return s
1239
1240 def window(self, t0: float, t1: float) -> dict[str, float | None]:
1241 win = [s for s in self.samples if t0 <= s["t"] <= t1]
1242 if len(win) < 2:
1243 return {}
1244 a, b = win[0], win[-1]
1245 dt = b["t"] - a["t"]
1246 ncpu = os.cpu_count() or 1
1247
1248 def rate(key: str) -> float | None:
1249 return (b[key] - a[key]) / dt if key in a and key in b else None
1250
1251 def mean(key: str) -> float | None:
1252 vals = [statistics.fmean(s[key]) for s in win if s[key]]
1253 return statistics.fmean(vals) if vals else None
1254
1255 host, cgroup = rate("host_cpu"), rate("cgroup_cpu")
1256 return {
1257 "gpu_util_pct": mean("gpu"),
1258 "dec_util_pct": mean("dec"),
1259 "gpu_mem_max_mb": max(
1260 (max(s["mem"]) for s in win if s["mem"]), default=None
1261 ),
1262 "host_cpu_pct": 100 * host / ncpu if host is not None else None,
1263 "cgroup_cpu_pct": 100 * cgroup / ncpu if cgroup is not None else None,
1264 "trainer_cpu_cores": max(rate("trainer_cpu") or 0.0, 0.0),
1265 "loader_cpu_cores": max(rate("loader_cpu") or 0.0, 0.0),
1266 "proc_cpu_pct": 100
1267 * (
1268 max(rate("trainer_cpu") or 0.0, 0.0)
1269 + max(rate("loader_cpu") or 0.0, 0.0)
1270 )
1271 / ncpu,
1272 "outside_cgroup_cores": host - cgroup
1273 if host is not None and cgroup is not None
1274 else None,
1275 "cgroup_mem_max_gb": max((s.get("cgroup_mem", 0) for s in win), default=0)
1276 / 1e9,
1277 "trainer_rss_max_gb": max(s["trainer_rss"] for s in win) / 1e9,
1278 "loader_rss_max_gb": max(s["loader_rss"] for s in win) / 1e9,
1279 }
1280
1281
1282# ---------------------------------------------------------------------------
1283# Pipeline statistics from the per-rank logs
1284# ---------------------------------------------------------------------------
1285
1286_STAT_RE = re.compile(r"^(\S+ \S+) \[I\] \[Rank(\d+)(/loader)?\] \S+: \[(.+?)\]\t(.*)$")
1287
1288
1289def _stage_stats(
1290 paths: Sequence[str], t0: float, t1: float
1291) -> dict[str, dict[str, float]]:
1292 acc: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
1293 for path in paths:
1294 for line in (_read(path) or "").splitlines():
1295 if not (m := _STAT_RE.match(line)):
1296 continue
1297 ts = datetime.strptime(m.group(1), "%Y-%m-%d %H:%M:%S,%f").timestamp()
1298 body = m.group(5)
1299 if not t0 <= ts <= t1:
1300 continue
1301 info = m.group(4).split(":")
1302 name = ("loader " if m.group(3) else "trainer ") + ":".join(
1303 info[1:] if len(info) >= 3 else info
1304 )
1305 times = [
1306 float(v) * (1e-3 if u == "ms" else 1.0)
1307 for v, u in re.findall(r"([\d.]+) \[(ms|sec)\]", body)
1308 ]
1309 if body.startswith("Completed"):
1310 if times:
1311 acc[name]["ave_task_ms"].append(1e3 * times[0])
1312 elif body.startswith("Processed"):
1313 name = name.removesuffix("_queue") + " (queue)"
1314 if occ := re.search(r"Occupancy rate: (\d+)%", body):
1315 acc[name]["occupancy_pct"].append(float(occ.group(1)))
1316 if q := re.search(r"QPS:\s*([\d.]+)", body):
1317 acc[name]["qps"].append(float(q.group(1)))
1318 return {
1319 n: {k: statistics.fmean(v) for k, v in f.items() if v} for n, f in acc.items()
1320 }
1321
1322
1323# ---------------------------------------------------------------------------
1324# Profiling
1325# ---------------------------------------------------------------------------
1326
1327
1328def _union(intervals: list[tuple[float, float]]) -> float:
1329 total, end = 0.0, float("-inf")
1330 for s, e in sorted(intervals):
1331 if s > end:
1332 total, end = total + e - s, e
1333 elif e > end:
1334 total, end = total + e - end, e
1335 return total
1336
1337
1338def _pct(values: list[float], q: float) -> float:
1339 return sorted(values)[min(int(len(values) * q), len(values) - 1)]
1340
1341
1342def _summarize_trace(trace: dict[str, Any]) -> dict[str, Any]:
1343 """Where the profiled steps' time goes (microseconds per step).
1344
1345 The training stream is the one with the most kernels. ``launch`` covers the
1346 kernel launch calls of the training thread and of the other threads; the
1347 longest training-thread launches list the calls other threads were in at
1348 the time."""
1349 events = [e for e in trace.get("traceEvents", []) if e.get("ph") == "X"]
1350 steps = sorted(
1351 (e["ts"], e["ts"] + e["dur"], e["tid"])
1352 for e in events
1353 if e.get("name") == _STEP_ANNOTATION and e.get("cat") == "user_annotation"
1354 )
1355 if not steps:
1356 return {"error": "no step annotations"}
1357 t0, t1, main_tid = steps[0][0], steps[-1][1], steps[0][2]
1358 n = len(steps)
1359
1360 def inside(e: dict[str, Any]) -> bool:
1361 return t0 <= e["ts"] and e["ts"] + e.get("dur", 0) <= t1
1362
1363 def busy(es: list[dict[str, Any]]) -> float:
1364 return _union([(e["ts"], e["ts"] + e["dur"]) for e in es])
1365
1366 gpu_cats = ("kernel", "gpu_memcpy", "gpu_memset")
1367 gpu = [e for e in events if e.get("cat") in gpu_cats and inside(e)]
1368 by_stream: dict[int, list[dict[str, Any]]] = defaultdict(list)
1369 for e in gpu:
1370 by_stream[int(e.get("args", {}).get("stream", -1))].append(e)
1371 if not by_stream:
1372 return {"error": "no GPU activity", "steps": n}
1373
1374 def kernels(es: list[dict[str, Any]]) -> list[dict[str, Any]]:
1375 return [e for e in es if e["cat"] == "kernel"]
1376
1377 train_stream = max(by_stream, key=lambda s: len(kernels(by_stream[s])))
1378 train = sorted(by_stream[train_stream], key=lambda e: e["ts"])
1379 gaps = [
1380 (b["ts"] - a["ts"] - a["dur"], a["ts"] + a["dur"], b["ts"])
1381 for a, b in zip(train, train[1:], strict=False)
1382 if b["ts"] > a["ts"] + a["dur"]
1383 ]
1384 other = [e for s, es in by_stream.items() if s != train_stream for e in es]
1385 streams = {}
1386 for s, es in sorted(by_stream.items(), key=lambda kv: -busy(kv[1])):
1387 names: dict[str, float] = defaultdict(float)
1388 for e in kernels(es):
1389 names[e["name"][:60]] += e["dur"]
1390 streams[str(s)] = {
1391 "kernels_per_step": len(kernels(es)) / n,
1392 "kernel_us": sum(e["dur"] for e in kernels(es)) / n,
1393 "memcpy_us": sum(e["dur"] for e in es if e["cat"] == "gpu_memcpy") / n,
1394 "busy_us": busy(es) / n,
1395 "top_kernels": {
1396 k: v / n for k, v in sorted(names.items(), key=lambda kv: -kv[1])[:3]
1397 },
1398 }
1399 api = [
1400 e
1401 for e in events
1402 if e.get("cat") in ("cuda_runtime", "cuda_driver") and inside(e)
1403 ]
1404 main_api: dict[str, list[float]] = defaultdict(list)
1405 rest_api: dict[str, list[float]] = defaultdict(list)
1406 for e in api:
1407 (main_api if e["tid"] == main_tid else rest_api)[e["name"]].append(e["dur"])
1408
1409 def top(d: dict[str, list[float]]) -> dict[str, dict[str, float]]:
1410 rows = sorted(d.items(), key=lambda kv: -sum(kv[1]))[:8]
1411 return {
1412 k: {
1413 "per_step_us": sum(v) / n,
1414 "calls_per_step": len(v) / n,
1415 "mean_us": statistics.fmean(v),
1416 "p90_us": _pct(v, 0.9),
1417 "max_us": max(v),
1418 }
1419 for k, v in rows
1420 }
1421
1422 launch_names = (
1423 "cudaLaunchKernel",
1424 "hipLaunchKernel",
1425 "cuLaunchKernel",
1426 "cuLaunchKernelEx",
1427 )
1428 main_launch = sorted(
1429 (e for e in api if e["tid"] == main_tid and e["name"] in launch_names),
1430 key=lambda e: -e["dur"],
1431 )
1432 longest = []
1433 for e in main_launch[:5]:
1434 s0, s1 = e["ts"], e["ts"] + e["dur"]
1435 overlap: dict[str, int] = defaultdict(int)
1436 for o in api:
1437 if o["tid"] != main_tid and o["ts"] < s1 and o["ts"] + o["dur"] > s0:
1438 overlap[o["name"]] += 1
1439 longest.append(
1440 {
1441 "name": e["name"],
1442 "us": e["dur"],
1443 "concurrent_calls_in_other_threads": dict(overlap),
1444 }
1445 )
1446 biggest_gaps = []
1447 for g, g0, g1 in sorted(gaps, reverse=True)[:5]:
1448 during: dict[str, float] = defaultdict(float)
1449 for o in other:
1450 lo, hi = max(g0, o["ts"]), min(g1, o["ts"] + o["dur"])
1451 if hi > lo:
1452 during[o["name"][:50]] += hi - lo
1453 main_calls: dict[str, float] = defaultdict(float)
1454 for o in api:
1455 if o["tid"] == main_tid:
1456 lo, hi = max(g0, o["ts"]), min(g1, o["ts"] + o["dur"])
1457 if hi > lo:
1458 main_calls[o["name"]] += hi - lo
1459 biggest_gaps.append(
1460 {
1461 "us": g,
1462 "other_streams": dict(
1463 sorted(during.items(), key=lambda kv: -kv[1])[:4]
1464 ),
1465 "training_thread_calls": dict(
1466 sorted(main_calls.items(), key=lambda kv: -kv[1])[:4]
1467 ),
1468 }
1469 )
1470 launches = [e["dur"] for e in main_launch]
1471 return {
1472 "steps": n,
1473 "step_us": (t1 - t0) / n,
1474 "train_stream": train_stream,
1475 "train_stream_kernels_per_step": len(kernels(train)) / n,
1476 "train_stream_kernel_us": sum(e["dur"] for e in kernels(train)) / n,
1477 "train_stream_busy_us": busy(train) / n,
1478 "train_stream_gap_us": sum(g for g, _, _ in gaps) / n,
1479 "train_stream_gap_over_1ms_us": sum(g for g, _, _ in gaps if g > 1000) / n,
1480 "other_streams_busy_us": busy(other) / n,
1481 "overlap_us": (busy(train) + busy(other) - busy(gpu)) / n,
1482 "streams": streams,
1483 "training_thread_launch": {
1484 "per_step": len(launches) / n,
1485 "mean_us": statistics.fmean(launches) if launches else None,
1486 "p50_us": _pct(launches, 0.5) if launches else None,
1487 "p99_us": _pct(launches, 0.99) if launches else None,
1488 "over_1ms_per_step": sum(1 for d in launches if d > 1000) / n,
1489 "over_1ms_us": sum(d for d in launches if d > 1000) / n,
1490 },
1491 "longest_training_thread_launches": longest,
1492 "biggest_training_stream_gaps": biggest_gaps,
1493 "training_thread_api": top(main_api),
1494 "other_threads_api": top(rest_api),
1495 }
1496
1497
1498def crop_trace(path: str, num_steps: int = 2) -> dict[str, Any]:
1499 """The GPU, CUDA API and step events of the middle ``num_steps`` profiled
1500 steps of a trace written by :py:func:`run` (a small trace to look at)."""
1501 with open(path) as f:
1502 trace = json.load(f)
1503 events = trace.get("traceEvents", [])
1504 steps = sorted(
1505 (e["ts"], e["ts"] + e["dur"])
1506 for e in events
1507 if e.get("name") == _STEP_ANNOTATION
1508 and e.get("ph") == "X"
1509 and e.get("cat") == "user_annotation"
1510 )
1511 if not steps:
1512 return {"traceEvents": []}
1513 mid = len(steps) // 2
1514 t0, t1 = steps[mid][0], steps[min(mid + num_steps, len(steps)) - 1][1]
1515 keep = (
1516 "kernel",
1517 "gpu_memcpy",
1518 "gpu_memset",
1519 "cuda_runtime",
1520 "cuda_driver",
1521 "user_annotation",
1522 )
1523 return {
1524 "traceEvents": [
1525 e
1526 for e in events
1527 if e.get("ph") == "M"
1528 or (e.get("cat") in keep and t0 <= e.get("ts", 0) <= t1)
1529 ]
1530 }
1531
1532
1533# ---------------------------------------------------------------------------
1534# One run
1535# ---------------------------------------------------------------------------
1536
1537
1538def _summary(values: Sequence[float]) -> dict[str, float]:
1539 s = sorted(values)
1540 return (
1541 {
1542 "mean": statistics.fmean(s),
1543 "p50": s[len(s) // 2],
1544 "p90": s[int(len(s) * 0.9)],
1545 "max": s[-1],
1546 }
1547 if s
1548 else {}
1549 )
1550
1551
1552def run(cfg: BenchmarkConfig, clips: Sequence[Clip]) -> dict[str, Any] | None:
1553 """Train ``cfg.warmup_steps + cfg.measure_steps`` steps on this rank's GPU
1554 with ``cfg.arm``'s loader, and measure.
1555
1556 Call it in every rank, with the default process group initialized (NCCL,
1557 one GPU per rank, all ranks on one host for the host sampling and the
1558 pipeline statistics).
1559
1560 Returns:
1561 The result on rank 0 (``None`` on the other ranks): configuration,
1562 throughput, step and data-wait times, host samples, pipeline
1563 statistics, the first steps' loss, decoder counters, and the profile.
1564 """
1565 rank, world_size = dist.get_rank(), dist.get_world_size()
1566 local_rank = int(os.environ.get("LOCAL_RANK", rank))
1567 device = torch.device(f"cuda:{local_rank}")
1568 torch.set_num_threads(1)
1569 random.seed(cfg.seed)
1570 torch.manual_seed(cfg.seed)
1571 log_dir = [
1572 cfg.log_dir or (tempfile.mkdtemp(prefix="video_training_") if rank == 0 else "")
1573 ]
1574 dist.broadcast_object_list(log_dir)
1575 log_path = os.path.join(log_dir[0], f"rank{rank}.log")
1576 handler = logging.FileHandler(log_path)
1577 handler.setFormatter(
1578 logging.Formatter(
1579 f"%(asctime)s [%(levelname).1s] [Rank{rank}] %(name)s: %(message)s"
1580 )
1581 )
1582 logging.getLogger().addHandler(handler)
1583 logging.getLogger().setLevel(logging.INFO)
1584 pids: list[int] = [0] * world_size
1585 dist.all_gather_object(pids, os.getpid())
1586
1587 model = DDP(
1588 build_model(cfg.model, cfg.num_classes).to(device), device_ids=[local_rank]
1589 )
1590 optimizer = torch.optim.AdamW(
1591 model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay, fused=True
1592 )
1593 loader = build_loader(
1594 cfg, clips, rank=rank, world_size=world_size, device=device, log_path=log_path
1595 )
1596 fixed = next(_synthetic(cfg, device)) if cfg.train_on_synthetic else None
1597 sampler = _HostSampler(pids) if local_rank == 0 else None
1598 profiler: Any = None
1599 profile: dict[str, Any] | None = None
1600 prof_start = cfg.warmup_steps + 50
1601 waits: list[float] = []
1602 steps: list[float] = []
1603 losses: list[float] = []
1604 t_start = 0.0
1605 gc.disable()
1606 with sampler if sampler is not None else contextlib.nullcontext():
1607 for step in range(cfg.warmup_steps + cfg.measure_steps):
1608 if step == cfg.warmup_steps:
1609 torch.cuda.synchronize()
1610 torch.cuda.reset_peak_memory_stats(device)
1611 t_start = time.time()
1612 if cfg.profile and rank == 0 and step == prof_start:
1613 profiler = torch.profiler.profile(
1614 activities=[
1615 torch.profiler.ProfilerActivity.CPU,
1616 torch.profiler.ProfilerActivity.CUDA,
1617 ]
1618 )
1619 profiler.__enter__()
1620 with torch.profiler.record_function(_STEP_ANNOTATION):
1621 t0 = time.perf_counter()
1622 batch = next(loader.iterator)
1623 if (ready := batch.pop("ready", None)) is not None:
1624 stream = torch.cuda.current_stream(device)
1625 stream.wait_event(ready)
1626 for t in batch.values():
1627 t.record_stream(stream)
1628 if fixed is not None:
1629 batch = fixed
1630 t1 = time.perf_counter()
1631 with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
1632 loss = F.cross_entropy(model(batch["video"]), batch["label"])
1633 loss.backward()
1634 torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.max_grad_norm)
1635 optimizer.step()
1636 optimizer.zero_grad()
1637 loss_value = loss.item()
1638 t2 = time.perf_counter()
1639 if profiler is not None and step == prof_start + 29:
1640 torch.cuda.synchronize()
1641 profiler.__exit__(None, None, None)
1642 path = os.path.join(log_dir[0], "trace.json")
1643 profiler.export_chrome_trace(path)
1644 with open(path) as f:
1645 profile = {"trace": path, **_summarize_trace(json.load(f))}
1646 profiler = None
1647 if rank == 0 and (step + 1) % 50 == 0:
1648 _LG.info(
1649 "Step %d: loss %.3f, data wait %.1f ms, step %.1f ms",
1650 step + 1,
1651 loss_value,
1652 1e3 * (t1 - t0),
1653 1e3 * (t2 - t0),
1654 )
1655 if step < cfg.loss_steps:
1656 losses.append(loss_value)
1657 if step >= cfg.warmup_steps:
1658 waits.append(t1 - t0)
1659 steps.append(t2 - t0)
1660 t_end = time.time()
1661 local = {
1662 "rank": rank,
1663 "wait_s": sum(waits),
1664 "step_s": sum(steps),
1665 "wait": _summary(waits),
1666 "step": _summary(steps),
1667 "losses": losses,
1668 "max_reserved_bytes": torch.cuda.max_memory_reserved(device),
1669 "decoder_stats": loader.stats(),
1670 "profile": profile,
1671 }
1672 gathered: list[Any] = [None] * world_size
1673 dist.all_gather_object(gathered, local)
1674 loader.close()
1675 if rank != 0:
1676 return None
1677 elapsed = t_end - t_start
1678 n = min(len(r["losses"]) for r in gathered)
1679 result = {
1680 "config": asdict(cfg),
1681 "world_size": world_size,
1682 "samples_per_s": cfg.measure_steps * cfg.batch_size * world_size / elapsed,
1683 "step_time_ms": 1e3 * elapsed / cfg.measure_steps,
1684 "data_wait_fraction": statistics.fmean(
1685 r["wait_s"] / r["step_s"] for r in gathered
1686 ),
1687 "data_wait_fraction_max_rank": max(r["wait_s"] / r["step_s"] for r in gathered),
1688 "step_with_data_ready_ms": 1e3
1689 * min((r["step_s"] - r["wait_s"]) for r in gathered)
1690 / cfg.measure_steps,
1691 "mean_loss": [
1692 statistics.fmean(r["losses"][i] for r in gathered) for i in range(n)
1693 ],
1694 "sys": sampler.window(t_start, t_end) if sampler is not None else {},
1695 "stages": _stage_stats(
1696 [os.path.join(log_dir[0], f"rank{r}.log") for r in range(world_size)],
1697 t_start,
1698 t_end,
1699 ),
1700 "per_rank": [{k: v for k, v in r.items() if k != "losses"} for r in gathered],
1701 }
1702 if cfg.output:
1703 with open(cfg.output, "a") as f:
1704 f.write(json.dumps(result) + "\n")
1705 return result
1706
1707
1708# ---------------------------------------------------------------------------
1709# Command line
1710# ---------------------------------------------------------------------------
1711
1712_FLAGS: dict[str, str] = {
1713 "num_fetch_threads": "fetch-threads",
1714 "num_demux_threads": "demux-threads",
1715 "num_decode_threads": "decode-threads",
1716 "num_lanes": "lanes",
1717}
1718
1719
1720# Options that only the ``cuda_decoders`` arm uses.
1721_CUDA_DECODERS_ONLY = (
1722 "gpu_select_frames",
1723 "gpu_decode_in_subprocess",
1724 "decoder_gpu_offset",
1725 "drop_outputs",
1726 "post_only",
1727 "decoder_process",
1728)
1729
1730
1731def parse_args(
1732 argv: Sequence[str] | None = None,
1733) -> tuple[BenchmarkConfig, argparse.Namespace]:
1734 """Parse the command line into the run's configuration (the model's
1735 recipe, then the explicit flags) and the remaining arguments
1736 (``manifest``, ``data_dir``)."""
1737 p = argparse.ArgumentParser(
1738 description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
1739 )
1740 p.add_argument("--manifest", required=True)
1741 p.add_argument("--data-dir", default="")
1742 defaults = BenchmarkConfig()
1743 for f in dataclasses.fields(BenchmarkConfig):
1744 flag = "--" + _FLAGS.get(f.name, f.name.replace("_", "-"))
1745 default = getattr(defaults, f.name)
1746 if isinstance(default, bool):
1747 p.add_argument(
1748 flag, dest=f.name, action=argparse.BooleanOptionalAction, default=None
1749 )
1750 elif f.name == "num_lanes":
1751 p.add_argument(flag, dest=f.name, type=int, default=None)
1752 else:
1753 p.add_argument(flag, dest=f.name, type=type(default), default=None)
1754 args = p.parse_args(argv)
1755 values = {
1756 k: v
1757 for k, v in RECIPES[args.model or defaults.model].items()
1758 if k in {f.name for f in dataclasses.fields(BenchmarkConfig)}
1759 }
1760 values.update(
1761 {
1762 f.name: getattr(args, f.name)
1763 for f in dataclasses.fields(BenchmarkConfig)
1764 if getattr(args, f.name) is not None
1765 }
1766 )
1767 cfg = BenchmarkConfig(**values)
1768 if cfg.arm not in ARMS:
1769 p.error(f"--arm must be one of {ARMS}")
1770 if cfg.arm != "cuda_decoders":
1771 for name in _CUDA_DECODERS_ONLY:
1772 if getattr(cfg, name) != getattr(defaults, name):
1773 flag = "--" + _FLAGS.get(name, name.replace("_", "-"))
1774 p.error(f"{flag} applies only to --arm cuda_decoders")
1775 return cfg, args
1776
1777
1778def main(argv: Sequence[str] | None = None) -> None:
1779 """Entry point of one rank, launched with ``torchrun``."""
1780 logging.basicConfig(
1781 level=logging.INFO, format="%(asctime)s [%(levelname).1s] %(name)s: %(message)s"
1782 )
1783 cfg, args = parse_args(argv)
1784 if cfg.block_pyav:
1785 _block_pyav()
1786 os.environ.setdefault("OMP_NUM_THREADS", "1")
1787 if cfg.cuda_max_connections:
1788 # Read when the CUDA context is created.
1789 os.environ["CUDA_DEVICE_MAX_CONNECTIONS"] = str(cfg.cuda_max_connections)
1790 local_rank = int(os.environ.get("LOCAL_RANK", 0))
1791 torch.cuda.set_device(local_rank)
1792 dist.init_process_group(
1793 "nccl",
1794 timeout=timedelta(minutes=20),
1795 device_id=torch.device(f"cuda:{local_rank}"),
1796 )
1797 try:
1798 clips, num_classes = load_clips(
1799 args.manifest, cfg.model, args.data_dir, cfg.seed
1800 )
1801 result = run(dataclasses.replace(cfg, num_classes=num_classes), clips)
1802 if result is not None:
1803 keys = (
1804 "samples_per_s",
1805 "step_time_ms",
1806 "data_wait_fraction",
1807 "step_with_data_ready_ms",
1808 )
1809 print(
1810 json.dumps(
1811 {
1812 "arm": cfg.arm,
1813 **{k: result[k] for k in keys},
1814 "sys": result["sys"],
1815 }
1816 )
1817 )
1818 finally:
1819 dist.destroy_process_group()
1820
1821
1822if __name__ == "__main__":
1823 main()
API Reference¶
Functions
- build_loader(cfg: BenchmarkConfig, clips: Sequence[Clip], *, rank: int, world_size: int, device: device, log_path: str) Loader[source]¶
Build the data loader of one rank for
cfg.arm.- Parameters:
cfg – The run’s configuration.
clips – All clips; each rank reads its shard (
DistributedRandomSampler).rank – The rank and the number of ranks.
world_size – The rank and the number of ranks.
device – The rank’s GPU.
log_path – The log file of the loader subprocess (stage statistics).
- build_model(name: str, num_classes: int) Module[source]¶
The model:
"videomae"(VideoMAE ViT-B/16, randomly initialized, SDPA attention; needstransformers) or"r3d18"(needstorchvision).Imported lazily: the loader subprocesses import the main module, and the model libraries must not be loaded there.
- crop_trace(path: str, num_steps: int = 2) dict[str, Any][source]¶
The GPU, CUDA API and step events of the middle
num_stepsprofiled steps of a trace written byrun()(a small trace to look at).
- load_clips(manifest: str, model: str, data_dir: str = '', seed: int = 0) tuple[list[Clip], int][source]¶
Read a manifest and assign each clip its window and resize.
- Parameters:
manifest – CSV file with the columns
pathandlabel, and optionallyfps,duration_s,widthandheight(otherwise probed from the files).model – The model whose input recipe applies (
RECIPES).data_dir – Directory relative paths are resolved against (default: the manifest’s directory).
seed – Seed of the window starts. Every rank and every arm gets the same windows.
- Returns:
The clips and the number of classes.
- main(argv: Sequence[str] | None = None) None[source]¶
Entry point of one rank, launched with
torchrun.
- parse_args(argv: Sequence[str] | None = None) tuple[BenchmarkConfig, Namespace][source]¶
Parse the command line into the run’s configuration (the model’s recipe, then the explicit flags) and the remaining arguments (
manifest,data_dir).
- run(cfg: BenchmarkConfig, clips: Sequence[Clip]) dict[str, Any] | None[source]¶
Train
cfg.warmup_steps + cfg.measure_stepssteps on this rank’s GPU withcfg.arm’s loader, and measure.Call it in every rank, with the default process group initialized (NCCL, one GPU per rank, all ranks on one host for the host sampling and the pipeline statistics).
- Returns:
configuration, throughput, step and data-wait times, host samples, pipeline statistics, the first steps’ loss, decoder counters, and the profile.
- Return type:
The result on rank 0 (
Noneon the other ranks)
Classes
- class BenchmarkConfig[source]¶
Configuration of one run (one arm).
- decoder_process: bool = False¶
decode in a separate process on the rank’s GPU (dropping the frames) while the trainer trains on a fixed batch.
- Type:
Diagnostic
- gpu_decode_in_subprocess: bool = False¶
decode and post-process in the loader subprocess (on the rank’s GPU) instead of the trainer process; the clips are handed to the trainer with CUDA IPC.
- Type:
cuda_decoders
- gpu_select_frames: bool = False¶
pass the sampled frame indices to the decoder, so that it outputs only those frames (needs a
decodethat acceptsframe_indices).- Type:
cuda_decoders
- num_decode_threads: int = 32¶
decode concurrency in the loader subprocess; GPU arms: concurrency of the decode stage.
- Type:
cpu
- class Clip[source]¶
One training sample: a video file, its label, and the part of it to use.