a
    d(                  
   @   s   d dl Z d dlmZ d dlZd dlmZ d dlmZ d dlm	Z	m
Z
mZ d dlmZ deeeeeee edd	d
ZG dd dejZdeeeeeee ee edddZG dd dejZdS )    N)Optional)Tensor)KORNIA_CHECKKORNIA_CHECK_IS_TENSORKORNIA_CHECK_SHAPE)one_hot       @none)inputtargetalphagamma	reductionepsreturnc                 C   sN  |dur"t j s"tjdtdd t| g d | jd }|f| jdd  }t|jdd | jdd kd| d	|	   t| j
|j
kd
| j
 d|j
  | d}| d}	t|| jd | j
| jd}
t | d |}| | |	 }t d|
|f}|dkr|}n:|dkr&t |}n$|dkr<t |}ntd| |S )uO  Criterion that computes Focal loss.

    According to :cite:`lin2018focal`, the Focal loss is computed as follows:

    .. math::

        \text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)

    Where:
       - :math:`p_t` is the model's estimated probability for each class.

    Args:
        input: logits tensor with shape :math:`(N, C, *)` where C = number of classes.
        target: labels tensor with shape :math:`(N, *)` where each value is :math:`0 ≤ targets[i] ≤ C−1`.
        alpha: Weighting factor :math:`\alpha \in [0, 1]`.
        gamma: Focusing parameter :math:`\gamma >= 0`.
        reduction: Specifies the reduction to apply to the
          output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
          will be applied, ``'mean'``: the sum of the output will be divided by
          the number of elements in the output, ``'sum'``: the output will be
          summed.
        eps: Deprecated: scalar to enforce numerical stabiliy. This is no longer used.

    Return:
        the computed loss.

    Example:
        >>> N = 5  # num_classes
        >>> input = torch.randn(1, N, 3, 5, requires_grad=True)
        >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
        >>> output = focal_loss(input, target, alpha=0.5, gamma=2.0, reduction='mean')
        >>> output.backward()
    Nzm`focal_loss` has been reworked for improved numerical stability and the `eps` argument is no longer necessary   
stacklevelBC*r      zExpected target size z, got z2input and target must be in the same device. Got: z and )Znum_classesdevicedtype      ?zbc...,bc...->b...r	   meansumInvalid reduction mode: )torchjitis_scriptingwarningswarnDeprecationWarningr   shaper   sizer   ZsoftmaxZlog_softmaxr   r   powZeinsumr   r   NotImplementedError)r
   r   r   r   r   r   nZout_sizeZ
input_softZlog_input_softZtarget_one_hotZweightZfocalloss_tmploss r,   \/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/kornia/losses/focal.py
focal_loss   s8    )
2





r.   c                       sF   e Zd ZdZdeeeee dd fddZeeedd	d
Z	  Z
S )	FocalLossud  Criterion that computes Focal loss.

    According to :cite:`lin2018focal`, the Focal loss is computed as follows:

    .. math::

        \text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)

    Where:
       - :math:`p_t` is the model's estimated probability for each class.

    Args:
        alpha: Weighting factor :math:`\alpha \in [0, 1]`.
        gamma: Focusing parameter :math:`\gamma >= 0`.
        reduction: Specifies the reduction to apply to the
          output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
          will be applied, ``'mean'``: the sum of the output will be divided by
          the number of elements in the output, ``'sum'``: the output will be
          summed.
        eps: Deprecated: scalar to enforce numerical stability. This is no longer
          used.

    Shape:
        - Input: :math:`(N, C, *)` where C = number of classes.
        - Target: :math:`(N, *)` where each value is
          :math:`0 ≤ targets[i] ≤ C−1`.

    Example:
        >>> N = 5  # num_classes
        >>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
        >>> criterion = FocalLoss(**kwargs)
        >>> input = torch.randn(1, N, 3, 5, requires_grad=True)
        >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
        >>> output = criterion(input, target)
        >>> output.backward()
    r   r	   N)r   r   r   r   r   c                    s&   t    || _|| _|| _|| _d S N)super__init__r   r   r   r   )selfr   r   r   r   	__class__r,   r-   r2      s
    
zFocalLoss.__init__r
   r   r   c                 C   s   t ||| j| j| j| jS r0   )r.   r   r   r   r   r3   r
   r   r,   r,   r-   forward   s    zFocalLoss.forward)r   r	   N)__name__
