Performance analysis¶

This example shows how to collect runtime performance statistics using custom hooks and then export the data to a database.

Note

To learn how to interpret the performance statistics, please refer to Optimization Guide.

The Pipeline class can collect runtime statistics and periodically publish them via hooks and queues. This example shows how to use a buffer-based logging pattern with SQLite as the storage backend to collect and query performance statistics.

The performance stats are exposed as spdl.pipeline.TaskPerfStats and spdl.pipeline.QueuePerfStats classes. These are collected via hooks and queues into a shared buffer, which is then asynchronously written to a SQLite database by a dedicated writer thread.

Architecture¶

The following diagram illustrates the relationship between the pipeline, buffer, and writer thread:

graph LR subgraph Pipeline A[Task Hooks] C[Queues] end A -->|Task Stats| B[Shared Buffer] C -->|Queue Stats| B D[GC Events] -->|Event Logs| B B -->|Async Write| E[Writer Thread] E -->|Persist| F[(SQLite Database)] F -->|Query| G[performance_analysis_plot.py]

Example Usage¶

This example demonstrates:

  1. Using TaskStatsHookWithLogging to log task performance to a buffer

  2. Using StatsQueueWithLogging to log queue performance to a buffer

  3. Using SQLiteStatsWriter to asynchronously flush the buffer to SQLite

Running this example on Kinetics K400 dataset produces the following output:

================================================================================
PIPELINE PERFORMANCE SUMMARY
================================================================================
📊 Task Statistics:
--------------------------------------------------------------------------------

  Stage: 0:1:decode[10]
    Total tasks processed: 240435
    Total failures: 1458
    Average task time: 0.4241s
    Success rate: 99.4%
    Number of log entries: 169

📈 Queue Statistics:
--------------------------------------------------------------------------------

  Queue: 0:0:src_queue
    Total items processed: 240445
    Average QPS: 23.71
    Average put time: 0.0417s
    Average get time: 0.0000s
    Average occupancy rate: 100.0%
    Number of log entries: 169

  Queue: 0:1:decode[10]_queue
    Total items processed: 238977
    Average QPS: 23.57
    Average put time: 0.0000s
    Average get time: 0.0424s
    Average occupancy rate: 0.1%
    Number of log entries: 169

  Queue: 0:2:sink_queue
    Total items processed: 238977
    Average QPS: 23.57
    Average put time: 0.0000s
    Average get time: 0.0421s
    Average occupancy rate: 0.1%
    Number of log entries: 169

Visualization¶

The SQLite database can be queried using standard SQL tools or the built-in query API to analyze:

  • Task execution times and failure rates

  • Queue throughput (QPS) and occupancy rates

  • Pipeline bottlenecks and resource utilization

You can use the performance_analysis_plot.py script to query the data from the database and generate plots for visualization and analysis.

