Ë
    l^(ho&  ã                  ó®   — d dl mZ d dlZd dlZd dlmZ d dlZd dlZd dl	m
Z d dl	mZ d dlmZ d dlmZ d dlmZ d d	lmZ  G d
„ dej*                  «      Zy)é    )ÚannotationsN)ÚPath)Ú	load_file)Ú	save_file)Ú	Tokenizer)Únn)ÚPreTrainedTokenizerFast)Úget_device_namec                  óÂ   ‡ — e Zd Z	 	 d	 	 	 	 	 	 	 dˆ fd„Zdd„Zdd„Zdd„Zedd„«       Zdd„Z	ddd„Z
dd„Ze	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dd	„«       Zedd
„«       Zˆ xZS )ÚStaticEmbeddingc                óŒ  •— t         ‰| �  «        t        |t        «      r|j                  }nt        |t
        «      st        d«      ‚|�Vt        |t        j                  «      rt        j                  |«      }t        j                  j                  |d¬«      | _        n7|�*t        j                  |j                  «       |«      | _        nt        d«      ‚| j                  j                   | _        | j                  j"                  | _        || _        | j$                  j'                  «        |j)                  dd«      | _        y)a  
        Initializes the StaticEmbedding model given a tokenizer. The model is a simple embedding bag model that
        takes the mean of trained per-token embeddings to compute text embeddings.

        Args:
            tokenizer (Tokenizer | PreTrainedTokenizerFast): The tokenizer to be used. Must be a fast tokenizer
                from ``transformers`` or ``tokenizers``.
            embedding_weights (np.ndarray | torch.Tensor | None, optional): Pre-trained embedding weights.
                Defaults to None.
            embedding_dim (int | None, optional): Dimension of the embeddings. Required if embedding_weights
                is not provided. Defaults to None.

        Example::

            from sentence_transformers import SentenceTransformer
            from sentence_transformers.models import StaticEmbedding
            from tokenizers import Tokenizer

            # Pre-distilled embeddings:
            static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
            # or distill your own embeddings:
            static_embedding = StaticEmbedding.from_distillation("BAAI/bge-base-en-v1.5", device="cuda")
            # or start with randomized embeddings:
            tokenizer = Tokenizer.from_pretrained("FacebookAI/xlm-roberta-base")
            static_embedding = StaticEmbedding(tokenizer, embedding_dim=512)

            model = SentenceTransformer(modules=[static_embedding])

            embeddings = model.encode(["What are Pandas?", "The giant panda, also known as the panda bear or simply the panda, is a bear native to south central China."])
            similarity = model.similarity(embeddings[0], embeddings[1])
            # tensor([[0.8093]]) (If you use potion-base-8M)
            # tensor([[0.6234]]) (If you use the distillation method)
            # tensor([[-0.0693]]) (For example, if you use randomized embeddings)

        Raises:
            ValueError: If the tokenizer is not a fast tokenizer.
            ValueError: If neither `embedding_weights` nor `embedding_dim` is provided.
        zŒThe tokenizer must be fast (i.e. Rust-backed) to use this class. Use Tokenizer.from_pretrained() from `tokenizers` to load a fast tokenizer.NF)Úfreezez?Either `embedding_weights` or `embedding_dim` must be provided.Ú
base_model)ÚsuperÚ__init__Ú
isinstancer	   Ú
_tokenizerr   Ú
ValueErrorÚnpÚndarrayÚtorchÚ
from_numpyr   ÚEmbeddingBagÚfrom_pretrainedÚ	embeddingÚget_vocab_sizeÚnum_embeddingsÚembedding_dimÚ	tokenizerÚ
no_paddingÚgetr   )Úselfr   Úembedding_weightsr   ÚkwargsÚ	__class__s        €új/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/sentence_transformers/models/StaticEmbedding.pyr   zStaticEmbedding.__init__   s  ø€ ôZ 	‰ÑÔä�iÔ!8Ô9Ø!×,Ñ,‰IÜ˜I¤yÔ1Üð^óð ð
 Ð(ÜÐ+¬R¯Z©ZÔ8Ü$)×$4Ñ$4Ð5FÓ$GÐ!äŸ_™_×<Ñ<Ð=NÐW\Ð<Ó]ˆD�NØÐ&ÜŸ_™_¨Y×-EÑ-EÓ-GÈÓWˆD�NäÐ^Ó_Ð_à"Ÿn™n×;Ñ;ˆÔØ!Ÿ^™^×9Ñ9ˆÔà$-ˆŒØ�‰×!Ñ!Ô#ð !Ÿ*™* \°4Ó8ˆ�ó    c                óœ  — | j                   j                  |d¬«      }|D �cg c]  }|j                  ‘Œ }}t        j                  t        j                  dg|d d D �cg c]  }t        |«      ‘Œ c}z   «      «      }t        j                  |D ��cg c]  }|D ]  }|‘Œ Œ c}}t        j                  ¬«      }	|	|dœS c c}w c c}w c c}}w )NF)Úadd_special_tokensr   éÿÿÿÿ)Údtype)Ú	input_idsÚoffsets)
