base.py 28 KB
Newer Older
mibaumgartner's avatar
mibaumgartner committed
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
"""
Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany

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.
"""

from __future__ import annotations

import os
import copy
from collections import defaultdict
from pathlib import Path
from functools import partial
from typing import Callable, Hashable, Sequence, Dict, Any, Type

import torch
import numpy as np
from loguru import logger
mibaumgartner's avatar
models  
mibaumgartner committed
29
from torchvision.models.detection.rpn import AnchorGenerator
mibaumgartner's avatar
mibaumgartner committed
30
31
32
33
34

from nndet.utils.tensor import to_numpy
from nndet.evaluator.det import BoxEvaluator
from nndet.evaluator.seg import SegmentationEvaluator

mibaumgartner's avatar
core  
mibaumgartner committed
35
36
37
38
39
from nndet.core.retina import BaseRetinaNet
from nndet.core.boxes.matcher import IoUMatcher
from nndet.core.boxes.sampler import HardNegativeSamplerBatched
from nndet.core.boxes.coder import CoderType, BoxCoderND
from nndet.core.boxes.anchors import get_anchor_generator
mibaumgartner's avatar
mibaumgartner committed
40
from nndet.core.boxes.ops import box_iou
mibaumgartner's avatar
mibaumgartner committed
41
from nndet.core.boxes.anchors import AnchorGeneratorType
mibaumgartner's avatar
mibaumgartner committed
42
43
44

from nndet.ptmodule.base_module import LightningBaseModuleSWA, LightningBaseModule

mibaumgartner's avatar
mibaumgartner committed
45
46
47
48
49
50
51
52
53
from nndet.arch.conv import Generator, ConvInstanceRelu, ConvGroupRelu
from nndet.arch.blocks.basic import StackedConvBlock2
from nndet.arch.encoder.abstract import EncoderType
from nndet.arch.encoder.modular import Encoder
from nndet.arch.decoder.base import DecoderType, BaseUFPN, UFPNModular
from nndet.arch.heads.classifier import ClassifierType, CEClassifier
from nndet.arch.heads.regressor import RegressorType, L1Regressor
from nndet.arch.heads.comb import HeadType, DetectionHeadHNM
from nndet.arch.heads.segmenter import SegmenterType, DiCESegmenter
mibaumgartner's avatar
mibaumgartner committed
54
55
56
57
58
59
60

from nndet.training.optimizer import get_params_no_wd_on_norm
from nndet.training.learning_rate import LinearWarmupPolyLR

from nndet.inference.predictor import Predictor
from nndet.inference.sweeper import BoxSweeper
from nndet.inference.transforms import get_tta_transforms, Inference2D
61
from nndet.inference.loading import get_loader_fn
mibaumgartner's avatar
mibaumgartner committed
62
63
from nndet.inference.helper import predict_dir
from nndet.inference.ensembler.segmentation import SegmentationEnsembler
mibaumgartner's avatar
mibaumgartner committed
64
from nndet.inference.ensembler.detection import BoxEnsemblerSelective
mibaumgartner's avatar
mibaumgartner committed
65

mibaumgartner's avatar
mibaumgartner committed
66
67
68
69
70
from nndet.io.transforms import (
    Compose,
    Instances2Boxes,
    Instances2Segmentation,
    FindInstances,
71
)
mibaumgartner's avatar
mibaumgartner committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86


class RetinaUNetModule(LightningBaseModuleSWA):
    base_conv_cls = ConvInstanceRelu
    head_conv_cls = ConvGroupRelu
    block = StackedConvBlock2
    encoder_cls = Encoder
    decoder_cls = UFPNModular
    matcher_cls = IoUMatcher
    head_cls = DetectionHeadHNM
    head_classifier_cls = CEClassifier
    head_regressor_cls = L1Regressor
    head_sampler_cls = HardNegativeSamplerBatched
    segmenter_cls = DiCESegmenter

87
    def __init__(self, model_cfg: dict, trainer_cfg: dict, plan: dict, **kwargs):
