segmenter.py 19.4 KB
Newer Older
mibaumgartner's avatar
models  
mibaumgartner committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
"""
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.
"""

import torch
import torch.nn as nn

from torch import Tensor
from typing import Dict, List, Union, Sequence, Optional, Tuple, TypeVar

mibaumgartner's avatar
mibaumgartner committed
23
24
25
from nndet.arch.conv import compute_padding_for_kernel, conv_kwargs_helper
from nndet.arch.heads.comb import AbstractHead
from nndet.arch.layers.interpolation import InterpolateToShapes
mibaumgartner's avatar
models  
mibaumgartner committed
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
from nndet.losses.segmentation import SoftDiceLoss, TopKLoss


class Segmenter(AbstractHead):
    def __init__(self,
                 seg_classes: int,
                 in_channels: Sequence[int],
                 decoder_levels: Sequence[int],
                 **kwargs,
                 ):
        """
        Abstract interface for segmentation head

        Args:
            seg_classes: number of foreground classes
                (!! internally +1 added for background)!!)
            in_channels: number of input channels at all decoder levels
            decoder_levels: decoder levels used for detection
        """
        super().__init__()
        self.seg_classes = seg_classes + 1
        self.in_channels = in_channels
        self.decoder_levels = decoder_levels


class DiCESegmenter(Segmenter):
    def __init__(self,
                 conv,
                 seg_classes: int,
                 in_channels: Sequence[int],
                 decoder_levels: Sequence[int],
                 internal_channels: Optional[int] = None,
                 num_internal: int = 0,
                 add_norm: bool = True,
                 add_act: bool= True,
                 kernel_size: Union[int, Sequence[int]] = 3,
                 alpha: float = 0.5,
                 ce_kwargs: Optional[dict] = None,
                 dice_kwargs: Optional[dict] = None,
                 **kwargs,
                 ):
        """
        Basic Segmentation Head with dice and CE loss
        (num_internal x conv [kernel_size]) -> final conv [1x1]

        Args:
            conv: Convolution modules which handles a single layer
            seg_classes: number of foreground classes
                (!! internally +1 added for background)!!)
            in_channels: number of input channels at all decoder levels
            decoder_levels: decoder levels used for detection
            internal_channels: number of channels of internal convolutions
            num_internal: number of internal convolutions
            add_norm: add normalization layers to internal convolutions
            add_act: add activation layers to internal convolutions
            kernel_size: kernel size of conv
            alpha: weight dice and ce loss (alpha * ce + (1-alpha) * soft_dice)
            ce_kwargs: keyword arguments passed to CE loss
            dice_kwargs: keyword arguments passed to dice loss
        """
        super().__init__(
            seg_classes=seg_classes,
            in_channels=in_channels,
            decoder_levels=decoder_levels,
            )
        self.num_internal = num_internal
        
        if internal_channels is None:
            self.internal_channels = self.in_channels[0]
        else:
            self.internal_channels = internal_channels

        self.conv_out = self.build_conv_out(conv)
        self.conv_intermediate = self.build_conv_internal(
            conv,
            kernel_size=kernel_size,
            add_norm=add_norm,
            add_act=add_act,
            **kwargs,
        )

        if dice_kwargs is None:
            dice_kwargs = {}
        dice_kwargs.setdefault("smooth_nom", 1e-5)
        dice_kwargs.setdefault("smooth_denom", 1e-5)
        dice_kwargs.setdefault("do_bg", False)
        self.dice_loss = SoftDiceLoss(nonlin=torch.nn.Softmax(dim=1), **dice_kwargs)

        if ce_kwargs is None:
            ce_kwargs = {}
        self.ce_loss = torch.nn.CrossEntropyLoss(**ce_kwargs)

        self.logits_convert_fn = nn.Softmax(dim=1)
        self.alpha = alpha

    def build_conv_out(self, conv) -> nn.Module:
        """
        Build output convolution
        """
        _intermediate_channels = self.internal_channels if self.num_internal > 0 else self.in_channels[0]
        return conv(
            _intermediate_channels,
            self.seg_classes,
            kernel_size=1,
            padding=0,
            add_norm=None,
            add_act=None,
            bias=True,
            )

    def build_conv_internal(self,
                            conv,
                            kernel_size: Union[int, Tuple[int]],
                            add_norm: bool,
                            add_act: bool,
                            **kwargs,
                            ) -> Optional[nn.Module]:
        """
        Buld internal convolutions
        """
        padding = compute_padding_for_kernel(kernel_size)
        if self.num_internal > 0:
            _intermediate = torch.nn.Sequential()
            for i in range(self.num_internal):
                _intermediate.add_module(
                    f"c_intermediate{i}",
                    conv(
                        self.in_channels if i == 0 else self.internal_channels,
                        self.internal_channels,
                        kernel_size=kernel_size,
                        padding=padding,
                        stride=1,
                        add_norm=add_norm,
                        add_act=add_act,
                        **kwargs
                        )
                    )
        else:
            _intermediate = None
        return _intermediate

    def forward(self,
                x: List[torch.Tensor],
                ) -> Dict[str, torch.Tensor]:
        """
        Forward pass

        Args:
            x: all features produced by decoder. Largest to smallest.

        Returns:
            torch.Tensor: result
        """
        x = x[0]
        if self.conv_intermediate is not None:
            x = self.conv_intermediate(x)
        return {"seg_logits": self.conv_out(x)}

    def compute_loss(self,
                     pred_seg: Dict[str, torch.Tensor],
                     target: torch.Tensor,
                     ) -> Dict[str, torch.Tensor]:
        """
        Compute weighted dice and cross entropy loss

        Args:
            pred_seg: segmentation predictions
                `seg_logits`: predicted logits
            target: ground truth segmentation of top layer

        Returns:
            Dict[str, torch.Tensor]: computed loss (contained in key seg)
        """
        seg_logits = pred_seg["seg_logits"]
        return {
            "seg_ce": self.alpha * self.ce_loss(seg_logits, target.long()),
            "seg_dice": (1 - self.alpha) * self.dice_loss(seg_logits, target),
            }

    def postprocess_for_inference(self,
                                  prediction: Dict[str, torch.Tensor],
                                  *args, **kwargs,
                                  ) -> Dict[str, torch.Tensor]:
        """
        Postprocess predictions for inference e.g. convert logits to probs

        Args:
            Dict[str, torch.Tensor]: predictions from this head
                `seg_logits`: predicted logits

        Returns:
            Dict[str, torch.Tensor]: postprocessed predictions
                `pred_seg`: predicted probabilities [N, C, dims]
        """
        return {"pred_seg": self.logits_convert_fn(prediction["seg_logits"])}


