"vscode:/vscode.git/clone" did not exist on "583697cd71faa65a2e132a014743f5ff5c63890a"
test_modeling_distillation.py 27.4 KB
Newer Older
Matthew Yu's avatar
Matthew Yu committed
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved

import unittest
from typing import List

import mock
import numpy as np
import torch
import torch.nn as nn
from d2go.config import CfgNode
Yanghan Wang's avatar
Yanghan Wang committed
12
from d2go.modeling import modeling_hook as mh
Matthew Yu's avatar
Matthew Yu committed
13
14
from d2go.modeling.distillation import (
    _build_teacher,
15
    _set_device,
Matthew Yu's avatar
Matthew Yu committed
16
17
    add_distillation_configs,
    BaseDistillationHelper,
18
    CachedLayer,
19
    compute_layer_losses,
20
    DefaultLossCombiner,
Matthew Yu's avatar
Matthew Yu committed
21
    DistillationModelingHook,
Matthew Yu's avatar
Matthew Yu committed
22
    DomainAdaptation,
Matthew Yu's avatar
Matthew Yu committed
23
    ExampleDistillationHelper,
24
    get_default_kd_image_classification_layer_losses,
Matthew Yu's avatar
Matthew Yu committed
25
    KnowledgeDistillation,
Matthew Yu's avatar
Matthew Yu committed
26
    LabelDistillation,
27
    LayerLossMetadata,
Matthew Yu's avatar
Matthew Yu committed
28
29
    NoopPseudoLabeler,
    PseudoLabeler,
30
    record_layers,
31
    register_layer_losses_and_to_device,
Matthew Yu's avatar
Matthew Yu committed
32
    RelabelTargetInBatch,
Matthew Yu's avatar
Matthew Yu committed
33
    set_cache_dict,
34
    unrecord_layers,
Matthew Yu's avatar
Matthew Yu committed
35
36
37
38
)
from d2go.registry.builtin import (
    DISTILLATION_ALGORITHM_REGISTRY,
    DISTILLATION_HELPER_REGISTRY,
39
    META_ARCH_REGISTRY,
Matthew Yu's avatar
Matthew Yu committed
40
)
41
from d2go.runner.default_runner import BaseRunner
Matthew Yu's avatar
Matthew Yu committed
42
from d2go.utils.testing import helper
43
44
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.utils.file_io import PathManager
Matthew Yu's avatar
Matthew Yu committed
45
from mobile_cv.common.misc.file_utils import make_temp_directory
46
from mobile_cv.common.misc.mixin import dynamic_mixin, remove_dynamic_mixin
Matthew Yu's avatar
Matthew Yu committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67


class DivideInputBy2(nn.Module):
    def forward(self, batched_inputs: List):
        """Divide all targets by 2 and batch output"""
        return [x / 2.0 for x in batched_inputs]


class DivideInputDictBy2(nn.Module):
    def forward(self, batched_inputs: List):
        """Divide all inputs by 2 and batch output

        Should be used with a pseudo labeler that will unpack the
        resulting tensor
        """
        output = []
        for d in batched_inputs:
            output.append(d["input"] / 2.0)
        return torch.stack(output)


68
69
70
71
72
73
class DivideInputBy2OutputDict(nn.Module):
    def forward(self, batched_inputs: List):
        """Divide all targets by 2 and return dict output"""
        return {i: x / 2.0 for i, x in enumerate(batched_inputs)}


Matthew Yu's avatar
Matthew Yu committed
74
75
76
77
78
79
80
81
class AddOne(nn.Module):
    def __init__(self):
        super().__init__()
        self.weight = nn.Parameter(torch.Tensor([1]))

    def forward(self, x):
        return x + self.weight

82
83
84
85
    @property
    def device(self):
        return self.weight.device

Matthew Yu's avatar
Matthew Yu committed
86