mibaumgartner's avatar
mibaumgartner committed
88
89
        """
        RetinaUNet Lightning Module Skeleton
90

mibaumgartner's avatar
mibaumgartner committed
91
92
93
94
95
96
97
98
99
100
101
102
103
        Args:
            model_cfg: model configuration. Check :method:`from_config_plan`
                for more information
            trainer_cfg: trainer information
            plan: contains parameters which were derived from the planning
                stage
        """
        super().__init__(
            model_cfg=model_cfg,
            trainer_cfg=trainer_cfg,
            plan=plan,
        )

104
105
106
        _classes = [
            f"class{c}" for c in range(plan["architecture"]["classifier_classes"])
        ]
mibaumgartner's avatar
mibaumgartner committed
107
108
109
110
        self.box_evaluator = BoxEvaluator.create(
            classes=_classes,
            fast=True,
            save_dir=None,
111
        )
mibaumgartner's avatar
mibaumgartner committed
112
113
114
115
116
117
        self.seg_evaluator = SegmentationEvaluator.create()

        self.pre_trafo = Compose(
            FindInstances(
                instance_key="target",
                save_key="present_instances",
118
            ),
mibaumgartner's avatar
mibaumgartner committed
119
120
121
122
123
124
            Instances2Boxes(
                instance_key="target",
                map_key="instance_mapping",
                box_key="boxes",
                class_key="classes",
                present_instances="present_instances",
125
            ),
mibaumgartner's avatar
mibaumgartner committed
126
127
128
129
            Instances2Segmentation(
                instance_key="target",
                map_key="instance_mapping",
                present_instances="present_instances",
130
131
            ),
        )
mibaumgartner's avatar
mibaumgartner committed
132
133

        self.eval_score_key = "mAP_IoU_0.10_0.50_0.05_MaxDet_100"
chenxi226's avatar
chenxi226 committed
134
135
        self.training_step_outputs = []
        self.validation_step_outputs = []
mibaumgartner's avatar
mibaumgartner committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149

    def training_step(self, batch, batch_idx):
        """
        Computes a single training step
        See :class:`BaseRetinaNet` for more information
        """
        with torch.no_grad():
            batch = self.pre_trafo(**batch)

        losses, _ = self.model.train_step(
            images=batch["data"],
            targets={
                "target_boxes": batch["boxes"],
                "target_classes": batch["classes"],
150
151
                "target_seg": batch["target"][:, 0],  # Remove channel dimension
            },
mibaumgartner's avatar
mibaumgartner committed
152
153
154
155
            evaluation=False,
            batch_num=batch_idx,
        )
        loss = sum(losses.values())
chenxi226's avatar
chenxi226 committed
156
        self.training_step_outputs.append(loss)
mibaumgartner's avatar
mibaumgartner committed
157
158
159
160
161
162
163
164
165
166
167
        return {"loss": loss, **{key: l.detach().item() for key, l in losses.items()}}

    def validation_step(self, batch, batch_idx):
        """
        Computes a single validation step (same as train step but with
        additional prediciton processing)
        See :class:`BaseRetinaNet` for more information
        """
        with torch.no_grad():
            batch = self.pre_trafo(**batch)
            targets = {
168
169
170
171
                "target_boxes": batch["boxes"],
                "target_classes": batch["classes"],
                "target_seg": batch["target"][:, 0],  # Remove channel dimension
            }
mibaumgartner's avatar
mibaumgartner committed
172
173
174
175
176
177
178
179
180
            losses, prediction = self.model.train_step(
                images=batch["data"],
                targets=targets,
                evaluation=True,
                batch_num=batch_idx,
            )
            loss = sum(losses.values())

        self.evaluation_step(prediction=prediction, targets=targets)
chenxi226's avatar
chenxi226 committed
181
        output = {
182
183
184
            "loss": loss.detach().item(),
            **{key: l.detach().item() for key, l in losses.items()},
        }
chenxi226's avatar
chenxi226 committed
185
186
        self.validation_step_outputs.append(output)
        return output