class DiCESegmenterFgBg(DiCESegmenter):
    def __init__(self,
                 conv,
                 seg_classes: int,
                 in_channels: Sequence[int],
                 decoder_levels: Sequence[int],
                 internal_channels: Optional[int] = None,
                 num_internal: int = 0,
                 add_norm: bool = True,
                 add_act: bool= True,
                 kernel_size: Union[int, Sequence[int]] = 3,
                 alpha: float = 0.5,
                 **kwargs,
                 ):
        """
        Basic Segmentation Head with dice and CE loss which only
        differentiates foreground and background
        (num_internal x conv [kernel_size]) -> final conv [1x1]

        Args:
            conv: Convolution modules which handles a single layer
            seg_classes: ignored!
            in_channels: number of input channels at all decoder levels
            decoder_levels: decoder levels used for detection
            internal_channels: number of channels of internal convolutions
            num_internal: number of internal convolutions
            add_norm: add normalization layers to internal convolutions
            add_act: add activation layers to internal convolutions
            kernel_size: kernel size of conv
            alpha: weight dice and ce loss (alpha * ce + (1-alpha) * soft_dice)
            ce_kwargs: keyword arguments passed to CE loss
            dice_kwargs: keyword arguments passed to dice loss

        Warnings:
            If this class is used, the reportet dice scores during training
            are wrong if multiple classes are present in the dataset. 
        """
        super().__init__(conv=conv,
                         in_channels=in_channels,
                         seg_classes=1,
                         decoder_levels=decoder_levels,
                         internal_channels=internal_channels,
                         num_internal=num_internal,
                         add_norm=add_norm,
                         add_act=add_act,
                         kernel_size=kernel_size,
                         alpha=alpha,
                         **kwargs,
                         )

    def compute_loss(self,
                     pred_seg: Dict[str, torch.Tensor],
                     target: torch.Tensor,
                     ) -> Dict[str, torch.Tensor]:
        """
        Compute weighted dice and cross entropy loss

        Args:
            pred_seg: segmentation predictions
                `seg_logits`: predicted logits
            target: ground truth segmentation of top layer

        Returns:
            Dict[str, torch.Tensor]: computed loss (contained in key seg)
        """
        target[target > 0] = 1
        return super().compute_loss(pred_seg, target)


