test_models.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. import contextlib
  2. import functools
  3. import operator
  4. import os
  5. import pkgutil
  6. import platform
  7. import sys
  8. import warnings
  9. from collections import OrderedDict
  10. from tempfile import TemporaryDirectory
  11. from typing import Any
  12. import pytest
  13. import torch
  14. import torch.fx
  15. import torch.nn as nn
  16. from _utils_internal import get_relative_path
  17. from common_utils import cpu_and_cuda, freeze_rng_state, map_nested_tensor_object, needs_cuda, set_rng_seed
  18. from PIL import Image
  19. from torchvision import models, transforms
  20. from torchvision.models import get_model_builder, list_models
  21. ACCEPT = os.getenv("EXPECTTEST_ACCEPT", "0") == "1"
  22. SKIP_BIG_MODEL = os.getenv("SKIP_BIG_MODEL", "1") == "1"
  23. @contextlib.contextmanager
  24. def disable_tf32():
  25. previous = torch.backends.cudnn.allow_tf32
  26. torch.backends.cudnn.allow_tf32 = False
  27. try:
  28. yield
  29. finally:
  30. torch.backends.cudnn.allow_tf32 = previous
  31. def list_model_fns(module):
  32. return [get_model_builder(name) for name in list_models(module)]
  33. def _get_image(input_shape, real_image, device, dtype=None):
  34. """This routine loads a real or random image based on `real_image` argument.
  35. Currently, the real image is utilized for the following list of models:
  36. - `retinanet_resnet50_fpn`,
  37. - `retinanet_resnet50_fpn_v2`,
  38. - `keypointrcnn_resnet50_fpn`,
  39. - `fasterrcnn_resnet50_fpn`,
  40. - `fasterrcnn_resnet50_fpn_v2`,
  41. - `fcos_resnet50_fpn`,
  42. - `maskrcnn_resnet50_fpn`,
  43. - `maskrcnn_resnet50_fpn_v2`,
  44. in `test_classification_model` and `test_detection_model`.
  45. To do so, a keyword argument `real_image` was added to the abovelisted models in `_model_params`
  46. """
  47. if real_image:
  48. # TODO: Maybe unify file discovery logic with test_image.py
  49. GRACE_HOPPER = os.path.join(
  50. os.path.dirname(os.path.abspath(__file__)), "assets", "encode_jpeg", "grace_hopper_517x606.jpg"
  51. )
  52. img = Image.open(GRACE_HOPPER)
  53. original_width, original_height = img.size
  54. # make the image square
  55. img = img.crop((0, 0, original_width, original_width))
  56. img = img.resize(input_shape[1:3])
  57. convert_tensor = transforms.ToTensor()
  58. image = convert_tensor(img)
  59. assert tuple(image.size()) == input_shape
  60. return image.to(device=device, dtype=dtype)
  61. # RNG always on CPU, to ensure x in cuda tests is bitwise identical to x in cpu tests
  62. return torch.rand(input_shape).to(device=device, dtype=dtype)
  63. @pytest.fixture
  64. def disable_weight_loading(mocker):
  65. """When testing models, the two slowest operations are the downloading of the weights to a file and loading them
  66. into the model. Unless, you want to test against specific weights, these steps can be disabled without any
  67. drawbacks.
  68. Including this fixture into the signature of your test, i.e. `test_foo(disable_weight_loading)`, will recurse
  69. through all models in `torchvision.models` and will patch all occurrences of the function
  70. `download_state_dict_from_url` as well as the method `load_state_dict` on all subclasses of `nn.Module` to be
  71. no-ops.
  72. .. warning:
  73. Loaded models are still executable as normal, but will always have random weights. Make sure to not use this
  74. fixture if you want to compare the model output against reference values.
  75. """
  76. starting_point = models
  77. function_name = "load_state_dict_from_url"
  78. method_name = "load_state_dict"
  79. module_names = {info.name for info in pkgutil.walk_packages(starting_point.__path__, f"{starting_point.__name__}.")}
  80. targets = {f"torchvision._internally_replaced_utils.{function_name}", f"torch.nn.Module.{method_name}"}
  81. for name in module_names:
  82. module = sys.modules.get(name)
  83. if not module:
  84. continue
  85. if function_name in module.__dict__:
  86. targets.add(f"{module.__name__}.{function_name}")
  87. targets.update(
  88. {
  89. f"{module.__name__}.{obj.__name__}.{method_name}"
  90. for obj in module.__dict__.values()
  91. if isinstance(obj, type) and issubclass(obj, nn.Module) and method_name in obj.__dict__
  92. }
  93. )
  94. for target in targets:
  95. # See https://github.com/pytorch/vision/pull/4867#discussion_r743677802 for details
  96. with contextlib.suppress(AttributeError):
  97. mocker.patch(target)
  98. def _get_expected_file(name=None):
  99. # Determine expected file based on environment
  100. expected_file_base = get_relative_path(os.path.realpath(__file__), "expect")
  101. # Note: for legacy reasons, the reference file names all had "ModelTest.test_" in their names
  102. # We hardcode it here to avoid having to re-generate the reference files
  103. expected_file = os.path.join(expected_file_base, "ModelTester.test_" + name)
  104. expected_file += "_expect.pkl"
  105. if not ACCEPT and not os.path.exists(expected_file):
  106. raise RuntimeError(
  107. f"No expect file exists for {os.path.basename(expected_file)} in {expected_file}; "
  108. "to accept the current output, re-run the failing test after setting the EXPECTTEST_ACCEPT "
  109. "env variable. For example: EXPECTTEST_ACCEPT=1 pytest test/test_models.py -k alexnet"
  110. )
  111. return expected_file
  112. def _assert_expected(output, name, prec=None, atol=None, rtol=None):
  113. """Test that a python value matches the recorded contents of a file
  114. based on a "check" name. The value must be
  115. pickable with `torch.save`. This file
  116. is placed in the 'expect' directory in the same directory
  117. as the test script. You can automatically update the recorded test
  118. output using an EXPECTTEST_ACCEPT=1 env variable.
  119. """
  120. expected_file = _get_expected_file(name)
  121. if ACCEPT:
  122. filename = {os.path.basename(expected_file)}
  123. print(f"Accepting updated output for {filename}:\n\n{output}")
  124. torch.save(output, expected_file)
  125. MAX_PICKLE_SIZE = 50 * 1000 # 50 KB
  126. binary_size = os.path.getsize(expected_file)
  127. if binary_size > MAX_PICKLE_SIZE:
  128. raise RuntimeError(f"The output for {filename}, is larger than 50kb - got {binary_size}kb")
  129. else:
  130. expected = torch.load(expected_file)
  131. rtol = rtol or prec # keeping prec param for legacy reason, but could be removed ideally
  132. atol = atol or prec
  133. torch.testing.assert_close(output, expected, rtol=rtol, atol=atol, check_dtype=False, check_device=False)
  134. def _check_jit_scriptable(nn_module, args, unwrapper=None, eager_out=None):
  135. """Check that a nn.Module's results in TorchScript match eager and that it can be exported"""
  136. def get_export_import_copy(m):
  137. """Save and load a TorchScript model"""
  138. with TemporaryDirectory() as dir:
  139. path = os.path.join(dir, "script.pt")
  140. m.save(path)
  141. imported = torch.jit.load(path)
  142. return imported
  143. sm = torch.jit.script(nn_module)
  144. sm.eval()
  145. if eager_out is None:
  146. with torch.no_grad(), freeze_rng_state():
  147. eager_out = nn_module(*args)
  148. with torch.no_grad(), freeze_rng_state():
  149. script_out = sm(*args)
  150. if unwrapper:
  151. script_out = unwrapper(script_out)
  152. torch.testing.assert_close(eager_out, script_out, atol=1e-4, rtol=1e-4)
  153. m_import = get_export_import_copy(sm)
  154. with torch.no_grad(), freeze_rng_state():
  155. imported_script_out = m_import(*args)
  156. if unwrapper:
  157. imported_script_out = unwrapper(imported_script_out)
  158. torch.testing.assert_close(script_out, imported_script_out, atol=3e-4, rtol=3e-4)
  159. def _check_fx_compatible(model, inputs, eager_out=None):
  160. model_fx = torch.fx.symbolic_trace(model)
  161. if eager_out is None:
  162. eager_out = model(inputs)
  163. with torch.no_grad(), freeze_rng_state():
  164. fx_out = model_fx(inputs)
  165. torch.testing.assert_close(eager_out, fx_out)
  166. def _check_input_backprop(model, inputs):
  167. if isinstance(inputs, list):
  168. requires_grad = list()
  169. for inp in inputs:
  170. requires_grad.append(inp.requires_grad)
  171. inp.requires_grad_(True)
  172. else:
  173. requires_grad = inputs.requires_grad
  174. inputs.requires_grad_(True)
  175. out = model(inputs)
  176. if isinstance(out, dict):
  177. out["out"].sum().backward()
  178. else:
  179. if isinstance(out[0], dict):
  180. out[0]["scores"].sum().backward()
  181. else:
  182. out[0].sum().backward()
  183. if isinstance(inputs, list):
  184. for i, inp in enumerate(inputs):
  185. assert inputs[i].grad is not None
  186. inp.requires_grad_(requires_grad[i])
  187. else:
  188. assert inputs.grad is not None
  189. inputs.requires_grad_(requires_grad)
  190. # If 'unwrapper' is provided it will be called with the script model outputs
  191. # before they are compared to the eager model outputs. This is useful if the
  192. # model outputs are different between TorchScript / Eager mode
  193. script_model_unwrapper = {
  194. "googlenet": lambda x: x.logits,
  195. "inception_v3": lambda x: x.logits,
  196. "fasterrcnn_resnet50_fpn": lambda x: x[1],
  197. "fasterrcnn_resnet50_fpn_v2": lambda x: x[1],
  198. "fasterrcnn_mobilenet_v3_large_fpn": lambda x: x[1],
  199. "fasterrcnn_mobilenet_v3_large_320_fpn": lambda x: x[1],
  200. "maskrcnn_resnet50_fpn": lambda x: x[1],
  201. "maskrcnn_resnet50_fpn_v2": lambda x: x[1],
  202. "keypointrcnn_resnet50_fpn": lambda x: x[1],
  203. "retinanet_resnet50_fpn": lambda x: x[1],
  204. "retinanet_resnet50_fpn_v2": lambda x: x[1],
  205. "ssd300_vgg16": lambda x: x[1],
  206. "ssdlite320_mobilenet_v3_large": lambda x: x[1],
  207. "fcos_resnet50_fpn": lambda x: x[1],
  208. }
  209. # The following models exhibit flaky numerics under autocast in _test_*_model harnesses.
  210. # This may be caused by the harness environment (e.g. num classes, input initialization
  211. # via torch.rand), and does not prove autocast is unsuitable when training with real data
  212. # (autocast has been used successfully with real data for some of these models).
  213. # TODO: investigate why autocast numerics are flaky in the harnesses.
  214. #
  215. # For the following models, _test_*_model harnesses skip numerical checks on outputs when
  216. # trying autocast. However, they still try an autocasted forward pass, so they still ensure
  217. # autocast coverage suffices to prevent dtype errors in each model.
  218. autocast_flaky_numerics = (
  219. "inception_v3",
  220. "resnet101",
  221. "resnet152",
  222. "wide_resnet101_2",
  223. "deeplabv3_resnet50",
  224. "deeplabv3_resnet101",
  225. "deeplabv3_mobilenet_v3_large",
  226. "fcn_resnet50",
  227. "fcn_resnet101",
  228. "lraspp_mobilenet_v3_large",
  229. "maskrcnn_resnet50_fpn",
  230. "maskrcnn_resnet50_fpn_v2",
  231. "keypointrcnn_resnet50_fpn",
  232. )
  233. # The tests for the following quantized models are flaky possibly due to inconsistent
  234. # rounding errors in different platforms. For this reason the input/output consistency
  235. # tests under test_quantized_classification_model will be skipped for the following models.
  236. quantized_flaky_models = ("inception_v3", "resnet50")
  237. # The tests for the following detection models are flaky.
  238. # We run those tests on float64 to avoid floating point errors.
  239. # FIXME: we shouldn't have to do that :'/
  240. detection_flaky_models = ("keypointrcnn_resnet50_fpn", "maskrcnn_resnet50_fpn", "maskrcnn_resnet50_fpn_v2")
  241. # The following contains configuration parameters for all models which are used by
  242. # the _test_*_model methods.
  243. _model_params = {
  244. "inception_v3": {"input_shape": (1, 3, 299, 299), "init_weights": True},
  245. "retinanet_resnet50_fpn": {
  246. "num_classes": 20,
  247. "score_thresh": 0.01,
  248. "min_size": 224,
  249. "max_size": 224,
  250. "input_shape": (3, 224, 224),
  251. "real_image": True,
  252. },
  253. "retinanet_resnet50_fpn_v2": {
  254. "num_classes": 20,
  255. "score_thresh": 0.01,
  256. "min_size": 224,
  257. "max_size": 224,
  258. "input_shape": (3, 224, 224),
  259. "real_image": True,
  260. },
  261. "keypointrcnn_resnet50_fpn": {
  262. "num_classes": 2,
  263. "min_size": 224,
  264. "max_size": 224,
  265. "box_score_thresh": 0.17,
  266. "input_shape": (3, 224, 224),
  267. "real_image": True,
  268. },
  269. "fasterrcnn_resnet50_fpn": {
  270. "num_classes": 20,
  271. "min_size": 224,
  272. "max_size": 224,
  273. "input_shape": (3, 224, 224),
  274. "real_image": True,
  275. },
  276. "fasterrcnn_resnet50_fpn_v2": {
  277. "num_classes": 20,
  278. "min_size": 224,
  279. "max_size": 224,
  280. "input_shape": (3, 224, 224),
  281. "real_image": True,
  282. },
  283. "fcos_resnet50_fpn": {
  284. "num_classes": 2,
  285. "score_thresh": 0.05,
  286. "min_size": 224,
  287. "max_size": 224,
  288. "input_shape": (3, 224, 224),
  289. "real_image": True,
  290. },
  291. "maskrcnn_resnet50_fpn": {
  292. "num_classes": 10,
  293. "min_size": 224,
  294. "max_size": 224,
  295. "input_shape": (3, 224, 224),
  296. "real_image": True,
  297. },
  298. "maskrcnn_resnet50_fpn_v2": {
  299. "num_classes": 10,
  300. "min_size": 224,
  301. "max_size": 224,
  302. "input_shape": (3, 224, 224),
  303. "real_image": True,
  304. },
  305. "fasterrcnn_mobilenet_v3_large_fpn": {
  306. "box_score_thresh": 0.02076,
  307. },
  308. "fasterrcnn_mobilenet_v3_large_320_fpn": {
  309. "box_score_thresh": 0.02076,
  310. "rpn_pre_nms_top_n_test": 1000,
  311. "rpn_post_nms_top_n_test": 1000,
  312. },
  313. "vit_h_14": {
  314. "image_size": 56,
  315. "input_shape": (1, 3, 56, 56),
  316. },
  317. "mvit_v1_b": {
  318. "input_shape": (1, 3, 16, 224, 224),
  319. },
  320. "mvit_v2_s": {
  321. "input_shape": (1, 3, 16, 224, 224),
  322. },
  323. "s3d": {
  324. "input_shape": (1, 3, 16, 224, 224),
  325. },
  326. "googlenet": {"init_weights": True},
  327. }
  328. # speeding up slow models:
  329. slow_models = [
  330. "convnext_base",
  331. "convnext_large",
  332. "resnext101_32x8d",
  333. "resnext101_64x4d",
  334. "wide_resnet101_2",
  335. "efficientnet_b6",
  336. "efficientnet_b7",
  337. "efficientnet_v2_m",
  338. "efficientnet_v2_l",
  339. "regnet_y_16gf",
  340. "regnet_y_32gf",
  341. "regnet_y_128gf",
  342. "regnet_x_16gf",
  343. "regnet_x_32gf",
  344. "swin_t",
  345. "swin_s",
  346. "swin_b",
  347. "swin_v2_t",
  348. "swin_v2_s",
  349. "swin_v2_b",
  350. ]
  351. for m in slow_models:
  352. _model_params[m] = {"input_shape": (1, 3, 64, 64)}
  353. # skip big models to reduce memory usage on CI test. We can exclude combinations of (platform-system, device).
  354. skipped_big_models = {
  355. "vit_h_14": {("Windows", "cpu"), ("Windows", "cuda")},
  356. "regnet_y_128gf": {("Windows", "cpu"), ("Windows", "cuda")},
  357. "mvit_v1_b": {("Windows", "cuda"), ("Linux", "cuda")},
  358. "mvit_v2_s": {("Windows", "cuda"), ("Linux", "cuda")},
  359. }
  360. def is_skippable(model_name, device):
  361. if model_name not in skipped_big_models:
  362. return False
  363. platform_system = platform.system()
  364. device_name = str(device).split(":")[0]
  365. return (platform_system, device_name) in skipped_big_models[model_name]
  366. # The following contains configuration and expected values to be used tests that are model specific
  367. _model_tests_values = {
  368. "retinanet_resnet50_fpn": {
  369. "max_trainable": 5,
  370. "n_trn_params_per_layer": [36, 46, 65, 78, 88, 89],
  371. },
  372. "retinanet_resnet50_fpn_v2": {
  373. "max_trainable": 5,
  374. "n_trn_params_per_layer": [44, 74, 131, 170, 200, 203],
  375. },
  376. "keypointrcnn_resnet50_fpn": {
  377. "max_trainable": 5,
  378. "n_trn_params_per_layer": [48, 58, 77, 90, 100, 101],
  379. },
  380. "fasterrcnn_resnet50_fpn": {
  381. "max_trainable": 5,
  382. "n_trn_params_per_layer": [30, 40, 59, 72, 82, 83],
  383. },
  384. "fasterrcnn_resnet50_fpn_v2": {
  385. "max_trainable": 5,
  386. "n_trn_params_per_layer": [50, 80, 137, 176, 206, 209],
  387. },
  388. "maskrcnn_resnet50_fpn": {
  389. "max_trainable": 5,
  390. "n_trn_params_per_layer": [42, 52, 71, 84, 94, 95],
  391. },
  392. "maskrcnn_resnet50_fpn_v2": {
  393. "max_trainable": 5,
  394. "n_trn_params_per_layer": [66, 96, 153, 192, 222, 225],
  395. },
  396. "fasterrcnn_mobilenet_v3_large_fpn": {
  397. "max_trainable": 6,
  398. "n_trn_params_per_layer": [22, 23, 44, 70, 91, 97, 100],
  399. },
  400. "fasterrcnn_mobilenet_v3_large_320_fpn": {
  401. "max_trainable": 6,
  402. "n_trn_params_per_layer": [22, 23, 44, 70, 91, 97, 100],
  403. },
  404. "ssd300_vgg16": {
  405. "max_trainable": 5,
  406. "n_trn_params_per_layer": [45, 51, 57, 63, 67, 71],
  407. },
  408. "ssdlite320_mobilenet_v3_large": {
  409. "max_trainable": 6,
  410. "n_trn_params_per_layer": [96, 99, 138, 200, 239, 257, 266],
  411. },
  412. "fcos_resnet50_fpn": {
  413. "max_trainable": 5,
  414. "n_trn_params_per_layer": [54, 64, 83, 96, 106, 107],
  415. },
  416. }
  417. def _make_sliced_model(model, stop_layer):
  418. layers = OrderedDict()
  419. for name, layer in model.named_children():
  420. layers[name] = layer
  421. if name == stop_layer:
  422. break
  423. new_model = torch.nn.Sequential(layers)
  424. return new_model
  425. @pytest.mark.parametrize("model_fn", [models.densenet121, models.densenet169, models.densenet201, models.densenet161])
  426. def test_memory_efficient_densenet(model_fn):
  427. input_shape = (1, 3, 300, 300)
  428. x = torch.rand(input_shape)
  429. model1 = model_fn(num_classes=50, memory_efficient=True)
  430. params = model1.state_dict()
  431. num_params = sum(x.numel() for x in model1.parameters())
  432. model1.eval()
  433. out1 = model1(x)
  434. out1.sum().backward()
  435. num_grad = sum(x.grad.numel() for x in model1.parameters() if x.grad is not None)
  436. model2 = model_fn(num_classes=50, memory_efficient=False)
  437. model2.load_state_dict(params)
  438. model2.eval()
  439. out2 = model2(x)
  440. assert num_params == num_grad
  441. torch.testing.assert_close(out1, out2, rtol=0.0, atol=1e-5)
  442. _check_input_backprop(model1, x)
  443. _check_input_backprop(model2, x)
  444. @pytest.mark.parametrize("dilate_layer_2", (True, False))
  445. @pytest.mark.parametrize("dilate_layer_3", (True, False))
  446. @pytest.mark.parametrize("dilate_layer_4", (True, False))
  447. def test_resnet_dilation(dilate_layer_2, dilate_layer_3, dilate_layer_4):
  448. # TODO improve tests to also check that each layer has the right dimensionality
  449. model = models.resnet50(replace_stride_with_dilation=(dilate_layer_2, dilate_layer_3, dilate_layer_4))
  450. model = _make_sliced_model(model, stop_layer="layer4")
  451. model.eval()
  452. x = torch.rand(1, 3, 224, 224)
  453. out = model(x)
  454. f = 2 ** sum((dilate_layer_2, dilate_layer_3, dilate_layer_4))
  455. assert out.shape == (1, 2048, 7 * f, 7 * f)
  456. def test_mobilenet_v2_residual_setting():
  457. model = models.mobilenet_v2(inverted_residual_setting=[[1, 16, 1, 1], [6, 24, 2, 2]])
  458. model.eval()
  459. x = torch.rand(1, 3, 224, 224)
  460. out = model(x)
  461. assert out.shape[-1] == 1000
  462. @pytest.mark.parametrize("model_fn", [models.mobilenet_v2, models.mobilenet_v3_large, models.mobilenet_v3_small])
  463. def test_mobilenet_norm_layer(model_fn):
  464. model = model_fn()
  465. assert any(isinstance(x, nn.BatchNorm2d) for x in model.modules())
  466. def get_gn(num_channels):
  467. return nn.GroupNorm(1, num_channels)
  468. model = model_fn(norm_layer=get_gn)
  469. assert not (any(isinstance(x, nn.BatchNorm2d) for x in model.modules()))
  470. assert any(isinstance(x, nn.GroupNorm) for x in model.modules())
  471. def test_inception_v3_eval():
  472. kwargs = {}
  473. kwargs["transform_input"] = True
  474. kwargs["aux_logits"] = True
  475. kwargs["init_weights"] = False
  476. name = "inception_v3"
  477. model = models.Inception3(**kwargs)
  478. model.aux_logits = False
  479. model.AuxLogits = None
  480. model = model.eval()
  481. x = torch.rand(1, 3, 299, 299)
  482. _check_jit_scriptable(model, (x,), unwrapper=script_model_unwrapper.get(name, None))
  483. _check_input_backprop(model, x)
  484. def test_fasterrcnn_double():
  485. model = models.detection.fasterrcnn_resnet50_fpn(num_classes=50, weights=None, weights_backbone=None)
  486. model.double()
  487. model.eval()
  488. input_shape = (3, 300, 300)
  489. x = torch.rand(input_shape, dtype=torch.float64)
  490. model_input = [x]
  491. out = model(model_input)
  492. assert model_input[0] is x
  493. assert len(out) == 1
  494. assert "boxes" in out[0]
  495. assert "scores" in out[0]
  496. assert "labels" in out[0]
  497. _check_input_backprop(model, model_input)
  498. def test_googlenet_eval():
  499. kwargs = {}
  500. kwargs["transform_input"] = True
  501. kwargs["aux_logits"] = True
  502. kwargs["init_weights"] = False
  503. name = "googlenet"
  504. model = models.GoogLeNet(**kwargs)
  505. model.aux_logits = False
  506. model.aux1 = None
  507. model.aux2 = None
  508. model = model.eval()
  509. x = torch.rand(1, 3, 224, 224)
  510. _check_jit_scriptable(model, (x,), unwrapper=script_model_unwrapper.get(name, None))
  511. _check_input_backprop(model, x)
  512. @needs_cuda
  513. def test_fasterrcnn_switch_devices():
  514. def checkOut(out):
  515. assert len(out) == 1
  516. assert "boxes" in out[0]
  517. assert "scores" in out[0]
  518. assert "labels" in out[0]
  519. model = models.detection.fasterrcnn_resnet50_fpn(num_classes=50, weights=None, weights_backbone=None)
  520. model.cuda()
  521. model.eval()
  522. input_shape = (3, 300, 300)
  523. x = torch.rand(input_shape, device="cuda")
  524. model_input = [x]
  525. out = model(model_input)
  526. assert model_input[0] is x
  527. checkOut(out)
  528. with torch.cuda.amp.autocast():
  529. out = model(model_input)
  530. checkOut(out)
  531. _check_input_backprop(model, model_input)
  532. # now switch to cpu and make sure it works
  533. model.cpu()
  534. x = x.cpu()
  535. out_cpu = model([x])
  536. checkOut(out_cpu)
  537. _check_input_backprop(model, [x])
  538. def test_generalizedrcnn_transform_repr():
  539. min_size, max_size = 224, 299
  540. image_mean = [0.485, 0.456, 0.406]
  541. image_std = [0.229, 0.224, 0.225]
  542. t = models.detection.transform.GeneralizedRCNNTransform(
  543. min_size=min_size, max_size=max_size, image_mean=image_mean, image_std=image_std
  544. )
  545. # Check integrity of object __repr__ attribute
  546. expected_string = "GeneralizedRCNNTransform("
  547. _indent = "\n "
  548. expected_string += f"{_indent}Normalize(mean={image_mean}, std={image_std})"
  549. expected_string += f"{_indent}Resize(min_size=({min_size},), max_size={max_size}, "
  550. expected_string += "mode='bilinear')\n)"
  551. assert t.__repr__() == expected_string
  552. test_vit_conv_stem_configs = [
  553. models.vision_transformer.ConvStemConfig(kernel_size=3, stride=2, out_channels=64),
  554. models.vision_transformer.ConvStemConfig(kernel_size=3, stride=2, out_channels=128),
  555. models.vision_transformer.ConvStemConfig(kernel_size=3, stride=1, out_channels=128),
  556. models.vision_transformer.ConvStemConfig(kernel_size=3, stride=2, out_channels=256),
  557. models.vision_transformer.ConvStemConfig(kernel_size=3, stride=1, out_channels=256),
  558. models.vision_transformer.ConvStemConfig(kernel_size=3, stride=2, out_channels=512),
  559. ]
  560. def vitc_b_16(**kwargs: Any):
  561. return models.VisionTransformer(
  562. image_size=224,
  563. patch_size=16,
  564. num_layers=12,
  565. num_heads=12,
  566. hidden_dim=768,
  567. mlp_dim=3072,
  568. conv_stem_configs=test_vit_conv_stem_configs,
  569. **kwargs,
  570. )
  571. @pytest.mark.parametrize("model_fn", [vitc_b_16])
  572. @pytest.mark.parametrize("dev", cpu_and_cuda())
  573. def test_vitc_models(model_fn, dev):
  574. test_classification_model(model_fn, dev)
  575. @disable_tf32() # see: https://github.com/pytorch/vision/issues/7618
  576. @pytest.mark.parametrize("model_fn", list_model_fns(models))
  577. @pytest.mark.parametrize("dev", cpu_and_cuda())
  578. def test_classification_model(model_fn, dev):
  579. set_rng_seed(0)
  580. defaults = {
  581. "num_classes": 50,
  582. "input_shape": (1, 3, 224, 224),
  583. }
  584. model_name = model_fn.__name__
  585. if SKIP_BIG_MODEL and is_skippable(model_name, dev):
  586. pytest.skip("Skipped to reduce memory usage. Set env var SKIP_BIG_MODEL=0 to enable test for this model")
  587. kwargs = {**defaults, **_model_params.get(model_name, {})}
  588. num_classes = kwargs.get("num_classes")
  589. input_shape = kwargs.pop("input_shape")
  590. real_image = kwargs.pop("real_image", False)
  591. model = model_fn(**kwargs)
  592. model.eval().to(device=dev)
  593. x = _get_image(input_shape=input_shape, real_image=real_image, device=dev)
  594. out = model(x)
  595. # FIXME: this if/else is nasty and only here to please our CI prior to the
  596. # release. We rethink these tests altogether.
  597. if model_name == "resnet101":
  598. prec = 0.2
  599. else:
  600. # FIXME: this is probably still way too high.
  601. prec = 0.1
  602. _assert_expected(out.cpu(), model_name, prec=prec)
  603. assert out.shape[-1] == num_classes
  604. _check_jit_scriptable(model, (x,), unwrapper=script_model_unwrapper.get(model_name, None), eager_out=out)
  605. _check_fx_compatible(model, x, eager_out=out)
  606. if dev == "cuda":
  607. with torch.cuda.amp.autocast():
  608. out = model(x)
  609. # See autocast_flaky_numerics comment at top of file.
  610. if model_name not in autocast_flaky_numerics:
  611. _assert_expected(out.cpu(), model_name, prec=0.1)
  612. assert out.shape[-1] == 50
  613. _check_input_backprop(model, x)
  614. @pytest.mark.parametrize("model_fn", list_model_fns(models.segmentation))
  615. @pytest.mark.parametrize("dev", cpu_and_cuda())
  616. def test_segmentation_model(model_fn, dev):
  617. set_rng_seed(0)
  618. defaults = {
  619. "num_classes": 10,
  620. "weights_backbone": None,
  621. "input_shape": (1, 3, 32, 32),
  622. }
  623. model_name = model_fn.__name__
  624. kwargs = {**defaults, **_model_params.get(model_name, {})}
  625. input_shape = kwargs.pop("input_shape")
  626. model = model_fn(**kwargs)
  627. model.eval().to(device=dev)
  628. # RNG always on CPU, to ensure x in cuda tests is bitwise identical to x in cpu tests
  629. x = torch.rand(input_shape).to(device=dev)
  630. with torch.no_grad(), freeze_rng_state():
  631. out = model(x)
  632. def check_out(out):
  633. prec = 0.01
  634. try:
  635. # We first try to assert the entire output if possible. This is not
  636. # only the best way to assert results but also handles the cases
  637. # where we need to create a new expected result.
  638. _assert_expected(out.cpu(), model_name, prec=prec)
  639. except AssertionError:
  640. # Unfortunately some segmentation models are flaky with autocast
  641. # so instead of validating the probability scores, check that the class
  642. # predictions match.
  643. expected_file = _get_expected_file(model_name)
  644. expected = torch.load(expected_file)
  645. torch.testing.assert_close(
  646. out.argmax(dim=1), expected.argmax(dim=1), rtol=prec, atol=prec, check_device=False
  647. )
  648. return False # Partial validation performed
  649. return True # Full validation performed
  650. full_validation = check_out(out["out"])
  651. _check_jit_scriptable(model, (x,), unwrapper=script_model_unwrapper.get(model_name, None), eager_out=out)
  652. _check_fx_compatible(model, x, eager_out=out)
  653. if dev == "cuda":
  654. with torch.cuda.amp.autocast(), torch.no_grad(), freeze_rng_state():
  655. out = model(x)
  656. # See autocast_flaky_numerics comment at top of file.
  657. if model_name not in autocast_flaky_numerics:
  658. full_validation &= check_out(out["out"])
  659. if not full_validation:
  660. msg = (
  661. f"The output of {test_segmentation_model.__name__} could only be partially validated. "
  662. "This is likely due to unit-test flakiness, but you may "
  663. "want to do additional manual checks if you made "
  664. "significant changes to the codebase."
  665. )
  666. warnings.warn(msg, RuntimeWarning)
  667. pytest.skip(msg)
  668. _check_input_backprop(model, x)
  669. @pytest.mark.parametrize("model_fn", list_model_fns(models.detection))
  670. @pytest.mark.parametrize("dev", cpu_and_cuda())
  671. def test_detection_model(model_fn, dev):
  672. set_rng_seed(0)
  673. defaults = {
  674. "num_classes": 50,
  675. "weights_backbone": None,
  676. "input_shape": (3, 300, 300),
  677. }
  678. model_name = model_fn.__name__
  679. if model_name in detection_flaky_models:
  680. dtype = torch.float64
  681. else:
  682. dtype = torch.get_default_dtype()
  683. kwargs = {**defaults, **_model_params.get(model_name, {})}
  684. input_shape = kwargs.pop("input_shape")
  685. real_image = kwargs.pop("real_image", False)
  686. model = model_fn(**kwargs)
  687. model.eval().to(device=dev, dtype=dtype)
  688. x = _get_image(input_shape=input_shape, real_image=real_image, device=dev, dtype=dtype)
  689. model_input = [x]
  690. with torch.no_grad(), freeze_rng_state():
  691. out = model(model_input)
  692. assert model_input[0] is x
  693. def check_out(out):
  694. assert len(out) == 1
  695. def compact(tensor):
  696. tensor = tensor.cpu()
  697. size = tensor.size()
  698. elements_per_sample = functools.reduce(operator.mul, size[1:], 1)
  699. if elements_per_sample > 30:
  700. return compute_mean_std(tensor)
  701. else:
  702. return subsample_tensor(tensor)
  703. def subsample_tensor(tensor):
  704. num_elems = tensor.size(0)
  705. num_samples = 20
  706. if num_elems <= num_samples:
  707. return tensor
  708. ith_index = num_elems // num_samples
  709. return tensor[ith_index - 1 :: ith_index]
  710. def compute_mean_std(tensor):
  711. # can't compute mean of integral tensor
  712. tensor = tensor.to(torch.double)
  713. mean = torch.mean(tensor)
  714. std = torch.std(tensor)
  715. return {"mean": mean, "std": std}
  716. output = map_nested_tensor_object(out, tensor_map_fn=compact)
  717. prec = 0.01
  718. try:
  719. # We first try to assert the entire output if possible. This is not
  720. # only the best way to assert results but also handles the cases
  721. # where we need to create a new expected result.
  722. _assert_expected(output, model_name, prec=prec)
  723. except AssertionError:
  724. # Unfortunately detection models are flaky due to the unstable sort
  725. # in NMS. If matching across all outputs fails, use the same approach
  726. # as in NMSTester.test_nms_cuda to see if this is caused by duplicate
  727. # scores.
  728. expected_file = _get_expected_file(model_name)
  729. expected = torch.load(expected_file)
  730. torch.testing.assert_close(
  731. output[0]["scores"], expected[0]["scores"], rtol=prec, atol=prec, check_device=False, check_dtype=False
  732. )
  733. # Note: Fmassa proposed turning off NMS by adapting the threshold
  734. # and then using the Hungarian algorithm as in DETR to find the
  735. # best match between output and expected boxes and eliminate some
  736. # of the flakiness. Worth exploring.
  737. return False # Partial validation performed
  738. return True # Full validation performed
  739. full_validation = check_out(out)
  740. _check_jit_scriptable(model, ([x],), unwrapper=script_model_unwrapper.get(model_name, None), eager_out=out)
  741. if dev == "cuda":
  742. with torch.cuda.amp.autocast(), torch.no_grad(), freeze_rng_state():
  743. out = model(model_input)
  744. # See autocast_flaky_numerics comment at top of file.
  745. if model_name not in autocast_flaky_numerics:
  746. full_validation &= check_out(out)
  747. if not full_validation:
  748. msg = (
  749. f"The output of {test_detection_model.__name__} could only be partially validated. "
  750. "This is likely due to unit-test flakiness, but you may "
  751. "want to do additional manual checks if you made "
  752. "significant changes to the codebase."
  753. )
  754. warnings.warn(msg, RuntimeWarning)
  755. pytest.skip(msg)
  756. _check_input_backprop(model, model_input)
  757. @pytest.mark.parametrize("model_fn", list_model_fns(models.detection))
  758. def test_detection_model_validation(model_fn):
  759. set_rng_seed(0)
  760. model = model_fn(num_classes=50, weights=None, weights_backbone=None)
  761. input_shape = (3, 300, 300)
  762. x = [torch.rand(input_shape)]
  763. # validate that targets are present in training
  764. with pytest.raises(AssertionError):
  765. model(x)
  766. # validate type
  767. targets = [{"boxes": 0.0}]
  768. with pytest.raises(AssertionError):
  769. model(x, targets=targets)
  770. # validate boxes shape
  771. for boxes in (torch.rand((4,)), torch.rand((1, 5))):
  772. targets = [{"boxes": boxes}]
  773. with pytest.raises(AssertionError):
  774. model(x, targets=targets)
  775. # validate that no degenerate boxes are present
  776. boxes = torch.tensor([[1, 3, 1, 4], [2, 4, 3, 4]])
  777. targets = [{"boxes": boxes}]
  778. with pytest.raises(AssertionError):
  779. model(x, targets=targets)
  780. @pytest.mark.parametrize("model_fn", list_model_fns(models.video))
  781. @pytest.mark.parametrize("dev", cpu_and_cuda())
  782. def test_video_model(model_fn, dev):
  783. set_rng_seed(0)
  784. # the default input shape is
  785. # bs * num_channels * clip_len * h *w
  786. defaults = {
  787. "input_shape": (1, 3, 4, 112, 112),
  788. "num_classes": 50,
  789. }
  790. model_name = model_fn.__name__
  791. if SKIP_BIG_MODEL and is_skippable(model_name, dev):
  792. pytest.skip("Skipped to reduce memory usage. Set env var SKIP_BIG_MODEL=0 to enable test for this model")
  793. kwargs = {**defaults, **_model_params.get(model_name, {})}
  794. num_classes = kwargs.get("num_classes")
  795. input_shape = kwargs.pop("input_shape")
  796. # test both basicblock and Bottleneck
  797. model = model_fn(**kwargs)
  798. model.eval().to(device=dev)
  799. # RNG always on CPU, to ensure x in cuda tests is bitwise identical to x in cpu tests
  800. x = torch.rand(input_shape).to(device=dev)
  801. out = model(x)
  802. _assert_expected(out.cpu(), model_name, prec=0.1)
  803. assert out.shape[-1] == num_classes
  804. _check_jit_scriptable(model, (x,), unwrapper=script_model_unwrapper.get(model_name, None), eager_out=out)
  805. _check_fx_compatible(model, x, eager_out=out)
  806. assert out.shape[-1] == num_classes
  807. if dev == "cuda":
  808. with torch.cuda.amp.autocast():
  809. out = model(x)
  810. # See autocast_flaky_numerics comment at top of file.
  811. if model_name not in autocast_flaky_numerics:
  812. _assert_expected(out.cpu(), model_name, prec=0.1)
  813. assert out.shape[-1] == num_classes
  814. _check_input_backprop(model, x)
  815. @pytest.mark.skipif(
  816. not (
  817. "fbgemm" in torch.backends.quantized.supported_engines
  818. and "qnnpack" in torch.backends.quantized.supported_engines
  819. ),
  820. reason="This Pytorch Build has not been built with fbgemm and qnnpack",
  821. )
  822. @pytest.mark.parametrize("model_fn", list_model_fns(models.quantization))
  823. def test_quantized_classification_model(model_fn):
  824. set_rng_seed(0)
  825. defaults = {
  826. "num_classes": 5,
  827. "input_shape": (1, 3, 224, 224),
  828. "quantize": True,
  829. }
  830. model_name = model_fn.__name__
  831. kwargs = {**defaults, **_model_params.get(model_name, {})}
  832. input_shape = kwargs.pop("input_shape")
  833. # First check if quantize=True provides models that can run with input data
  834. model = model_fn(**kwargs)
  835. model.eval()
  836. x = torch.rand(input_shape)
  837. out = model(x)
  838. if model_name not in quantized_flaky_models:
  839. _assert_expected(out.cpu(), model_name + "_quantized", prec=2e-2)
  840. assert out.shape[-1] == 5
  841. _check_jit_scriptable(model, (x,), unwrapper=script_model_unwrapper.get(model_name, None), eager_out=out)
  842. _check_fx_compatible(model, x, eager_out=out)
  843. else:
  844. try:
  845. torch.jit.script(model)
  846. except Exception as e:
  847. raise AssertionError("model cannot be scripted.") from e
  848. kwargs["quantize"] = False
  849. for eval_mode in [True, False]:
  850. model = model_fn(**kwargs)
  851. if eval_mode:
  852. model.eval()
  853. model.qconfig = torch.ao.quantization.default_qconfig
  854. else:
  855. model.train()
  856. model.qconfig = torch.ao.quantization.default_qat_qconfig
  857. model.fuse_model(is_qat=not eval_mode)
  858. if eval_mode:
  859. torch.ao.quantization.prepare(model, inplace=True)
  860. else:
  861. torch.ao.quantization.prepare_qat(model, inplace=True)
  862. model.eval()
  863. torch.ao.quantization.convert(model, inplace=True)
  864. @pytest.mark.parametrize("model_fn", list_model_fns(models.detection))
  865. def test_detection_model_trainable_backbone_layers(model_fn, disable_weight_loading):
  866. model_name = model_fn.__name__
  867. max_trainable = _model_tests_values[model_name]["max_trainable"]
  868. n_trainable_params = []
  869. for trainable_layers in range(0, max_trainable + 1):
  870. model = model_fn(weights=None, weights_backbone="DEFAULT", trainable_backbone_layers=trainable_layers)
  871. n_trainable_params.append(len([p for p in model.parameters() if p.requires_grad]))
  872. assert n_trainable_params == _model_tests_values[model_name]["n_trn_params_per_layer"]
  873. @needs_cuda
  874. @pytest.mark.parametrize("model_fn", list_model_fns(models.optical_flow))
  875. @pytest.mark.parametrize("scripted", (False, True))
  876. def test_raft(model_fn, scripted):
  877. torch.manual_seed(0)
  878. # We need very small images, otherwise the pickle size would exceed the 50KB
  879. # As a result we need to override the correlation pyramid to not downsample
  880. # too much, otherwise we would get nan values (effective H and W would be
  881. # reduced to 1)
  882. corr_block = models.optical_flow.raft.CorrBlock(num_levels=2, radius=2)
  883. model = model_fn(corr_block=corr_block).eval().to("cuda")
  884. if scripted:
  885. model = torch.jit.script(model)
  886. bs = 1
  887. img1 = torch.rand(bs, 3, 80, 72).cuda()
  888. img2 = torch.rand(bs, 3, 80, 72).cuda()
  889. preds = model(img1, img2)
  890. flow_pred = preds[-1]
  891. # Tolerance is fairly high, but there are 2 * H * W outputs to check
  892. # The .pkl were generated on the AWS cluter, on the CI it looks like the results are slightly different
  893. _assert_expected(flow_pred.cpu(), name=model_fn.__name__, atol=1e-2, rtol=1)
  894. def test_presets_antialias():
  895. img = torch.randint(0, 256, size=(1, 3, 224, 224), dtype=torch.uint8)
  896. match = "The default value of the antialias parameter"
  897. with pytest.warns(UserWarning, match=match):
  898. models.ResNet18_Weights.DEFAULT.transforms()(img)
  899. with pytest.warns(UserWarning, match=match):
  900. models.segmentation.DeepLabV3_ResNet50_Weights.DEFAULT.transforms()(img)
  901. with warnings.catch_warnings():
  902. warnings.simplefilter("error")
  903. models.ResNet18_Weights.DEFAULT.transforms(antialias=True)(img)
  904. models.segmentation.DeepLabV3_ResNet50_Weights.DEFAULT.transforms(antialias=True)(img)
  905. models.detection.FasterRCNN_ResNet50_FPN_Weights.DEFAULT.transforms()(img)
  906. models.video.R3D_18_Weights.DEFAULT.transforms()(img)
  907. models.optical_flow.Raft_Small_Weights.DEFAULT.transforms()(img, img)
  908. if __name__ == "__main__":
  909. pytest.main([__file__])