mibaumgartner's avatar
mibaumgartner committed
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

    def evaluation_step(
        self,
        prediction: dict,
        targets: dict,
    ):
        """
        Perform an evaluation step to add predictions and gt to
        caching mechanism which is evaluated at the end of the epoch

        Args:
            prediction: predictions obtained from model
                'pred_boxes': List[Tensor]: predicted bounding boxes for
                    each image List[[R, dim * 2]]
                'pred_scores': List[Tensor]: predicted probability for
                    the class List[[R]]
                'pred_labels': List[Tensor]: predicted class List[[R]]
                'pred_seg': Tensor: predicted segmentation [N, dims]
            targets: ground truth
                `target_boxes` (List[Tensor]): ground truth bounding boxes
                    (x1, y1, x2, y2, (z1, z2))[X, dim * 2], X= number of ground
                        truth boxes in image
                `target_classes` (List[Tensor]): ground truth class per box
                    (classes start from 0) [X], X= number of ground truth
                    boxes in image
                `target_seg` (Tensor): segmentation ground truth (if seg was
                    found in input dict)
        """
        pred_boxes = to_numpy(prediction["pred_boxes"])
        pred_classes = to_numpy(prediction["pred_labels"])
        pred_scores = to_numpy(prediction["pred_scores"])

        gt_boxes = to_numpy(targets["target_boxes"])
        gt_classes = to_numpy(targets["target_classes"])
        gt_ignore = None

        self.box_evaluator.run_online_evaluation(
            pred_boxes=pred_boxes,
            pred_classes=pred_classes,
            pred_scores=pred_scores,
            gt_boxes=gt_boxes,
            gt_classes=gt_classes,
            gt_ignore=gt_ignore,
230
        )
mibaumgartner's avatar
mibaumgartner committed
231
232
233
234
235
236
237

        pred_seg = to_numpy(prediction["pred_seg"])
        gt_seg = to_numpy(targets["target_seg"])

        self.seg_evaluator.run_online_evaluation(
            seg_probs=pred_seg,
            target=gt_seg,
238
        )
mibaumgartner's avatar
mibaumgartner committed
239

chenxi226's avatar
chenxi226 committed
240
    def on_train_epoch_end(self):
mibaumgartner's avatar
mibaumgartner committed
241
        """
chenxi226's avatar
chenxi226 committed
242
        Log train loss to loguru logger (PyTorch Lightning 2.x version)
mibaumgartner's avatar
mibaumgartner committed
243
        """
chenxi226's avatar
chenxi226 committed
244
245
246
247
248
249
250
251
252
253
        # 直接计算平均 loss(training_step_outputs 是 Tensor 列表)
        avg_loss = torch.stack(self.training_step_outputs).mean()
        
        logger.info(f"Train loss reached: {avg_loss.item():0.5f}")
        self.log(f"train_loss", avg_loss, sync_dist=True)
        
        # 清理内存
        self.training_step_outputs.clear()

    def on_validation_epoch_end(self):
mibaumgartner's avatar
mibaumgartner committed
254
        """
chenxi226's avatar
chenxi226 committed
255
        Log val loss to loguru logger (PyTorch Lightning 2.x version)
mibaumgartner's avatar
mibaumgartner committed
256
        """
chenxi226's avatar
chenxi226 committed
257
258
259
        # 从实例变量获取保存的输出
        validation_step_outputs = self.validation_step_outputs
        
mibaumgartner's avatar
mibaumgartner committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
        # process and log losses
        vals = defaultdict(list)
        for _val in validation_step_outputs:
            for _k, _v in _val.items():
                vals[_k].append(_v)

        for _key, _vals in vals.items():
            mean_val = np.mean(_vals)
            if _key == "loss":
                logger.info(f"Val loss reached: {mean_val:0.5f}")
            self.log(f"val_{_key}", mean_val, sync_dist=True)

        # process and log metrics
        self.evaluation_end()
chenxi226's avatar
chenxi226 committed
274
275
276
        
        # 清理内存(重要!)
        self.validation_step_outputs.clear()
mibaumgartner's avatar
mibaumgartner committed
277
278
279
280
281
282
283
284
285

    def evaluation_end(self):
        """
        Uses the cached values from `evaluation_step` to perform the evaluation
        of the epoch
        """
        metric_scores, _ = self.box_evaluator.finish_online_evaluation()
        self.box_evaluator.reset()

286
287
288
289
290
        logger.info(
            f"mAP@0.1:0.5:0.05: {metric_scores['mAP_IoU_0.10_0.50_0.05_MaxDet_100']:0.3f}  "
            f"AP@0.1: {metric_scores['AP_IoU_0.10_MaxDet_100']:0.3f}  "
            f"AP@0.5: {metric_scores['AP_IoU_0.50_MaxDet_100']:0.3f}"
        )