class DiceTopKSegmenter(DiCESegmenter):
    def __init__(self,
                 conv,
                 seg_classes: int,
                 in_channels: Sequence[int],
                 decoder_levels: Sequence[int],
                 internal_channels: Optional[int] = None,
                 num_internal: int = 0,
                 add_norm: bool = True,
                 add_act: bool= True,
                 kernel_size: Union[int, Sequence[int]] = 3,
                 alpha: float = 0.5,
                 topk: float = 0.1,
                 **kwargs,
                 ):
        """
        Basic Segmentation Head with dice and TopK loss
        (num_internal x conv [kernel_size]) -> final conv [1x1]

        Args:
            conv: Convolution modules which handles a single layer
            seg_classes: number of foreground classes
                (!! internally +1 added for background)!!)
            in_channels: number of input channels at all decoder levels
            decoder_levels: decoder levels used for detection
            internal_channels: number of channels of internal convolutions
            num_internal: number of internal convolutions
            add_norm: add normalization layers to internal convolutions
            add_act: add activation layers to internal convolutions
            kernel_size: kernel size of conv
            alpha: weight dice and ce loss (alpha * ce + (1-alpha) * soft_dice)
            ce_kwargs: keyword arguments passed to CE loss
            topk: percentage of all entries to use for loss computation
        """
        super().__init__(conv=conv,
                    in_channels=in_channels,
                    seg_classes=seg_classes,
                    decoder_levels=decoder_levels,
                    internal_channels=internal_channels,
                    num_internal=num_internal,
                    add_norm=add_norm,
                    add_act=add_act,
                    kernel_size=kernel_size,
                    alpha=alpha,
                    ce_kwargs=None,
                    **kwargs,
                    )
        self.ce_loss = TopKLoss(
            topk=topk
        )


class DiceTopKSegmenterFgBg(DiCESegmenterFgBg):
    def __init__(self,
                 conv,
                 seg_classes: int,
                 in_channels: Sequence[int],
                 decoder_levels: Sequence[int],
                 internal_channels: Optional[int] = None,
                 num_internal: int = 0,
                 add_norm: bool = True,
                 add_act: bool= True,
                 kernel_size: Union[int, Sequence[int]] = 3,
                 alpha: float = 0.5,
                 topk: float = 0.1,
                 **kwargs,
                 ):
        """
        Basic Segmentation Head with dice and CE loss which only
        differentiates foreground and background
        (num_internal x conv [kernel_size]) -> final conv [1x1]

        Args:
            conv: Convolution modules which handles a single layer
            seg_classes: ignored!
            in_channels: number of input channels at all decoder levels
            decoder_levels: decoder levels used for detection
            internal_channels: number of channels of internal convolutions
            num_internal: number of internal convolutions
            add_norm: add normalization layers to internal convolutions
            add_act: add activation layers to internal convolutions
            kernel_size: kernel size of conv
            alpha: weight dice and ce loss (alpha * ce + (1-alpha) * soft_dice)
            ce_kwargs: keyword arguments passed to CE loss
            topk: percentage of all entries to use for loss computation

        Warnings:
            If this class is used, the reportet dice scores during training
            are wrong if multiple classes are present in the dataset. 
        """
        super().__init__(conv=conv,
                         in_channels=in_channels,
                         seg_classes=seg_classes,
                         decoder_levels=decoder_levels,
                         internal_channels=internal_channels,
                         num_internal=num_internal,
                         add_norm=add_norm,
                         add_act=add_act,
                         kernel_size=kernel_size,
                         alpha=alpha,
                         **kwargs,
                         )
        self.ce_loss = TopKLoss(
            topk=topk
        )


