models.rst 17.1 KB
Newer Older
1
2
.. _models:

3
4
Models and pre-trained weights
##############################
5

6
The ``torchvision.models`` subpackage contains definitions of models for addressing
7
different tasks, including: image classification, pixelwise semantic
8
segmentation, object detection, instance segmentation, person
9
keypoint detection, video classification, and optical flow.
10

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
General information on pre-trained weights
==========================================

TorchVision offers pre-trained weights for every provided architecture, using
the PyTorch :mod:`torch.hub`. Instancing a pre-trained model will download its
weights to a cache directory. This directory can be set using the `TORCH_HOME`
environment variable. See :func:`torch.hub.load_state_dict_from_url` for details.

.. note::

    The pre-trained models provided in this library may have their own licenses or
    terms and conditions derived from the dataset used for training. It is your
    responsibility to determine whether you have permission to use the models for
    your use case.

26
.. note ::
27
28
29
30
31
32
33
    Backward compatibility is guaranteed for loading a serialized
    ``state_dict`` to the model created using old PyTorch version.
    On the contrary, loading entire saved models or serialized
    ``ScriptModules`` (serialized using older versions of PyTorch)
    may not preserve the historic behaviour. Refer to the following
    `documentation
    <https://pytorch.org/docs/stable/notes/serialization.html#id6>`_
34

35

36
37
Initializing pre-trained models
-------------------------------
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
38

39
40
41
As of v0.13, TorchVision offers a new `Multi-weight support API
<https://pytorch.org/blog/introducing-torchvision-new-multi-weight-support-api/>`_
for loading different weights to the existing model builder methods:
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
42
43
44

.. code:: python

45
    from torchvision.models import resnet50, ResNet50_Weights
46

47
48
    # Old weights with accuracy 76.130%
    resnet50(weights=ResNet50_Weights.IMAGENET1K_V1)
49

50
51
    # New weights with accuracy 80.858%
    resnet50(weights=ResNet50_Weights.IMAGENET1K_V2)
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
52

53
54
55
    # Best available weights (currently alias for IMAGENET1K_V2)
    # Note that these weights may change across versions
    resnet50(weights=ResNet50_Weights.DEFAULT)
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
56

57
58
    # Strings are also supported
    resnet50(weights="IMAGENET1K_V2")
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
59

60
61
    # No weights - random initialization
    resnet50(weights=None)
62

Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
63

64
Migrating to the new API is very straightforward. The following method calls between the 2 APIs are all equivalent:
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
65

66
.. code:: python
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
67

68
    from torchvision.models import resnet50, ResNet50_Weights
69

70
71
72
73
74
    # Using pretrained weights:
    resnet50(weights=ResNet50_Weights.IMAGENET1K_V1)
    resnet50(weights="IMAGENET1K_V1")
    resnet50(pretrained=True)  # deprecated
    resnet50(True)  # deprecated
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
75

76
77
78
79
80
    # Using no weights:
    resnet50(weights=None)
    resnet50()
    resnet50(pretrained=False)  # deprecated
    resnet50(False)  # deprecated
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
81

82
Note that the ``pretrained`` parameter is now deprecated, using it will emit warnings and will be removed on v0.15.
83

84
85
Using the pre-trained models
----------------------------
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
86

87
88
89
90
91
92
Before using the pre-trained models, one must preprocess the image
(resize with right resolution/interpolation, apply inference transforms,
rescale the values etc). There is no standard way to do this as it depends on
how a given model was trained. It can vary across model families, variants or
even weight versions. Using the correct preprocessing method is critical and
failing to do so may lead to decreased accuracy or incorrect outputs.
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
93

94
95
96
97
All the necessary information for the inference transforms of each pre-trained
model is provided on its weights documentation. To simplify inference, TorchVision
bundles the necessary preprocessing transforms into each model weight. These are
accessible via the ``weight.transforms`` attribute:
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
98

99
.. code:: python
100

101
102
103
    # Initialize the Weight Transforms
    weights = ResNet50_Weights.DEFAULT
    preprocess = weights.transforms()
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
104

105
106
    # Apply it to the input image
    img_transformed = preprocess(img)
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
107

108

109
110
111
112
Some models use modules which have different training and evaluation
behavior, such as batch normalization. To switch between these modes, use
``model.train()`` or ``model.eval()`` as appropriate. See
:meth:`~torch.nn.Module.train` or :meth:`~torch.nn.Module.eval` for details.
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
113

114
.. code:: python
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
115

116
117
118
    # Initialize model
    weights = ResNet50_Weights.DEFAULT
    model = resnet50(weights=weights)
119

120
121
    # Set model to eval mode
    model.eval()
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
122