mibaumgartner's avatar
mibaumgartner committed
291
292
293
294
295
296
297
298

        seg_scores, _ = self.seg_evaluator.finish_online_evaluation()
        self.seg_evaluator.reset()
        metric_scores.update(seg_scores)

        logger.info(f"Proxy FG Dice: {seg_scores['seg_dice']:0.3f}")

        for key, item in metric_scores.items():
299
300
301
            self.log(
                f"{key}", item, on_step=None, on_epoch=True, prog_bar=False, logger=True
            )
mibaumgartner's avatar
mibaumgartner committed
302
303
304
305
306
307
308
309

    def configure_optimizers(self):
        """
        Configure optimizer and scheduler
        Base configuration is SGD with LinearWarmup and PolyLR learning rate
        schedule
        """
        # configure optimizer
310
311
312
313
314
315
316
317
318
        logger.info(
            f"Running: initial_lr {self.trainer_cfg['initial_lr']} "
            f"weight_decay {self.trainer_cfg['weight_decay']} "
            f"SGD with momentum {self.trainer_cfg['sgd_momentum']} and "
            f"nesterov {self.trainer_cfg['sgd_nesterov']}"
        )
        wd_groups = get_params_no_wd_on_norm(
            self, weight_decay=self.trainer_cfg["weight_decay"]
        )
mibaumgartner's avatar
mibaumgartner committed
319
320
321
322
323
324
        optimizer = torch.optim.SGD(
            wd_groups,
            self.trainer_cfg["initial_lr"],
            weight_decay=self.trainer_cfg["weight_decay"],
            momentum=self.trainer_cfg["sgd_momentum"],
            nesterov=self.trainer_cfg["sgd_nesterov"],
325
        )
mibaumgartner's avatar
mibaumgartner committed
326
327

        # configure lr scheduler
328
329
330
331
        num_iterations = (
            self.trainer_cfg["max_num_epochs"]
            * self.trainer_cfg["num_train_batches_per_epoch"]
        )
mibaumgartner's avatar
mibaumgartner committed
332
333
334
335
336
        scheduler = LinearWarmupPolyLR(
            optimizer=optimizer,
            warm_iterations=self.trainer_cfg["warm_iterations"],
            warm_lr=self.trainer_cfg["warm_lr"],
            poly_gamma=self.trainer_cfg["poly_gamma"],
337
            num_iterations=num_iterations,
mibaumgartner's avatar
mibaumgartner committed
338
        )
339
        return [optimizer], {"scheduler": scheduler, "interval": "step"}
mibaumgartner's avatar
mibaumgartner committed
340
341

    @classmethod
342
343
344
345
346
347
348
349
    def from_config_plan(
        cls,
        model_cfg: dict,
        plan_arch: dict,
        plan_anchors: dict,
        log_num_anchors: str = None,
        **kwargs,
    ):
mibaumgartner's avatar
mibaumgartner committed
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
        """
        Create Configurable RetinaUNet

        Args:
            model_cfg: model configurations
                See example configs for more info
            plan_arch: plan architecture
                `dim` (int): number of spatial dimensions
                `in_channels` (int): number of input channels
                `classifier_classes` (int): number of classes
                `seg_classes` (int): number of classes
                `start_channels` (int): number of start channels in encoder
                `fpn_channels` (int): number of channels to use for FPN
                `head_channels` (int): number of channels to use for head
                `decoder_levels` (int): decoder levels to user for detection
            plan_anchors: parameters for anchors (see
                :class:`AnchorGenerator` for more info)
                    `stride`: stride
                    `aspect_ratios`: aspect ratios
                    `sizes`: sized for 2d acnhors
                    (`zsizes`: additional z sizes for 3d)
            log_num_anchors: name of logger to use; if None, no logging
                will be performed
            **kwargs:
        """
375
376
377
378
379
380
381
        logger.info(
            f"Architecture overwrites: {model_cfg['plan_arch_overwrites']} "
            f"Anchor overwrites: {model_cfg['plan_anchors_overwrites']}"
        )
        logger.info(
            f"Building architecture according to plan of {plan_arch.get('arch_name', 'not_found')}"
        )
