+
    &jP                     0   ^ RI t ^ RIHtHtHt ^ RIHt ]R!,          tR"R R llt	R#R R llt
R$R R lltR%R	 R
 lltR%R R lltR&R R lltR'R R lltR&R R lltR(R R lltR)R R lltR"R R lltR*R R lltR"R R lltR+R R lltR,R R  lltR# )-    N)LiteralOptionalget_argsc                D    V ^8  d   QhR\         P                  R\        /# )   loss	reductionmxarray	Reduction)formats   "e/Users/jameslopez/projects/CWCArchive/cwc-podcast/.venv/lib/python3.14/site-packages/mlx/nn/losses.py__annotate__r      s     	 	"(( 	y 	    c                     V\        \        4      9  d   \        R \        \        4       R24      hVR8X  d   \        P                  ! V 4      # VR8X  d   \        P
                  ! V 4      # VR8X  d   V # R# )z"Invalid reduction. Must be one of .meansumnoneN)r   r   
ValueErrorr   r   r   )r   r	   s   &&r   _reducer      si    ++=hy>Q=RRSTUUFwwt}	e	vvd|	f	 
r   c                    V ^8  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        R\        R\
        R\         P                  /# )r   logitstargetsweightsaxislabel_smoothingr	   return)r   r   r   intfloatr   )r   s   "r   r   r      sl     ^$ ^$HH^$XX^$ bhh^$ 	^$
 ^$ ^$ XX^$r   c                   V^ 8  g   V^8  d   \        RV R24      hVP                  V P                  8H  pR pV'       d   VP                  V P                  8w  g+   V'       gI   VP                  V! V P                  V4      8w  d'   \        RVP                   RV P                   R24      hV'       d    \        P                  ! W,          VR7      pM;\        P
                  ! V \        P                  ! W4      V4      P                  V4      p\        P                  ! WR7      p	V^ 8  d=   ^V,
          V,          p
V P                  VR7      pV) V,          pW,
          V,           pMW,
          pVeJ   VP                  VP                  8w  d'   \        RVP                   RVP                   R24      hW,          p\        W4      # )	a  
Computes the cross entropy loss.

Args:
    logits (array): The unnormalized logits.
    targets (array): The ground truth values. These can be class indices or
        probabilities for each class. If the ``targets`` are class indices,
        then ``targets`` shape should match the ``logits`` shape with
        the ``axis`` dimension removed. If the ``targets`` are probabilities
        (or one-hot encoded), then the ``targets`` shape should be the same as
        the ``logits`` shape.
    weights (array, optional): Optional weights for each target. Default: ``None``.
    axis (int, optional): The axis over which to compute softmax. Default: ``-1``.
    label_smoothing (float, optional): Label smoothing factor. Default: ``0``.
    reduction (str, optional): Specifies the reduction to apply to the output:
        ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    array: The computed cross entropy loss.

Examples:
    >>> import mlx.core as mx
    >>> import mlx.nn as nn
    >>>
    >>> # Class indices as targets
    >>> logits = mx.array([[2.0, -1.0], [-1.0, 2.0]])
    >>> targets = mx.array([0, 1])
    >>> nn.losses.cross_entropy(logits, targets)
    array([0.0485873, 0.0485873], dtype=float32)
    >>>
    >>> # Probabilities (or one-hot vectors) as targets
    >>> logits = mx.array([[2.0, -1.0], [-1.0, 2.0]])
    >>> targets = mx.array([[0.9, 0.1], [0.1, 0.9]])
    >>> nn.losses.cross_entropy(logits, targets)
    array([0.348587, 0.348587], dtype=float32)
z$Label smoothing must in [0, 1), got r   c                 P    \        V 4      p V P                  V4       \        V 4      # )N)listpoptuple)shaper   s   &&r   	_drop_dim cross_entropy.<locals>._drop_dimI   s     U		$U|r   zTargets shape z does not match logits shape r   Weights with shape + is not the same as output loss with shape )r   ndimr'   r   r   take_along_axisexpand_dimssqueeze	logsumexpr   r   )r   r   r   r   r   r	   targets_as_probsr(   scorelogsumexp_logitsadjusted_scoremean_logitssmoothed_lossr   s   &&&&&&        r   cross_entropyr8      s   X o2??PPQRSS ||v{{2 	W]]fll:)FLL$2O!OW]]O+HVWX
 	
 v'd3""62>>'+H$OWW
 ||F6o-6 kktk,$6  0=@' ==DJJ&%gmm_ 5**.**Q8  	 4##r   c                    V ^8  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        R\        R\         P                  /# )r   inputsr   r   with_logitsr	   r   )r   r   r   boolr   )r   s   "r   r   r   x   sY     ?$ ?$HH?$XX?$ bhh?$ 	?$
 ?$ XX?$r   c                   V P                   VP                   8w  d'   \        RV P                    RVP                    R24      hV'       d&   \        P                  ! RV 4      W,          ,
          pM\        P                  ! \        P
                  ! V 4      R	RR7      p\        P                  ! \        P
                  ! ^V ,
          4      R	RR7      pW,          ^V,
          V,          ,           ) pVeJ   VP                   VP                   8w  d'   \        RVP                    RVP                    R24      hWR,          p\        WT4      # )
