Ë
    l^(hÄ  ã                  ór   — d dl mZ d dlZd dlZd dlmZ d dlmZmZ d dl	m
Z
  G d„ dej                  «      Zy)é    )ÚannotationsN)ÚOrderedDict)ÚTensorÚnn)Úimport_from_stringc                  óP   ‡ — e Zd Zddˆ fd„Zd	d„Zd
d„Zd„ Zdd„Zed„ «       Z	ˆ xZ
S )ÚAsymc                óø   •— || _         || _        t        «       }|j                  «       D ]?  \  }}t	        |t
        «      s|g}t        |«      D ]  \  }}|||dz   t        |«      z   <   Œ ŒA t        ‰| �%  |«       y)a  
        This model allows to create asymmetric SentenceTransformer models, that apply different models depending on the specified input key.

        In the below example, we create two different Dense models for 'query' and 'doc'. Text that is passed as {'query': 'My query'} will
        be passed along along the first Dense model, and text that will be passed as {'doc': 'My document'} will use the other Dense model.

        Note, that when you call encode(), that only inputs of the same type can be encoded. Mixed-Types cannot be encoded.

        Example:
            ::

                from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer, losses
                from datasets import Dataset

                # Load a SentenceTransformer model (pretrained or not), and add an Asym module
                model = SentenceTransformer("microsoft/mpnet-base")
                dim = model.get_sentence_embedding_dimension()
                asym_model = models.Asym({
                    'query': [models.Dense(dim, dim)],
                    'doc': [models.Dense(dim, dim)]
                })
                model.add_module("asym", asym_model)

                train_dataset = Dataset.from_dict({
                    "query": ["is toprol xl the same as metoprolol?", "are eyes always the same size?"],
                    "answer": ["Metoprolol succinate is also known by the brand name Toprol XL.", "The eyes are always the same size from birth to death."],
                })

                # This mapper turns normal texts into a dictionary mapping Asym keys to the text
                def mapper(sample):
                    return {
                        "question": {"query": sample["question"]},
                        "answer": {"doc": sample["answer"]},
                    }

                train_dataset = train_dataset.map(mapper)
                loss = losses.MultipleNegativesRankingLoss(model)

                trainer = SentenceTransformerTrainer(
                    model=model,
                    train_dataset=train_dataset,
                    loss=loss,
                )
                trainer.train()

                # For inference, you can pass dictionaries with the Asym keys:
                model.encode([
                    {'query': 'how long do you have to wait to apply for cerb?'},
                    {'query': '<3 what does this symbol mean?'},
                    {'doc': 'The definition of <3 is "Love".'}]
                )

        Note:
            These models are not necessarily stronger than non-asymmetric models. Rudimentary experiments indicate
            that non-Asym models perform better in most cases.

        Args:
            sub_modules: Dict in the format str -> List[models]. The
                models in the specified list will be applied for input
                marked with the respective key.
            allow_empty_key: If true, inputs without a key can be
                processed. If false, an exception will be thrown if no
                key is specified.
        ú-N)
Úsub_modulesÚallow_empty_keyr   ÚitemsÚ
isinstanceÚlistÚ	enumerateÚstrÚsuperÚ__init__)	Úselfr   r   Úordered_dictÚnameÚmodelsÚidxÚmodelÚ	__class__s	           €ú_/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/sentence_transformers/models/Asym.pyr   zAsym.__init__   sˆ   ø€ ðB 'ˆÔØ.ˆÔä"“}ˆØ'×-Ñ-Ó/ò 	<‰LˆD�&Ü˜f¤dÔ+Ø ˜�ä'¨Ó/ò <‘
��UØ6;�˜T C™Z¬#¨c«(Ñ2Ò3ñ<ð		<ô 	‰Ñ˜Õ&ó    c                óª   — d|v r7t        |d   «      dkD  r&|d   d   }| j                  |   D ]
  } ||«      }Œ |S | j                  st        d«      ‚|S )NÚ	text_keysr   z;Input did not specify any keys and allow_empty_key is False)Úlenr   r   Ú
