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

# 假设的常量，用于匹配测试环境
N, C, H, W = 32, 64, 56, 56


class CauchyLoss(nn.Module):
    """
    Cauchy Loss (Lorentzian Loss) Implementation.
    Loss = log(1 + (diff / beta)^2)
    """

    def __init__(self, reduction='mean', beta=1.0):
        super().__init__()
        self.reduction = reduction
        self.beta = float(beta)
        if reduction not in ['none', 'mean', 'sum']:
            raise ValueError("Invalid reduction mode")

    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        # Calculate the absolute difference
        diff = torch.abs(input - target)

        # Calculate the squared normalized difference: (diff / beta)^2
        normalized_diff_sq = (diff / self.beta) ** 2

        # Calculate the loss: log(1 + normalized_diff_sq)
        loss = torch.log1p(normalized_diff_sq)

        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 = CauchyLoss(reduction, beta)

    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        # Benchmark functions usually pass inputs as a list/tuple
        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.randn(N, C, H, W, dtype=torch.float32)
    return [input, target]


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