a  
Computes the binary cross entropy loss.

By default, this function takes the pre-sigmoid logits, which results in a faster
and more precise loss. For improved numerical stability when ``with_logits=False``,
the loss calculation clips the input probabilities (in log-space) to a minimum value
of ``-100``.

Args:
    inputs (array): The predicted values. If ``with_logits`` is ``True``, then
        ``inputs`` are unnormalized logits. Otherwise, ``inputs`` are probabilities.
    targets (array): The binary target values in {0, 1}.
    with_logits (bool, optional): Whether ``inputs`` are logits. Default: ``True``.
    weights (array, optional): Optional weights for each target. Default: ``None``.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``.

Returns:
    array: The computed binary cross entropy loss.
Examples:
    >>> import mlx.core as mx
    >>> import mlx.nn as nn

    >>> logits = mx.array([0.105361, 0.223144, 1.20397, 0.916291])
    >>> targets = mx.array([0, 0, 1, 1])
    >>> loss = nn.losses.binary_cross_entropy(logits, targets, reduction="mean")
    >>> loss
    array(0.539245, dtype=float32)

    >>> probs = mx.array([0.1, 0.1, 0.4, 0.4])
    >>> targets = mx.array([0, 0, 1, 1])
    >>> loss = nn.losses.binary_cross_entropy(probs, targets, with_logits=False, reduction="mean")
    >>> loss
    array(0.510826, dtype=float32)
Inputs shape  does not match targets shape r           N)a_mina_maxr+   r,   i)r'   r   r   	logaddexpcliplogr   )r:   r   r   r;   r	   r   log_inputs_cliplog_inputs_inv_clips   &&&&&   r   binary_cross_entropyrH   x   s   T ||w}}$FLL>)GVWX
 	
 ||C(6+;;''"&&.DI ggbffQZ&8DQ*a'k=P-PPQ ==DJJ&%gmm_ 5**.**Q8  	4##r   c                    V ^8  d   QhR\         P                  R\         P                  R\        R\         P                  /# r   predictionsr   r	   r   r
   )r   s   "r   r   r      8     $ $$$&HH$9B$XX$r   c                    V P                   VP                   8w  d'   \        RV P                    RVP                    R24      h\        P                  ! W,
          4      p\	        W24      # )a/  
Computes the L1 loss.

Args:
    predictions (array): The predicted values.
    targets (array): The target values.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``.

Returns:
    array: The computed L1 loss.
Predictions shape r?   r   )r'   r   r   absr   rK   r   r	   r   s   &&& r   l1_lossrQ      sd     GMM) !2!2 3 4$]]O1.
 	
 66+'(D4##r   c                    V ^8  d   QhR\         P                  R\         P                  R\        R\         P                  /# rJ   r
   )r   s   "r   r   r      rL   r   c                    V P                   VP                   8w  d'   \        RV P                    RVP                    R24      h\        P                  ! W,
          4      p\	        W24      # )aO  
Computes the mean squared error loss.

Args:
    predictions (array): The predicted values.
    targets (array): The target values.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``.

Returns:
    array: The computed mean squared error loss.
rN   r?   r   )r'   r   r   squarer   rP   s   &&& r   mse_lossrU      sd     GMM) !2!2 3 4$]]O1.
 	

 99[*+D4##r   c          
          V ^8  d   QhR\         P                  R\         P                  R\        R\        R\         P                  /# r   r:   r   r   r	   r   r   r   r    r   )r   s   "r   r   r      s@     $ $HH$!xx$/2$DM$XX$r   c                t    \         P                  ! WR,          V4      P                  R4      ) p\        WC4      # )a  
Computes the negative log likelihood loss.

Args:
    inputs (array): The predicted distribution in log space.
    targets (array): The target values.
    axis (int, optional): The distribution axis. Default: ``-1``.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    array: The computed NLL loss.
).N)r   r.   r0   r   r:   r   r   r	   r   s   &&&& r   nll_lossr\      s4      vy'94@HHLLD4##r   c                    V ^8  d   QhR\         P                  R\         P                  R\         P                  R\        R\        R\        R\         P                  /# )r   r:   r   varsfullepsr	   r   )r   r   r<   r!   r   )r   s   "r   r   r     s^     4$ 4$HH4$XX4$ ((4$ 	4$
 