123
124
125
126
127
Model Registration Mechanism
----------------------------

.. betastatus:: registration mechanism

Nghia's avatar
Nghia committed
128
As of v0.14, TorchVision offers a new model registration mechanism which allows retrieving models
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
and weights by their names. Here are a few examples on how to use them:

.. code:: python

    # List available models
    all_models = list_models()
    classification_models = list_models(module=torchvision.models)

    # Initialize models
    m1 = get_model("mobilenet_v3_large", weights=None)
    m2 = get_model("quantized_mobilenet_v3_large", weights="DEFAULT")

    # Fetch weights
    weights = get_weight("MobileNet_V3_Large_QuantizedWeights.DEFAULT")
    assert weights == MobileNet_V3_Large_QuantizedWeights.DEFAULT

    weights_enum = get_model_weights("quantized_mobilenet_v3_large")
    assert weights_enum == MobileNet_V3_Large_QuantizedWeights

    weights_enum2 = get_model_weights(torchvision.models.quantization.mobilenet_v3_large)
    assert weights_enum == weights_enum2

Here are the available public methods of the model registration mechanism:

.. currentmodule:: torchvision.models
.. autosummary::
    :toctree: generated/
    :template: function.rst

    get_model
    get_model_weights
    get_weight
    list_models

163
164
Using models from Hub
---------------------
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
165

166
Most pre-trained models can be accessed directly via PyTorch Hub without having TorchVision installed:
167

168
.. code:: python
Sasank Chilamkurthy's avatar
Sasank Chilamkurthy committed
169

170
    import torch
171

172
173
    # Option 1: passing weights param as string
    model = torch.hub.load("pytorch/vision", "resnet50", weights="IMAGENET1K_V2")
174

175
176
177
    # Option 2: passing weights param as enum
    weights = torch.hub.load("pytorch/vision", "get_weight", weights="ResNet50_Weights.IMAGENET1K_V2")
    model = torch.hub.load("pytorch/vision", "resnet50", weights=weights)
178

179
180
181
182
183
184
185
186
187
You can also retrieve all the available weights of a specific model via PyTorch Hub by doing:

.. code:: python

    import torch

    weight_enum = torch.hub.load("pytorch/vision", "get_model_weights", name="resnet50")
    print([weight for weight in weight_enum])

188
189
190
The only exception to the above are the detection models included on
:mod:`torchvision.models.detection`. These models require TorchVision
to be installed because they depend on custom C++ operators.
Bar's avatar
Bar committed
191

192
193
Classification
==============
194

195
.. currentmodule:: torchvision.models
Bar's avatar
Bar committed
196

197
198
199
200
201
202
203
204
205
206
207
208
209
The following classification models are available, with or without pre-trained
weights:

.. toctree::
   :maxdepth: 1

   models/alexnet
   models/convnext
   models/densenet
   models/efficientnet
   models/efficientnetv2
   models/googlenet
   models/inception
Ponku's avatar
Ponku committed
210
   models/maxvit
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
   models/mnasnet
   models/mobilenetv2
   models/mobilenetv3
   models/regnet
   models/resnet
   models/resnext
   models/shufflenetv2
   models/squeezenet
   models/swin_transformer
   models/vgg
   models/vision_transformer
   models/wide_resnet

|

Here is an example of how to use the pre-trained image classification models:
227

228
.. code:: python
229

230
231
    from torchvision.io import read_image
    from torchvision.models import resnet50, ResNet50_Weights
232

233
    img = read_image("test/assets/encode_jpeg/grace_hopper_517x606.jpg")
234

235
236
237
238
    # Step 1: Initialize model with the best available weights
    weights = ResNet50_Weights.DEFAULT
    model = resnet50(weights=weights)
    model.eval()
239

240
241
    # Step 2: Initialize the inference transforms
    preprocess = weights.transforms()
242

243
244
    # Step 3: Apply inference preprocessing transforms
    batch = preprocess(img).unsqueeze(0)
245

246
247
248
249
250
251
    # Step 4: Use the model and print the predicted category
    prediction = model(batch).squeeze(0).softmax(0)
    class_id = prediction.argmax().item()
    score = prediction[class_id].item()
    category_name = weights.meta["categories"][class_id]
    print(f"{category_name}: {100 * score:.1f}%")
252

253
The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
254

255
256
Table of all available classification weights
---------------------------------------------
257

258
Accuracies are reported on ImageNet-1K using single crops:
259

260
.. include:: generated/classification_table.rst
261

262
263
Quantized models
----------------
264

265
.. currentmodule:: torchvision.models.quantization
266

