Imagenet classification¶
Benchmark the performance of loading images from local file systems and classifying them using a GPU.
This script builds the data loader and instantiates an image classification model in a GPU. The data loader transfers the batch image data to the GPU concurrently, and the foreground thread run the model on data one by one.
To run the benchmark, pass it to the script like the following.
python imagenet_classification.py
--root-dir ~/imagenet/
--split val
Source¶
Source
Click here to see the source.
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the BSD-style license found in the
5# LICENSE file in the root directory of this source tree.
6
7"""Benchmark the performance of loading images from local file systems and
8classifying them using a GPU.
9
10This script builds the data loader and instantiates an image
11classification model in a GPU.
12The data loader transfers the batch image data to the GPU concurrently, and
13the foreground thread run the model on data one by one.
14
15.. include:: ../plots/imagenet_classification_chart.txt
16
17To run the benchmark, pass it to the script like the following.
18
19.. code-block::
20
21 python imagenet_classification.py
22 --root-dir ~/imagenet/
23 --split val
24"""
25
26import argparse
27import contextlib
28import logging
29import time
30from argparse import Namespace
31from collections.abc import Callable, Iterable, Iterator
32from pathlib import Path
33from typing import cast
34
35import spdl.io
36import spdl.io.utils
37import torch
38from spdl.dataloader import DataLoader
39from spdl.source.imagenet import ImageNet
40from torch import Tensor
41from torch.profiler import profile
42
43_LG: logging.Logger = logging.getLogger(__name__)
44
45
46__all__ = [
47 "entrypoint",
48 "benchmark",
49 "get_decode_func",
50 "get_dataloader",
51 "get_model",
52 "ModelBundle",
53 "Classification",
54 "Preprocessing",
55]
56
57
58def _parse_args(args: list[str] | None) -> Namespace:
59 parser = argparse.ArgumentParser(
60 description=__doc__,
61 formatter_class=argparse.RawDescriptionHelpFormatter,
62 )
63 parser.add_argument("--debug", action="store_true")
64 parser.add_argument("--root-dir", type=Path, required=True)
65 parser.add_argument("--max-batches", type=int, default=float("inf"))
66 parser.add_argument("--batch-size", type=int, default=32)
67 parser.add_argument("--split", default="val", choices=["train", "val"])
68 parser.add_argument("--trace", type=Path)
69 parser.add_argument("--buffer-size", type=int, default=16)
70 parser.add_argument("--num-threads", type=int, default=16)
71 parser.add_argument("--no-compile", action="store_false", dest="compile")
72 parser.add_argument("--no-bf16", action="store_false", dest="use_bf16")
73 parser.add_argument("--use-nvjpeg", action="store_true")
74 ns = parser.parse_args(args)
75 if ns.trace:
76 ns.max_batches = 60
77 return ns
78
79
80# Handroll the transforms so as to support `torch.compile`
81class Preprocessing(torch.nn.Module):
82 """Perform pixel normalization and data type conversion.
83
84 Args:
85 mean: The mean value of the dataset.
86 std: The standard deviation of the dataset.
87 """
88
89 def __init__(self, mean: Tensor, std: Tensor) -> None:
90 super().__init__()
91 self.register_buffer("mean", mean)
92 self.register_buffer("std", std)
93
94 def forward(self, x: Tensor) -> Tensor:
95 """Normalize the given image batch.
96
97 Args:
98 x: The input image batch. Pixel values are expected to be
99 in the range of ``[0, 255]``.
100 Returns:
101 The normalized image batch.
102 """
103 x = x.float() / 255.0
104 return (x - cast(Tensor, self.mean)) / cast(Tensor, self.std)
105
106
107class Classification(torch.nn.Module):
108 """Classification()"""
109
110 def forward(self, x: Tensor, labels: Tensor) -> tuple[Tensor, Tensor]:
111 """Given a batch of features and labels, compute the top1 and top5 accuracy.
112
113 Args:
114 images: A batch of images. The shape is ``(batch_size, 3, 224, 224)``.
115 labels: A batch of labels. The shape is ``(batch_size,)``.
116
117 Returns:
118 A tuple of top1 and top5 accuracy.
119 """
120
121 probs = torch.nn.functional.softmax(x, dim=-1)
122 top_prob, top_catid = torch.topk(probs, 5)
123 top1 = (top_catid[:, :1] == labels).sum()
124 top5 = (top_catid == labels).sum()
125 return top1, top5
126
127
128class ModelBundle(torch.nn.Module):
129 """ModelBundle()
130
131 Bundle the transform, model backbone, and classification head into a single module
132 for a simple handling."""
133
134 def __init__(
135 self,
136 model: Callable[[Tensor], Tensor],
137 preprocessing: Callable[[Tensor], Tensor],
138 classification: Classification,
139 use_bf16: bool,
140 ) -> None:
141 super().__init__()
142 self.model = model
143 self.preprocessing = preprocessing
144 self.classification = classification
145 self.use_bf16 = use_bf16
146
147 def forward(self, images: Tensor, labels: Tensor) -> tuple[Tensor, Tensor]:
148 """Given a batch of images and labels, compute the top1, top5 accuracy.
149
150 Args:
151 images: A batch of images. The shape is ``(batch_size, 3, 224, 224)``.
152 labels: A batch of labels. The shape is ``(batch_size,)``.
153
154 Returns:
155 A tuple of top1 and top5 accuracy.
156 """
157
158 x = self.preprocessing(images)
159
160 if self.use_bf16:
161 x = x.to(torch.bfloat16)
162
163 output = self.model(x)
164
165 return self.classification(output, labels)
166
167
168def _expand(vals: list[float], batch_size: int, res: int) -> Tensor:
169 return torch.tensor(vals).view(1, 3, 1, 1).expand(batch_size, 3, res, res).clone()
170
171
172def get_model(
173 batch_size: int,
174 device_index: int,
175 compile: bool,
176 use_bf16: bool,
177 model_type: str = "mobilenetv3_large_100",
178) -> ModelBundle:
179 """Build computation model, including transfor, model, and classification head.
180
181 Args:
182 batch_size: The batch size of the input.
183 device_index: The index of the target GPU device.
184 compile: Whether to compile the model.
185 use_bf16: Whether to use bfloat16 for the model.
186 model_type: The type of the model. Passed to ``timm.create_model()``.
187
188 Returns:
189 The resulting computation model.
190 """
191 import timm
192
193 device = torch.device(f"cuda:{device_index}")
194
195 model = timm.create_model(model_type, pretrained=True)
196 model = model.eval().to(device=device)
197
198 if use_bf16:
199 model = model.to(dtype=torch.bfloat16)
200
201 preprocessing: Callable[[Tensor], Tensor] = Preprocessing(
202 mean=_expand([0.4850, 0.4560, 0.4060], batch_size, 224),
203 std=_expand([0.2290, 0.2240, 0.2250], batch_size, 224),
204 ).to(device)
205
206 classification = Classification().to(device)
207 model_fn: Callable[[Tensor], Tensor] = model
208
209 if compile:
210 with torch.no_grad():
211 mode = "max-autotune"
212 model_fn = torch.compile(model, mode=mode)
213 preprocessing = torch.compile(preprocessing, mode=mode)
214
215 return ModelBundle(model_fn, preprocessing, classification, use_bf16)
216
217
218def get_decode_func(
219 device_index: int,
220 width: int = 224,
221 height: int = 224,
222) -> Callable[[list[tuple[str, int]]], tuple[Tensor, Tensor]]:
223 """Get a function to decode images from a list of paths.
224
225 Args:
226 device_index: The index of the target GPU device.
227 width: The width of the decoded image.
228 height: The height of the decoded image.
229
230 Returns:
231 Async function to decode images in to batch tensor of NCHW format
232 and labels of shape ``(batch_size, 1)``.
233 """
234 device: torch.device = torch.device(f"cuda:{device_index}")
235
236 filter_desc: str | None = spdl.io.get_video_filter_desc(
237 scale_width=256,
238 scale_height=256,
239 crop_width=width,
240 crop_height=height,
241 pix_fmt="rgb24",
242 )
243
244 # Execute loading and batching images in one native call.
245 @spdl.io.fuse
246 def decode_images(items: list[tuple[str, int]]) -> tuple[Tensor, Tensor]:
247 paths = [item for item, _ in items]
248 labels = [[item] for _, item in items]
249 labels = torch.tensor(labels, dtype=torch.int64, device=device)
250 buffer = spdl.io.load_image_batch(
251 paths,
252 width=None,
253 height=None,
254 pix_fmt=None,
255 strict=True,
256 filter_desc=filter_desc,
257 device_config=spdl.io.cuda_config(
258 device_index=0,
259 allocator=(
260 torch.cuda.caching_allocator_alloc,
261 torch.cuda.caching_allocator_delete,
262 ),
263 ),
264 )
265 batch = spdl.io.to_torch(buffer)
266 batch = batch.permute((0, 3, 1, 2))
267 return batch, labels
268
269 return decode_images
270
271
272def _get_experimental_nvjpeg_decode_function(
273 device_index: int,
274 width: int = 224,
275 height: int = 224,
276) -> Callable[[list[tuple[str, int]]], tuple[Tensor, Tensor]]:
277 device: torch.device = torch.device(f"cuda:{device_index}")
278 device_config: spdl.io.CUDAConfig = spdl.io.cuda_config(
279 device_index=device_index,
280 allocator=(
281 torch.cuda.caching_allocator_alloc,
282 torch.cuda.caching_allocator_delete,
283 ),
284 )
285
286 def decode_images_nvjpeg(
287 items: list[tuple[str, int]],
288 ) -> tuple[Tensor, Tensor]:
289 paths = [item for item, _ in items]
290 labels = [[item] for _, item in items]
291 labels = torch.tensor(labels, dtype=torch.int64, device=device)
292 buffer = spdl.io.load_image_batch_nvjpeg(
293 paths,
294 device_config=device_config,
295 width=width,
296 height=height,
297 pix_fmt="rgb",
298 # strict=True,
299 )
300 batch = spdl.io.to_torch(buffer)
301 return batch, labels
302
303 return decode_images_nvjpeg
304
305
306def get_dataloader(
307 src: Iterator[tuple[str, int]],
308 batch_size: int,
309 decode_func: Callable[[list[tuple[str, int]]], tuple[Tensor, Tensor]],
310 buffer_size: int,
311 num_threads: int,
312) -> Iterator[tuple[Tensor, Tensor]]:
313 """Build the dataloader for the ImageNet classification task.
314
315 The dataloader uses the ``decode_func`` for decoding images concurrently and
316 send the resulting data to GPU.
317
318 Args:
319 src: The source of the data. See :py:func:`source`.
320 batch_size: The number of images in a batch.
321 decode_func: The function to decode images.
322 buffer_size: The size of the buffer for the dataloader sink
323 num_threads: The number of worker threads.
324
325 """
326 return DataLoader( # pyre-ignore[7]
327 src,
328 batch_size=batch_size,
329 drop_last=True,
330 aggregator=decode_func,
331 buffer_size=buffer_size,
332 num_threads=num_threads,
333 timeout=20,
334 )
335
336
337def benchmark(
338 dataloader: Iterable[tuple[Tensor, Tensor]],
339 model: ModelBundle,
340 max_batches: float = float("nan"),
341) -> None:
342 """The main loop that measures the performance of dataloading and model inference.
343
344 Args:
345 loader: The dataloader to benchmark.
346 model: The model to benchmark.
347 max_batches: The number of batch before stopping.
348 """
349
350 _LG.info("Running inference.")
351 num_frames = 0
352 num_correct_top1: float | Tensor = 0
353 num_correct_top5: float | Tensor = 0
354 t0 = time.monotonic()
355 try:
356 for i, (batch, labels) in enumerate(dataloader):
357 if i == 20:
358 t0 = time.monotonic()
359 num_frames, num_correct_top1, num_correct_top5 = 0, 0, 0
360
361 with (
362 torch.profiler.record_function(f"iter_{i}"),
363 spdl.io.utils.trace_event(f"iter_{i}"),
364 ):
365 top1, top5 = model(batch, labels)
366
367 num_frames += batch.shape[0]
368 num_correct_top1 += top1
369 num_correct_top5 += top5
370
371 if i + 1 >= max_batches:
372 break
373 finally:
374 elapsed = time.monotonic() - t0
375 if num_frames != 0:
376 num_correct_top1 = cast(Tensor, num_correct_top1).item()
377 num_correct_top5 = cast(Tensor, num_correct_top5).item()
378 fps = num_frames / elapsed
379 _LG.info(f"FPS={fps:.2f} ({num_frames}/{elapsed:.2f})")
380 acc1 = 0 if num_frames == 0 else num_correct_top1 / num_frames
381 _LG.info(f"Accuracy (top1)={acc1:.2%} ({num_correct_top1}/{num_frames})")
382 acc5 = 0 if num_frames == 0 else num_correct_top5 / num_frames
383 _LG.info(f"Accuracy (top5)={acc5:.2%} ({num_correct_top5}/{num_frames})")
384
385
386def _get_dataloader(
387 args: Namespace, device_index: int
388) -> Iterator[tuple[Tensor, Tensor]]:
389 src = ImageNet(args.root_dir, split=args.split)
390
391 if args.use_nvjpeg:
392 decode_func = _get_experimental_nvjpeg_decode_function(device_index)
393 else:
394 decode_func = get_decode_func(device_index)
395
396 return get_dataloader(
397 src, # pyre-ignore[6]
398 args.batch_size,
399 decode_func,
400 args.buffer_size,
401 args.num_threads,
402 )
403
404
405def entrypoint(args_: list[str] | None = None) -> None:
406 """CLI entrypoint. Run pipeline, transform and model and measure its performance."""
407
408 args = _parse_args(args_)
409 _init_logging(args.debug)
410 _LG.info(args)
411
412 device_index = 0
413 model = get_model(args.batch_size, device_index, args.compile, args.use_bf16)
414 dataloader = _get_dataloader(args, device_index)
415
416 trace_path = f"{args.trace}"
417 if args.use_nvjpeg:
418 trace_path = f"{trace_path}.nvjpeg"
419
420 with (
421 torch.no_grad(),
422 profile() if args.trace else contextlib.nullcontext() as prof,
423 spdl.io.utils.tracing(f"{trace_path}.pftrace", enable=args.trace is not None),
424 ):
425 benchmark(dataloader, model, args.max_batches)
426
427 if args.trace:
428 cast(profile, prof).export_chrome_trace(f"{trace_path}.json")
429
430
431def _init_logging(debug: bool = False) -> None:
432 fmt = "%(asctime)s [%(filename)s:%(lineno)d] [%(levelname)s] %(message)s"
433 level = logging.DEBUG if debug else logging.INFO
434 logging.basicConfig(format=fmt, level=level)
435
436
437if __name__ == "__main__":
438 entrypoint()
API Reference¶
Functions
- entrypoint(args_: list[str] | None = None) None[source]¶
CLI entrypoint. Run pipeline, transform and model and measure its performance.
- benchmark(dataloader: Iterable[tuple[Tensor, Tensor]], model: ModelBundle, max_batches: float = nan) None[source]¶
The main loop that measures the performance of dataloading and model inference.
- Parameters:
loader – The dataloader to benchmark.
model – The model to benchmark.
max_batches – The number of batch before stopping.
- get_decode_func(device_index: int, width: int = 224, height: int = 224) Callable[[list[tuple[str, int]]], tuple[Tensor, Tensor]][source]¶
Get a function to decode images from a list of paths.
- Parameters:
device_index – The index of the target GPU device.
width – The width of the decoded image.
height – The height of the decoded image.
- Returns:
Async function to decode images in to batch tensor of NCHW format and labels of shape
(batch_size, 1).
- get_dataloader(src: Iterator[tuple[str, int]], batch_size: int, decode_func: Callable[[list[tuple[str, int]]], tuple[Tensor, Tensor]], buffer_size: int, num_threads: int) Iterator[tuple[Tensor, Tensor]][source]¶
Build the dataloader for the ImageNet classification task.
The dataloader uses the
decode_funcfor decoding images concurrently and send the resulting data to GPU.- Parameters:
src – The source of the data. See
source().batch_size – The number of images in a batch.
decode_func – The function to decode images.
buffer_size – The size of the buffer for the dataloader sink
num_threads – The number of worker threads.
- get_model(batch_size: int, device_index: int, compile: bool, use_bf16: bool, model_type: str = 'mobilenetv3_large_100') ModelBundle[source]¶
Build computation model, including transfor, model, and classification head.
- Parameters:
batch_size – The batch size of the input.
device_index – The index of the target GPU device.
compile – Whether to compile the model.
use_bf16 – Whether to use bfloat16 for the model.
model_type – The type of the model. Passed to
timm.create_model().
- Returns:
The resulting computation model.
Classes
- class ModelBundle[source]¶
Bundle the transform, model backbone, and classification head into a single module for a simple handling.
- forward(images: Tensor, labels: Tensor) tuple[Tensor, Tensor][source]¶
Given a batch of images and labels, compute the top1, top5 accuracy.
- Parameters:
images – A batch of images. The shape is
(batch_size, 3, 224, 224).labels – A batch of labels. The shape is
(batch_size,).
- Returns:
A tuple of top1 and top5 accuracy.
- class Classification[source]¶
- forward(x: Tensor, labels: Tensor) tuple[Tensor, Tensor][source]¶
Given a batch of features and labels, compute the top1 and top5 accuracy.
- Parameters:
images – A batch of images. The shape is
(batch_size, 3, 224, 224).labels – A batch of labels. The shape is
(batch_size,).
- Returns:
A tuple of top1 and top5 accuracy.