4$ 4$ XX4$r   c                T   V P                   VP                   8w  d'   \        RV P                    RVP                    R24      hV P                   VP                   8w  d'   \        RV P                    RVP                    R24      h\        P                  ! W$4      pR\        P                  ! V4      \        P
                  ! W,
          4      V,          ,           ,          pV'       d:   VR\        P                  ! ^\        P                  ,          4      ,          ,          p\        We4      # )a  
Computes the negative log likelihood loss for a Gaussian distribution.

The loss is given by:

.. math::
    \frac{1}{2}\left(\log\left(\max\left(\text{vars},
    \ \epsilon\right)\right) + \frac{\left(\text{inputs} - \text{targets} \right)^2}
    {\max\left(\text{vars}, \ \epsilon \right)}\right) + \text{const.}

where ``inputs`` are the predicted means and ``vars`` are the the
predicted variances.

Args:
    inputs (array): The predicted expectation of the Gaussian distribution.
    targets (array): The target values (samples from the Gaussian distribution).
    vars (array): The predicted variance of the Gaussian distribution.
    full (bool, optional): Whether to include the constant term in the loss calculation.
        Default: ``False``.
    eps (float, optional): Small positive constant for numerical stability.
        Default: ``1e-6``.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    array: The Gaussian NLL loss.
r>   r?   r   z does not match vars shape       ?)	r'   r   r   maximumrE   rT   mathpir   )r:   r   r^   r_   r`   r	   r   s   &&&&&& r   gaussian_nll_lossrf     s    F ||w}}$FLL>)GVWX
 	
 ||tzz!FLL>)DTZZLPQR
 	

 ::d D"&&,7+;!<t!CCDDdhhq477{+++4##r   c          
          V ^8  d   QhR\         P                  R\         P                  R\        R\        R\         P                  /# rW   rX   )r   s   "r   r   r   8  s@     $ $HH$!xx$/2$DM$XX$r   c                    \         P                  ! \         P                  ! V4      W,
          ,          V4      p\        WC4      # )aX  
Computes the Kullback-Leibler divergence loss.

Computes the following when ``reduction == 'none'``:

.. code-block:: python

    mx.exp(targets) * (targets - inputs).sum(axis)

Args:
    inputs (array): Log probabilities for the predicted distribution.
    targets (array): Log probabilities for the target distribution.
    axis (int, optional): The distribution axis. Default: ``-1``.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    array: The computed Kullback-Leibler divergence loss.
)r   r   expr   r[   s   &&&& r   kl_div_lossrj   8  s/    , 66"&&/W%56=D4##r   c          
          V ^8  d   QhR\         P                  R\         P                  R\        R\        R\         P                  /# )r   rK   r   betar	   r   r   r   r!   r   )r   s   "r   r   r   S  sF     ,$ ,$,$XX,$ ,$ 	,$
 XX,$r   c                   V P                   VP                   8w  d'   \        RV P                    RVP                    R24      h\        P                  ! W,
          4      p\        P                  ! WB8  R\        P
                  ! V4      ,          V,          \        P                  ! V4      RV,          ,
          4      p\        WS4      # )a5  
Computes the smooth L1 loss.

The smooth L1 loss is a variant of the L1 loss which replaces the absolute
difference with a squared difference when the absolute difference is less
than ``beta``.

The formula for the smooth L1 Loss is:

.. math::

  l = \begin{cases}
        0.5 (x - y)^2 / \beta, & \text{if } |x - y| < \beta \\
        |x - y| - 0.5 \beta, & \text{otherwise}
      \end{cases}

Args:
    predictions (array): Predicted values.
    targets (array): Ground truth values.
    beta (float, optional): The threshold after which the loss changes
      from the squared to the absolute difference. Default: ``1.0``.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``.

Returns:
    array: The computed smooth L1 loss.
rN   r?   r   rb   )r'   r   r   rO   whererT   r   )rK   r   rl   r	   diffr   s   &&&&  r   smooth_l1_lossrq   S  s    B GMM) !2!2 3 4$]]O1.
 	

 66+'(D88S299T?*T1266$<#*3LD 4##r   c                    V ^8  d   QhR\         P                  R\         P                  R\         P                  R\        R\        R\        R\        R\        R	\         P                  /	# )
