-
Notifications
You must be signed in to change notification settings - Fork 388
/
testers.py
618 lines (531 loc) · 22.9 KB
/
testers.py
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import pickle
import sys
from functools import partial
from typing import Any, Callable, Dict, List, Optional, Sequence, Union
import numpy as np
import pytest
import torch
from torch import Tensor, tensor
from torch.multiprocessing import Pool, set_start_method
from torchmetrics import Metric
from torchmetrics.detection.mean_ap import MAPMetricResults
from torchmetrics.utilities.data import apply_to_collection
try:
set_start_method("spawn")
except RuntimeError:
pass
NUM_PROCESSES = 2
NUM_BATCHES = 4 # Need to be divisible with the number of processes
BATCH_SIZE = 32
NUM_CLASSES = 5
EXTRA_DIM = 3
THRESHOLD = 0.5
MAX_PORT = 8100
START_PORT = 8088
CURRENT_PORT = START_PORT
def setup_ddp(rank, world_size):
"""Setup ddp environment."""
global CURRENT_PORT
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = str(CURRENT_PORT)
CURRENT_PORT += 1
if CURRENT_PORT > MAX_PORT:
CURRENT_PORT = START_PORT
if torch.distributed.is_available() and sys.platform not in ("win32", "cygwin"):
torch.distributed.init_process_group("gloo", rank=rank, world_size=world_size)
def _assert_allclose(pl_result: Any, sk_result: Any, atol: float = 1e-8, key: Optional[str] = None) -> None:
"""Utility function for recursively asserting that two results are within a certain tolerance."""
# single output compare
if isinstance(pl_result, Tensor):
assert np.allclose(pl_result.detach().cpu().numpy(), sk_result, atol=atol, equal_nan=True)
# multi output compare
elif isinstance(pl_result, Sequence):
for pl_res, sk_res in zip(pl_result, sk_result):
_assert_allclose(pl_res, sk_res, atol=atol)
elif isinstance(pl_result, Dict):
if key is None:
raise KeyError("Provide Key for Dict based metric results.")
assert np.allclose(pl_result[key].detach().cpu().numpy(), sk_result, atol=atol, equal_nan=True)
else:
raise ValueError("Unknown format for comparison")
def _assert_tensor(pl_result: Any, key: Optional[str] = None) -> None:
"""Utility function for recursively checking that some input only consists of torch tensors."""
if isinstance(pl_result, Sequence):
for plr in pl_result:
_assert_tensor(plr)
elif isinstance(pl_result, Dict):
if key is None:
raise KeyError("Provide Key for Dict based metric results.")
assert isinstance(pl_result[key], Tensor)
elif isinstance(pl_result, MAPMetricResults):
for val_index in [a for a in dir(pl_result) if not a.startswith("__")]:
assert isinstance(pl_result[val_index], Tensor)
else:
assert isinstance(pl_result, Tensor)
def _assert_requires_grad(metric: Metric, pl_result: Any, key: Optional[str] = None) -> None:
"""Utility function for recursively asserting that metric output is consistent with the `is_differentiable`
attribute."""
if isinstance(pl_result, Sequence):
for plr in pl_result:
_assert_requires_grad(metric, plr, key=key)
elif isinstance(pl_result, Dict):
if key is None:
raise KeyError("Provide Key for Dict based metric results.")
assert metric.is_differentiable == pl_result[key].requires_grad
else:
assert metric.is_differentiable == pl_result.requires_grad
def _class_test(
rank: int,
worldsize: int,
preds: Union[Tensor, List[Dict[str, Tensor]]],
target: Union[Tensor, List[Dict[str, Tensor]]],
metric_class: Metric,
sk_metric: Callable,
dist_sync_on_step: bool,
metric_args: dict = None,
check_dist_sync_on_step: bool = True,
check_batch: bool = True,
atol: float = 1e-8,
device: str = "cpu",
fragment_kwargs: bool = False,
check_scriptable: bool = True,
check_state_dict: bool = True,
**kwargs_update: Any,
):
"""Utility function doing the actual comparison between class metric and reference metric.
Args:
rank: rank of current process
worldsize: number of processes
preds: torch tensor with predictions
target: torch tensor with targets
metric_class: metric class that should be tested
sk_metric: callable function that is used for comparison
dist_sync_on_step: bool, if true will synchronize metric state across
processes at each ``forward()``
metric_args: dict with additional arguments used for class initialization
check_dist_sync_on_step: bool, if true will check if the metric is also correctly
calculated per batch per device (and not just at the end)
check_batch: bool, if true will check if the metric is also correctly
calculated across devices for each batch (and not just at the end)
device: determine which device to run on, either 'cuda' or 'cpu'
fragment_kwargs: whether tensors in kwargs should be divided as `preds` and `target` among processes
kwargs_update: Additional keyword arguments that will be passed with preds and
target when running update on the metric.
"""
assert len(preds) == len(target)
num_batches = len(preds)
if not metric_args:
metric_args = {}
# Instantiate metric
metric = metric_class(dist_sync_on_step=dist_sync_on_step, **metric_args)
with pytest.raises(RuntimeError):
metric.is_differentiable = not metric.is_differentiable
with pytest.raises(RuntimeError):
metric.higher_is_better = not metric.higher_is_better
# check that the metric is scriptable
if check_scriptable:
torch.jit.script(metric)
# move to device
metric = metric.to(device)
preds = apply_to_collection(preds, Tensor, lambda x: x.to(device))
target = apply_to_collection(target, Tensor, lambda x: x.to(device))
kwargs_update = {k: v.to(device) if isinstance(v, Tensor) else v for k, v in kwargs_update.items()}
# verify metrics work after being loaded from pickled state
pickled_metric = pickle.dumps(metric)
metric = pickle.loads(pickled_metric)
for i in range(rank, num_batches, worldsize):
batch_kwargs_update = {k: v[i] if isinstance(v, Tensor) else v for k, v in kwargs_update.items()}
batch_result = metric(preds[i], target[i], **batch_kwargs_update)
if metric.dist_sync_on_step and check_dist_sync_on_step and rank == 0:
if isinstance(preds, Tensor):
ddp_preds = torch.cat([preds[i + r] for r in range(worldsize)]).cpu()
ddp_target = torch.cat([target[i + r] for r in range(worldsize)]).cpu()
else:
ddp_preds = [preds[i + r] for r in range(worldsize)]
ddp_target = [target[i + r] for r in range(worldsize)]
ddp_kwargs_upd = {
k: torch.cat([v[i + r] for r in range(worldsize)]).cpu() if isinstance(v, Tensor) else v
for k, v in (kwargs_update if fragment_kwargs else batch_kwargs_update).items()
}
sk_batch_result = sk_metric(ddp_preds, ddp_target, **ddp_kwargs_upd)
if isinstance(batch_result, dict):
for key in batch_result:
_assert_allclose(batch_result, sk_batch_result[key].numpy(), atol=atol, key=key)
else:
_assert_allclose(batch_result, sk_batch_result, atol=atol)
elif check_batch and not metric.dist_sync_on_step:
batch_kwargs_update = {
k: v.cpu() if isinstance(v, Tensor) else v
for k, v in (batch_kwargs_update if fragment_kwargs else kwargs_update).items()
}
preds_ = preds[i].cpu() if isinstance(preds, Tensor) else preds[i]
target_ = target[i].cpu() if isinstance(target, Tensor) else target[i]
sk_batch_result = sk_metric(preds_, target_, **batch_kwargs_update)
if isinstance(batch_result, dict):
for key in batch_result.keys():
_assert_allclose(batch_result, sk_batch_result[key].numpy(), atol=atol, key=key)
else:
_assert_allclose(batch_result, sk_batch_result, atol=atol)
# check that metrics are hashable
assert hash(metric)
# assert that state dict is empty
if check_state_dict:
assert metric.state_dict() == {}
# check on all batches on all ranks
result = metric.compute()
if isinstance(result, dict):
for key in result.keys():
_assert_tensor(result, key=key)
else:
_assert_tensor(result)
if isinstance(preds, Tensor):
total_preds = torch.cat([preds[i] for i in range(num_batches)]).cpu()
total_target = torch.cat([target[i] for i in range(num_batches)]).cpu()
else:
total_preds = [item for sublist in preds for item in sublist]
total_target = [item for sublist in target for item in sublist]
total_kwargs_update = {
k: torch.cat([v[i] for i in range(num_batches)]).cpu() if isinstance(v, Tensor) else v
for k, v in kwargs_update.items()
}
sk_result = sk_metric(total_preds, total_target, **total_kwargs_update)
# assert after aggregation
if isinstance(sk_result, dict):
for key in sk_result.keys():
_assert_allclose(result, sk_result[key].numpy(), atol=atol, key=key)
else:
_assert_allclose(result, sk_result, atol=atol)
def _functional_test(
preds: Tensor,
target: Tensor,
metric_functional: Callable,
sk_metric: Callable,
metric_args: dict = None,
atol: float = 1e-8,
device: str = "cpu",
fragment_kwargs: bool = False,
**kwargs_update,
):
"""Utility function doing the actual comparison between functional metric and reference metric.
Args:
preds: torch tensor with predictions
target: torch tensor with targets
metric_functional: metric functional that should be tested
sk_metric: callable function that is used for comparison
metric_args: dict with additional arguments used for class initialization
device: determine which device to run on, either 'cuda' or 'cpu'
fragment_kwargs: whether tensors in kwargs should be divided as `preds` and `target` among processes
kwargs_update: Additional keyword arguments that will be passed with preds and
target when running update on the metric.
"""
assert preds.shape[0] == target.shape[0]
num_batches = preds.shape[0]
if not metric_args:
metric_args = {}
metric = partial(metric_functional, **metric_args)
# move to device
preds = preds.to(device)
target = target.to(device)
kwargs_update = {k: v.to(device) if isinstance(v, Tensor) else v for k, v in kwargs_update.items()}
for i in range(num_batches):
extra_kwargs = {k: v[i] if isinstance(v, Tensor) else v for k, v in kwargs_update.items()}
tm_result = metric(preds[i], target[i], **extra_kwargs)
extra_kwargs = {
k: v.cpu() if isinstance(v, Tensor) else v
for k, v in (extra_kwargs if fragment_kwargs else kwargs_update).items()
}
sk_result = sk_metric(preds[i].cpu(), target[i].cpu(), **extra_kwargs)
# assert its the same
_assert_allclose(tm_result, sk_result, atol=atol)
def _assert_half_support(
metric_module: Optional[Metric],
metric_functional: Optional[Callable],
preds: Tensor,
target: Tensor,
device: str = "cpu",
**kwargs_update,
):
"""Test if an metric can be used with half precision tensors.
Args:
metric_module: the metric module to test
metric_functional: the metric functional to test
preds: torch tensor with predictions
target: torch tensor with targets
device: determine device, either "cpu" or "cuda"
kwargs_update: Additional keyword arguments that will be passed with preds and
target when running update on the metric.
"""
y_hat = preds[0].half().to(device) if preds[0].is_floating_point() else preds[0].to(device)
y = target[0].half().to(device) if target[0].is_floating_point() else target[0].to(device)
kwargs_update = {
k: (v[0].half() if v.is_floating_point() else v[0]).to(device) if isinstance(v, Tensor) else v
for k, v in kwargs_update.items()
}
if metric_module is not None:
metric_module = metric_module.to(device)
_assert_tensor(metric_module(y_hat, y, **kwargs_update))
if metric_functional is not None:
_assert_tensor(metric_functional(y_hat, y, **kwargs_update))
class MetricTester:
"""Class used for efficiently run alot of parametrized tests in ddp mode. Makes sure that ddp is only setup
once and that pool of processes are used for all tests.
All tests should subclass from this and implement a new method called `test_metric_name` where the method
`self.run_metric_test` is called inside.
"""
atol: float = 1e-8
poolSize: int
pool: Pool
def setup_class(self):
"""Setup the metric class.
This will spawn the pool of workers that are used for metric testing and setup_ddp
"""
self.poolSize = NUM_PROCESSES
self.pool = Pool(processes=self.poolSize)
self.pool.starmap(setup_ddp, [(rank, self.poolSize) for rank in range(self.poolSize)])
def teardown_class(self):
"""Close pool of workers."""
self.pool.close()
self.pool.join()
def run_functional_metric_test(
self,
preds: Tensor,
target: Tensor,
metric_functional: Callable,
sk_metric: Callable,
metric_args: dict = None,
fragment_kwargs: bool = False,
**kwargs_update,
):
"""Main method that should be used for testing functions. Call this inside testing method.
Args:
preds: torch tensor with predictions
target: torch tensor with targets
metric_functional: metric class that should be tested
sk_metric: callable function that is used for comparison
metric_args: dict with additional arguments used for class initialization
fragment_kwargs: whether tensors in kwargs should be divided as `preds` and `target` among processes
kwargs_update: Additional keyword arguments that will be passed with preds and
target when running update on the metric.
"""
device = "cuda" if (torch.cuda.is_available() and torch.cuda.device_count() > 0) else "cpu"
_functional_test(
preds=preds,
target=target,
metric_functional=metric_functional,
sk_metric=sk_metric,
metric_args=metric_args,
atol=self.atol,
device=device,
fragment_kwargs=fragment_kwargs,
**kwargs_update,
)
def run_class_metric_test(
self,
ddp: bool,
preds: Union[Tensor, List[Dict]],
target: Union[Tensor, List[Dict]],
metric_class: Metric,
sk_metric: Callable,
dist_sync_on_step: bool,
metric_args: dict = None,
check_dist_sync_on_step: bool = True,
check_batch: bool = True,
fragment_kwargs: bool = False,
check_scriptable: bool = True,
**kwargs_update,
):
"""Main method that should be used for testing class. Call this inside testing methods.
Args:
ddp: bool, if running in ddp mode or not
preds: torch tensor with predictions
target: torch tensor with targets
metric_class: metric class that should be tested
sk_metric: callable function that is used for comparison
dist_sync_on_step: bool, if true will synchronize metric state across
processes at each ``forward()``
metric_args: dict with additional arguments used for class initialization
check_dist_sync_on_step: bool, if true will check if the metric is also correctly
calculated per batch per device (and not just at the end)
check_batch: bool, if true will check if the metric is also correctly
calculated across devices for each batch (and not just at the end)
fragment_kwargs: whether tensors in kwargs should be divided as `preds` and `target` among processes
check_scriptable:
kwargs_update: Additional keyword arguments that will be passed with preds and
target when running update on the metric.
"""
if not metric_args:
metric_args = {}
if ddp:
if sys.platform == "win32":
pytest.skip("DDP not supported on windows")
self.pool.starmap(
partial(
_class_test,
preds=preds,
target=target,
metric_class=metric_class,
sk_metric=sk_metric,
dist_sync_on_step=dist_sync_on_step,
metric_args=metric_args,
check_dist_sync_on_step=check_dist_sync_on_step,
check_batch=check_batch,
atol=self.atol,
fragment_kwargs=fragment_kwargs,
check_scriptable=check_scriptable,
**kwargs_update,
),
[(rank, self.poolSize) for rank in range(self.poolSize)],
)
else:
device = "cuda" if (torch.cuda.is_available() and torch.cuda.device_count() > 0) else "cpu"
_class_test(
rank=0,
worldsize=1,
preds=preds,
target=target,
metric_class=metric_class,
sk_metric=sk_metric,
dist_sync_on_step=dist_sync_on_step,
metric_args=metric_args,
check_dist_sync_on_step=check_dist_sync_on_step,
check_batch=check_batch,
atol=self.atol,
device=device,
fragment_kwargs=fragment_kwargs,
check_scriptable=check_scriptable,
**kwargs_update,
)
@staticmethod
def run_precision_test_cpu(
preds: Tensor,
target: Tensor,
metric_module: Optional[Metric] = None,
metric_functional: Optional[Callable] = None,
metric_args: Optional[dict] = None,
**kwargs_update,
):
"""Test if a metric can be used with half precision tensors on cpu
Args:
preds: torch tensor with predictions
target: torch tensor with targets
metric_module: the metric module to test
metric_functional: the metric functional to test
metric_args: dict with additional arguments used for class initialization
kwargs_update: Additional keyword arguments that will be passed with preds and
target when running update on the metric.
"""
metric_args = metric_args or {}
_assert_half_support(
metric_module(**metric_args) if metric_module is not None else None,
metric_functional,
preds,
target,
device="cpu",
**kwargs_update,
)
@staticmethod
def run_precision_test_gpu(
preds: Tensor,
target: Tensor,
metric_module: Optional[Metric] = None,
metric_functional: Optional[Callable] = None,
metric_args: Optional[dict] = None,
**kwargs_update,
):
"""Test if a metric can be used with half precision tensors on gpu
Args:
preds: torch tensor with predictions
target: torch tensor with targets
metric_module: the metric module to test
metric_functional: the metric functional to test
metric_args: dict with additional arguments used for class initialization
kwargs_update: Additional keyword arguments that will be passed with preds and
target when running update on the metric.
"""
metric_args = metric_args or {}
_assert_half_support(
metric_module(**metric_args) if metric_module is not None else None,
metric_functional,
preds,
target,
device="cuda",
**kwargs_update,
)
@staticmethod
def run_differentiability_test(
preds: Tensor,
target: Tensor,
metric_module: Metric,
metric_functional: Optional[Callable] = None,
metric_args: Optional[dict] = None,
):
"""Test if a metric is differentiable or not.
Args:
preds: torch tensor with predictions
target: torch tensor with targets
metric_module: the metric module to test
metric_functional:
metric_args: dict with additional arguments used for class initialization
"""
metric_args = metric_args or {}
# only floating point tensors can require grad
metric = metric_module(**metric_args)
if preds.is_floating_point():
preds.requires_grad = True
out = metric(preds[0, :2], target[0, :2])
# Check if requires_grad matches is_differentiable attribute
_assert_requires_grad(metric, out)
if metric.is_differentiable and metric_functional is not None:
# check for numerical correctness
assert torch.autograd.gradcheck(
partial(metric_functional, **metric_args), (preds[0, :2].double(), target[0, :2])
)
# reset as else it will carry over to other tests
preds.requires_grad = False
class DummyMetric(Metric):
name = "Dummy"
full_state_update: Optional[bool] = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_state("x", tensor(0.0), dist_reduce_fx="sum")
def update(self):
pass
def compute(self):
pass
class DummyListMetric(Metric):
name = "DummyList"
full_state_update: Optional[bool] = True
def __init__(self):
super().__init__()
self.add_state("x", [], dist_reduce_fx="cat")
def update(self):
pass
def compute(self):
pass
class DummyMetricSum(DummyMetric):
def update(self, x):
self.x += x
def compute(self):
return self.x
class DummyMetricDiff(DummyMetric):
def update(self, y):
self.x -= y
def compute(self):
return self.x
class DummyMetricMultiOutput(DummyMetricSum):
def compute(self):
return [self.x, self.x]