../_images/example-performance-analysis-task-stats.png ../_images/example-performance-analysis-queue-stats.png

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"""This example shows how to collect runtime performance statistics using
  9custom hooks and then export the data to a database.
 10
 11.. note::
 12
 13   To learn how to interpret the performance statistics, please refer to
 14   :doc:`../optimization_guide/index`.
 15
 16The :py:class:`~spdl.pipeline.Pipeline` class can collect runtime statistics
 17and periodically publish them via hooks and queues.
 18This example shows how to use a buffer-based logging pattern with
 19SQLite as the storage backend to collect and query performance statistics.
 20
 21The performance stats are exposed as :py:class:`spdl.pipeline.TaskPerfStats` and
 22:py:class:`spdl.pipeline.QueuePerfStats` classes. These are collected via hooks
 23and queues into a shared buffer, which is then asynchronously written
 24to a SQLite database by a dedicated writer thread.
 25
 26Architecture
 27------------
 28
 29The following diagram illustrates the relationship between the pipeline, buffer,
 30and writer thread:
 31
 32.. mermaid::
 33
 34   graph LR
 35       subgraph Pipeline
 36           A[Task Hooks]
 37           C[Queues]
 38       end
 39       A -->|Task Stats| B[Shared Buffer]
 40       C -->|Queue Stats| B
 41       D[GC Events] -->|Event Logs| B
 42       B -->|Async Write| E[Writer Thread]
 43       E -->|Persist| F[(SQLite Database)]
 44       F -->|Query| G[performance_analysis_plot.py]
 45
 46Example Usage
 47-------------
 48
 49This example demonstrates:
 50
 51#. Using :py:class:`TaskStatsHookWithLogging` to log task performance to a buffer
 52#. Using :py:class:`StatsQueueWithLogging` to log queue performance to a buffer
 53#. Using :py:class:`SQLiteStatsWriter` to asynchronously flush the buffer to SQLite
 54
 55Running this example on Kinetics K400 dataset produces the following output:
 56
 57.. code-block:: text
 58
 59   ================================================================================
 60   PIPELINE PERFORMANCE SUMMARY
 61   ================================================================================
 62   📊 Task Statistics:
 63   --------------------------------------------------------------------------------
 64
 65     Stage: 0:1:decode[10]
 66       Total tasks processed: 240435
 67       Total failures: 1458
 68       Average task time: 0.4241s
 69       Success rate: 99.4%
 70       Number of log entries: 169
 71
 72   📈 Queue Statistics:
 73   --------------------------------------------------------------------------------
 74
 75     Queue: 0:0:src_queue
 76       Total items processed: 240445
 77       Average QPS: 23.71
 78       Average put time: 0.0417s
 79       Average get time: 0.0000s
 80       Average occupancy rate: 100.0%
 81       Number of log entries: 169
 82
 83     Queue: 0:1:decode[10]_queue
 84       Total items processed: 238977
 85       Average QPS: 23.57
 86       Average put time: 0.0000s
 87       Average get time: 0.0424s
 88       Average occupancy rate: 0.1%
 89       Number of log entries: 169
 90
 91     Queue: 0:2:sink_queue
 92       Total items processed: 238977
 93       Average QPS: 23.57
 94       Average put time: 0.0000s
 95       Average get time: 0.0421s
 96       Average occupancy rate: 0.1%
 97       Number of log entries: 169
 98
 99Visualization
100-------------
101
102The SQLite database can be queried using standard SQL tools or the
103built-in query API to analyze:
104
105- Task execution times and failure rates
106- Queue throughput (QPS) and occupancy rates
107- Pipeline bottlenecks and resource utilization
108
109You can use the ``performance_analysis_plot.py`` script to query the data from
110the database and generate plots for visualization and analysis.
111
112.. image:: ../_static/data/example-performance-analysis-task-stats.png
113
114.. image:: ../_static/data/example-performance-analysis-queue-stats.png
115
116"""
117
118import argparse
119import gc
120import logging
121import time
122from collections.abc import Iterable
123from functools import partial
124from pathlib import Path
125from queue import Queue
126
127import spdl.io
128import torch
129from spdl.pipeline import (
130    Pipeline,
131    PipelineBuilder,
132    QueuePerfStats,
133    StageInfo,
134    StatsQueue,
135    TaskHook,
136    TaskPerfStats,
137    TaskStatsHook,
138)
139
140try:
141    from examples.sqlite_stats_logger import (  # pyre-ignore[21]
142        EventLogEntry,
143        log_stats_summary,
144        QueueStatsLogEntry,
145        SQLiteStatsWriter,
146        TaskStatsLogEntry,
147    )
148except ImportError:
149    from spdl.examples.sqlite_stats_logger import (  # type: ignore[import-not-found, no-redef]
150        EventLogEntry,
151        log_stats_summary,
152        QueueStatsLogEntry,
153        SQLiteStatsWriter,
154        TaskStatsLogEntry,
155    )
156
157
158__all__ = [
159    "parse_args",
160    "main",
161    "build_pipeline",
162    "decode",
163    "TaskStatsHookWithLogging",
164    "StatsQueueWithLogging",
165    "SQLiteStatsWriter",
166]
167
168
169_LG: logging.Logger = logging.getLogger(__name__)
170
171
172class TaskStatsHookWithLogging(TaskStatsHook):
173    """Task hook that logs statistics to a shared buffer.
174
175    This hook collects task performance statistics and writes them to a
176    plain Python queue.
177
178    Args:
179        info: The stage identity.
180        buffer: Shared queue to write stats entries. This queue is typically
181            consumed by a separate writer (e.g., ``SQLiteStatsWriter``).
182        interval: The interval (in seconds) to report the performance stats
183            periodically.
184    """
185
186    def __init__(
187        self,
188        info: StageInfo,
189        buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry | EventLogEntry],
190        interval: float = 59,
191    ) -> None:
192        super().__init__(info, interval=interval)
193        self._buffer = buffer
194
195    async def interval_stats_callback(self, stats: TaskPerfStats) -> None:
196        """Log interval statistics to the buffer."""
197        await super().interval_stats_callback(stats)
198
199        entry = TaskStatsLogEntry(
200            timestamp=time.time(),
201            name=str(self.info),
202            stats=stats,
203        )
204        self._buffer.put(entry)
205
206
207class StatsQueueWithLogging(StatsQueue):
208    """Queue that logs statistics to a shared buffer.
209
210    This queue collects queue performance statistics and writes them to a
211    plain Python queue.
212
213    Args:
214        info: The stage identity. Assigned by PipelineBuilder.
215        buffer: Shared queue to write stats entries. This queue is typically
216            consumed by a separate writer (e.g., ``SQLiteStatsWriter``).
217        buffer_size: The buffer size. Assigned by PipelineBuilder.
218        interval: The interval (in seconds) to report the performance stats
219            periodically.
220    """
221
222    def __init__(
223        self,
224        info: StageInfo,
225        buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry | EventLogEntry],
226        buffer_size: int = 1,
227        interval: float = 59,
228    ) -> None:
229        super().__init__(info, buffer_size=buffer_size, interval=interval)
230        self._buffer = buffer
231
232    async def interval_stats_callback(self, stats: QueuePerfStats) -> None:
233        """Log interval statistics to the buffer."""
234        await super().interval_stats_callback(stats)
235
236        entry = QueueStatsLogEntry(
237            timestamp=time.time(),
238            name=str(self.info),
239            stats=stats,
240        )
241        self._buffer.put(entry)
242
243
244def parse_args() -> argparse.Namespace:
245    """Parse command line arguments."""
246    parser = argparse.ArgumentParser(
247        description=__doc__,
248    )
249    parser.add_argument(
250        "--dataset-dir",
251        type=Path,
252        required=True,
253        help="Directory containing video files (*.mp4)",
254    )
255    parser.add_argument(
256        "--db-path",
257        type=Path,
258        default=Path("pipeline_stats.db"),
259        help="Path to SQLite database for stats (default: pipeline_stats.db)",
260    )
261    parser.add_argument(
262        "--log-interval",
263        type=float,
264        default=60,
265        help="Interval in seconds for logging stats to database (default: 60)",
266    )
267    parser.add_argument(
268        "--concurrency",
269        type=int,
270        default=10,
271        help="Number of concurrent decoding tasks (default: 10)",
272    )
273    return parser.parse_args()
274
275
276@spdl.io.fuse
277def decode(path: Path, width: int = 128, height: int = 128) -> torch.Tensor:
278    """Decode the video from the given path with rescaling.
279
280    The decorator :py:func:`spdl.io.fuse` makes the IO functions execute in one
281    native call.
282
283    Args:
284        path: The path to the video file.
285        width,height: The resolution of video after rescaling.
286
287    Returns:
288        Uint8 tensor in shape of ``[N, C, H, W]``: Video frames in Tensor.
289    """
290    packets = spdl.io.demux_video(path)
291    frames = spdl.io.decode_packets(
292        packets,
293        filter_desc=spdl.io.get_filter_desc(
294            packets,
295            scale_width=width,
296            scale_height=height,
297            pix_fmt="rgb24",
298        ),
299    )
300    buffer = spdl.io.convert_frames(frames)
301    return spdl.io.to_torch(buffer).permute(0, 2, 3, 1)
302
303
304def build_pipeline(
305    source: Iterable[Path],
306    log_interval: float,
307    concurrency: int,
308    buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry | EventLogEntry],
309) -> Pipeline:
310    """Build the pipeline with stats logging to a buffer.
311
312    Args:
313        source: A data source containing video file paths.
314        log_interval: The interval (in seconds) the performance data is saved.
315        concurrency: The concurrency for video decoding.
316        buffer: Shared queue for collecting stats entries. This queue should
317            be consumed by a ``SQLiteStatsWriter`` instance.
318
319    Returns:
320        A configured Pipeline instance ready for execution.
321    """
322
323    def hook_factory(info: StageInfo) -> list[TaskHook]:
324        return [
325            TaskStatsHookWithLogging(
326                info,
327                buffer=buffer,
328                interval=log_interval,
329            )
330        ]
331
332    return (
333        PipelineBuilder()
334        .add_source(source=source)
335        .pipe(decode, concurrency=concurrency)
336        .add_sink()
337        .build(
338            num_threads=concurrency,
339            queue_class=partial(  # pyre-ignore[6]
340                StatsQueueWithLogging,
341                buffer=buffer,
342                interval=log_interval,
343            ),
344            task_hook_factory=hook_factory,
345        )
346    )
347
348
349def _validate_dataset(dataset_dir: Path) -> list[Path]:
350    """Validate dataset directory and return list of video files.
351
352    Args:
353        dataset_dir: Path to the dataset directory.
354
355    Returns:
356        List of video file paths.
357
358    Raises:
359        ValueError: If the directory doesn't exist or contains no videos.
360    """
361    if not dataset_dir.exists():
362        raise ValueError(f"Dataset directory does not exist: {dataset_dir}")
363
364    video_files = list(dataset_dir.rglob("*.mp4"))
365    if not video_files:
366        raise ValueError(f"No *.mp4 files found in {dataset_dir}")
367
368    return video_files
369
370
371def setup_gc_callbacks(
372    buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry | EventLogEntry],
373) -> None:
374    """Set up garbage collection callbacks to log GC events.
375
376    Args:
377        buffer: Shared queue for collecting stats entries.
378    """
379
380    def gc_callback(phase: str, _info: dict[str, int]) -> None:
381        """Callback invoked during garbage collection phases.
382
383        Args:
384            phase: The GC phase ('start' or 'stop').
385            _info: Dictionary containing GC information (unused).
386        """
387        event_name = f"gc_{phase}"
388        entry = EventLogEntry(
389            timestamp=time.time(),
390            event_name=event_name,
391        )
392        buffer.put(entry)
393        _LG.debug("GC event logged: %s", event_name)
394
395    # Register the callback with the garbage collector
396    gc.callbacks.append(gc_callback)
397    _LG.info("Garbage collection callbacks registered")
398
399
400def main() -> None:
401    """The main entry point for the example."""
402    logging.basicConfig(
403        level=logging.INFO,
404        format="%(asctime)s [%(levelname).1s]: %(message)s",
405    )
406
407    args = parse_args()
408
409    # Validate dataset and get video files
410    video_files = _validate_dataset(args.dataset_dir)
411
412    print("\n🎬 Starting video processing pipeline")
413    print(f"   Dataset: {args.dataset_dir}")
414    print(f"   Videos found: {len(video_files)}")
415    print(f"   Database: {args.db_path}")
416    print(f"   Concurrency: {args.concurrency}")
417    print(f"   Log interval: {args.log_interval}s\n")
418    print("", flush=True)
419
420    # Create shared buffer and writer
421    buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry | EventLogEntry] = Queue()
422    writer = SQLiteStatsWriter(
423        str(args.db_path),
424        buffer,
425        flush_interval=max(0.1, args.log_interval - 1),
426    )
427    writer.start()
428
429    # Set up garbage collection callbacks
430    setup_gc_callbacks(buffer)
431
432    # Build and run pipeline
433    pipeline = build_pipeline(
434        source=video_files,
435        log_interval=args.log_interval,
436        concurrency=args.concurrency,
437        buffer=buffer,
438    )
439
440    try:
441        start_time = time.monotonic()
442        with pipeline.auto_stop():
443            for _ in pipeline:
444                pass
445
446        elapsed = time.monotonic() - start_time
447        print(f"\n✅ Pipeline completed in {elapsed:.2f} seconds")
448
449    finally:
450        # Ensure all stats are flushed to database
451        writer.shutdown()
452
453        # Log stats summary
454        log_stats_summary(args.db_path)
455
456
457if __name__ == "__main__":
458    main()

