ó
    — óhï  ã                  ób   • S SK Jr  S SKJr  S SKJr  S SKJr  S SKJ	r	  S SK
Jr   " S S\	5      rg	)
é    )Úannotations)ÚIterable)ÚTensor)Úutil)ÚSparseCoSENTLoss)ÚSparseEncoderc                  ó:   ^ • \ rS rSrSSU 4S jjjrSS jrSrU =r$ )ÚSparseAnglELossé   c                ó<   >• [         TU ]  X[        R                  S9$ )aM
  
This class implements AnglE (Angle Optimized).
This is a modification of :class:`SparseCoSENTLoss`, designed to address the following issue:
The cosine function's gradient approaches 0 as the wave approaches the top or bottom of its form.
This can hinder the optimization process, so AnglE proposes to instead optimize the angle difference
in complex space in order to mitigate this effect.

It expects that each of the InputExamples consists of a pair of texts and a float valued label, representing
the expected similarity score between the pair.

It computes the following loss function:

``loss = logsum(1+exp(s(k,l)-s(i,j))+exp...)``, where ``(i,j)`` and ``(k,l)`` are any of the input pairs in the
batch such that the expected similarity of ``(i,j)`` is greater than ``(k,l)``. The summation is over all possible
pairs of input pairs in the batch that match this condition. This is the same as CoSENTLoss, with a different
similarity function.

Args:
    model: SparseEncoder
    scale: Output of similarity function is multiplied by scale
        value. Represents the inverse temperature.

References:
    - For further details, see: https://arxiv.org/abs/2309.12871v1

Requirements:
    - Need to be used in SpladeLoss or CSRLoss as a loss function.
    - Sentence pairs with corresponding similarity scores in range of the similarity function. Default is [-1,1].

Inputs:
    +--------------------------------+------------------------+
    | Texts                          | Labels                 |
    +================================+========================+
    | (sentence_A, sentence_B) pairs | float similarity score |
    +--------------------------------+------------------------+

Relations:
    - :class:`SparseCoSENTLoss` is AnglELoss with ``pairwise_cos_sim`` as the metric, rather than ``pairwise_angle_sim``.

Example:
    ::

        from datasets import Dataset

        from sentence_transformers.sparse_encoder import SparseEncoder, SparseEncoderTrainer, losses

        model = SparseEncoder("distilbert/distilbert-base-uncased")
        train_dataset = Dataset.from_dict(
            {
                "sentence1": ["It's nice weather outside today.", "He drove to work."],
                "sentence2": ["It's so sunny.", "She walked to the store."],
                "score": [1.0, 0.3],
            }
        )
        loss = losses.SpladeLoss(
            model=model, loss=losses.SparseAnglELoss(model), document_regularizer_weight=5e-5, use_document_regularizer_only=True
        )

        trainer = SparseEncoderTrainer(model=model, train_dataset=train_dataset, loss=loss)
        trainer.train()
)Úsimilarity_fct)ÚsuperÚ__init__r   Úpairwise_angle_sim)ÚselfÚmodelÚscaleÚ	__class__s      €Úu/home/james-whalen/.local/lib/python3.13/site-packages/sentence_transformers/sparse_encoder/losses/SparseAnglELoss.pyr   ÚSparseAnglELoss.__init__   s!   ø€ ô| ‰wÑ ¼T×=TÑ=TÐÐUÐUó    c                ó   • [        S5      e)NzLSparseAnglELoss should not be used alone. Use it with SpladeLoss or CSRLoss.)ÚAttributeError)r   Úsentence_featuresÚlabelss      r   ÚforwardÚSparseAnglELoss.forwardM   s   € ÜÐkÓlÐlr   © )g      4@)r   r   r   ÚfloatÚreturnÚNone)r   zIterable[dict[str, Tensor]]r   r   r    r   )Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__r   r   Ú__static_attributes__Ú__classcell__)r   s   @r   r
   r
      s   ø† ÷>Vñ >V÷@mò mr   r
   N)Ú
__future__r   Úcollections.abcr   Útorchr   Úsentence_transformersr   Ú<sentence_transformers.sparse_encoder.losses.SparseCoSENTLossr   Ú2sentence_transformers.sparse_encoder.SparseEncoderr   r
   r   r   r   Ú<module>r.      s(   ðÝ "å $å å &Ý YÝ LôBmÐ&õ Bmr   