Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

models.rst 17 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
  1. .. _models:
  2. Models and pre-trained weights
  3. ##############################
  4. The ``torchvision.models`` subpackage contains definitions of models for addressing
  5. different tasks, including: image classification, pixelwise semantic
  6. segmentation, object detection, instance segmentation, person
  7. keypoint detection, video classification, and optical flow.
  8. General information on pre-trained weights
  9. ==========================================
  10. TorchVision offers pre-trained weights for every provided architecture, using
  11. the PyTorch :mod:`torch.hub`. Instancing a pre-trained model will download its
  12. weights to a cache directory. This directory can be set using the `TORCH_HOME`
  13. environment variable. See :func:`torch.hub.load_state_dict_from_url` for details.
  14. .. note::
  15. The pre-trained models provided in this library may have their own licenses or
  16. terms and conditions derived from the dataset used for training. It is your
  17. responsibility to determine whether you have permission to use the models for
  18. your use case.
  19. .. note ::
  20. Backward compatibility is guaranteed for loading a serialized
  21. ``state_dict`` to the model created using old PyTorch version.
  22. On the contrary, loading entire saved models or serialized
  23. ``ScriptModules`` (serialized using older versions of PyTorch)
  24. may not preserve the historic behaviour. Refer to the following
  25. `documentation
  26. <https://pytorch.org/docs/stable/notes/serialization.html#id6>`_
  27. Initializing pre-trained models
  28. -------------------------------
  29. As of v0.13, TorchVision offers a new `Multi-weight support API
  30. <https://pytorch.org/blog/introducing-torchvision-new-multi-weight-support-api/>`_
  31. for loading different weights to the existing model builder methods:
  32. .. code:: python
  33. from torchvision.models import resnet50, ResNet50_Weights
  34. # Old weights with accuracy 76.130%
  35. resnet50(weights=ResNet50_Weights.IMAGENET1K_V1)
  36. # New weights with accuracy 80.858%
  37. resnet50(weights=ResNet50_Weights.IMAGENET1K_V2)
  38. # Best available weights (currently alias for IMAGENET1K_V2)
  39. # Note that these weights may change across versions
  40. resnet50(weights=ResNet50_Weights.DEFAULT)
  41. # Strings are also supported
  42. resnet50(weights="IMAGENET1K_V2")
  43. # No weights - random initialization
  44. resnet50(weights=None)
  45. Migrating to the new API is very straightforward. The following method calls between the 2 APIs are all equivalent:
  46. .. code:: python
  47. from torchvision.models import resnet50, ResNet50_Weights
  48. # Using pretrained weights:
  49. resnet50(weights=ResNet50_Weights.IMAGENET1K_V1)
  50. resnet50(weights="IMAGENET1K_V1")
  51. resnet50(pretrained=True) # deprecated
  52. resnet50(True) # deprecated
  53. # Using no weights:
  54. resnet50(weights=None)
  55. resnet50()
  56. resnet50(pretrained=False) # deprecated
  57. resnet50(False) # deprecated
  58. Note that the ``pretrained`` parameter is now deprecated, using it will emit warnings and will be removed on v0.15.
  59. Using the pre-trained models
  60. ----------------------------
  61. Before using the pre-trained models, one must preprocess the image
  62. (resize with right resolution/interpolation, apply inference transforms,
  63. rescale the values etc). There is no standard way to do this as it depends on
  64. how a given model was trained. It can vary across model families, variants or
  65. even weight versions. Using the correct preprocessing method is critical and
  66. failing to do so may lead to decreased accuracy or incorrect outputs.
  67. All the necessary information for the inference transforms of each pre-trained
  68. model is provided on its weights documentation. To simplify inference, TorchVision
  69. bundles the necessary preprocessing transforms into each model weight. These are
  70. accessible via the ``weight.transforms`` attribute:
  71. .. code:: python
  72. # Initialize the Weight Transforms
  73. weights = ResNet50_Weights.DEFAULT
  74. preprocess = weights.transforms()
  75. # Apply it to the input image
  76. img_transformed = preprocess(img)
  77. Some models use modules which have different training and evaluation
  78. behavior, such as batch normalization. To switch between these modes, use
  79. ``model.train()`` or ``model.eval()`` as appropriate. See
  80. :meth:`~torch.nn.Module.train` or :meth:`~torch.nn.Module.eval` for details.
  81. .. code:: python
  82. # Initialize model
  83. weights = ResNet50_Weights.DEFAULT
  84. model = resnet50(weights=weights)
  85. # Set model to eval mode
  86. model.eval()
  87. Listing and retrieving available models
  88. ---------------------------------------
  89. As of v0.14, TorchVision offers a new mechanism which allows listing and
  90. retrieving models and weights by their names. Here are a few examples on how to
  91. use them:
  92. .. code:: python
  93. # List available models
  94. all_models = list_models()
  95. classification_models = list_models(module=torchvision.models)
  96. # Initialize models
  97. m1 = get_model("mobilenet_v3_large", weights=None)
  98. m2 = get_model("quantized_mobilenet_v3_large", weights="DEFAULT")
  99. # Fetch weights
  100. weights = get_weight("MobileNet_V3_Large_QuantizedWeights.DEFAULT")
  101. assert weights == MobileNet_V3_Large_QuantizedWeights.DEFAULT
  102. weights_enum = get_model_weights("quantized_mobilenet_v3_large")
  103. assert weights_enum == MobileNet_V3_Large_QuantizedWeights
  104. weights_enum2 = get_model_weights(torchvision.models.quantization.mobilenet_v3_large)
  105. assert weights_enum == weights_enum2
  106. Here are the available public functions to retrieve models and their corresponding weights:
  107. .. currentmodule:: torchvision.models
  108. .. autosummary::
  109. :toctree: generated/
  110. :template: function.rst
  111. get_model
  112. get_model_weights
  113. get_weight
  114. list_models
  115. Using models from Hub
  116. ---------------------
  117. Most pre-trained models can be accessed directly via PyTorch Hub without having TorchVision installed:
  118. .. code:: python
  119. import torch
  120. # Option 1: passing weights param as string
  121. model = torch.hub.load("pytorch/vision", "resnet50", weights="IMAGENET1K_V2")
  122. # Option 2: passing weights param as enum
  123. weights = torch.hub.load(
  124. "pytorch/vision",
  125. "get_weight",
  126. weights="ResNet50_Weights.IMAGENET1K_V2",
  127. )
  128. model = torch.hub.load("pytorch/vision", "resnet50", weights=weights)
  129. You can also retrieve all the available weights of a specific model via PyTorch Hub by doing:
  130. .. code:: python
  131. import torch
  132. weight_enum = torch.hub.load("pytorch/vision", "get_model_weights", name="resnet50")
  133. print([weight for weight in weight_enum])
  134. The only exception to the above are the detection models included on
  135. :mod:`torchvision.models.detection`. These models require TorchVision
  136. to be installed because they depend on custom C++ operators.
  137. Classification
  138. ==============
  139. .. currentmodule:: torchvision.models
  140. The following classification models are available, with or without pre-trained
  141. weights:
  142. .. toctree::
  143. :maxdepth: 1
  144. models/alexnet
  145. models/convnext
  146. models/densenet
  147. models/efficientnet
  148. models/efficientnetv2
  149. models/googlenet
  150. models/inception
  151. models/maxvit
  152. models/mnasnet
  153. models/mobilenetv2
  154. models/mobilenetv3
  155. models/regnet
  156. models/resnet
  157. models/resnext
  158. models/shufflenetv2
  159. models/squeezenet
  160. models/swin_transformer
  161. models/vgg
  162. models/vision_transformer
  163. models/wide_resnet
  164. |
  165. Here is an example of how to use the pre-trained image classification models:
  166. .. code:: python
  167. from torchvision.io import decode_image
  168. from torchvision.models import resnet50, ResNet50_Weights
  169. img = decode_image("test/assets/encode_jpeg/grace_hopper_517x606.jpg")
  170. # Step 1: Initialize model with the best available weights
  171. weights = ResNet50_Weights.DEFAULT
  172. model = resnet50(weights=weights)
  173. model.eval()
  174. # Step 2: Initialize the inference transforms
  175. preprocess = weights.transforms()
  176. # Step 3: Apply inference preprocessing transforms
  177. batch = preprocess(img).unsqueeze(0)
  178. # Step 4: Use the model and print the predicted category
  179. prediction = model(batch).squeeze(0).softmax(0)
  180. class_id = prediction.argmax().item()
  181. score = prediction[class_id].item()
  182. category_name = weights.meta["categories"][class_id]
  183. print(f"{category_name}: {100 * score:.1f}%")
  184. The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
  185. Table of all available classification weights
  186. ---------------------------------------------
  187. Accuracies are reported on ImageNet-1K using single crops:
  188. .. include:: generated/classification_table.rst
  189. Quantized models
  190. ----------------
  191. .. currentmodule:: torchvision.models.quantization
  192. The following architectures provide support for INT8 quantized models, with or without
  193. pre-trained weights:
  194. .. toctree::
  195. :maxdepth: 1
  196. models/googlenet_quant
  197. models/inception_quant
  198. models/mobilenetv2_quant
  199. models/mobilenetv3_quant
  200. models/resnet_quant
  201. models/resnext_quant
  202. models/shufflenetv2_quant
  203. |
  204. Here is an example of how to use the pre-trained quantized image classification models:
  205. .. code:: python
  206. from torchvision.io import decode_image
  207. from torchvision.models.quantization import resnet50, ResNet50_QuantizedWeights
  208. img = decode_image("test/assets/encode_jpeg/grace_hopper_517x606.jpg")
  209. # Step 1: Initialize model with the best available weights
  210. weights = ResNet50_QuantizedWeights.DEFAULT
  211. model = resnet50(weights=weights, quantize=True)
  212. model.eval()
  213. # Step 2: Initialize the inference transforms
  214. preprocess = weights.transforms()
  215. # Step 3: Apply inference preprocessing transforms
  216. batch = preprocess(img).unsqueeze(0)
  217. # Step 4: Use the model and print the predicted category
  218. prediction = model(batch).squeeze(0).softmax(0)
  219. class_id = prediction.argmax().item()
  220. score = prediction[class_id].item()
  221. category_name = weights.meta["categories"][class_id]
  222. print(f"{category_name}: {100 * score}%")
  223. The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
  224. Table of all available quantized classification weights
  225. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  226. Accuracies are reported on ImageNet-1K using single crops:
  227. .. include:: generated/classification_quant_table.rst
  228. Semantic Segmentation
  229. =====================
  230. .. currentmodule:: torchvision.models.segmentation
  231. .. betastatus:: segmentation module
  232. The following semantic segmentation models are available, with or without
  233. pre-trained weights:
  234. .. toctree::
  235. :maxdepth: 1
  236. models/deeplabv3
  237. models/fcn
  238. models/lraspp
  239. |
  240. Here is an example of how to use the pre-trained semantic segmentation models:
  241. .. code:: python
  242. from torchvision.io.image import decode_image
  243. from torchvision.models.segmentation import fcn_resnet50, FCN_ResNet50_Weights
  244. from torchvision.transforms.functional import to_pil_image
  245. img = decode_image("gallery/assets/dog1.jpg")
  246. # Step 1: Initialize model with the best available weights
  247. weights = FCN_ResNet50_Weights.DEFAULT
  248. model = fcn_resnet50(weights=weights)
  249. model.eval()
  250. # Step 2: Initialize the inference transforms
  251. preprocess = weights.transforms()
  252. # Step 3: Apply inference preprocessing transforms
  253. batch = preprocess(img).unsqueeze(0)
  254. # Step 4: Use the model and visualize the prediction
  255. prediction = model(batch)["out"]
  256. normalized_masks = prediction.softmax(dim=1)
  257. class_to_idx = {cls: idx for (idx, cls) in enumerate(weights.meta["categories"])}
  258. mask = normalized_masks[0, class_to_idx["dog"]]
  259. to_pil_image(mask).show()
  260. The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
  261. The output format of the models is illustrated in :ref:`semantic_seg_output`.
  262. Table of all available semantic segmentation weights
  263. ----------------------------------------------------
  264. All models are evaluated a subset of COCO val2017, on the 20 categories that are present in the Pascal VOC dataset:
  265. .. include:: generated/segmentation_table.rst
  266. .. _object_det_inst_seg_pers_keypoint_det:
  267. Object Detection, Instance Segmentation and Person Keypoint Detection
  268. =====================================================================
  269. The pre-trained models for detection, instance segmentation and
  270. keypoint detection are initialized with the classification models
  271. in torchvision. The models expect a list of ``Tensor[C, H, W]``.
  272. Check the constructor of the models for more information.
  273. .. betastatus:: detection module
  274. Object Detection
  275. ----------------
  276. .. currentmodule:: torchvision.models.detection
  277. The following object detection models are available, with or without pre-trained
  278. weights:
  279. .. toctree::
  280. :maxdepth: 1
  281. models/faster_rcnn
  282. models/fcos
  283. models/retinanet
  284. models/ssd
  285. models/ssdlite
  286. |
  287. Here is an example of how to use the pre-trained object detection models:
  288. .. code:: python
  289. from torchvision.io.image import decode_image
  290. from torchvision.models.detection import fasterrcnn_resnet50_fpn_v2, FasterRCNN_ResNet50_FPN_V2_Weights
  291. from torchvision.utils import draw_bounding_boxes
  292. from torchvision.transforms.functional import to_pil_image
  293. img = decode_image("test/assets/encode_jpeg/grace_hopper_517x606.jpg")
  294. # Step 1: Initialize model with the best available weights
  295. weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT
  296. model = fasterrcnn_resnet50_fpn_v2(weights=weights, box_score_thresh=0.9)
  297. model.eval()
  298. # Step 2: Initialize the inference transforms
  299. preprocess = weights.transforms()
  300. # Step 3: Apply inference preprocessing transforms
  301. batch = [preprocess(img)]
  302. # Step 4: Use the model and visualize the prediction
  303. prediction = model(batch)[0]
  304. labels = [weights.meta["categories"][i] for i in prediction["labels"]]
  305. box = draw_bounding_boxes(img, boxes=prediction["boxes"],
  306. labels=labels,
  307. colors="red",
  308. width=4, font_size=30)
  309. im = to_pil_image(box.detach())
  310. im.show()
  311. The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
  312. For details on how to plot the bounding boxes of the models, you may refer to :ref:`instance_seg_output`.
  313. Table of all available Object detection weights
  314. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  315. Box MAPs are reported on COCO val2017:
  316. .. include:: generated/detection_table.rst
  317. Instance Segmentation
  318. ---------------------
  319. .. currentmodule:: torchvision.models.detection
  320. The following instance segmentation models are available, with or without pre-trained
  321. weights:
  322. .. toctree::
  323. :maxdepth: 1
  324. models/mask_rcnn
  325. |
  326. For details on how to plot the masks of the models, you may refer to :ref:`instance_seg_output`.
  327. Table of all available Instance segmentation weights
  328. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  329. Box and Mask MAPs are reported on COCO val2017:
  330. .. include:: generated/instance_segmentation_table.rst
  331. Keypoint Detection
  332. ------------------
  333. .. currentmodule:: torchvision.models.detection
  334. The following person keypoint detection models are available, with or without
  335. pre-trained weights:
  336. .. toctree::
  337. :maxdepth: 1
  338. models/keypoint_rcnn
  339. |
  340. The classes of the pre-trained model outputs can be found at ``weights.meta["keypoint_names"]``.
  341. For details on how to plot the bounding boxes of the models, you may refer to :ref:`keypoint_output`.
  342. Table of all available Keypoint detection weights
  343. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  344. Box and Keypoint MAPs are reported on COCO val2017:
  345. .. include:: generated/detection_keypoint_table.rst
  346. Video Classification
  347. ====================
  348. .. currentmodule:: torchvision.models.video
  349. .. betastatus:: video module
  350. The following video classification models are available, with or without
  351. pre-trained weights:
  352. .. toctree::
  353. :maxdepth: 1
  354. models/video_mvit
  355. models/video_resnet
  356. models/video_s3d
  357. models/video_swin_transformer
  358. |
  359. Here is an example of how to use the pre-trained video classification models:
  360. .. code:: python
  361. from torchvision.io.video import read_video
  362. from torchvision.models.video import r3d_18, R3D_18_Weights
  363. vid, _, _ = read_video("test/assets/videos/v_SoccerJuggling_g23_c01.avi", output_format="TCHW")
  364. vid = vid[:32] # optionally shorten duration
  365. # Step 1: Initialize model with the best available weights
  366. weights = R3D_18_Weights.DEFAULT
  367. model = r3d_18(weights=weights)
  368. model.eval()
  369. # Step 2: Initialize the inference transforms
  370. preprocess = weights.transforms()
  371. # Step 3: Apply inference preprocessing transforms
  372. batch = preprocess(vid).unsqueeze(0)
  373. # Step 4: Use the model and print the predicted category
  374. prediction = model(batch).squeeze(0).softmax(0)
  375. label = prediction.argmax().item()
  376. score = prediction[label].item()
  377. category_name = weights.meta["categories"][label]
  378. print(f"{category_name}: {100 * score}%")
  379. The classes of the pre-trained model outputs can be found at ``weights.meta["categories"]``.
  380. Table of all available video classification weights
  381. ---------------------------------------------------
  382. Accuracies are reported on Kinetics-400 using single crops for clip length 16:
  383. .. include:: generated/video_table.rst
  384. Optical Flow
  385. ============
  386. .. currentmodule:: torchvision.models.optical_flow
  387. The following Optical Flow models are available, with or without pre-trained
  388. .. toctree::
  389. :maxdepth: 1
  390. models/raft
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...