API Reference¶

Functions

parse_args() → Namespace[source]¶

Parse command line arguments.

main() → None[source]¶

The main entry point for the example.

build_pipeline(source: Iterable[Path], log_interval: float, concurrency: int, buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry | EventLogEntry]) → Pipeline[source]¶

Build the pipeline with stats logging to a buffer.

Parameters:
  • source – A data source containing video file paths.

  • log_interval – The interval (in seconds) the performance data is saved.

  • concurrency – The concurrency for video decoding.

  • buffer – Shared queue for collecting stats entries. This queue should be consumed by a SQLiteStatsWriter instance.

Returns:

A configured Pipeline instance ready for execution.

decode(path: Path, width: int = 128, height: int = 128) → Tensor[source]¶

Decode the video from the given path with rescaling.

The decorator spdl.io.fuse() makes the IO functions execute in one native call.

Parameters:
  • path – The path to the video file.

  • width – The resolution of video after rescaling.

  • height – The resolution of video after rescaling.

Returns:

Video frames in Tensor.

Return type:

Uint8 tensor in shape of [N, C, H, W]

Classes

class TaskStatsHookWithLogging(info: StageInfo, buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry | EventLogEntry], interval: float = 59)[source]¶

Task hook that logs statistics to a shared buffer.