mibaumgartner's avatar
mibaumgartner committed
382
383
        plan_arch.update(model_cfg["plan_arch_overwrites"])
        plan_anchors.update(model_cfg["plan_anchors_overwrites"])
384
385
386
387
388
        logger.info(
            f"Start channels: {plan_arch['start_channels']}; "
            f"head channels: {plan_arch['head_channels']}; "
            f"fpn channels: {plan_arch['fpn_channels']}"
        )
mibaumgartner's avatar
mibaumgartner committed
389
390

        _plan_anchors = copy.deepcopy(plan_anchors)
391
392
393
394
395
396
397
398
399
400
        coder = BoxCoderND(weights=(1.0,) * (plan_arch["dim"] * 2))
        s_param = (
            False
            if ("aspect_ratios" in _plan_anchors)
            and (_plan_anchors["aspect_ratios"] is not None)
            else True
        )
        anchor_generator = get_anchor_generator(plan_arch["dim"], s_param=s_param)(
            **_plan_anchors
        )
mibaumgartner's avatar
mibaumgartner committed
401
402
403
404

        encoder = cls._build_encoder(
            plan_arch=plan_arch,
            model_cfg=model_cfg,
405
        )
mibaumgartner's avatar
mibaumgartner committed
406
407
408
409
        decoder = cls._build_decoder(
            encoder=encoder,
            plan_arch=plan_arch,
            model_cfg=model_cfg,
410
        )
mibaumgartner's avatar
mibaumgartner committed
411
412
413
        matcher = cls.matcher_cls(
            similarity_fn=box_iou,
            **model_cfg["matcher_kwargs"],
414
        )
mibaumgartner's avatar
mibaumgartner committed
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430

        classifier = cls._build_head_classifier(
            plan_arch=plan_arch,
            model_cfg=model_cfg,
            anchor_generator=anchor_generator,
        )
        regressor = cls._build_head_regressor(
            plan_arch=plan_arch,
            model_cfg=model_cfg,
            anchor_generator=anchor_generator,
        )
        head = cls._build_head(
            plan_arch=plan_arch,
            model_cfg=model_cfg,
            classifier=classifier,
            regressor=regressor,
431
            coder=coder,
mibaumgartner's avatar
mibaumgartner committed
432
433
434
435
436
437
438
439
440
441
442
443
444
        )
        segmenter = cls._build_segmenter(
            plan_arch=plan_arch,
            model_cfg=model_cfg,
            decoder=decoder,
        )

        detections_per_img = plan_arch.get("detections_per_img", 100)
        score_thresh = plan_arch.get("score_thresh", 0)
        topk_candidates = plan_arch.get("topk_candidates", 10000)
        remove_small_boxes = plan_arch.get("remove_small_boxes", 0.01)
        nms_thresh = plan_arch.get("nms_thresh", 0.6)

445
446
447
448
449
450
451
        # logger.info(f"Model Inference Summary: \n"
        #            f"detections_per_img: {detections_per_img} \n"
        #            f"score_thresh: {score_thresh} \n"
        #           f"topk_candidates: {topk_candidates} \n"
        #           f"remove_small_boxes: {remove_small_boxes} \n"
        #            f"nms_thresh: {nms_thresh}",
        #            )
mibaumgartner's avatar
mibaumgartner committed
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

        return BaseRetinaNet(
            dim=plan_arch["dim"],
            encoder=encoder,
            decoder=decoder,
            head=head,
            anchor_generator=anchor_generator,
            matcher=matcher,
            num_classes=plan_arch["classifier_classes"],
            decoder_levels=plan_arch["decoder_levels"],
            segmenter=segmenter,
            # model_max_instances_per_batch_element (in mdt per img, per class; here: per img)
            detections_per_img=detections_per_img,
            score_thresh=score_thresh,
            topk_candidates=topk_candidates,
            remove_small_boxes=remove_small_boxes,
            nms_thresh=nms_thresh,
        )

    @classmethod
    def _build_encoder(
        cls,
        plan_arch: dict,
        model_cfg: dict,
    ) -> EncoderType:
        """
        Build encoder network

        Args:
            plan_arch: architecture settings
            model_cfg: additional architecture settings

        Returns:
            EncoderType: encoder instance
        """
        conv = Generator(cls.base_conv_cls, plan_arch["dim"])
