"vscode:/vscode.git/clone" did not exist on "7a0bbe6a64ee61f0bd22811a3b72bc7418e15c17"
test_forward.py 6.06 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
zhangwenwei's avatar
zhangwenwei committed
2
"""Test model forward process.
zhangwenwei's avatar
zhangwenwei committed
3
4

CommandLine:
5
6
    pytest tests/test_models/test_forward.py
    xdoctest tests/test_models/test_forward.py zero
zhangwenwei's avatar
zhangwenwei committed
7
8
"""
import copy
9
10
from os.path import dirname, exists, join

zhangwenwei's avatar
zhangwenwei committed
11
12
13
14
15
import numpy as np
import torch


def _get_config_directory():
zhangwenwei's avatar
zhangwenwei committed
16
    """Find the predefined detector config directory."""
zhangwenwei's avatar
zhangwenwei committed
17
    try:
18
19
        # Assume we are running in the source mmdetection3d repo
        repo_dpath = dirname(dirname(dirname(__file__)))
zhangwenwei's avatar
zhangwenwei committed
20
21
    except NameError:
        # For IPython development when this __file__ is not defined
22
23
        import mmdet3d
        repo_dpath = dirname(dirname(mmdet3d.__file__))
zhangwenwei's avatar
zhangwenwei committed
24
25
26
27
28
29
30
    config_dpath = join(repo_dpath, 'configs')
    if not exists(config_dpath):
        raise Exception('Cannot find config path')
    return config_dpath


def _get_config_module(fname):
zhangwenwei's avatar
zhangwenwei committed
31
    """Load a configuration as a python module."""
zhangwenwei's avatar
zhangwenwei committed
32
33
34
35
36
37
38
39
    from mmcv import Config
    config_dpath = _get_config_directory()
    config_fpath = join(config_dpath, fname)
    config_mod = Config.fromfile(config_fpath)
    return config_mod


def _get_detector_cfg(fname):
zhangwenwei's avatar
zhangwenwei committed
40
41
    """Grab configs necessary to create a detector.

42
43
    These are deep copied to allow for safe modification of parameters without
    influencing other tests.
zhangwenwei's avatar
zhangwenwei committed
44
45
46
    """
    config = _get_config_module(fname)
    model = copy.deepcopy(config.model)
47
    return model
zhangwenwei's avatar
zhangwenwei committed
48
49
50


def _test_two_stage_forward(cfg_file):
51
    model = _get_detector_cfg(cfg_file)
zhangwenwei's avatar
zhangwenwei committed
52
53
54
    model['pretrained'] = None

    from mmdet.models import build_detector
55
    detector = build_detector(model)
zhangwenwei's avatar
zhangwenwei committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

    input_shape = (1, 3, 256, 256)

    # Test forward train with a non-empty truth batch
    mm_inputs = _demo_mm_inputs(input_shape, num_items=[10])
    imgs = mm_inputs.pop('imgs')
    img_metas = mm_inputs.pop('img_metas')
    gt_bboxes = mm_inputs['gt_bboxes']
    gt_labels = mm_inputs['gt_labels']
    gt_masks = mm_inputs['gt_masks']
    losses = detector.forward(
        imgs,
        img_metas,
        gt_bboxes=gt_bboxes,
        gt_labels=gt_labels,
        gt_masks=gt_masks,
        return_loss=True)
    assert isinstance(losses, dict)
zhangwenwei's avatar
zhangwenwei committed
74
75
76
77
    loss, _ = detector._parse_losses(losses)
    loss.requires_grad_(True)
    assert float(loss.item()) > 0
    loss.backward()
zhangwenwei's avatar
zhangwenwei committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

    # Test forward train with an empty truth batch
    mm_inputs = _demo_mm_inputs(input_shape, num_items=[0])
    imgs = mm_inputs.pop('imgs')
    img_metas = mm_inputs.pop('img_metas')
    gt_bboxes = mm_inputs['gt_bboxes']
    gt_labels = mm_inputs['gt_labels']
    gt_masks = mm_inputs['gt_masks']
    losses = detector.forward(
        imgs,
        img_metas,
        gt_bboxes=gt_bboxes,
        gt_labels=gt_labels,
        gt_masks=gt_masks,
        return_loss=True)
    assert isinstance(losses, dict)