This hook collects task performance statistics and writes them to a plain Python queue.

Parameters:
  • info – The stage identity.

  • buffer – Shared queue to write stats entries. This queue is typically consumed by a separate writer (e.g., SQLiteStatsWriter).

  • interval – The interval (in seconds) to report the performance stats periodically.

async interval_stats_callback(stats: TaskPerfStats) → None[source]¶

Log interval statistics to the buffer.

class StatsQueueWithLogging(info: StageInfo, buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry | EventLogEntry], buffer_size: int = 1, interval: float = 59)[source]¶

Queue that logs statistics to a shared buffer.

This queue collects queue performance statistics and writes them to a plain Python queue.

Parameters:
  • info – The stage identity. Assigned by PipelineBuilder.

  • buffer – Shared queue to write stats entries. This queue is typically consumed by a separate writer (e.g., SQLiteStatsWriter).

  • buffer_size – The buffer size. Assigned by PipelineBuilder.

  • interval – The interval (in seconds) to report the performance stats periodically.

async interval_stats_callback(stats: QueuePerfStats) → None[source]¶

Log interval statistics to the buffer.

class SQLiteStatsWriter(db_path: str, buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry | EventLogEntry], flush_interval: float)[source]¶

Background writer thread for flushing statistics to SQLite.