488
489
490
        logger.info(
            f"Building:: encoder {cls.encoder_cls.__name__}: {model_cfg['encoder_kwargs']} "
        )
mibaumgartner's avatar
mibaumgartner committed
491
492
493
494
495
496
497
498
499
        encoder = cls.encoder_cls(
            conv=conv,
            conv_kernels=plan_arch["conv_kernels"],
            strides=plan_arch["strides"],
            block_cls=cls.block,
            in_channels=plan_arch["in_channels"],
            start_channels=plan_arch["start_channels"],
            stage_kwargs=None,
            max_channels=plan_arch.get("max_channels", 320),
500
            **model_cfg["encoder_kwargs"],
mibaumgartner's avatar
mibaumgartner committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
        )
        return encoder

    @classmethod
    def _build_decoder(
        cls,
        plan_arch: dict,
        model_cfg: dict,
        encoder: EncoderType,
    ) -> DecoderType:
        """
        Build decoder network

        Args:
            plan_arch: architecture settings
            model_cfg: additional architecture settings

        Returns:
            DecoderType: decoder instance
        """
        conv = Generator(cls.base_conv_cls, plan_arch["dim"])
522
523
524
        logger.info(
            f"Building:: decoder {cls.decoder_cls.__name__}: {model_cfg['decoder_kwargs']}"
        )
mibaumgartner's avatar
mibaumgartner committed
525
526
527
528
529
530
531
        decoder = cls.decoder_cls(
            conv=conv,
            conv_kernels=plan_arch["conv_kernels"],
            strides=encoder.get_strides(),
            in_channels=encoder.get_channels(),
            decoder_levels=plan_arch["decoder_levels"],
            fixed_out_channels=plan_arch["fpn_channels"],
532
            **model_cfg["decoder_kwargs"],
mibaumgartner's avatar
mibaumgartner committed
533
534
535
536
537
538
539
540
        )
        return decoder

    @classmethod
    def _build_head_classifier(
        cls,
        plan_arch: dict,
        model_cfg: dict,
mibaumgartner's avatar
mibaumgartner committed
541
        anchor_generator: AnchorGeneratorType,
mibaumgartner's avatar
mibaumgartner committed
542
543
544
545
546
547
548
549
550
551
552
553
554
555
    ) -> ClassifierType:
        """
        Build classification subnetwork for detection head

        Args:
            anchor_generator: anchor generator instance
            plan_arch: architecture settings
            model_cfg: additional architecture settings

        Returns:
            ClassifierType: classification instance
        """
        conv = Generator(cls.head_conv_cls, plan_arch["dim"])
        name = cls.head_classifier_cls.__name__
556
        kwargs = model_cfg["head_classifier_kwargs"]
mibaumgartner's avatar
mibaumgartner committed
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574

        logger.info(f"Building:: classifier {name}: {kwargs}")
        classifier = cls.head_classifier_cls(
            conv=conv,
            in_channels=plan_arch["fpn_channels"],
            internal_channels=plan_arch["head_channels"],
            num_classes=plan_arch["classifier_classes"],
            anchors_per_pos=anchor_generator.num_anchors_per_location()[0],
            num_levels=len(plan_arch["decoder_levels"]),
            **kwargs,
        )
        return classifier

    @classmethod
    def _build_head_regressor(
        cls,
        plan_arch: dict,
        model_cfg: dict,
mibaumgartner's avatar
mibaumgartner committed
575
        anchor_generator: AnchorGeneratorType,
mibaumgartner's avatar
mibaumgartner committed
576
577
578
579
580
581
582
583
584
585
586
587
588
589
    ) -> RegressorType:
        """
        Build regression subnetwork for detection head

        Args:
            plan_arch: architecture settings
            model_cfg: additional architecture settings
            anchor_generator: anchor generator instance

        Returns:
            RegressorType: classification instance
        """
        conv = Generator(cls.head_conv_cls, plan_arch["dim"])
        name = cls.head_regressor_cls.__name__
590
        kwargs = model_cfg["head_regressor_kwargs"]