87
88
89
90
91
92
93
94
95
96
97
class AddLayers(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer0 = AddOne()
        self.layer1 = AddOne()
        self.layer2 = AddOne()

    def forward(self, x):
        x = self.layer0(x)
        x = self.layer1(x)
        x = self.layer2(x)
Matthew Yu's avatar
Matthew Yu committed
98
99
100
        if not self.training:
            return x
        return {"output": x}
101

102
103
104
105
106
107
108
109
110
111
112
113
114
115
    @property
    def device(self):
        return self.layer0.weight.device


class SimpleAdd(nn.Module):
    def forward(self, x, y):
        return x + y


class SimpleMul(nn.Module):
    def forward(self, x, y):
        return x * y

116

Matthew Yu's avatar
Matthew Yu committed
117
118
119
120
121
122
123
124
class TestLabeler(PseudoLabeler):
    def __init__(self, teacher):
        self.teacher = teacher

    def label(self, x):
        return self.teacher(x)


125
126
127
128
129
130
131
132
133
134
@META_ARCH_REGISTRY.register()
class TestMetaArchAddRand(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        self.weight = nn.Parameter(torch.rand(1))

    def forward(self, x):
        return x + self.weight


Matthew Yu's avatar
Matthew Yu committed
135
136
137
138
139
140
@DISTILLATION_HELPER_REGISTRY.register()
class TestHelper(BaseDistillationHelper):
    def get_pseudo_labeler(self):
        """Run teacher model on inputs"""
        return TestLabeler(self.teacher)

Matthew Yu's avatar
Matthew Yu committed
141
142
143
144
145
146
147
148
149
    def get_preprocess_student_input(self):
        return lambda x: x + 1

    def get_preprocess_teacher_input(self):
        return lambda x: x + 2

    def get_layer_losses(self, model=None):
        return [
            LayerLossMetadata(
150
                loss=SimpleAdd(),
Matthew Yu's avatar
Matthew Yu committed
151
152
153
154
155
                name="add",
                layer0="layer0",
                layer1="layer0",
            ),
            LayerLossMetadata(
156
                loss=SimpleMul(),
Matthew Yu's avatar
Matthew Yu committed
157
158
159
160
161
162
163
164
165
166
167
168
169
                name="mul",
                layer0="layer1",
                layer1="layer1",
            ),
        ]

    def get_combine_losses(self):
        return lambda d: {
            "output": d["output"] * 0.1,
            "add": d["add"] * 0.5,
            "mul": d["mul"] * 10.0,
        }

Matthew Yu's avatar
Matthew Yu committed
170

Matthew Yu's avatar
Matthew Yu committed
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
class TestDAHelper(BaseDistillationHelper):
    def get_preprocess_domain0_input(self):
        return lambda x: x["real"]

    def get_preprocess_domain1_input(self):
        return lambda x: x["synthetic"]

    def get_layer_losses(self, model=None):
        return [
            LayerLossMetadata(
                loss=SimpleAdd(),
                name="add",
                layer0="layer0",
                layer1="layer0",
            )
        ]

    def get_combine_losses(self):
        return lambda d0, d1, da, ta: {
            "real": d0["output"] * 0.1,
            "synthetic": d1["output"] * 0.5,
            "add": da["add"] * 10.0,
        }


Matthew Yu's avatar
Matthew Yu committed
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
class Noop(nn.Module):
    def forward(self, x):
        return x


def _get_input_data(n: int = 2, use_input_target: bool = False, requires_grad=False):
    """Return input data, dict if use_input_target is specified"""
    if not use_input_target:
        return torch.randn(n, requires_grad=requires_grad)

    return [
        {
            "input": torch.randn(1, requires_grad=requires_grad),
            "target": torch.randn(1),
        }
        for _ in range(n)
    ]


def _get_default_cfg():
    cfg = CfgNode()
    cfg.MODEL = CfgNode()
    cfg.MODEL.DEVICE = "cpu"
    cfg.MODEL.META_ARCHITECTURE = "TestArch"
    add_distillation_configs(cfg)
221
    # model_ema.add_model_ema_configs(cfg)
Matthew Yu's avatar
Matthew Yu committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    cfg.DISTILLATION.ALGORITHM = "LabelDistillation"
    cfg.DISTILLATION.HELPER = "BaseDistillationHelper"
    cfg.DISTILLATION.TEACHER.TORCHSCRIPT_FNAME = ""
    cfg.DISTILLATION.TEACHER.DEVICE = ""
    return cfg


class TestDistillation(unittest.TestCase):
    def test_add_distillation_configs(self):
        """Check default config"""
        cfg = CfgNode()
        add_distillation_configs(cfg)
        self.assertTrue(isinstance(cfg.DISTILLATION.TEACHER, CfgNode))

236
237
238
239
240
        # check teacher model config is clone of student model
        self.assertEqual(cfg.DISTILLATION.TEACHER.CONFIG_FNAME, "")

    def test_build_teacher_torchscript(self):
        """Check can build teacher using torchscript fname in config"""
Matthew Yu's avatar
Matthew Yu committed
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
        # create torchscript
        model = DivideInputBy2()
        traced_model = torch.jit.trace(model, torch.randn(5))
        with make_temp_directory("tmp") as output_dir:
            fname = f"{output_dir}/tmp.pt"
            torch.jit.save(traced_model, fname)

            # create teacher
            cfg = _get_default_cfg()
            cfg.DISTILLATION.TEACHER.TORCHSCRIPT_FNAME = fname
            teacher = _build_teacher(cfg)
            batched_inputs = torch.randn(5)
            gt = batched_inputs / 2.0
            output = teacher(batched_inputs)
            torch.testing.assert_close(torch.Tensor(output), gt)

    @helper.skip_if_no_gpu
258
    def test_build_teacher_torchscript_gpu(self):
Matthew Yu's avatar
Matthew Yu committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        """Check teacher moved to cuda"""
        model = AddOne()
        traced_model = torch.jit.trace(model, torch.randn(5))
        with make_temp_directory("tmp") as output_dir:
            fname = f"{output_dir}/tmp.pt"
            torch.jit.save(traced_model, fname)

            # create teacher
            cfg = _get_default_cfg()
            cfg.MODEL.DEVICE = "cuda"
            cfg.DISTILLATION.TEACHER.TORCHSCRIPT_FNAME = fname
            teacher = _build_teacher(cfg)
            batched_inputs = torch.randn(5).to("cuda")
            gt = batched_inputs + torch.Tensor([1]).to("cuda")
            output = teacher(batched_inputs)
            torch.testing.assert_close(torch.Tensor(output), gt)

276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
    def test_build_teacher_config(self):
        """Check build pytorch model using config"""
        # build model
        cfg = _get_default_cfg()
        cfg.MODEL.META_ARCHITECTURE = "TestMetaArchAddRand"
        gt_model = BaseRunner().build_model(cfg)
        with make_temp_directory("tmp") as output_dir:
            # save model
            checkpointer = DetectionCheckpointer(gt_model, save_dir=output_dir)
            checkpointer.save("checkpoint")
            cfg.MODEL.WEIGHTS = f"{output_dir}/checkpoint.pth"
            config_fname = f"{output_dir}/config.yaml"
            with PathManager.open(config_fname, "w") as f:
                f.write(cfg.dump())

            # load model and compare to gt
            cfg.DISTILLATION.TEACHER.TYPE = "config"
            cfg.DISTILLATION.TEACHER.CONFIG_FNAME = config_fname
294
295
296
            model = _build_teacher(cfg)
            self.assertEqual(gt_model.weight, model.weight)

Matthew Yu's avatar
Matthew Yu committed
297
298
299
300
301
302
303
304
305
    def test_build_teacher_none(self):
        """Check that we can ignore building the teacher"""
        # build model
        cfg = _get_default_cfg()
        cfg.MODEL.META_ARCHITECTURE = "TestMetaArchAddRand"
        cfg.DISTILLATION.TEACHER.TYPE = "no_teacher"
        model = _build_teacher(cfg)
        self.assertTrue(isinstance(model, nn.Module))

306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    def test_override_teacher_config_gpu_on_cpu(self):
        """Teacher cuda model can be run on cpu if specified in config"""
        # build model where teacher is specified on gpu but user overrides cpu
        cfg = _get_default_cfg()
        cfg.MODEL.META_ARCHITECTURE = "TestMetaArchAddRand"
        gt_model = BaseRunner().build_model(cfg)
        with make_temp_directory("tmp") as output_dir:
            # save model
            checkpointer = DetectionCheckpointer(gt_model, save_dir=output_dir)
            checkpointer.save("checkpoint")
            cfg.MODEL.WEIGHTS = f"{output_dir}/checkpoint.pth"
            cfg.MODEL.DEVICE = "cuda"
            config_fname = f"{output_dir}/config.yaml"
            with PathManager.open(config_fname, "w") as f:
                f.write(cfg.dump())

            # load model and compare to gt
            cfg.DISTILLATION.TEACHER.TYPE = "config"
            cfg.DISTILLATION.TEACHER.CONFIG_FNAME = config_fname
            cfg.DISTILLATION.TEACHER.DEVICE = "cpu"
326
327
328
            model = _build_teacher(cfg)
            self.assertEqual(gt_model.weight, model.weight)

329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
    def test_set_device(self):
        """Check teacher device is set"""
        # without attr
        model = Noop()
        self.assertFalse(hasattr(model, "device"))
        device = torch.device("cpu")

        # without property
        model = _set_device(model, device)
        self.assertEqual(model.device, device)

        # with property
        model = AddOne()
        model = _set_device(model, device)
        self.assertEqual(model.device, device)

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
    def test_cached_layer_tensor(self):
        """Check cached layer saves layer output"""
        model = AddOne()
        cache = {}
        dynamic_mixin(
            model,
            CachedLayer,
            init_dict={"label": "test_layer", "cache": cache},
        )
        input = torch.randn(1)
        output = model(input)
        self.assertEqual(output, cache["test_layer"])

    def test_cached_layer_list(self):
        """Check cached layer saves list"""
        model = DivideInputBy2()
        cache = {}
        dynamic_mixin(
            model,
            CachedLayer,
            init_dict={"label": "test_layer", "cache": cache},
        )
        input = [torch.randn(1) for _ in range(2)]
        output = model(input)
        self.assertEqual(output, cache["test_layer"])

Matthew Yu's avatar
Matthew Yu committed
371
372
373
374
375
376
377
378
379
380
381
382
383
    def test_cached_layer_tuple(self):
        """Check cached layer saves list"""
        model = DivideInputBy2()
        cache = {}
        dynamic_mixin(
            model,
            CachedLayer,
            init_dict={"label": "test_layer", "cache": cache},
        )
        input = (torch.randn(1) for _ in range(2))
        output = model(input)
        self.assertEqual(output, cache["test_layer"])

384
385
386
387
388
389
390
391
392
393
394
395
396
    def test_cached_layer_dict(self):
        """Check cached layer saves dict"""
        model = DivideInputBy2OutputDict()
        cache = {}
        dynamic_mixin(
            model,
            CachedLayer,
            init_dict={"label": "test_layer", "cache": cache},
        )
        input = [torch.randn(1) for _ in range(2)]
        output = model(input)
        self.assertEqual(output, cache["test_layer"])

397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    def test_record_layers(self):
        """Check we can record specified layer"""
        model = AddLayers()
        cache = record_layers(model, ["", "layer0", "layer1", "layer2"])

        input = torch.Tensor([0])
        output = model(input)
        self.assertEqual(cache["layer0"], torch.Tensor([1]))
        self.assertEqual(cache["layer1"], torch.Tensor([2]))
        self.assertEqual(cache["layer2"], torch.Tensor([3]))
        self.assertEqual(cache[""], output)

    def test_unrecord_layers(self):
        """Check we can remove a recorded layer"""
        model = AddLayers()
        _ = record_layers(model, ["", "layer0", "layer1", "layer2"])
        unrecord_layers(model, ["", "layer0"])
        self.assertFalse(hasattr(model.layer0, "cache"))

416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
    def test_compute_layer_losses(self):
        """Check iterating over loss dicts"""
        layer_losses = [
            LayerLossMetadata(
                loss=lambda x, y: x + y, name="add", layer0="l00", layer1="l10"
            ),
            LayerLossMetadata(
                loss=lambda x, y: x / y, name="div", layer0="l01", layer1="l11"
            ),
        ]
        layer0_cache = {"l00": torch.randn(1), "l01": torch.randn(1)}
        layer1_cache = {"l10": torch.randn(1), "l11": torch.randn(1)}
        output = compute_layer_losses(layer_losses, layer0_cache, layer1_cache)
        self.assertEqual(output["add"], layer0_cache["l00"] + layer1_cache["l10"])
        self.assertEqual(output["div"], layer0_cache["l01"] / layer1_cache["l11"])

Matthew Yu's avatar
Matthew Yu committed
432
433
434
435
436
437
438
439
440
441
442
443
444
445
    def test_set_cache_dict(self):
        """Check we can swap the cache dict used when recording layers"""
        model = AddLayers()
        cache = record_layers(model, ["", "layer0", "layer1", "layer2"])
        new_cache = {}
        set_cache_dict(model, new_cache)
        input = torch.Tensor([0])
        output = model(input)
        self.assertEqual(cache, {})
        torch.testing.assert_close(new_cache["layer0"], torch.Tensor([1]))
        torch.testing.assert_close(new_cache["layer1"], torch.Tensor([2]))
        torch.testing.assert_close(new_cache["layer2"], torch.Tensor([3]))
        torch.testing.assert_close(new_cache[""], output)

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
    def test_register_layer_losses(self):
        """Check losses can be registered to model"""
        model = AddOne()
        ll = [
            LayerLossMetadata(
                loss=SimpleAdd(),
                name="mul",
                layer0="layer1",
                layer1="layer1",
            ),
        ]
        registered_losses = register_layer_losses_and_to_device(ll, model)
        self.assertTrue(hasattr(model, "mul"))
        self.assertEqual(model.mul, registered_losses[0].loss)

    @helper.skip_if_no_gpu
    def test_register_layer_losses_and_to_device(self):
        """Check losses can be registered to model"""
        model = AddOne()
        model = model.to("cuda")
        ll = [
            LayerLossMetadata(
                loss=AddOne(),
                name="mul",
                layer0="layer1",
                layer1="layer1",
            ),
        ]
        register_layer_losses_and_to_device(ll, model)
        self.assertEqual(model.mul.device, model.device)

Matthew Yu's avatar
Matthew Yu committed
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

class TestPseudoLabeler(unittest.TestCase):
    def test_noop(self):
        """Check noop"""
        pseudo_labeler = NoopPseudoLabeler()
        x = np.random.randn(1)
        output = pseudo_labeler.label(x)
        self.assertEqual(x, output)

    def test_relabeltargetinbatch(self):
        """Check target is relabed using teacher"""
        teacher = DivideInputDictBy2()
        teacher.eval()
        teacher.device = torch.device("cpu")
        relabeler = RelabelTargetInBatch(teacher=teacher)
        batched_inputs = _get_input_data(n=2, use_input_target=True)
        gt = [{"input": d["input"], "target": d["input"] / 2.0} for d in batched_inputs]
        outputs = relabeler.label(batched_inputs)
        self.assertEqual(outputs, gt)


class TestDistillationHelper(unittest.TestCase):
    def test_registry(self):
        """Check base class in registry"""
        self.assertTrue("BaseDistillationHelper" in DISTILLATION_HELPER_REGISTRY)

    def test_base_distillation_helper(self):
        """Check base distillation helper returns input as output"""
        dh = BaseDistillationHelper(cfg=None, teacher=None)
        pseudo_labeler = dh.get_pseudo_labeler()
        self.assertTrue(isinstance(pseudo_labeler, NoopPseudoLabeler))

Matthew Yu's avatar
Matthew Yu committed
509
510
    def test_example_distillation_helper(self):
        """Example distillation uses teacher to relabel targets"""
Matthew Yu's avatar
Matthew Yu committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
        teacher = Noop()
        dh = ExampleDistillationHelper(cfg=None, teacher=teacher)
        pseudo_labeler = dh.get_pseudo_labeler()
        self.assertTrue(isinstance(pseudo_labeler, RelabelTargetInBatch))
        self.assertTrue(isinstance(pseudo_labeler.teacher, Noop))


class TestDistillationAlgorithm(unittest.TestCase):
    class LabelDistillationNoop(LabelDistillation, Noop):
        """Distillation should be used with dynamic mixin so we create
        a new class with mixin of a noop to test"""

        pass

    def test_registry(self):
        """Check distillation teacher in registry"""
Matthew Yu's avatar
Matthew Yu committed
527
528
529
530
531
        for algorithm in [
            "LabelDistillation",
            "KnowledgeDistillation",
            "DomainAdaptation",
        ]:
Matthew Yu's avatar
Matthew Yu committed
532
            self.assertTrue(algorithm in DISTILLATION_ALGORITHM_REGISTRY)
Matthew Yu's avatar
Matthew Yu committed
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

    def test_label_distillation_inference(self):
        """Check inference defaults to student

        Use LabelDistillationNoop to set student model to noop
        """
        batched_inputs = _get_input_data(n=2)
        gt = batched_inputs.detach().clone()
        model = self.LabelDistillationNoop()
        model.dynamic_mixin_init(
            distillation_helper=TestHelper(cfg=None, teacher=DivideInputBy2()),
        )
        model.eval()
        output = model(batched_inputs)
        np.testing.assert_array_equal(output, gt)

    def test_label_distillation_training(self):
        """Check training uses pseudo labeler

        Distillation teacher should run the teacher model on the inputs and
        then pass to the noop
        """
        batched_inputs = _get_input_data(n=2, requires_grad=True)
        gt = [x / 2.0 for x in batched_inputs]
        model = self.LabelDistillationNoop()
        model.dynamic_mixin_init(
            distillation_helper=TestHelper(cfg=None, teacher=DivideInputBy2()),
        )
        model.train()
        output = model(batched_inputs)
        torch.testing.assert_close(output, gt)

        sum(output).backward()
        torch.testing.assert_close(batched_inputs.grad, torch.Tensor([0.5, 0.5]))

Matthew Yu's avatar
Matthew Yu committed
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
    def test_kd_inference(self):
        """Check inference defaults to student (and preprocessing)"""
        distillation_helper = TestHelper(cfg=CfgNode(), teacher=AddLayers())
        model = AddLayers()
        dynamic_mixin(
            model,
            KnowledgeDistillation,
            init_dict={"distillation_helper": distillation_helper},
        )
        model.eval()
        input = torch.randn(1)
        output = model(input)
        torch.testing.assert_close(output, input + 4.0)

    def test_kd_train(self):
        """Check train pass results in updated loss output"""
        distillation_helper = TestHelper(cfg=CfgNode(), teacher=AddLayers())
        model = AddLayers()
        dynamic_mixin(
            model,
            KnowledgeDistillation,
            init_dict={"distillation_helper": distillation_helper},
        )
        model.train()
        input = torch.randn(1)
        output = model(input)
        torch.testing.assert_close(output["output"], (input + 4.0) * 0.1)
        torch.testing.assert_close(output["add"], ((input + 2.0) + (input + 3.0)) * 0.5)
        torch.testing.assert_close(output["mul"], (input + 3.0) * (input + 4.0) * 10.0)

    def test_kd_remove_dynamic_mixin(self):
        """Check removing dynamic mixin removes cached layers"""
        distillation_helper = TestHelper(cfg=CfgNode(), teacher=AddLayers())
        model = AddLayers()
        dynamic_mixin(
            model,
            KnowledgeDistillation,
            init_dict={"distillation_helper": distillation_helper},
        )
        remove_dynamic_mixin(model)
        for module in model.modules():
            self.assertFalse(hasattr(module, "cache"))

Matthew Yu's avatar
Matthew Yu committed
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
    def test_da_inference(self):
        """Check inference defaults to student (and preprocessing)"""
        distillation_helper = TestDAHelper(cfg=CfgNode(), teacher=nn.Identity())
        model = AddLayers()
        dynamic_mixin(
            model,
            DomainAdaptation,
            init_dict={"distillation_helper": distillation_helper},
        )
        model.eval()
        input = {"real": torch.randn(1), "synthetic": torch.randn(1)}
        output = model(input)
        self.assertEqual(output, input["real"] + 3.0)

    def test_da_train(self):
        """Check train pass results in updated loss output"""
        distillation_helper = TestDAHelper(cfg=CfgNode(), teacher=nn.Identity())
        model = AddLayers()
        dynamic_mixin(
            model,
            DomainAdaptation,
            init_dict={"distillation_helper": distillation_helper},
        )
        model.train()
        input = {"real": torch.randn(1), "synthetic": torch.randn(1)}
        output = model(input)
        self.assertEqual(
            output,
            {
                "real": (input["real"] + 3.0) * 0.1,
                "synthetic": (input["synthetic"] + 3.0) * 0.5,
                "add": ((input["real"] + 1.0) + (input["synthetic"] + 1.0)) * 10.0,
            },
        )

    def test_da_remove_dynamic_mixin(self):
        """Check removing dynamic mixin removes cached layers"""
        distillation_helper = TestHelper(cfg=CfgNode(), teacher=nn.Identity())
        model = AddLayers()
        dynamic_mixin(
            model,
            DomainAdaptation,
            init_dict={"distillation_helper": distillation_helper},
        )
        remove_dynamic_mixin(model)
        for module in model.modules():
            self.assertFalse(hasattr(module, "cache"))

Matthew Yu's avatar
Matthew Yu committed
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726

class TestDistillationModelingHook(unittest.TestCase):
    _build_teacher_ref = "d2go.modeling.distillation._build_teacher"

    def test_exists(self):
        """Check that the hook is registered"""
        self.assertTrue("DistillationModelingHook" in mh.MODELING_HOOK_REGISTRY)

    def test_init(self):
        """Check that we can build hook"""
        cfg = _get_default_cfg()
        with mock.patch(self._build_teacher_ref):
            DistillationModelingHook(cfg)

    def test_apply(self):
        """Check new model has distillation methods"""
        model = Noop()
        model.test_attr = "12345"
        cfg = _get_default_cfg()
        cfg.DISTILLATION.HELPER = "TestHelper"
        with mock.patch(self._build_teacher_ref):
            hook = DistillationModelingHook(cfg)
        hook.apply(model)
        # set teacher manually to override _build_teacher
        model.pseudo_labeler.teacher = DivideInputBy2()

        # check distillation attrs
        self.assertTrue(isinstance(model.distillation_helper, TestHelper))
        self.assertEqual(model._original_model_class, Noop)

        # check retains attrs
        self.assertTrue(hasattr(model, "test_attr"))
        self.assertEqual(model.test_attr, "12345")

        # check inference uses the baseline model which is a noop
        batched_inputs = _get_input_data(n=2)
        model.eval()
        gt = batched_inputs.detach().clone()
        output = model(batched_inputs)
        torch.testing.assert_close(output, gt)

        # check training uses the pseudo labeler
        model.train()
        gt = [x / 2.0 for x in batched_inputs]
        output = model(batched_inputs)
        torch.testing.assert_close(output, gt)

    def test_unapply(self):
        """Check removing distillation"""
        model = Noop()
        cfg = _get_default_cfg()
        with mock.patch(self._build_teacher_ref):
            hook = DistillationModelingHook(cfg)
        hook.apply(model)
        hook.unapply(model)

        for distillation_attr in [
            "distillation_helper",
            "_original_model_class",
        ]:
            self.assertFalse(hasattr(model, distillation_attr))

        # check forward is the original noop
        batched_inputs = _get_input_data(n=2)
        gt = batched_inputs.detach().clone()
        model.train()
        output = model(batched_inputs)
        torch.testing.assert_close(output, gt)
727
728


729
class TestDistillationMiscTests(unittest.TestCase):
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    def test_teacher_outside_updated_parameters(self):
        """
        Check that teacher values are ignored when updating student

        The teacher can often be referenced in the mixed in model. A common
        example is when the teacher is an attributed of the distillation
        helper.
         => DistillationModel.distillation_helper.teacher

        This raises the question of whether the teacher model will be affected
        by calls to the mixed in model:
            DisillationModel.train() => does teacher switch to training?
            setup_qat(DistillationModel) => will fuse occur on the teacher modules?

        The answer to these questions should be no as we want the teacher to remain static
        during training (unless specified). This is the case as long as teacher is an
        attribute of a non-module class (e.g., distillation_helper). This is because
        modules are registered in PyTorch as part of __setattr__. __setattr__ only checks
        if the value is a module or parameter. If the value is an object
        (e.g., distillation_helper) which contains modules, these modules are ignored.
        https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module.register_parameter

        This unittest builds the teacher model and checks that only the student
        parameter is registered.
        """
        cfg = _get_default_cfg()
        cfg.MODEL.META_ARCHITECTURE = "TestMetaArchAddRand"
        prebuilt_teacher = BaseRunner().build_model(cfg)
        with make_temp_directory("tmp") as output_dir:
            checkpointer = DetectionCheckpointer(prebuilt_teacher, save_dir=output_dir)
            checkpointer.save("checkpoint")
            cfg.MODEL.WEIGHTS = f"{output_dir}/checkpoint.pth"
            config_fname = f"{output_dir}/config.yaml"
            with PathManager.open(config_fname, "w") as f:
                f.write(cfg.dump())
            cfg.DISTILLATION.TEACHER.TYPE = "config"
            cfg.DISTILLATION.TEACHER.CONFIG_FNAME = config_fname
            cfg.DISTILLATION.HELPER = "TestHelper"
            cfg.MODEL.MODELING_HOOKS = ["DistillationModelingHook"]
            distilled_model = BaseRunner().build_model(cfg)
            self.assertEqual(len(list(distilled_model.parameters())), 1)
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787


class TestDistillationDefaults(unittest.TestCase):
    def test_kd_image_classification_layer_losses(self):
        """Check the default returns a list of layerlossmetadata"""
        layer_losses = get_default_kd_image_classification_layer_losses()
        self.assertTrue(isinstance(layer_losses, List))
        self.assertTrue(isinstance(layer_losses[0], LayerLossMetadata))

    def test_default_loss_combiner(self):
        """Check combiner multiplies loss by weights"""
        weights = {"a": torch.randn(1), "b": torch.randn(1)}
        combiner = DefaultLossCombiner(weights)
        input = {"a": 1.0, "b": 10.0}
        output = combiner(input)
        torch.testing.assert_close(output["a"], input["a"] * weights["a"])
        torch.testing.assert_close(output["b"], input["b"] * weights["b"])