|
| 1 | +# Copyright (c) MONAI Consortium |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import warnings |
| 15 | + |
| 16 | +import torch |
| 17 | +from torch.nn.modules.loss import _Loss |
| 18 | + |
| 19 | +from monai.networks.layers.utils import get_act_layer |
| 20 | +from monai.utils import LossReduction |
| 21 | +from monai.utils.enums import StrEnum |
| 22 | + |
| 23 | + |
| 24 | +class AdversarialCriterions(StrEnum): |
| 25 | + BCE = "bce" |
| 26 | + HINGE = "hinge" |
| 27 | + LEAST_SQUARE = "least_squares" |
| 28 | + |
| 29 | + |
| 30 | +class PatchAdversarialLoss(_Loss): |
| 31 | + """ |
| 32 | + Calculates an adversarial loss on a Patch Discriminator or a Multi-scale Patch Discriminator. |
| 33 | + Warning: due to the possibility of using different criterions, the output of the discrimination |
| 34 | + mustn't be passed to a final activation layer. That is taken care of internally within the loss. |
| 35 | +
|
| 36 | + Args: |
| 37 | + reduction: {``"none"``, ``"mean"``, ``"sum"``} |
| 38 | + Specifies the reduction to apply to the output. Defaults to ``"mean"``. |
| 39 | +
|
| 40 | + - ``"none"``: no reduction will be applied. |
| 41 | + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. |
| 42 | + - ``"sum"``: the output will be summed. |
| 43 | +
|
| 44 | + criterion: which criterion (hinge, least_squares or bce) you want to use on the discriminators outputs. |
| 45 | + Depending on the criterion, a different activation layer will be used. Make sure you don't run the outputs |
| 46 | + through an activation layer prior to calling the loss. |
| 47 | + no_activation_leastsq: if True, the activation layer in the case of least-squares is removed. |
| 48 | + """ |
| 49 | + |
| 50 | + def __init__( |
| 51 | + self, |
| 52 | + reduction: LossReduction | str = LossReduction.MEAN, |
| 53 | + criterion: str = AdversarialCriterions.LEAST_SQUARE, |
| 54 | + no_activation_leastsq: bool = False, |
| 55 | + ) -> None: |
| 56 | + super().__init__(reduction=LossReduction(reduction)) |
| 57 | + |
| 58 | + if criterion.lower() not in list(AdversarialCriterions): |
| 59 | + raise ValueError( |
| 60 | + "Unrecognised criterion entered for Adversarial Loss. Must be one in: %s" |
| 61 | + % ", ".join(AdversarialCriterions) |
| 62 | + ) |
| 63 | + |
| 64 | + # Depending on the criterion, a different activation layer is used. |
| 65 | + self.real_label = 1.0 |
| 66 | + self.fake_label = 0.0 |
| 67 | + self.loss_fct: _Loss |
| 68 | + if criterion == AdversarialCriterions.BCE: |
| 69 | + self.activation = get_act_layer("SIGMOID") |
| 70 | + self.loss_fct = torch.nn.BCELoss(reduction=reduction) |
| 71 | + elif criterion == AdversarialCriterions.HINGE: |
| 72 | + self.activation = get_act_layer("TANH") |
| 73 | + self.fake_label = -1.0 |
| 74 | + elif criterion == AdversarialCriterions.LEAST_SQUARE: |
| 75 | + if no_activation_leastsq: |
| 76 | + self.activation = None |
| 77 | + else: |
| 78 | + self.activation = get_act_layer(name=("LEAKYRELU", {"negative_slope": 0.05})) |
| 79 | + self.loss_fct = torch.nn.MSELoss(reduction=reduction) |
| 80 | + |
| 81 | + self.criterion = criterion |
| 82 | + self.reduction = reduction |
| 83 | + |
| 84 | + def get_target_tensor(self, input: torch.Tensor, target_is_real: bool) -> torch.Tensor: |
| 85 | + """ |
| 86 | + Gets the ground truth tensor for the discriminator depending on whether the input is real or fake. |
| 87 | +
|
| 88 | + Args: |
| 89 | + input: input tensor from the discriminator (output of discriminator, or output of one of the multi-scale |
| 90 | + discriminator). This is used to match the shape. |
| 91 | + target_is_real: whether the input is real or wannabe-real (1s) or fake (0s). |
| 92 | + Returns: |
| 93 | + """ |
| 94 | + filling_label = self.real_label if target_is_real else self.fake_label |
| 95 | + label_tensor = torch.tensor(1).fill_(filling_label).type(input.type()).to(input[0].device) |
| 96 | + label_tensor.requires_grad_(False) |
| 97 | + return label_tensor.expand_as(input) |
| 98 | + |
| 99 | + def get_zero_tensor(self, input: torch.Tensor) -> torch.Tensor: |
| 100 | + """ |
| 101 | + Gets a zero tensor. |
| 102 | +
|
| 103 | + Args: |
| 104 | + input: tensor which shape you want the zeros tensor to correspond to. |
| 105 | + Returns: |
| 106 | + """ |
| 107 | + |
| 108 | + zero_label_tensor = torch.tensor(0).type(input[0].type()).to(input[0].device) |
| 109 | + zero_label_tensor.requires_grad_(False) |
| 110 | + return zero_label_tensor.expand_as(input) |
| 111 | + |
| 112 | + def forward( |
| 113 | + self, input: torch.Tensor | list, target_is_real: bool, for_discriminator: bool |
| 114 | + ) -> torch.Tensor | list[torch.Tensor]: |
| 115 | + """ |
| 116 | +
|
| 117 | + Args: |
| 118 | + input: output of Multi-Scale Patch Discriminator or Patch Discriminator; being a list of tensors |
| 119 | + or a tensor; they shouldn't have gone through an activation layer. |
| 120 | + target_is_real: whereas the input corresponds to discriminator output for real or fake images |
| 121 | + for_discriminator: whereas this is being calculated for discriminator or generator loss. In the last |
| 122 | + case, target_is_real is set to True, as the generator wants the input to be dimmed as real. |
| 123 | + Returns: if reduction is None, returns a list with the loss tensors of each discriminator if multi-scale |
| 124 | + discriminator is active, or the loss tensor if there is just one discriminator. Otherwise, it returns the |
| 125 | + summed or mean loss over the tensor and discriminator/s. |
| 126 | +
|
| 127 | + """ |
| 128 | + |
| 129 | + if not for_discriminator and not target_is_real: |
| 130 | + target_is_real = True # With generator, we always want this to be true! |
| 131 | + warnings.warn( |
| 132 | + "Variable target_is_real has been set to False, but for_discriminator is set" |
| 133 | + "to False. To optimise a generator, target_is_real must be set to True." |
| 134 | + ) |
| 135 | + |
| 136 | + if type(input) is not list: |
| 137 | + input = [input] |
| 138 | + target_ = [] |
| 139 | + for _, disc_out in enumerate(input): |
| 140 | + if self.criterion != AdversarialCriterions.HINGE: |
| 141 | + target_.append(self.get_target_tensor(disc_out, target_is_real)) |
| 142 | + else: |
| 143 | + target_.append(self.get_zero_tensor(disc_out)) |
| 144 | + |
| 145 | + # Loss calculation |
| 146 | + loss_list = [] |
| 147 | + for disc_ind, disc_out in enumerate(input): |
| 148 | + if self.activation is not None: |
| 149 | + disc_out = self.activation(disc_out) |
| 150 | + if self.criterion == AdversarialCriterions.HINGE and not target_is_real: |
| 151 | + loss_ = self._forward_single(-disc_out, target_[disc_ind]) |
| 152 | + else: |
| 153 | + loss_ = self._forward_single(disc_out, target_[disc_ind]) |
| 154 | + loss_list.append(loss_) |
| 155 | + |
| 156 | + loss: torch.Tensor | list[torch.Tensor] |
| 157 | + if loss_list is not None: |
| 158 | + if self.reduction == LossReduction.MEAN: |
| 159 | + loss = torch.mean(torch.stack(loss_list)) |
| 160 | + elif self.reduction == LossReduction.SUM: |
| 161 | + loss = torch.sum(torch.stack(loss_list)) |
| 162 | + else: |
| 163 | + loss = loss_list |
| 164 | + return loss |
| 165 | + |
| 166 | + def _forward_single(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: |
| 167 | + forward: torch.Tensor |
| 168 | + if self.criterion == AdversarialCriterions.BCE or self.criterion == AdversarialCriterions.LEAST_SQUARE: |
| 169 | + forward = self.loss_fct(input, target) |
| 170 | + elif self.criterion == AdversarialCriterions.HINGE: |
| 171 | + minval = torch.min(input - 1, self.get_zero_tensor(input)) |
| 172 | + forward = -torch.mean(minval) |
| 173 | + return forward |
0 commit comments