mibaumgartner's avatar
mibaumgartner committed
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
619
620
621
622
623
624
625

        logger.info(f"Building:: regressor {name}: {kwargs}")
        regressor = cls.head_regressor_cls(
            conv=conv,
            in_channels=plan_arch["fpn_channels"],
            internal_channels=plan_arch["head_channels"],
            anchors_per_pos=anchor_generator.num_anchors_per_location()[0],
            num_levels=len(plan_arch["decoder_levels"]),
            **kwargs,
        )
        return regressor

    @classmethod
    def _build_head(
        cls,
        plan_arch: dict,
        model_cfg: dict,
        classifier: ClassifierType,
        regressor: RegressorType,
        coder: CoderType,
    ) -> HeadType:
        """
        Build detection head

        Args:
            plan_arch: architecture settings
            model_cfg: additional architecture settings
            classifier: classifier instance
            regressor: regressor instance
            coder: coder instance to encode boxes

        Returns:
            HeadType: instantiated head
        """
        head_name = cls.head_cls.__name__
626
        head_kwargs = model_cfg["head_kwargs"]
mibaumgartner's avatar
mibaumgartner committed
627
        sampler_name = cls.head_sampler_cls.__name__
628
        sampler_kwargs = model_cfg["head_sampler_kwargs"]
mibaumgartner's avatar
mibaumgartner committed
629

630
631
632
633
        logger.info(
            f"Building:: head {head_name}: {head_kwargs} "
            f"sampler {sampler_name}: {sampler_kwargs}"
        )
mibaumgartner's avatar
mibaumgartner committed
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
659
660
661
662
663
664
        sampler = cls.head_sampler_cls(**sampler_kwargs)
        head = cls.head_cls(
            classifier=classifier,
            regressor=regressor,
            coder=coder,
            sampler=sampler,
            log_num_anchors=None,
            **head_kwargs,
        )
        return head

    @classmethod
    def _build_segmenter(
        cls,
        plan_arch: dict,
        model_cfg: dict,
        decoder: DecoderType,
    ) -> SegmenterType:
        """
        Build segmenter head

        Args:
            plan_arch: architecture settings
            model_cfg: additional architecture settings
            decoder: decoder instance

        Returns:
            SegmenterType: segmenter head
        """
        if cls.segmenter_cls is not None:
            name = cls.segmenter_cls.__name__
665
            kwargs = model_cfg["segmenter_kwargs"]
mibaumgartner's avatar
mibaumgartner committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
            conv = Generator(cls.base_conv_cls, plan_arch["dim"])

            logger.info(f"Building:: segmenter {name} {kwargs}")
            segmenter = cls.segmenter_cls(
                conv,
                seg_classes=plan_arch["seg_classes"],
                in_channels=decoder.get_channels(),
                decoder_levels=plan_arch["decoder_levels"],
                **kwargs,
            )
        else:
            segmenter = None
        return segmenter

    @staticmethod
    def get_ensembler_cls(key: Hashable, dim: int) -> Callable:
        """
        Get ensembler classes to combine multiple predictions
        Needs to be overwritten in subclasses!
        """
        _lookup = {
            2: {
mibaumgartner's avatar
mibaumgartner committed
688
689
                "boxes": None,
                "seg": None,
mibaumgartner's avatar
mibaumgartner committed
690
691
692
693
            },
            3: {
                "boxes": BoxEnsemblerSelective,
                "seg": SegmentationEnsembler,
694
695
            },
        }
mibaumgartner's avatar
mibaumgartner committed
696
697
        if dim == 2:
            raise NotImplementedError
mibaumgartner's avatar
mibaumgartner committed
698
699
700
        return _lookup[dim][key]

    @classmethod
701
702
703
704
705
706
707
708
    def get_predictor(
        cls,
        plan: Dict,
        models: Sequence[RetinaUNetModule],
        num_tta_transforms: int = None,
        do_seg: bool = False,
        **kwargs,
    ) -> Predictor:
mibaumgartner's avatar
mibaumgartner committed
709
710
711
712
713
714
715
716
717
        # process plan
        crop_size = plan["patch_size"]
        batch_size = plan["batch_size"]
        inferene_plan = plan.get("inference_plan", {})
        logger.info(f"Found inference plan: {inferene_plan} for prediction")
        if num_tta_transforms is None:
            num_tta_transforms = 8 if plan["network_dim"] == 3 else 4

        # setup