ValueError)r   ÚfeaturesÚtext_keyr   s       r   ÚforwardzAsym.forwardZ   sp   € Ø˜(Ñ"¤s¨8°KÑ+@Ó'AÀAÒ'EØ Ñ,¨QÑ/ˆHØ×)Ñ)¨(Ñ3ò +�Ù  ›?‘ð+ð
 ˆð ×%Ò%ÜÐZÓ[Ð[àˆr   c                ó¢   — | j                   D ]@  }t        | j                   |   d   d«      sŒ | j                   |   d   j                  «       c S  y )Nr   Ú get_sentence_embedding_dimension)r   Úhasattrr&   )r   r   s     r   r&   z%Asym.get_sentence_embedding_dimensiond   sX   € Ø×$Ñ$ò 	TˆDÜ�t×'Ñ'¨Ñ-¨aÑ0Ð2TÕUØ×'Ñ'¨Ñ-¨aÑ0×QÑQÓSÒSð	Tð r   c                óÌ  — i }i }i }| j                   j                  «       D ]o  \  }}g ||<   |D ]`  }t        t        |«      «      dz   t	        |«      j
                  z   }|||<   t	        |«      j                  ||<   ||   j                  |«       Œb Œq |j                  «       D ]V  \  }}t        j                  j                  |t        |«      «      }	t        j                  |	d¬«       |j                  |	«       ŒX t        t        j                  j                  |d«      dd¬«      5 }
t        j                  ||d| j                   id	œ|
d
¬«       d d d «       y # 1 sw Y   y xY w)NÚ_T)Úexist_okúconfig.jsonÚwÚutf8)Úencodingr   )ÚtypesÚ	structureÚ
parametersé   )Úindent)r   r   r   ÚidÚtypeÚ__name__Ú
__module__ÚappendÚosÚpathÚjoinÚmakedirsÚsaveÚopenÚjsonÚdumpr   )r   Úoutput_pathÚmodel_lookupÚmodel_typesÚmodel_structurer   r   r   Úmodel_idÚ
model_pathÚfOuts              r   r=   z	Asym.savej   sP  € ØˆØˆØˆà ×,Ñ,×2Ñ2Ó4ò 	7‰LˆD�&Ø$&ˆO˜DÑ!Øò 7�Üœr %›y›>¨CÑ/´$°u³+×2FÑ2FÑF�Ø).�˜XÑ&Ü(,¨U«×(>Ñ(>�˜HÑ%Ø Ñ%×,Ñ,¨XÕ6ñ	7ð	7ð  ,×1Ñ1Ó3ò 	#‰OˆH�eÜŸ™Ÿ™ k´3°x³=ÓAˆJÜ�K‰K˜
¨TÕ2Ø�J‰J�zÕ"ð	#ô
 ”"—'‘'—,‘,˜{¨MÓ:¸CÈ&ÔQð 		ÐUYÜ�I‰Ià(Ø!0Ø#4°d×6JÑ6JÐ"Kñð
 Øõ÷		÷ 		ñ 		ús   Ä()EÅE#c                óö   — t        |d   t        «      st        d«      ‚d}|D ]2  }t        t	        |j                  «       «      «      \  }}|€|}||k(  rŒ2J ‚  | j                  |   d   j                  |fi |¤ŽS )z-Tokenizes a text and maps tokens to token-idsr   zDAsym. model requires that texts are passed as dicts: {'key': 'text'}N)r   ÚdictÚAttributeErrorÚnextÚiterr   r   Útokenize)r   ÚtextsÚkwargsÚ
module_keyÚlookupr#   Útexts          r   rM   zAsym.tokenize‡   sŒ   € ä˜% ™(¤DÔ)Ü Ð!gÓhÐhàˆ
àò 	*ˆFÜ!¤$ v§|¡|£~Ó"6Ó7‰NˆH�dØÐ!Ø%�
à˜zÓ)Ð)Ð)ð	*ð 8ˆt×Ñ 
Ñ+¨AÑ.×7Ñ7¸ÑHÀÑHÐHr   c                ó  — t        t        j                  j                  | d«      «      5 }t	        j
                  |«      }d d d «       i }d   j                  «       D ]D  \  }}t        |«      }|j                  t        j                  j                  | |«      «      }|||<   ŒF i }|d   j                  «       D ](  \  }	}
g ||	<   |
D ]  }||	   j                  ||   «       Œ Œ* t        |fi |d   ¤Ž}|S # 1 sw Y   Œ¶xY w)Nr+   r/   r0   r1   )
r>   r9   r:   r;   r?   Úloadr   r   r8   r	   )Ú
input_pathÚfInÚconfigÚmodulesrE   Ú
model_typeÚmodule_classÚmodulerD   Úkey_nameÚmodels_listr   s               r   rT   z	Asym.load–   s  € ä”"—'‘'—,‘,˜z¨=Ó9Ó:ð 	$¸cÜ—Y‘Y˜s“^ˆF÷	$ð ˆØ$*¨7¡O×$9Ñ$9Ó$;ò 	'Ñ ˆH�jÜ-¨jÓ9ˆLØ!×&Ñ&¤r§w¡w§|¡|°JÀÓ'IÓJˆFØ &ˆG�HÒð	'ð
 ˆØ%+¨KÑ%8×%>Ñ%>Ó%@ò 	DÑ!ˆH�kØ(*ˆO˜HÑ%Ø'ò D�Ø Ñ)×0Ñ0°¸Ñ1BÕCñDð	Dô
 �_Ñ=¨¨|Ñ(<Ñ=ˆØˆ÷!	$ð 	$ús   ªC5Ã5C>)T)r   zdict[str, list[nn.Module]]r   Úbool)r"   zdict[str, Tensor])ÚreturnÚint)rN   z!list[str] | list[tuple[str, str]])r6   r7   Ú__qualname__r   r$   r&   r=   rM   ÚstaticmethodrT   Ú__classcell__)r   s   @r   r	   r	      s3   ø„ öK'óZóòó:Ið ñó ôr   r	   )Ú
__future__r   r?   r9   Úcollectionsr   Útorchr   r   Úsentence_transformers.utilr   Ú
Sequentialr	   © r   r   ú<module>rj      s)   ðÝ "ã Û 	Ý #ç å 9ô\ˆ2�=‰=õ \r   