
    Nj-              	         d dl mZ d dl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mZmZ d dlmZ d d	lmZmZmZmZmZ d d
lmZ d dlmZ d dlmZmZ d dl m!Z!m"Z" d dl#m$Z$  ejJ                  e&      Z'dddddejP                  dejR                  f	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ*	 	 	 	 	 	 ddZ+ddddddejP                  dejR                  f		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ,y)    )annotationsN)cast)
model_info)TokenizerModel)reshape_embeddings)	AutoModelAutoTokenizerPreTrainedTokenizerFast)PreTrainedModel)
PCADimTypePoolingMode	apply_pcacompute_weightscreate_embeddings)select_optimal_device)StaticModel)DTypequantize_embeddings)clean_and_create_vocabularyturn_tokens_into_ids)quantize_vocabulary   g-C6?z\[unused\d+\]c
           
     h   t        |      }t        ||      \  }}
|g }t        |      }t        j                  |      }|j                         }|j                         }|j                  d|_        t        |||
      }|j                  }|st        d      t        ||      }t        | |      } t        || ||j                  xs d|	      }|5t        t!        |      |      }t#        |||      \  }}}t%        ||      }n2t        t!        |      |      }t%        ||      }||dddf   z  }d}d}t'        ||      }t)        | d	d
      }ddg||||j*                  d   dd|	d	}t,        j.                  j1                  |      r"t,        j.                  j3                  |      }d}n6	 t5        |      }|j6                  |j6                  j9                  dd      nd}tA        ||||jC                         |||d      S # t:        $ r%}t<        j?                  d| d       d}Y d}~Jd}~ww xY w)a  Distill a staticmodel from a sentence transformer.

    This function creates a set of embeddings from a sentence transformer. It does this by doing either
    a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
    vocabulary.

    If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
    If you don't pass a vocabulary, we use the model's tokenizer directly.

    :param model: The model to use.
    :param tokenizer: The tokenizer to use.
    :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
    :param device: The device to use.
    :param pca_dims: The number of components to use for PCA.
        If this is None, we don't apply PCA.
        If this is 'auto', we don't reduce dimensionality, but still apply PCA.
    :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
        Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.
    :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
        this regex pattern will be removed from the vocabulary.
        If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled
        into a valid regex, we also throw an error.
    :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
    :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no
         quantization is performed.
    :param pooling: The pooling mode to use for creating embeddings. Can be one of:
        'mean' (default): mean over all tokens. Robust and works well in most cases.
        'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.
        'first': use the first token's hidden state ([CLS] token in BERT-style models).
        'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.
    :return: A StaticModel.
    :raises ValueError: if the vocabulary is empty after preprocessing.

    NT)token_remove_regexzTThe vocabulary is empty after preprocessing. Please check your token_remove_pattern.r   )	tokenizedmodeldevicepad_token_idpooling)sif_coefficient)
n_clustersweights
embeddingsname_or_path 	model2vecr      i@B )	
model_typearchitecturestokenizer_namer   r    
hidden_dim
seq_length	normalizer   languagez7Couldn't get the model info from the Hugging Face Hub: z. Setting language to None.)vectorsr"   token_mapping	tokenizerconfigbase_model_namer.   r-   )"r   _validate_parametersr   r   from_transformers_tokenizerprune_added_tokens	deep_copyadds_prefix_spacer   sorted_vocabulary
ValueErrorr   r   r   r   r   lenr   r   r   getattrshapeospathexistsbasenamer   cardDataget	Exceptionloggerwarningr   to_tokenizer)r   r1   
vocabularyr   pca_dimsr    token_remove_patternquantize_tovocabulary_quantizationr   r   original_tokenizer_modeltokenizer_model
all_tokens	token_idsr#   r"   r0   
model_namer2   r.   infoes                          o/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/model2vec/distill/distillation.pydistill_from_modelrU      sl   \ $K*>Pd*e'O'
"6*F-II)T7JJL /88:O((4,0) 2/:btuO !22Jopp %Z1IJI u&>?E #-::?aJ *!#j/?S-@.J.
*
M7 z84
 "#j/?Sz84