__module____qualname____doc__floatstrr   r2   r   r8   __classcell__r,   r,   r4   r-   r/   c   s   % r/         ?)r
   r   r   r   r   r   
pos_weightr   c                 C   sX  |dur"t j s"tjdtdd t| g d t| jd |jd kd| jd  d|jd  d	 |du rt j	| jd
 | j
| jd}t| t| jd
 |jd kd |  }t |  }| | || | |    d| t || d|  |      }	|dkr|	}
n:|dkr0t |	}
n$|dkrFt |	}
ntd| |
S )u  Function that computes Binary Focal loss.

    .. math::

        \text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)

    where:
       - :math:`p_t` is the model's estimated probability for each class.

    Args:
        input: input data tensor of arbitrary shape.
        target: the target tensor with shape matching input.
        alpha: Weighting factor for the rare class :math:`\alpha \in [0, 1]`.
        gamma: Focusing parameter :math:`\gamma >= 0`.
        reduction: Specifies the reduction to apply to the
          output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
          will be applied, ``'mean'``: the sum of the output will be divided by
          the number of elements in the output, ``'sum'``: the output will be
          summed.
        eps: Deprecated: scalar for numerically stability when dividing. This is no longer used.
        pos_weight: a weight of positive examples.
          It’s possible to trade off recall and precision by adding weights to positive examples.
          Must be a vector with length equal to the number of classes.

    Returns:
        the computed loss.

    Examples:
        >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
        >>> logits = torch.tensor([[[6.325]],[[5.26]],[[87.49]]])
        >>> labels = torch.tensor([[[1.]],[[1.]],[[0.]]])
        >>> binary_focal_loss_with_logits(logits, labels, **kwargs)
        tensor(21.8725)
    Nz`binary_focal_loss_with_logits` has been reworked for improved numerical stability and the `eps` argument is no longer necessaryr   r   r   r   zExpected input batch_size (z) to match target batch_size (z).)r   r   z-Expected pos_weight equals number of classes.r   r   r	   r   r   r   )r   r    r!   r"   r#   r$   r   r   r%   Zonesr   r   r   Zsigmoidr'   logr   r   r(   )r
   r   r   r   r   r   rA   Z	probs_posZ	probs_negr*   r+   r,   r,   r-   binary_focal_loss_with_logits   s:    ,"(


rD   c                       sF   e Zd ZdZdeeeee dd fddZeeedd	d
Z	  Z
S )BinaryFocalLossWithLogitsuw  Criterion that computes Focal loss.

    According to :cite:`lin2018focal`, the Focal loss is computed as follows:

    .. math::

        \text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)

    where:
       - :math:`p_t` is the model's estimated probability for each class.

    Args:
        alpha: Weighting factor for the rare class :math:`\alpha \in [0, 1]`.
        gamma: Focusing parameter :math:`\gamma >= 0`.
        reduction: Specifies the reduction to apply to the
          output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
          will be applied, ``'mean'``: the sum of the output will be divided by
          the number of elements in the output, ``'sum'``: the output will be
          summed.
        pos_weight: a weight of positive examples.
          It’s possible to trade off recall and precision by adding weights to positive examples.
          Must be a vector with length equal to the number of classes.

    Shape:
        - Input: :math:`(N, *)`.
        - Target: :math:`(N, *)`.

    Examples:
        >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
        >>> loss = BinaryFocalLossWithLogits(**kwargs)
        >>> input = torch.randn(1, 3, 5, requires_grad=True)
        >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(2)
        >>> output = loss(input, target)
        >>> output.backward()
    r   r	   N)r   r   r   rA   r   c                    s&   t    || _|| _|| _|| _d S r0   )r1   r2   r   r   r   rA   )r3   r   r   r   rA   r4   r,   r-   r2     s
    
z"BinaryFocalLossWithLogits.__init__r6   c                 C   s   t ||| j| j| j| jdS )N)rA   )rD   r   r   r   rA   r7   r,   r,   r-   r8     s    z!BinaryFocalLossWithLogits.forward)r   r	   N)r9   r:   r;   r<   r=   r>   r   r   r2   r8   r?   r,   r,   r4   r-   rE      s   % 	rE   )r   r	   N)r@   r   r	   NN)r"   typingr   r   Ztorch.nnnnZkornia.corer   Zkornia.testingr   r   r   Zkornia.utils.one_hotr   r=   r>   r.   Moduler/   rD   rE   r,   r,   r,   r-   <module>   sF   
   T4     S