File size: 3,036 Bytes
d0f2b17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Regression checks for the RAQEEB partial-label training logic (CPU only)."""
import sys
import unittest
from pathlib import Path

import torch

sys.path.insert(0, str(Path(__file__).resolve().parent))
import raqeeb_trainer as rt  # noqa: E402


class MaskedBCETest(unittest.TestCase):
    def test_negatives_ignored_for_unannotated_classes_positives_kept(self):
        bce = rt.MaskedBCE()
        bce.mask = torch.tensor([[1., 0., 0.], [1., 1., 1.]])  # image0 annotates class 0 only
        pred = torch.zeros(2, 4, 3)
        tgt = torch.zeros(2, 4, 3)
        tgt[0, 0, 1] = 0.8  # a positive of a non-full (partial) class must still count
        loss = bce(pred, tgt)
        self.assertTrue(torch.all(loss[0, :, 0] > 0))           # full class: all anchors count
        self.assertGreater(loss[0, 0, 1].item(), 0)               # partial positive counts
        self.assertEqual(loss[0, 1:, 1].abs().sum().item(), 0)    # partial negatives ignored
        self.assertEqual(loss[0, :, 2].abs().sum().item(), 0)     # unannotated class ignored
        self.assertTrue(torch.all(loss[1] > 0))                    # fully annotated image unchanged

    def test_no_mask_is_plain_bce(self):
        bce = rt.MaskedBCE()
        p, t = torch.randn(2, 5, 3), torch.rand(2, 5, 3)
        ref = torch.nn.functional.binary_cross_entropy_with_logits(p, t, reduction='none')
        self.assertTrue(torch.allclose(bce(p, t), ref))


class CollateTest(unittest.TestCase):
    def test_cls_mask_stacked(self):
        b = [dict(img=torch.zeros(3, 8, 8, dtype=torch.uint8), cls=torch.zeros(1, 1), bboxes=torch.zeros(1, 4),
                  masks=torch.zeros(1, 2, 2), batch_idx=torch.zeros(1), cls_mask=torch.ones(11) * i,
                  im_file=f'x{i}') for i in range(3)]
        out = rt.RaqeebDataset.collate_fn(b)
        self.assertEqual(tuple(out['cls_mask'].shape), (3, 11))
        self.assertEqual(out['cls_mask'][2, 0].item(), 2)
        self.assertEqual(out['img'].shape[0], 3)


class MosaicSwapTest(unittest.TestCase):
    def test_swap(self):
        from ultralytics.data.augment import Compose, Mosaic
        m = Mosaic.__new__(Mosaic)
        c = Compose([Compose([m])])
        rt._swap_mosaic(c)
        self.assertIsInstance(m, rt.GroupMosaic)


class ValidatorFilterTest(unittest.TestCase):
    def test_predictions_of_unannotated_classes_dropped(self):
        v = rt.RaqeebSegValidator.__new__(rt.RaqeebSegValidator)
        seen = {}
        rt.SegmentationValidator.update_metrics = lambda self, preds, batch: seen.setdefault('p', preds)
        preds = [dict(cls=torch.tensor([0., 1., 2.]), conf=torch.tensor([.9, .8, .7]),
                      bboxes=torch.zeros(3, 4), masks=torch.zeros(3, 4, 4))]
        batch = dict(cls_mask=torch.tensor([[0., 1., 0.] + [0.] * 8]))
        v.update_metrics(preds, batch)
        p = seen['p'][0]
        self.assertEqual(p['cls'].tolist(), [1.0])
        self.assertEqual(tuple(p['masks'].shape), (1, 4, 4))


if __name__ == '__main__':
    unittest.main(verbosity=2)