r   anchors	positives	negativesr   pmarginr`   r	   r   r   r   r    r!   r   )r   s   "r   r   r     sr     '$ '$XX'$xx'$ xx'$ 	'$
 '$ '$ 
'$ '$ XX'$r   c           	     v   \         P                  ! \         P                  ! \         P                  ! W,
          V4      P	                  V4      V,           4      \         P                  ! \         P                  ! W,
          V4      P	                  V4      V,           4      ,
          V,           ^ 4      p\        W4      # )a  
Computes the triplet loss for a set of anchor, positive, and negative samples.
Margin is represented with alpha in the math section.

.. math::

   \max\left(\|A - P\|_p - \|A - N\|_p + \alpha, 0\right)

Args:
    anchors (array): The anchor samples.
    positives (array): The positive samples.
    negatives (array): The negative samples.
    axis (int, optional): The distribution axis. Default: ``-1``.
    p (int, optional): The norm degree for pairwise distance. Default: ``2``.
    margin (float, optional): Margin for the triplet loss. Defaults to ``1.0``.
    eps (float, optional): Small positive constant to prevent numerical instability. Defaults to ``1e-6``.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    array: Computed triplet loss. If reduction is "none", returns a tensor of the same shape as input;
              if reduction is "mean" or "sum", returns a scalar tensor.
)r   rc   sqrtpowerr   r   )	rs   rt   ru   r   rv   rw   r`   r	   r   s	   &&&&&&&& r   triplet_lossr|     s    B ::
,a044T:S@A
''"((7.266t<sB
C	D
	 	
	D 4##r   c                    V ^8  d   QhR\         P                  R\         P                  R\        R\         P                  /# r   r:   r   r	   r   r
   )r   s   "r   r   r     s8     $ $HH$!xx$4=$XX$r   c                `    \         P                  ! ^W,          ,
          ^ 4      p\        W24      # )a  
Computes the hinge loss between inputs and targets.

.. math::

   \text{hinge}(y, y_{\text{pred}}) = \max(0, 1 - y \cdot y_{\text{pred}})


Args:
    inputs (array): The predicted values.
    targets (array): The target values. They should be -1 or 1.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    array: The computed hinge loss.
)r   rc   r   )r:   r   r	   r   s   &&& r   
hinge_lossr     s'    ( ::a&**A.D4##r   c          
          V ^8  d   QhR\         P                  R\         P                  R\        R\        R\         P                  /# )r   r:   r   deltar	   r   rm   )r   s   "r   r   r     sF     "$ "$HH"$XX"$ "$ 	"$
 XX"$r   c                    W,
          p\         P                  ! V4      p\         P                  ! WR4      pWV,
          pRV^,          ,          W',          ,           p\        W4      # )a  
Computes the Huber loss between inputs and targets.

.. math::

    l_{\delta}(a) =
    \left\{ \begin{array}{ll}
        \frac{1}{2} a^2 & \text{for } |a| \leq \delta, \\
        \delta \left( |a| - \frac{1}{2} \delta \right) & \text{otherwise.}
    \end{array} \right.

Args:
    inputs (array): The predicted values.
    targets (array): The target values.
    delta (float, optional): The threshold at which to change between L1 and L2 loss.
      Default: ``1.0``.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    array: The computed Huber loss.
rb   )r   rO   minimumr   )	r:   r   r   r	   errors
abs_errors	quadraticlinearr   s	   &&&&     r   
huber_lossr     sO    8 FJ

:-I#FA.D4##r   c                    V ^8  d   QhR\         P                  R\         P                  R\        R\         P                  /# r~   r
   )r   s   "r   r   r     s8     $ $HH$!xx$4=$XX$r   c                    W,
          p\         P                  ! W3) 4      \        P                  ! ^4      ,
          p\	        WB4      # )a  
Computes the log cosh loss between inputs and targets.

Logcosh acts like L2 loss for small errors, ensuring stable gradients,
and like the L1 loss for large errors, reducing sensitivity to outliers. This
dual behavior offers a balanced, robust approach for regression tasks.

