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

test_backbone_utils.py 13 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
  1. import random
  2. from copy import deepcopy
  3. from itertools import chain
  4. from typing import Mapping, Sequence
  5. import pytest
  6. import torch
  7. from common_utils import set_rng_seed
  8. from torchvision import models
  9. from torchvision.models._utils import IntermediateLayerGetter
  10. from torchvision.models.detection.backbone_utils import BackboneWithFPN, mobilenet_backbone, resnet_fpn_backbone
  11. from torchvision.models.feature_extraction import create_feature_extractor, get_graph_node_names
  12. @pytest.mark.parametrize("backbone_name", ("resnet18", "resnet50"))
  13. def test_resnet_fpn_backbone(backbone_name):
  14. x = torch.rand(1, 3, 300, 300, dtype=torch.float32, device="cpu")
  15. model = resnet_fpn_backbone(backbone_name=backbone_name, weights=None)
  16. assert isinstance(model, BackboneWithFPN)
  17. y = model(x)
  18. assert list(y.keys()) == ["0", "1", "2", "3", "pool"]
  19. with pytest.raises(ValueError, match=r"Trainable layers should be in the range"):
  20. resnet_fpn_backbone(backbone_name=backbone_name, weights=None, trainable_layers=6)
  21. with pytest.raises(ValueError, match=r"Each returned layer should be in the range"):
  22. resnet_fpn_backbone(backbone_name=backbone_name, weights=None, returned_layers=[0, 1, 2, 3])
  23. with pytest.raises(ValueError, match=r"Each returned layer should be in the range"):
  24. resnet_fpn_backbone(backbone_name=backbone_name, weights=None, returned_layers=[2, 3, 4, 5])
  25. @pytest.mark.parametrize("backbone_name", ("mobilenet_v2", "mobilenet_v3_large", "mobilenet_v3_small"))
  26. def test_mobilenet_backbone(backbone_name):
  27. with pytest.raises(ValueError, match=r"Trainable layers should be in the range"):
  28. mobilenet_backbone(backbone_name=backbone_name, weights=None, fpn=False, trainable_layers=-1)
  29. with pytest.raises(ValueError, match=r"Each returned layer should be in the range"):
  30. mobilenet_backbone(backbone_name=backbone_name, weights=None, fpn=True, returned_layers=[-1, 0, 1, 2])
  31. with pytest.raises(ValueError, match=r"Each returned layer should be in the range"):
  32. mobilenet_backbone(backbone_name=backbone_name, weights=None, fpn=True, returned_layers=[3, 4, 5, 6])
  33. model_fpn = mobilenet_backbone(backbone_name=backbone_name, weights=None, fpn=True)
  34. assert isinstance(model_fpn, BackboneWithFPN)
  35. model = mobilenet_backbone(backbone_name=backbone_name, weights=None, fpn=False)
  36. assert isinstance(model, torch.nn.Sequential)
  37. # Needed by TestFxFeatureExtraction.test_leaf_module_and_function
  38. def leaf_function(x):
  39. return int(x)
  40. # Needed by TestFXFeatureExtraction. Checking that node naming conventions
  41. # are respected. Particularly the index postfix of repeated node names
  42. class TestSubModule(torch.nn.Module):
  43. def __init__(self):
  44. super().__init__()
  45. self.relu = torch.nn.ReLU()
  46. def forward(self, x):
  47. x = x + 1
  48. x = x + 1
  49. x = self.relu(x)
  50. x = self.relu(x)
  51. return x
  52. class TestModule(torch.nn.Module):
  53. def __init__(self):
  54. super().__init__()
  55. self.submodule = TestSubModule()
  56. self.relu = torch.nn.ReLU()
  57. def forward(self, x):
  58. x = self.submodule(x)
  59. x = x + 1
  60. x = x + 1
  61. x = self.relu(x)
  62. x = self.relu(x)
  63. return x
  64. test_module_nodes = [
  65. "x",
  66. "submodule.add",
  67. "submodule.add_1",
  68. "submodule.relu",
  69. "submodule.relu_1",
  70. "add",
  71. "add_1",
  72. "relu",
  73. "relu_1",
  74. ]
  75. class TestFxFeatureExtraction:
  76. inp = torch.rand(1, 3, 224, 224, dtype=torch.float32, device="cpu")
  77. model_defaults = {"num_classes": 1}
  78. leaf_modules = []
  79. def _create_feature_extractor(self, *args, **kwargs):
  80. """
  81. Apply leaf modules
  82. """
  83. tracer_kwargs = {}
  84. if "tracer_kwargs" not in kwargs:
  85. tracer_kwargs = {"leaf_modules": self.leaf_modules}
  86. else:
  87. tracer_kwargs = kwargs.pop("tracer_kwargs")
  88. return create_feature_extractor(*args, **kwargs, tracer_kwargs=tracer_kwargs, suppress_diff_warning=True)
  89. def _get_return_nodes(self, model):
  90. set_rng_seed(0)
  91. exclude_nodes_filter = [
  92. "getitem",
  93. "floordiv",
  94. "size",
  95. "chunk",
  96. "_assert",
  97. "eq",
  98. "dim",
  99. "getattr",
  100. ]
  101. train_nodes, eval_nodes = get_graph_node_names(
  102. model, tracer_kwargs={"leaf_modules": self.leaf_modules}, suppress_diff_warning=True
  103. )
  104. # Get rid of any nodes that don't return tensors as they cause issues
  105. # when testing backward pass.
  106. train_nodes = [n for n in train_nodes if not any(x in n for x in exclude_nodes_filter)]
  107. eval_nodes = [n for n in eval_nodes if not any(x in n for x in exclude_nodes_filter)]
  108. return random.sample(train_nodes, 10), random.sample(eval_nodes, 10)
  109. @pytest.mark.parametrize("model_name", models.list_models(models))
  110. def test_build_fx_feature_extractor(self, model_name):
  111. set_rng_seed(0)
  112. model = models.get_model(model_name, **self.model_defaults).eval()
  113. train_return_nodes, eval_return_nodes = self._get_return_nodes(model)
  114. # Check that it works with both a list and dict for return nodes
  115. self._create_feature_extractor(
  116. model, train_return_nodes={v: v for v in train_return_nodes}, eval_return_nodes=eval_return_nodes
  117. )
  118. self._create_feature_extractor(
  119. model, train_return_nodes=train_return_nodes, eval_return_nodes=eval_return_nodes
  120. )
  121. # Check must specify return nodes
  122. with pytest.raises(ValueError):
  123. self._create_feature_extractor(model)
  124. # Check return_nodes and train_return_nodes / eval_return nodes
  125. # mutual exclusivity
  126. with pytest.raises(ValueError):
  127. self._create_feature_extractor(
  128. model, return_nodes=train_return_nodes, train_return_nodes=train_return_nodes
  129. )
  130. # Check train_return_nodes / eval_return nodes must both be specified
  131. with pytest.raises(ValueError):
  132. self._create_feature_extractor(model, train_return_nodes=train_return_nodes)
  133. # Check invalid node name raises ValueError
  134. with pytest.raises(ValueError):
  135. # First just double check that this node really doesn't exist
  136. if not any(n.startswith("l") or n.startswith("l.") for n in chain(train_return_nodes, eval_return_nodes)):
  137. self._create_feature_extractor(model, train_return_nodes=["l"], eval_return_nodes=["l"])
  138. else: # otherwise skip this check
  139. raise ValueError
  140. def test_node_name_conventions(self):
  141. model = TestModule()
  142. train_nodes, _ = get_graph_node_names(model)
  143. assert all(a == b for a, b in zip(train_nodes, test_module_nodes))
  144. @pytest.mark.parametrize("model_name", models.list_models(models))
  145. def test_forward_backward(self, model_name):
  146. model = models.get_model(model_name, **self.model_defaults).train()
  147. train_return_nodes, eval_return_nodes = self._get_return_nodes(model)
  148. model = self._create_feature_extractor(
  149. model, train_return_nodes=train_return_nodes, eval_return_nodes=eval_return_nodes
  150. )
  151. out = model(self.inp)
  152. out_agg = 0
  153. for node_out in out.values():
  154. if isinstance(node_out, Sequence):
  155. out_agg += sum(o.float().mean() for o in node_out if o is not None)
  156. elif isinstance(node_out, Mapping):
  157. out_agg += sum(o.float().mean() for o in node_out.values() if o is not None)
  158. else:
  159. # Assume that the only other alternative at this point is a Tensor
  160. out_agg += node_out.float().mean()
  161. out_agg.backward()
  162. def test_feature_extraction_methods_equivalence(self):
  163. model = models.resnet18(**self.model_defaults).eval()
  164. return_layers = {"layer1": "layer1", "layer2": "layer2", "layer3": "layer3", "layer4": "layer4"}
  165. ilg_model = IntermediateLayerGetter(model, return_layers).eval()
  166. fx_model = self._create_feature_extractor(model, return_layers)
  167. # Check that we have same parameters
  168. for (n1, p1), (n2, p2) in zip(ilg_model.named_parameters(), fx_model.named_parameters()):
  169. assert n1 == n2
  170. assert p1.equal(p2)
  171. # And that outputs match
  172. with torch.no_grad():
  173. ilg_out = ilg_model(self.inp)
  174. fgn_out = fx_model(self.inp)
  175. assert all(k1 == k2 for k1, k2 in zip(ilg_out.keys(), fgn_out.keys()))
  176. for k in ilg_out.keys():
  177. assert ilg_out[k].equal(fgn_out[k])
  178. @pytest.mark.parametrize("model_name", models.list_models(models))
  179. def test_jit_forward_backward(self, model_name):
  180. set_rng_seed(0)
  181. model = models.get_model(model_name, **self.model_defaults).train()
  182. train_return_nodes, eval_return_nodes = self._get_return_nodes(model)
  183. model = self._create_feature_extractor(
  184. model, train_return_nodes=train_return_nodes, eval_return_nodes=eval_return_nodes
  185. )
  186. model = torch.jit.script(model)
  187. fgn_out = model(self.inp)
  188. out_agg = 0
  189. for node_out in fgn_out.values():
  190. if isinstance(node_out, Sequence):
  191. out_agg += sum(o.float().mean() for o in node_out if o is not None)
  192. elif isinstance(node_out, Mapping):
  193. out_agg += sum(o.float().mean() for o in node_out.values() if o is not None)
  194. else:
  195. # Assume that the only other alternative at this point is a Tensor
  196. out_agg += node_out.float().mean()
  197. out_agg.backward()
  198. def test_train_eval(self):
  199. class TestModel(torch.nn.Module):
  200. def __init__(self):
  201. super().__init__()
  202. self.dropout = torch.nn.Dropout(p=1.0)
  203. def forward(self, x):
  204. x = x.float().mean()
  205. x = self.dropout(x) # dropout
  206. if self.training:
  207. x += 100 # add
  208. else:
  209. x *= 0 # mul
  210. x -= 0 # sub
  211. return x
  212. model = TestModel()
  213. train_return_nodes = ["dropout", "add", "sub"]
  214. eval_return_nodes = ["dropout", "mul", "sub"]
  215. def checks(model, mode):
  216. with torch.no_grad():
  217. out = model(torch.ones(10, 10))
  218. if mode == "train":
  219. # Check that dropout is respected
  220. assert out["dropout"].item() == 0
  221. # Check that control flow dependent on training_mode is respected
  222. assert out["sub"].item() == 100
  223. assert "add" in out
  224. assert "mul" not in out
  225. elif mode == "eval":
  226. # Check that dropout is respected
  227. assert out["dropout"].item() == 1
  228. # Check that control flow dependent on training_mode is respected
  229. assert out["sub"].item() == 0
  230. assert "mul" in out
  231. assert "add" not in out
  232. # Starting from train mode
  233. model.train()
  234. fx_model = self._create_feature_extractor(
  235. model, train_return_nodes=train_return_nodes, eval_return_nodes=eval_return_nodes
  236. )
  237. # Check that the models stay in their original training state
  238. assert model.training
  239. assert fx_model.training
  240. # Check outputs
  241. checks(fx_model, "train")
  242. # Check outputs after switching to eval mode
  243. fx_model.eval()
  244. checks(fx_model, "eval")
  245. # Starting from eval mode
  246. model.eval()
  247. fx_model = self._create_feature_extractor(
  248. model, train_return_nodes=train_return_nodes, eval_return_nodes=eval_return_nodes
  249. )
  250. # Check that the models stay in their original training state
  251. assert not model.training
  252. assert not fx_model.training
  253. # Check outputs
  254. checks(fx_model, "eval")
  255. # Check outputs after switching to train mode
  256. fx_model.train()
  257. checks(fx_model, "train")
  258. def test_leaf_module_and_function(self):
  259. class LeafModule(torch.nn.Module):
  260. def forward(self, x):
  261. # This would raise a TypeError if it were not in a leaf module
  262. int(x.shape[0])
  263. return torch.nn.functional.relu(x + 4)
  264. class TestModule(torch.nn.Module):
  265. def __init__(self):
  266. super().__init__()
  267. self.conv = torch.nn.Conv2d(3, 1, 3)
  268. self.leaf_module = LeafModule()
  269. def forward(self, x):
  270. leaf_function(x.shape[0])
  271. x = self.conv(x)
  272. return self.leaf_module(x)
  273. model = self._create_feature_extractor(
  274. TestModule(),
  275. return_nodes=["leaf_module"],
  276. tracer_kwargs={"leaf_modules": [LeafModule], "autowrap_functions": [leaf_function]},
  277. ).train()
  278. # Check that LeafModule is not in the list of nodes
  279. assert "relu" not in [str(n) for n in model.graph.nodes]
  280. assert "leaf_module" in [str(n) for n in model.graph.nodes]
  281. # Check forward
  282. out = model(self.inp)
  283. # And backward
  284. out["leaf_module"].float().mean().backward()
  285. def test_deepcopy(self):
  286. # Non-regression test for https://github.com/pytorch/vision/issues/8634
  287. model = models.efficientnet_b3(weights=None)
  288. extractor = create_feature_extractor(model=model, return_nodes={"classifier.0": "out"})
  289. extractor.eval()
  290. extractor.train()
  291. extractor = deepcopy(extractor)
  292. extractor.eval()
  293. extractor.train()
Tip!

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

Comments

Loading...