zhangwenwei's avatar
zhangwenwei committed
94
95
96
    loss, _ = detector._parse_losses(losses)
    assert float(loss.item()) > 0
    loss.backward()
zhangwenwei's avatar
zhangwenwei committed
97
98
99
100
101
102
103
104
105
106
107
108

    # Test forward test
    with torch.no_grad():
        img_list = [g[None, :] for g in imgs]
        batch_results = []
        for one_img, one_meta in zip(img_list, img_metas):
            result = detector.forward([one_img], [[one_meta]],
                                      return_loss=False)
            batch_results.append(result)


def _test_single_stage_forward(cfg_file):
109
    model = _get_detector_cfg(cfg_file)
zhangwenwei's avatar
zhangwenwei committed
110
111
112
    model['pretrained'] = None

    from mmdet.models import build_detector
113
    detector = build_detector(model)
zhangwenwei's avatar
zhangwenwei committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

    input_shape = (1, 3, 300, 300)
    mm_inputs = _demo_mm_inputs(input_shape)

    imgs = mm_inputs.pop('imgs')
    img_metas = mm_inputs.pop('img_metas')

    # Test forward train
    gt_bboxes = mm_inputs['gt_bboxes']
    gt_labels = mm_inputs['gt_labels']
    losses = detector.forward(
        imgs,
        img_metas,
        gt_bboxes=gt_bboxes,
        gt_labels=gt_labels,
        return_loss=True)
    assert isinstance(losses, dict)
zhangwenwei's avatar
zhangwenwei committed
131
132
    loss, _ = detector._parse_losses(losses)
    assert float(loss.item()) > 0
zhangwenwei's avatar
zhangwenwei committed
133
134
135
136
137
138
139
140
141
142
143
144
145

    # Test forward test
    with torch.no_grad():
        img_list = [g[None, :] for g in imgs]
        batch_results = []
        for one_img, one_meta in zip(img_list, img_metas):
            result = detector.forward([one_img], [[one_meta]],
                                      return_loss=False)
            batch_results.append(result)


def _demo_mm_inputs(input_shape=(1, 3, 300, 300),
                    num_items=None, num_classes=10):  # yapf: disable
zhangwenwei's avatar
zhangwenwei committed
146
    """Create a superset of inputs needed to run test or train batches.
zhangwenwei's avatar
zhangwenwei committed
147
148
149
150
151

    Args:
        input_shape (tuple):
            input batch dimensions

152
        num_items (List[int]):
zhangwenwei's avatar
zhangwenwei committed
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
            specifies the number of boxes in each batch item

        num_classes (int):
            number of different labels a box might have
    """
    from mmdet.core import BitmapMasks

    (N, C, H, W) = input_shape

    rng = np.random.RandomState(0)

    imgs = rng.rand(*input_shape)

    img_metas = [{
        'img_shape': (H, W, C),
        'ori_shape': (H, W, C),
        'pad_shape': (H, W, C),
        'filename': '<demo>.png',
        'scale_factor': 1.0,
        'flip': False,
    } for _ in range(N)]

    gt_bboxes = []
    gt_labels = []
    gt_masks = []

    for batch_idx in range(N):
        if num_items is None:
            num_boxes = rng.randint(1, 10)
        else:
            num_boxes = num_items[batch_idx]

        cx, cy, bw, bh = rng.rand(num_boxes, 4).T

        tl_x = ((cx * W) - (W * bw / 2)).clip(0, W)
        tl_y = ((cy * H) - (H * bh / 2)).clip(0, H)
        br_x = ((cx * W) + (W * bw / 2)).clip(0, W)
        br_y = ((cy * H) + (H * bh / 2)).clip(0, H)

        boxes = np.vstack([tl_x, tl_y, br_x, br_y]).T
        class_idxs = rng.randint(1, num_classes, size=num_boxes)

        gt_bboxes.append(torch.FloatTensor(boxes))
        gt_labels.append(torch.LongTensor(class_idxs))

    mask = np.random.randint(0, 2, (len(boxes), H, W), dtype=np.uint8)
    gt_masks.append(BitmapMasks(mask, H, W))

    mm_inputs = {
        'imgs': torch.FloatTensor(imgs).requires_grad_(True),
        'img_metas': img_metas,
        'gt_bboxes': gt_bboxes,
        'gt_labels': gt_labels,
        'gt_bboxes_ignore': None,
        'gt_masks': gt_masks,
    }
    return mm_inputs