.. math::

   \text{logcosh}(y_{\text{true}}, y_{\text{pred}}) =
        \frac{1}{n} \sum_{i=1}^{n}
        \log(\cosh(y_{\text{pred}}^{(i)} - y_{\text{true}}^{(i)}))


Args:
    inputs (array): The predicted values.
    targets (array): The target values.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    array: The computed log cosh loss.
)r   rC   rd   rE   r   )r:   r   r	   r   r   s   &&&  r   log_cosh_lossr     s4    4 F<<(488A;6D4##r   c                    V ^8  d   QhR\         P                  R\         P                  R\        R\        R\        R\         P                  /# )r   x1x2r   r`   r	   r   rx   )r   s   "r   r   r   
  sP     !$ !$
!$
!$ !$ 
	!$
 !$ XX!$r   c                   \         P                  P                  WR7      p\         P                  P                  WR7      p\         P                  ! W,          VR7      \         P                  ! WV,          V4      ,          p\        Wt4      # )a  
Computes the cosine similarity between the two inputs.

The cosine similarity loss is given by

.. math::

    \frac{x_1 \cdot x_2}{\max(\|x_1\|  \cdot \|x_2\|, \epsilon)}

Args:
    x1 (mx.array): The first set of inputs.
    x2 (mx.array): The second set of inputs.
    axis (int, optional): The embedding axis. Default: ``1``.
    eps (float, optional): The minimum value of the denominator used for
      numerical stability. Default: ``1e-8``.
    reduction (str, optional): Specifies the reduction to apply to the output:
      ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    mx.array: The computed cosine similarity loss.
r*   )r   linalgnormr   rc   r   )r   r   r   r`   r	   x1_normx2_normr   s   &&&&&   r   cosine_similarity_lossr   
  s\    8 iinnRn+GiinnRn+G66"'%

73Dc(JJD4##r   c                    V ^8  d   QhR\         P                  R\         P                  R\         P                  R\        R\        R\         P                  /# )r   inputs1inputs2r   rw   r	   r   rm   )r   s   "r   r   r   .  sT     4$ 4$XX4$XX4$ XX4$ 	4$
 4$ XX4$r   c           	     8   V P                   VP                   u;8X  d   VP                   8X  g6   M \        RV P                    RVP                    RVP                    R24      hW,
          p\        P                  ! ^ V) V,          V,           4      p\	        Wd4      # )a  
Calculate the margin ranking loss that loss given inputs :math:`x_1`, :math:`x_2` and a label
:math:`y` (containing 1 or -1).

The loss is given by:

.. math::
    \text{loss} = \max (0, -y * (x_1 - x_2) + \text{margin})

Where :math:`y` represents ``targets``, :math:`x_1` represents ``inputs1`` and :math:`x_2`
represents ``inputs2``.

Args:
    inputs1 (array): Scores for the first input.
    inputs2 (array): Scores for the second input.
    targets (array): Labels indicating whether samples in ``inputs1`` should be ranked higher
        than samples in ``inputs2``. Values should be 1 or -1.
    margin (float, optional): The margin by which the scores should be separated.
        Default: ``0.0``.
    reduction (str, optional): Specifies the reduction to apply to the output:
        ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.

Returns:
    array: The computed margin ranking loss.

Examples:
    >>> import mlx.core as mx
    >>> import mlx.nn as nn
    >>> targets = mx.array([1, 1, -1])
    >>> inputs1 = mx.array([-0.573409, -0.765166, -0.0638])
    >>> inputs2 = mx.array([0.75596, 0.225763, 0.256995])
    >>> loss = nn.losses.margin_ranking_loss(inputs1, inputs2, targets)
    >>> loss
    array(0.773433, dtype=float32)
zPThe shapes of the arguments do not match. The provided shapes are inputs1.shape=z, inputs2.shape=z, and targets.shape=r   )r'   r   r   rc   r   )r   r   r   rw   r	   differencesr   s   &&&&&  r   margin_ranking_lossr   .  s    T MMW]];gmm;$]]O+;GMM? K$]]O1.
 	
 #K::a'K/&89D4##r   )r   r   r   )r   )NrZ   r@   r   )NTr   )r   )rZ   r   )Fư>r   )      ?r   )rZ   r   r   r   r   )r   r   )   g:0yE>r   )r@   r   )rd   typingr   r   r   mlx.corecorer   r   r   r8   rH   rQ   rU   r\   rf   rj   rq   r|   r   r   r   r   r    r   r   <module>r      sw     . . )*		^$B?$D$2$2$*4$n$6,$^'$T$2"$J$@!$H4$ 4$r   