This class manages a background thread that periodically flushes statistics from a shared queue to a SQLite database. It’s designed to be decoupled from the hooks and queues that populate the buffer, allowing flexibility in changing storage backends.

The writer uses a periodic flushing strategy: - Wakes up at regular intervals (configured by flush_interval) - Drains all entries from the queue - Flushes to database if any entries were collected - Repeats until shutdown

Thread Safety:

Uses queue.Queue which provides built-in thread safety for producer-consumer patterns.

Parameters:
  • db_path – Path to the SQLite database file. The database schema will be initialized if it doesn’t exist.

  • buffer – Shared queue that serves as the buffer for log entries. This buffer is populated by hooks/queues and consumed by this writer.

  • flush_interval – Duration in seconds to sleep between queue drain cycles. Lower values increase CPU usage but reduce latency.

Example

>>> from queue import Queue
>>> buffer: Queue[TaskStatsLogEntry | QueueStatsLogEntry] = Queue()
>>> writer = SQLiteStatsWriter("stats.db", buffer)
>>> writer.start()  # Start background thread
>>> # ... hooks populate buffer ...
>>> writer.shutdown()  # Flush remaining entries and stop thread
shutdown() → None[source]¶

Shutdown the writer and flush all pending entries.

start() → None[source]¶

Start the background writer thread.