267
268
The following architectures provide support for INT8 quantized models, with or without
pre-trained weights:
269

270
271
.. toctree::
   :maxdepth: 1
272

273
274
275
276
277
278
279
   models/googlenet_quant
   models/inception_quant
   models/mobilenetv2_quant
   models/mobilenetv3_quant
   models/resnet_quant
   models/resnext_quant
   models/shufflenetv2_quant
280

281
|
282

283
Here is an example of how to use the pre-trained quantized image classification models:
284
285
286

.. code:: python

287
288
289
290
291
292
293
294
    from torchvision.io import read_image
    from torchvision.models.quantization import resnet50, ResNet50_QuantizedWeights

    img = read_image("test/assets/encode_jpeg/grace_hopper_517x606.jpg")

    # Step 1: Initialize model with the best available weights
    weights = ResNet50_QuantizedWeights.DEFAULT
    model = resnet50(weights=weights, quantize=True)
295
296
    model.eval()

297
298
    # Step 2: Initialize the inference transforms
    preprocess = weights.transforms()
299

300
301
    # Step 3: Apply inference preprocessing transforms
    batch = preprocess(img).unsqueeze(0)
302

303
304
305
306
307
308
    # Step 4: Use the model and print the predicted category
    prediction = model(batch).squeeze(0).softmax(0)
    class_id = prediction.argmax().item()
    score = prediction[class_id].item()
    category_name = weights.meta["categories"][class_id]
    print(f"{category_name}: {100 * score}%")
309

310
The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
311

312

313
314
Table of all available quantized classification weights
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
315

316
Accuracies are reported on ImageNet-1K using single crops:
317

318
.. include:: generated/classification_quant_table.rst
319

320
321
Semantic Segmentation
=====================
322

323
.. currentmodule:: torchvision.models.segmentation
324

325
326
.. betastatus:: segmentation module

327
328
The following semantic segmentation models are available, with or without
pre-trained weights:
329

330
331
.. toctree::
   :maxdepth: 1
332

333
334
335
336
337
   models/deeplabv3
   models/fcn
   models/lraspp

|
338

339
Here is an example of how to use the pre-trained semantic segmentation models:
340

341
.. code:: python
342

343
344
345
    from torchvision.io.image import read_image
    from torchvision.models.segmentation import fcn_resnet50, FCN_ResNet50_Weights
    from torchvision.transforms.functional import to_pil_image
346

347
    img = read_image("gallery/assets/dog1.jpg")
348

349
350
351
352
    # Step 1: Initialize model with the best available weights
    weights = FCN_ResNet50_Weights.DEFAULT
    model = fcn_resnet50(weights=weights)
    model.eval()
353

354
355
    # Step 2: Initialize the inference transforms
    preprocess = weights.transforms()
356

357
358
    # Step 3: Apply inference preprocessing transforms
    batch = preprocess(img).unsqueeze(0)
359

360
361
362
363
364
365
    # Step 4: Use the model and visualize the prediction
    prediction = model(batch)["out"]
    normalized_masks = prediction.softmax(dim=1)
    class_to_idx = {cls: idx for (idx, cls) in enumerate(weights.meta["categories"])}
    mask = normalized_masks[0, class_to_idx["dog"]]
    to_pil_image(mask).show()
366

367
368
369
370
371
372
373
374
375
376
The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
The output format of the models is illustrated in :ref:`semantic_seg_output`.


Table of all available semantic segmentation weights
----------------------------------------------------

All models are evaluated a subset of COCO val2017, on the 20 categories that are present in the Pascal VOC dataset:

.. include:: generated/segmentation_table.rst
377

378

379
.. _object_det_inst_seg_pers_keypoint_det:
380
381
382
383
384
385

Object Detection, Instance Segmentation and Person Keypoint Detection
=====================================================================

The pre-trained models for detection, instance segmentation and
keypoint detection are initialized with the classification models
386
387
in torchvision. The models expect a list of ``Tensor[C, H, W]``.
Check the constructor of the models for more information.
388

389
390
.. betastatus:: detection module

391
392
Object Detection
----------------
393

394
.. currentmodule:: torchvision.models.detection
395

396
397
The following object detection models are available, with or without pre-trained
weights:
398

399
400
.. toctree::
   :maxdepth: 1
401

402
403
404
405
406
   models/faster_rcnn
   models/fcos
   models/retinanet
   models/ssd
   models/ssdlite
407

408
|
409

410
Here is an example of how to use the pre-trained object detection models:
411

412
.. code:: python
413

414

415
416
417
418
    from torchvision.io.image import read_image
    from torchvision.models.detection import fasterrcnn_resnet50_fpn_v2, FasterRCNN_ResNet50_FPN_V2_Weights
    from torchvision.utils import draw_bounding_boxes
    from torchvision.transforms.functional import to_pil_image
