import torch
import torch.nn as nn
import torch.nn.functional as F

N, C, H, W = 32, 1, 64, 64


class DiceLoss(nn.Module):
    def __init__(self, reduction='mean', beta=1.0):
        super().__init__()
        self.reduction = reduction
        self.epsilon = 1e-6

    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:

        probs = torch.sigmoid(input)

        dims = tuple(range(2, input.dim()))

        intersection = (probs * target).sum(dim=dims)
        denominator = probs.sum(dim=dims) + target.sum(dim=dims)

        dice_coeff = (2. * intersection + self.epsilon) / (denominator + self.epsilon)

        loss = 1. - dice_coeff

        if self.reduction == 'mean':
            return loss.mean()
        elif self.reduction == 'sum':
            return loss.sum()
        else:
            return loss


class Model(nn.Module):
    def __init__(self, reduction='mean', beta=1.0):
        super().__init__()
        self.op = DiceLoss(reduction, beta)

    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        if isinstance(input, (list, tuple)) and len(input) > 0:
            input = input[0]
            target = target[0] if len(target) > 0 else target

        return self.op(input, target)


def get_inputs():
    input = torch.randn(N, C, H, W, dtype=torch.float32)
    target = torch.randint(0, 2, (N, C, H, W), dtype=torch.float32)
    return [input, target]


def get_init_inputs():
    return ['mean', 1.0]