class DeepSupervisionSegmenterFGBG(DiCESegmenterFgBg):
    def __init__(self,
                 conv,
                 seg_classes: int,
                 in_channels: Sequence[int],
                 decoder_levels: Sequence[int],
                 internal_channels: Optional[int] = None,
                 num_internal: int = 0,
                 add_norm: bool = True,
                 add_act: bool= True,
                 kernel_size: Union[int, Sequence[int]] = 3,
                 alpha: float = 0.5,
                 dsv_weight: float = 1.,
                 **kwargs,
                 ):
        """
        Deep supervision segmenation which trains with CE and Dice
        to differentitate foreground and background
        (num_internal x conv [kernel_size]) -> final conv [1x1]

        Args:
            conv: Convolution modules which handles a single layer
            seg_classes: ignored!
                (!! internally +1 added for background)!!)
            in_channels: number of input channels at all decoder levels
            decoder_levels: decoder levels used for detection
            internal_channels: number of channels of internal convolutions
            num_internal: number of internal convolutions
            add_norm: add normalization layers to internal convolutions
            add_act: add activation layers to internal convolutions
            kernel_size: kernel size of conv
            alpha: weight dice and ce loss (alpha * ce + (1-alpha) * soft_dice)
            ce_kwargs: keyword arguments passed to CE loss
            dice_kwargs: keyword arguments passed to dice loss
            dsv_weight: additional weight for dsv losses
        """
        super().__init__(conv=conv,
                    in_channels=in_channels,
                    seg_classes=1,
                    decoder_levels=decoder_levels,
                    internal_channels=internal_channels,
                    num_internal=num_internal,
                    add_norm=add_norm,
                    add_act=add_act,
                    kernel_size=kernel_size,
                    alpha=alpha,
                    **kwargs,
                    )

        assert len(self.decoder_levels) > 0
        self.dsv_conv = conv(self.in_channels[-1],
                             2,
                             kernel_size=3,
                             padding=1,
                             add_norm=False,
                             add_act=False,
                             bias=True,
                             )
        self.interpolator = InterpolateToShapes()
        self.dsv_weight = dsv_weight

    def forward(self,
                x: List[torch.Tensor],
                ) -> Dict[str, torch.Tensor]:
        """
        Forward pass

        Args:
            x: all features produced by decoder. Largest to smallest.

        Returns:
            torch.Tensor: result
        """
        predictions = {}
        if self.intermediate is not None:
            predictions["seg_logits"] = self.conv_out(self.conv_intermediate(x[0]))
        else:
            predictions["seg_logits"] = self.conv_out(x[0])

        for dl in self.decoder_levels:
            predictions[f"dsv_logits_{dl}"] = self.dsv_conv(x[dl])
        return predictions

    def compute_loss(self,
                     pred_seg: Dict[str, torch.Tensor],
                     target: torch.Tensor,
                     ) -> Dict[str, torch.Tensor]:
        """
        Compute weighted dice and cross entropy loss

        Args:
            pred_seg: segmentation predictions
                `seg_logits`: predicted logits
            target: ground truth segmentation of top layer

        Returns:
            Dict[str, torch.Tensor]: computed loss (contained in key seg)
        """
        target[target > 0] = 1

        loss = self._compute_loss(pred_seg["seg_logits"], target)

        preds_decoder_level = [pred_seg[f"dsv_logits_{dl}"] for dl in self.decoder_levels]
        targets_interpolated = self.interpolator(preds_decoder_level, target)

        for pred, target in zip(preds_decoder_level, targets_interpolated):
            loss = loss + self.dsv_weight * self._compute_loss(pred, target)

        return {"seg_loss": loss / (len(self.decoder_levels) + 1)}

    def _compute_loss(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        return self.alpha * self.ce_loss(pred, target.long()) + \
            (1 - self.alpha) * self.dice_loss(pred, target)


SegmenterType = TypeVar('SegmenterType', bound=Segmenter)