718
719
720
721
722
723
724
725
726
727
728
729
730
        tta_transforms, tta_inverse_transforms = get_tta_transforms(
            num_tta_transforms, True
        )
        logger.info(
            f"Using {len(tta_transforms)} tta transformations for prediction (one dummy trafo)."
        )

        ensembler = {
            "boxes": partial(
                cls.get_ensembler_cls(key="boxes", dim=plan["network_dim"]).from_case,
                parameters=inferene_plan,
            )
        }
mibaumgartner's avatar
mibaumgartner committed
731
732
733
734
735
736
737
738
739
740
741
742
743
        if do_seg:
            ensembler["seg"] = partial(
                cls.get_ensembler_cls(key="seg", dim=plan["network_dim"]).from_case,
            )

        predictor = Predictor(
            ensembler=ensembler,
            models=models,
            crop_size=crop_size,
            tta_transforms=tta_transforms,
            tta_inverse_transforms=tta_inverse_transforms,
            batch_size=batch_size,
            **kwargs,
744
        )
mibaumgartner's avatar
mibaumgartner committed
745
        if plan["network_dim"] == 2:
mibaumgartner's avatar
mibaumgartner committed
746
            raise NotImplementedError
mibaumgartner's avatar
mibaumgartner committed
747
748
749
            predictor.pre_transform = Inference2D(["data"])
        return predictor

750
751
752
753
754
755
756
757
758
    def sweep(
        self,
        cfg: dict,
        save_dir: os.PathLike,
        train_data_dir: os.PathLike,
        case_ids: Sequence[str],
        run_prediction: bool = True,
        **kwargs,
    ) -> Dict[str, Any]:
mibaumgartner's avatar
mibaumgartner committed
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
        """
        Sweep detection parameters to find the best predictions

        Args:
            cfg: config used for training
            save_dir: save dir used for training
            train_data_dir: directory where preprocessed training/validation
                data is located
            case_ids: case identifies to prepare and predict
            run_prediction: predict cases
            **kwargs: keyword arguments passed to predict function

        Returns:
            Dict: inference plan
                e.g. (exact params depend on ensembler class usef for prediction)
                `iou_thresh` (float): best IoU threshold
                `score_thresh (float)`: best score threshold
                `no_overlap` (bool): enable/disable class independent NMS (ciNMS)
        """
        logger.info(f"Running parameter sweep on {case_ids}")

        train_data_dir = Path(train_data_dir)
        preprocessed_dir = train_data_dir.parent
        processed_eval_labels = preprocessed_dir / "labelsTr"

        _save_dir = save_dir / "sweep"
        _save_dir.mkdir(parents=True, exist_ok=True)

        prediction_dir = save_dir / "sweep_predictions"
        prediction_dir.mkdir(parents=True, exist_ok=True)

        if run_prediction:
            logger.info("Predict cases with default settings...")
            predictor = predict_dir(
                source_dir=train_data_dir,
                target_dir=prediction_dir,
                cfg=cfg,
                plan=self.plan,
                source_models=save_dir,
                num_models=1,
                num_tta_transforms=None,
                case_ids=case_ids,
                save_state=True,
802
                model_fn=get_loader_fn(mode=self.trainer_cfg.get("sweep_ckpt", "last")),
mibaumgartner's avatar
mibaumgartner committed
803
                **kwargs,
804
            )
mibaumgartner's avatar
mibaumgartner committed
805
806

        logger.info("Start parameter sweep...")
807
808
809
        ensembler_cls = self.get_ensembler_cls(
            key="boxes", dim=self.plan["network_dim"]
        )
mibaumgartner's avatar
mibaumgartner committed
810
811
812
813
814
815
816
        sweeper = BoxSweeper(
            classes=[item for _, item in cfg["data"]["labels"].items()],
            pred_dir=prediction_dir,
            gt_dir=processed_eval_labels,
            target_metric=self.eval_score_key,
            ensembler_cls=ensembler_cls,
            save_dir=_save_dir,
817
        )
mibaumgartner's avatar
mibaumgartner committed
818
819
        inference_plan = sweeper.run_postprocessing_sweep()
        return inference_plan