r   Úencode_batchÚidsr   r   r   ÚcumsumÚlenÚtensorÚlong)
r"   Útextsr$   Ú	encodingsÚencodingÚencodings_idsÚ	token_idsr-   Útoken_idr,   s
             r&   ÚtokenizezStaticEmbedding.tokenize]   s±   € Ø—N‘N×/Ñ/°È%Ð/ÓPˆ	Ø6?Ö@¨(˜Ÿ›Ð@ˆÐ@ä×"Ñ"¤2§9¡9¨a¨SÐTaÐbeÐceÐTfÖ3gÀy´C¸	µNÒ3gÑ-gÓ#hÓiˆÜ—L‘L¸M×!d¨yÐZcÒ!dÈh¢(Ð!d (Ó!dÔlq×lvÑlvÔwˆ	Ø&°7Ñ;Ð;ùò	 Aùâ3gùÛ!ds   ¢B>ÁCÂC
c                ó<   — | j                  |d   |d   «      |d<   |S )Nr,   r-   Úsentence_embedding)r   )r"   Úfeaturesr$   s      r&   ÚforwardzStaticEmbedding.forwarde   s(   € Ø)-¯©¸ÀÑ8MÈxÐXaÑObÓ)cˆÐ%Ñ&Øˆr'   c                ó   — i S ©N© ©r"   s    r&   Úget_config_dictzStaticEmbedding.get_config_dicti   s   € Øˆ	r'   c                ó"   — t         j                  S r@   )ÚmathÚinfrB   s    r&   Úmax_seq_lengthzStaticEmbedding.max_seq_lengthl   s   € ä�x‰xˆr'   c                ó   — | j                   S r@   )r   rB   s    r&   Ú get_sentence_embedding_dimensionz0StaticEmbedding.get_sentence_embedding_dimensionp   s   € Ø×!Ñ!Ð!r'   c                ó^  — |r9t        | j                  «       t        j                  j	                  |d«      «       nBt        j                  | j                  «       t        j                  j	                  |d«      «       | j                  j                  t        t        |«      dz  «      «       y )Númodel.safetensorsúpytorch_model.binútokenizer.json)
Úsave_safetensors_fileÚ
state_dictÚosÚpathÚjoinr   Úsaver   Ústrr   )r"   Úsave_dirÚsafe_serializationr$   s       r&   rS   zStaticEmbedding.saves   sl   € ÙÜ! $§/¡/Ó"3´R·W±W·\±\À(ÐL_Ó5`Õaä�J‰J�t—‘Ó(¬"¯'©'¯,©,°xÐATÓ*UÔVØ�‰×ÑœC¤ X£Ð1AÑ AÓBÕCr'   c                ó  — t        j                  t        t        | «      dz  «      «      }t        j
                  j                  t        j
                  j                  | d«      «      r*t        t        j
                  j                  | d«      «      }nIt        j                  t        j
                  j                  | d«      t        j                  d«      d¬«      }	 |d   }t        ||¬	«      S # t        $ r |d   }Y Œw xY w)
NrM   rK   rL   ÚcpuT)Úmap_locationÚweights_onlyzembedding.weightÚ
embeddings)r#   )r   Ú	from_filerT   r   rP   rQ   ÚexistsrR   Úload_safetensors_filer   ÚloadÚdeviceÚKeyErrorr   )Úload_dirr$   r   Úweightss       r&   r_   zStaticEmbedding.loadz   sÅ   € Ü×'Ñ'¬¬D°«NÐ=MÑ,MÓ(NÓOˆ	Ü�7‰7�>‰>œ"Ÿ'™'Ÿ,™, xÐ1DÓEÔFÜ+¬B¯G©G¯L©L¸ÐCVÓ,WÓX‰Gä—j‘jÜ—‘—‘˜XÐ':Ó;Ì%Ï,É,ÐW\ÓJ]ÐlpôˆGð	,ØÐ0Ñ1ˆGô ˜y¸GÔDÐDøô ò 	,à˜lÑ+ŠGð	,ús   ÃC. Ã.C?Ã>C?c                óR  — 	 ddl m} t        «       } |||||||¬«      }t	        |j
                  t        j                  «      r t        j                  |j
                  «      }	n|j
                  j                  }	|j                  }
 | |
|	|¬«      S # t        $ r t        d«      ‚w xY w)a  
        Creates a StaticEmbedding instance from a distillation process using the `model2vec` package.

        Args:
            model_name (str): The name of the model to distill.
            vocabulary (list[str] | None, optional): A list of vocabulary words to use. Defaults to None.
            device (str): The device to run the distillation on (e.g., 'cpu', 'cuda'). If not specified,
                the strongest device is automatically detected. Defaults to None.
            pca_dims (int | None, optional): The number of dimensions for PCA reduction. Defaults to 256.
            apply_zipf (bool): Whether to apply Zipf's law during distillation. Defaults to True.
            use_subword (bool): Whether to use subword tokenization. Defaults to True.

        Returns:
            StaticEmbedding: An instance of StaticEmbedding initialized with the distilled model's
                tokenizer and embedding weights.

        Raises:
            ImportError: If the `model2vec` package is not installed.
        r   )Údistillz\To use this method, please install the `model2vec` package: `pip install model2vec[distill]`)Ú
vocabularyr`   Úpca_dimsÚ
apply_zipfÚuse_subword©r#   r   )Úmodel2vec.distillre   ÚImportErrorr
   r   r   r   r   r   r   Úweightr   )ÚclsÚ