'!T'"22
$Z=J3J "'$* &&q)
F 
ww~~j!WW%%j1
	j)D>Bmm>Wt}}((T:]aH #!..0"	 	  	NNTUVTWWrstH	s   -5H 	H1H,,H1c                    | "d| cxk  rdk  st        d       t        d      d}|	 t        j                  |      }| |fS | |fS # t        j                  $ r}t        d|       |d}~ww xY w)a	  Validate the parameters passed to the distillation function.

    :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
        Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
    :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
        this regex pattern will be removed from the vocabulary.
    :return: The SIF coefficient to use.
    :raises ValueError: if the regex can't be compiled.

    Nr   g      ?z.SIF coefficient must be a value > 0 and < 1.0.z$Couldn't compile the regex pattern: )r:   recompileerror)r    rJ   r   rS   s       rT   r4   r4      s     "?(S(MNN )MNN15'	P!#,@!A ...?... xx 	PCA3GHaO	Ps   A A.A))A.Fc
                    t        j                  | |      }
t        t        t	        j                  | |d            }t        |
|||||||||	
      S )a  Distill a staticmodel from a sentence transformer.

    This function creates a set of embeddings from a sentence transformer. It does this by doing either
    a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
    vocabulary.

    If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
    If you don't pass a vocabulary, we use the model's tokenizer directly.

    :param model_name: The model name to use. Any sentencetransformer compatible model works.
    :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
    :param device: The device to use.
    :param pca_dims: The number of components to use for PCA.
        If this is None, we don't apply PCA.
        If this is 'auto', we don't reduce dimenionality, but still apply PCA.
    :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
        Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
    :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
        this regex pattern will be removed from the vocabulary.
    :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming
        from `transformers`. If this is True, we will load all components.
    :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
    :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no
        quantization is performed.
    :param pooling: The pooling mode to use for creating embeddings. Can be one of:
        'mean' (default): mean over all tokens. Robust and works well in most cases.
        'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.
        'first': use the first token's hidden state ([CLS] token in BERT-style models).
        'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.
    :return: A StaticModel

    )trust_remote_codeT)r[   use_fast)
r   r1   rH   r   rI   rJ   r    rK   rL   r   )r   from_pretrainedr   r
   r	   rU   )rQ   rH   r   rI   r    rJ   r[   rK   rL   r   r   r1   s               rT   distillr^      sf    X '66zUfgE%%jDU`deI
 1' 7     )r   r   r1   r
   rH   list[str] | Noner   
str | NonerI   r   r    float | NonerJ   ra   rK   DType | strrL   
int | Noner   PoolingMode | strreturnr   )r    rb   rJ   ra   rf   z+tuple[float | None, re.Pattern[str] | None])rQ   strrH   r`   r   ra   rI   r   r    rb   rJ   ra   r[   boolrK   rc   rL   rd   r   re   rf   r   )-
__future__r   loggingr>   rW   typingr   huggingface_hub.hf_apir   
skeletokenr    skeletoken.external.transformersr   transformersr   r	   r
   transformers.modeling_utilsr   model2vec.distill.inferencer   r   r   r   r   model2vec.distill.utilsr   model2vec.modelr   model2vec.quantizationr   r   model2vec.tokenizerr   r   !model2vec.vocabulary_quantizationr   	getLogger__name__rE   Float16MEANrU   r4   r^    r_   rT   <module>r|      s   "  	 	  - % ? J J 7 n n 9 ' = Q A			8	$ $($('7$}}*.!,!1!1KK&K !K 	K
 K "K %K K (K K K\/!/$/ 1/< $($('7#$}}*.!,!1!1== = = 	=
 "= %= = = (= = =r_   