419

420
    img = read_image("test/assets/encode_jpeg/grace_hopper_517x606.jpg")
Hu Ye's avatar
Hu Ye committed
421

422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    # Step 1: Initialize model with the best available weights
    weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT
    model = fasterrcnn_resnet50_fpn_v2(weights=weights, box_score_thresh=0.9)
    model.eval()

    # Step 2: Initialize the inference transforms
    preprocess = weights.transforms()

    # Step 3: Apply inference preprocessing transforms
    batch = [preprocess(img)]

    # Step 4: Use the model and visualize the prediction
    prediction = model(batch)[0]
    labels = [weights.meta["categories"][i] for i in prediction["labels"]]
    box = draw_bounding_boxes(img, boxes=prediction["boxes"],
                              labels=labels,
                              colors="red",
                              width=4, font_size=30)
    im = to_pil_image(box.detach())
    im.show()

The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
For details on how to plot the bounding boxes of the models, you may refer to :ref:`instance_seg_output`.

Table of all available Object detection weights
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Box MAPs are reported on COCO val2017:

.. include:: generated/detection_table.rst
Hu Ye's avatar
Hu Ye committed
452
453


454
455
Instance Segmentation
---------------------
456

457
.. currentmodule:: torchvision.models.detection
458

459
460
The following instance segmentation models are available, with or without pre-trained
weights:
461

462
463
.. toctree::
   :maxdepth: 1
464

465
   models/mask_rcnn
466

467
|
468

469

470
For details on how to plot the masks of the models, you may refer to :ref:`instance_seg_output`.
471

472
473
Table of all available Instance segmentation weights
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
474

475
Box and Mask MAPs are reported on COCO val2017:
476

477
.. include:: generated/instance_segmentation_table.rst
478

479
480
Keypoint Detection
------------------
481

482
.. currentmodule:: torchvision.models.detection
483

484
485
The following person keypoint detection models are available, with or without
pre-trained weights:
486

487
488
.. toctree::
   :maxdepth: 1
489

490
   models/keypoint_rcnn
491

492
|
493

494
495
The classes of the pre-trained model outputs can be found at ``weights.meta["keypoint_names"]``.
For details on how to plot the bounding boxes of the models, you may refer to :ref:`keypoint_output`.
496

497
498
Table of all available Keypoint detection weights
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
499

500
Box and Keypoint MAPs are reported on COCO val2017:
501

502
.. include:: generated/detection_keypoint_table.rst
503

504
505

Video Classification
506
507
====================

508
.. currentmodule:: torchvision.models.video
509

510
511
.. betastatus:: video module

512
513
The following video classification models are available, with or without
pre-trained weights:
514

515
516
.. toctree::
   :maxdepth: 1
517

518
   models/video_mvit
519
   models/video_resnet
520
   models/video_s3d
Aditya Oke's avatar
Aditya Oke committed
521
   models/video_swin_transformer
522

523
524
525
526
527
|

Here is an example of how to use the pre-trained video classification models:

.. code:: python
528
529


530
531
    from torchvision.io.video import read_video
    from torchvision.models.video import r3d_18, R3D_18_Weights
532

533
    vid, _, _ = read_video("test/assets/videos/v_SoccerJuggling_g23_c01.avi", output_format="TCHW")
534
    vid = vid[:32]  # optionally shorten duration
535

536
537
538
539
    # Step 1: Initialize model with the best available weights
    weights = R3D_18_Weights.DEFAULT
    model = r3d_18(weights=weights)
    model.eval()
540

541
542
    # Step 2: Initialize the inference transforms
    preprocess = weights.transforms()
543

544
545
    # Step 3: Apply inference preprocessing transforms
    batch = preprocess(vid).unsqueeze(0)
546

547
548
549
550
551
552
    # Step 4: Use the model and print the predicted category
    prediction = model(batch).squeeze(0).softmax(0)
    label = prediction.argmax().item()
    score = prediction[label].item()
    category_name = weights.meta["categories"][label]
    print(f"{category_name}: {100 * score}%")
553

554
The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
555

556

557
558
Table of all available video classification weights
---------------------------------------------------
559

560
Accuracies are reported on Kinetics-400 using single crops for clip length 16:
561

562
.. include:: generated/video_table.rst
563

564
Optical Flow
565
566
============

567
568
569
.. currentmodule:: torchvision.models.optical_flow

The following Optical Flow models are available, with or without pre-trained
570

571
572
.. toctree::
   :maxdepth: 1
573

574
   models/raft