model_namerf   r`   rg   rh   ri   re   Ústatic_modelr#   r   s              r&   Úfrom_distillationz!StaticEmbedding.from_distillation‰   s«   € ð<	Ý1ô !Ó"ˆÙØØ!ØØØ!Ø#ô
ˆô �l×,Ñ,¬b¯j©jÔ9Ü %× 0Ñ 0°×1GÑ1GÓ HÑà ,× 6Ñ 6× =Ñ =ÐØ+×5Ñ5ˆ	á�9Ð0AÈjÔYÐYøô) ò 	ÜØnóð ð	ús   ‚B ÂB&c                óD  — 	 ddl m} |j                  |«      }t	        |j
                  t        j                  «      r t        j                  |j
                  «      }n|j
                  j                  }|j                  } | |||¬«      S # t        $ r t        d«      ‚w xY w)aH  
        Create a StaticEmbedding instance from a model2vec model. This method loads a pre-trained model2vec model
        and extracts the embedding weights and tokenizer to create a StaticEmbedding instance.

        Args:
            model_id_or_path (str): The identifier or path to the pre-trained model2vec model.

        Returns:
            StaticEmbedding: An instance of StaticEmbedding initialized with the tokenizer and embedding weights
                 the model2vec model.

        Raises:
            ImportError: If the `model2vec` package is not installed.
        r   )ÚStaticModelzSTo use this method, please install the `model2vec` package: `pip install model2vec`rj   )Ú	model2vecrs   rl   r   r   r   r   r   r   r   rm   r   )rn   Úmodel_id_or_pathrs   rp   r#   r   s         r&   Úfrom_model2veczStaticEmbedding.from_model2vec¿   s–   € ð"	uÝ-ð #×2Ñ2Ð3CÓDˆÜ�l×,Ñ,¬b¯j©jÔ9Ü %× 0Ñ 0°×1GÑ1GÓ HÑà ,× 6Ñ 6× =Ñ =ÐØ+×5Ñ5ˆ	á�9Ð0AÐN^Ô_Ð_øô ò 	uÜÐsÓtÐtð	uús   ‚B
 Â
B)NN)r   z#Tokenizer | PreTrainedTokenizerFastr#   z np.ndarray | torch.Tensor | Noner   ú
int | NoneÚreturnÚNone)r4   z	list[str]rx   údict[str, torch.Tensor])r=   rz   rx   rz   )rx   zdict[str, float])rx   Úint)T)rU   rT   rV   Úboolrx   ry   )rb   rT   rx   r   )NNé   TT)ro   rT   rf   zlist[str] | Noner`   z
str | Nonerg   rw   rh   r|   ri   r|   rx   r   )ru   rT   rx   r   )Ú__name__Ú
__module__Ú__qualname__r   r:   r>   rC   ÚpropertyrG   rI   rS   r_   Úclassmethodrq   rv   Ú__classcell__)r%   s   @r&   r   r      sú   ø„ ð ?CØ$(ð	H9à6ðH9ð <ðH9ð "ð	H9ð 
õH9óT<óóð òó ðó"ôDóEð ð (,Ø!Ø"ØØ ð3Zàð3Zð %ð3Zð ð	3Zð
 ð3Zð ð3Zð ð3Zð 
ò3Zó ð3Zðj ò`ó ô`r'   r   )Ú
__future__r   rE   rP   Úpathlibr   Únumpyr   r   Úsafetensors.torchr   r^   r   rN   Ú
tokenizersr   r   Útransformersr	   Úsentence_transformers.utilr
   ÚModuler   rA   r'   r&   ú<module>rŒ      s=   ðÝ "ã Û 	Ý ã Û Ý @Ý @Ý  Ý Ý 0å 6ôJ`�b—i‘iõ J`r'   