ó
    pyüi÷, ã            
       ó€  • S SK r S SKrS SKJr  S SKJrJrJrJr  S SK	r
S SKrS SKJr  SSKJr  SSKJrJr  SSKJr  SS	KJrJrJr  \" 5       (       a  S S
KJr  \(       a  SSKJr  SSKJr  SSKJr   " S S5      r " S S\5      r  " S S\ 5      r! " S S\RD                  5      r# " S S\RD                  5      r$ " S S5      r% " S S5      r& " S S\!5      r' " S S\5      r( " S S \ 5      r) " S! S"\ 5      r*S#\+\,\4   S$\-S%\.S&\+\,\4   4S' jr/S#\+\,\4   S$\-S%\.S&\+\,\4   4S( jr0S#\+\,\4   S$\-S&\+\,\4   4S) jr1g)*é    N)ÚIterable)ÚTYPE_CHECKINGÚAnyÚOptionalÚcasté   )Úprune_linear_layer)ÚModelOutputÚis_sklearn_availableé   )ÚGenerationConfig)ÚLogitsProcessorListÚMinLengthLogitsProcessorÚSuppressTokensLogitsProcessor)Ú	roc_curve)ÚPreTrainedModel)ÚPreTrainedTokenizerBasec                   ó¾   • \ rS rSr% SrSr\\S'   S\R                  S\
\R                  \R                  4   4S jrS\R                  S\R                  S	\4S
 jrSrg)ÚCandidateGeneratoré'   z`Abstract base class for all candidate generators that can be applied during assisted generation.FÚrequires_model_outputsÚ	input_idsÚreturnc                 ó2   • [        U R                   S35      e)a  
Fetches the candidates to be tried for the current input.

Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)

Return:
    `torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
    assessed by the model and, optionally, a `torch.FloatTensor` of shape `(batch_size, candidate_length,
    vocabulary_size)` containing the logits associated to each candidate.
zT is an abstract class. Only classes inheriting this class can call `get_candidates`.©ÚNotImplementedErrorÚ	__class__)Úselfr   Úkwargss      Úh/home/mande/repo/quber/.venv/lib/python3.13/site-packages/transformers/generation/candidate_generator.pyÚget_candidatesÚ!CandidateGenerator.get_candidates,   s!   € ô "Ø�~‰~ÐÐrÐsó
ð 	
ó    ÚscoresÚnum_matchesc                 ó2   • [        U R                   S35      e)á’  
Updates the candidate generation strategy based on the outcomes.

Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
    scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
        Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
        beam search or log softmax for each vocabulary token when using beam search
    num_matches (`int`):
        The number of matches between the candidate sequences and the model predictions.
z_ is an abstract class. Only classes inheriting this class can call `update_candidate_strategy`.r   ©r   r   r$   r%   s       r    Úupdate_candidate_strategyÚ,CandidateGenerator.update_candidate_strategy=   s%   € ô "Ø�~‰~Ðð +ð +ó
ð 	
r#   © N)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   ÚboolÚ__annotations__ÚtorchÚ
LongTensorÚtupleÚFloatTensorr!   Úintr)   Ú__static_attributes__r+   r#   r    r   r   '   sg   ‡ Ùjà#(Ð˜DÓ(ð
¨×(8Ñ(8ð 
ÀuÈU×M]ÑM]Ð_d×_pÑ_pÐMpÑGqô 
ð"
°5×3CÑ3Cð 
ÈU×M^ÑM^ð 
Ðmp÷ 
r#   r   c                   óè  • \ rS rSrSr  SS\R                  SSSSS	\S
\R                  S-  S\	S   4S jjr
S\R                  S\\R                  \R                  4   4S jrS\R                  S\R                  S\4S jrS\R                  S\\\4   4S jr SS\R                  S\S\S\4S jjrS\R                  S\S\S\4S jrS\S\\R                  \R                  S-  4   4S jrSrg)ÚAssistedCandidateGeneratoréP   a&  
`CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates
candidates through the use of a smaller model. Read the following blog post for more information:
https://huggingface.co/blog/assisted-generation

Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
    assistant_model (`PreTrainedModel`):
        The model to be used for generating candidates. This model should be smaller than the main model.
    generation_config (`~generation.GenerationConfig`, *optional*):
        The generation configuration to be used as base parametrization for the generation call.
    logits_processor (`LogitsProcessorList`):
        An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
        used to modify the prediction scores of the language modeling head applied at each generation step.
    model_kwargs (`Dict`):
        The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
        model as well.
    inputs_tensor (`torch.Tensor`, *optional*):
        The model input tensor. In encoder-decoder models, this is the encoder input.
Nr   Úassistant_modelr   Úgeneration_configr   Úmodel_kwargsÚinputs_tensorÚlogits_processorr   c           	      ó&  • UR                   nUR                  U5      nUb  UR                  U5      nX l        [        R                  " UR
                  5      U l        U R                  R                  5       nU R                  R                  " S0 UDSS0D6  U R                  R                  U l	        U R                  R                  U l
        UR                  U R                  l        0 n	UR                  5        Hc  u  p«U
S;  d  M  [        U[        R                  5      (       a  UR!                  5       R                  U5      O[        R                  " U5      Xš'   Me     SU	;   a  UR#                  5       (       d  U	S	 UR$                  R&                  (       aF  UR)                  XPR                  R*                  U	5      u  p\n	UR-                  XYXÀR                  5      n	OSU;   a  US   U	S'   X�l        UR$                  R&                  (       a  SU l        OySU	;   al  SU l        U R.                  R3                  S[        R4                  " UR6                  S	   S
4UR                   [        R8                  S95      U R.                  S'   OSU l        Ub  UO	[;        5       U l        [        R                  " U5      U l        SU R
                  l        SU R
                  l         U R                  U R
                  l
        SU R
                  l!        U R
                  RD                  U l#        S U R
                  l"        S U R
                  l$        U R
                  RJ                  U l&        S U R
                  l%        U R<                   Vs/ s H  n[        U[N        5      (       a  M  UPM     snU l        SU R
                  l(        [S        5       (       a>  U R                  R                  (       a"  [U        U 5      [V        L a  / U l,        / U l-        g g g g s  snf )NÚdefaults_onlyT)Úencoder_outputsÚpast_key_valuesÚlogits_to_keeprC   Údecoder_input_idsr   Údecoder_attention_maskr   r   ©ÚdeviceÚdtypeÚattention_maskÚdynamic_fullr+   ).rI   Útor<   ÚcopyÚdeepcopyr=   Úassistant_generation_configÚ_get_default_generation_paramsÚupdateÚnum_assistant_tokensÚassistant_confidence_thresholdÚeos_token_idÚitemsÚ
isinstancer3   ÚTensorÚdetachÚ_supports_logits_to_keepÚconfigÚis_encoder_decoderÚ_prepare_model_inputsÚbos_token_idÚ._prepare_encoder_decoder_kwargs_for_generationÚassistant_kwargsÚinput_ids_keyÚgetÚonesÚshapeÚlongr   r@   Úreturn_dict_in_generateÚoutput_scoresÚis_assistantÚ
min_lengthÚmain_model_min_lengthÚmin_new_tokensÚ
max_lengthÚmain_model_max_lengthr   Úcache_implementationr   Útyper:   ÚprobsÚmatches)r   r   r<   r=   r>   r?   r@   rI   Úglobal_defaultsr`   ÚkeyÚvalueÚmodel_input_nameÚ	processors                 r    Ú__init__Ú#AssistedCandidateGenerator.__init__g   s‰  € ð !×'Ñ'ˆØ—L‘L Ó(ˆ	ØÑ$Ø)×,Ñ,¨VÓ4ˆMð  /Ôô ,0¯=ª=¸×9ZÑ9ZÓ+[ˆÔ(Ø×:Ñ:×YÑYÓ[ˆØ×(Ñ(×/Ò/ÑV°/ÑVÐQUÓVØ$(×$DÑ$D×$YÑ$YˆÔ!Ø.2×.NÑ.N×.mÑ.mˆÔ+ð 9J×8VÑ8Vˆ×(Ñ(Ô5ð ÐØ&×,Ñ,Ö.‰JˆCØÐ@Õ@ä1;¸EÄ5Ç<Á<×1PÑ1P�E—L‘L“N×%Ñ% fÔ-ÔVZ×VcÒVcÐdiÓVjð !Ó%ñ /ð Ð/Ó/¸×8`Ñ8`×8bÑ8bØ Ð!1Ð2ð ×!Ñ!×4×4Ø@O×@eÑ@eØ×?Ñ?×LÑLÐN^óAÑ=ˆMÐ-=ð  /×]Ñ]ØÐ1A×CcÑCcó Ñð  ,Ó.Ø2>Ð?PÑ2QÐÐ.Ñ/Ø 0Ôð ×!Ñ!×4×4à!4ˆDÕØÐ"2Ó2à!,ˆDÔØ6:×6KÑ6K×6OÑ6OØ(Ü—
’
˜IŸO™O¨AÑ.°Ð2¸9×;KÑ;KÔSX×S]ÑS]Ñ^ó7ˆD×!Ñ!Ð"2Ò3ð "-ˆDÔð 5EÑ4PÑ 0ÔViÓVkˆÔÜ!%§¢Ð/@Ó!AˆÔà9=ˆ×ÑÔ6Ø/3ˆ×ÑÔ,Ø@D×@cÑ@cˆ×ÑÔ=à.2ˆ×ÑÔ+ð &*×%;Ñ%;×%FÑ%FˆÔ"Ø,0ˆ×ÑÔ)Ø04ˆ×ÑÔ-Ø%)×%;Ñ%;×%FÑ%FˆÔ"Ø,0ˆ×ÑÔ)à'+×'<Ò'<ó!
Ú'<˜)ÄJÈyÔZr×Ds�IÑ'<ñ!
ˆÔð
 7Eˆ×ÑÔ3ô !×"Ñ"Ø×0Ñ0×O×OÜ�T“
Ô8Ò8àˆDŒJØˆD�Lð 9ð Pð #ùò!
s   ÎPÎ!Pr   c                 óø   • UR                  U R                  R                  5      nU R                  U5      u  p4US:X  a  US4$ U R	                  U5        U R                  XU5      nU R                  U5      u  pgXg4$ )á  
Fetches the candidates to be tried for the current input.

Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)

Return:
    `torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
    assessed by the model and a `torch.FloatTensor` of shape `(batch_size, candidate_length,
    vocabulary_size)` containing the logits associated to each candidate.
r   N)rM   r<   rI   Ú_calculate_new_tokensÚ_update_past_and_masksÚ_prepare_generation_argsÚ_generate_candidates)r   r   r   rk   Úmax_new_tokensÚgeneration_argsÚcandidate_idsÚcandidate_logitss           r    r!   Ú)AssistedCandidateGenerator.get_candidatesÊ   s€   € ð —L‘L ×!5Ñ!5×!<Ñ!<Ó=ˆ	à)-×)CÑ)CÀIÓ)NÑ&ˆØ˜QÓØ˜d�?Ð"à×#Ñ# IÔ.à×7Ñ7¸	ÐSaÓbˆØ*.×*CÑ*CÀOÓ*TÑ'ˆØÐ.Ð.r#   r$   r%   c                 óÊ  • U R                   R                  S;   aI  U[        US   5      S-
  :X  a  U =R                  S-  sl        O[	        SU R                  S-
  5      U l        [        5       (       Gap  U R                   R                  (       GaS  [        U 5      [        L Ga?  U R                  R                  S/U-  5        [        U R                  5      [        U R                  5      :”  a  U R                  R                  S5        [        U R                  5      [        U R                  5      -
  nUS:”  a  U R                  U* S2	 [        U R                  5      S:”  a~  SS1R                  U R                  5      (       a[  [        U R                  U R                  5      u  pVnSU-
  nUSU-  -   n	[        R                   " U	5      n
Xz   nX°R                   l        gggggg)r'   >   Ú	heuristicÚheuristic_transientr   r   r   Né   é   )rP   Únum_assistant_tokens_scheduleÚlenrS   Úmaxr   rT   ro   r:   rq   Úextendrp   ÚappendÚissubsetr   ÚnpÚargmin)r   r   r$   r%   Úexcess_lengthÚfprÚtprÚ
thresholdsÚfnrÚcostsÚoptimal_threshold_indexÚbest_thresholds               r    r)   Ú4AssistedCandidateGenerator.update_candidate_strategyã   sœ  € ð  ×+Ñ+×IÑIð N
ó 
ð
 œc &¨¡)›n¨qÑ0Ó0Ø×)Ò)¨QÑ.Ö)ä,/°°4×3LÑ3LÈqÑ3PÓ,Q�Ô)ô
 !×"Ò"Ø×0Ñ0×O×OÐOÜ�T“
Ô8Ó8ð �L‰L×Ñ   kÑ 1Ô2Ü�4—:‘:‹¤ T§\¡\Ó!2Ó2Ø—‘×#Ñ# AÔ&ô   §
¡
›O¬c°$·,±,Ó.?Ñ?ˆMØ˜qÓ Ø—J‘J ˜~™Ð/ô �D—J‘J“ !Ó#¨¨A¨¯©¸¿¹×(EÑ(Eä'0°·±¸t¿z¹zÓ'JÑ$�˜*Ø˜#‘g�ð ˜a #™g™�ô +-¯)ª)°EÓ*:Ð'Ø!+Ñ!D�àR`×0Ñ0ÕOð )FÐ#ð 9ð Pð #r#   c                 óÈ   • UR                   S   n[        [        U R                  5      U R                  U-
  S-
  5      n[        [        X0R                  U-
  5      S5      nXC4$ )zCCalculate the minimum and maximum number of new tokens to generate.éÿÿÿÿr   r   )rd   Úminr7   rS   rm   r‹   rj   )r   r   Únew_cur_lenr   rk   s        r    r{   Ú0AssistedCandidateGenerator._calculate_new_tokens  s_   € à—o‘o bÑ)ˆÜœS ×!:Ñ!:Ó;¸T×=WÑ=WÐZeÑ=eÐhiÑ=iÓjˆÜœS ×1KÑ1KÈkÑ1YÓZÐ\]Ó^ˆØÐ-Ð-r#   Úremove_from_pkvÚnum_added_tokensc                 óH  • U R                   R                  SS5      SLnU(       aü  UR                  S   S-
  U-
  nU R                   S   R                  XS-
  5        [	        U R                   UR                  S   U R
                  R                  R                  5      U l         [        U R                   UR                  S   U R
                  R                  R                  5      U l         [        U R                   UR                  S   5      U l         SU R                  l        U$ )zLUpdate past key values and attention masks for subsequent generation rounds.rD   Nr›   r   )r`   rb   rd   ÚcropÚ_prepare_attention_maskr<   r[   r\   Ú_prepare_position_idsÚ_prepare_token_type_idsr=   rn   )r   r   rŸ   r    Úhas_past_key_valuesÚnew_cache_sizes         r    r|   Ú1AssistedCandidateGenerator._update_past_and_masks$  s  € ð #×3Ñ3×7Ñ7Ð8IÈ4ÓPÐX\Ð\ÐÞØ&Ÿ_™_¨RÑ0°1Ñ4°ÑFˆNØ×!Ñ!Ð"3Ñ4×9Ñ9¸.Ñ:[Ô\Ü$;Ø×%Ñ% y§¡°rÑ':¸D×<PÑ<P×<WÑ<W×<jÑ<jó%ˆDÔ!ô %:Ø×%Ñ% y§¡°rÑ':¸D×<PÑ<P×<WÑ<W×<jÑ<jó%ˆDÔ!ô %<¸D×<QÑ<QÐS\×SbÑSbÐceÑSfÓ$gˆDÔ!ð ;?ˆD×"Ñ"Ô7à"Ð"r#   rk   r   c           
      óV   • U R                   USUSUSU R                  SU R                  0$ )z*Prepare arguments for the generation call.rk   r   r=   r@   )ra   r=   r@   )r   r   rk   r   s       r    r}   Ú3AssistedCandidateGenerator._prepare_generation_args:  s9   € ð ×Ñ 	Ø˜nØ˜nØ ×!7Ñ!7Ø × 5Ñ 5ð
ð 	
r#   r€   c                 ó’  • U R                   R                  " S0 UDU R                  D6nUR                  U R                  S'   [	        5       (       aÊ  U R
                  R                  (       a¯  [        U 5      [        L a�  [        R                  " UR                  SS9n[        R                  " USS9nUR                  S[        UR                  5      * S24   nU[        [        U5      5      U4   nU R                   R#                  UR%                  5       5        [        R&                  " UR                  SS9nUR                  nX‡4$ )z7Generate candidate sequences using the assistant model.rD   r   ©Údimr›   Nr   r+   )r<   Úgenerater`   rD   r   rP   rT   ro   r:   r3   Úcatr$   ÚsoftmaxÚ	sequencesrŠ   Úrangerp   rŒ   ÚtolistÚstack)	r   r€   Úassistant_outputÚscores_tensorÚscores_softmaxÚidsÚpr‚   r�   s	            r    r~   Ú/AssistedCandidateGenerator._generate_candidatesD  s  € à×/Ñ/×8Ò8Ñd¸?ÐdÈd×NcÑNcÑdÐØ3C×3SÑ3Sˆ×ÑÐ/Ñ0ä ×"Ñ"Ø×0Ñ0×O×OÜ�T“
Ô8Ò8ä!ŸIšIÐ&6×&=Ñ&=À1ÑEˆMÜ"Ÿ]š]¨=¸bÑAˆNØ"×,Ñ,¨R´#Ð6F×6MÑ6MÓ2NÐ1NÑ1PÐ-PÑQˆCØœu¤S¨£X›°Ð3Ñ4ˆAØ�J‰J×Ñ˜aŸh™h›jÔ)Ü Ÿ;š;Ð'7×'>Ñ'>ÀAÑFÐØ(×2Ñ2ˆØÐ.Ð.r#   )rT   rP   r`   r<   r=   ra   r@   rm   rj   rq   rS   rp   ©NN)r   r   )r,   r-   r.   r/   r0   r3   r4   ÚdictrX   r   rw   r5   r6   r!   r7   r)   r{   r1   r|   r}   r~   r8   r+   r#   r    r:   r:   P   st  † ñð8 .2Ø<@ñaà×#Ñ#ðað +ðað .ð	að
 ðað —|‘| dÑ*ðað #Ð#8Ñ9õaðF/¨×(8Ñ(8ð /ÀuÈU×M]ÑM]Ð_d×_pÑ_pÐMpÑGqô /ð28a°5×3CÑ3Cð 8aÈU×M^ÑM^ð 8aÐmpô 8aðt.¨u×/?Ñ/?ð .ÀEÈ#ÈsÈ(ÁOô .ð ^_ñ#Ø×)Ñ)ð#Ø<?ð#ØWZð#à	õ#ð,
°%×2BÑ2Bð 
ÐTWð 
Ðilð 
Ðquô 
ð/°Dð /¸UÀ5×CSÑCSÐUZ×UfÑUfÐimÑUmÐCmÑ=n÷ /r#   r:   c                   ó°  ^ • \ rS rSrSr  SS\R                  SSSSS	SS
SS\S\R                  S-  S\	S   4U 4S jjjr
\S 5       r\S 5       r\S 5       rS rS\R                  S\\R                  \R"                  4   4S jrS\R                  S\\R                  \4   4S jrS\R                  S\R                  S\R                  4S jrSrU =r$ )Ú-AssistedCandidateGeneratorDifferentTokenizersiW  a  
`CandidateGenerator` class to be used for Universal Assisted Generation (UAD): assisted generation with different tokenizers
for the assistant and main models. This class generates candidates through the use of a smaller
model.

The main model input tokens are re-encoded into assistant model tokens, then candidate tokens are generated in the assistant encoding, which are
in turn re-encoded into main model candidate tokens. Validation then proceeds as explained above.
The re-encoding steps involve decoding token ids into text and then encoding the text using a different tokenizer.
Since re-encoding the tokens may result in tokenization discrepancies, UAD finds the longest common subsequence between the source and target encodings,
to ensure the new tokens include the correct prompt suffix.

Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
    assistant_model (`PreTrainedModel`):
        The model to be used for generating candidates. This model should be smaller than the main model.
    target_tokenizer (`PreTrainedTokenizerBase`):
        The tokenizer used for the target model.
    assistant_tokenizer (`PreTrainedTokenizerBase`):
        The tokenizer used for the assistant model.
    generation_config (`~generation.GenerationConfig`, *optional*):
        The generation configuration to be used as base parametrization for the generation call.
    logits_processor (`LogitsProcessorList`):
        An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
        used to modify the prediction scores of the language modeling head applied at each generation step.
    model_kwargs (`Dict`):
        The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
        model as well.
    inputs_tensor (`torch.Tensor`, *optional*):
        The model input tensor. In encoder-decoder models, this is the encoder input.
Nr   r<   r   Útarget_tokenizerr   Úassistant_tokenizerr=   r   r>   r?   r@   r   c	                 óÈ   >• [         T	U ]  XXVXx5        X0l        X@l        S U l        S U l        U R                  R                  U l        U R                  R                  U l        g ©N)	Úsuperrw   r¿   rÀ   Úprev_target_ids_lenÚprev_assistant_idsrP   Útarget_lookbehindÚassistant_lookbehind)
r   r   r<   r¿   rÀ   r=   r>   r?   r@   r   s
            €r    rw   Ú6AssistedCandidateGeneratorDifferentTokenizers.__init__x  s\   ø€ ô 	‰Ñ˜Ð5FÐVcÔvà 0ÔØ#6Ô Ø/3ˆÔ Ø;?ˆÔØ!%×!AÑ!A×!SÑ!SˆÔØ$(×$DÑ$D×$YÑ$YˆÕ!r#   c                 ó  • [        5       n0 nU Hõ  n[        R                  " U5      n[        UR	                  5       5      nXb;   a  M9  UR                  U5        SnUS-  nUS   U R                  S   :  aŠ  US   U R                  S   :  at  [        UR	                  5       5      nUR                  U5        XS   US   4   S:X  a  US-  nUS-  nOO.US   U R                  S   :  a  US   U R                  S   :  a  Mt  XsU'   M÷     U$ )aŽ  
Calculates the length of the longest diagonal sequence in a given matrix.
Args:
    input_matrix (torch.Tensor): The input matrix.
    nonzero_idx (torch.Tensor): The indices of the non-zero elements in the matrix.
Returns:
    dict: A dictionary where the keys are the indices of the non-zero elements and the values are the lengths of the longest diagonal sequences starting from those indices.
r   r   )Úsetr3   Úcloner5   r³   Úaddrd   )Úinput_matrixÚnonzero_idxÚvisitedÚdiagsÚidxÚ	start_idxÚtuple_start_idxÚcur_diag_lens           r    Ú_get_longest_diag_dictÚDAssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_dictŒ  s  € ô “%ˆØˆÛˆCÜŸš CÓ(ˆIÜ# I×$4Ñ$4Ó$6Ó7ˆOàÓ)Ùà�K‰K˜Ô(ØˆLØ˜‰NˆIØ˜A‘, ×!3Ñ!3°AÑ!6Ó6¸9ÀQ¹<È,×J\ÑJ\Ð]^ÑJ_Ó;_Ü"'¨	×(8Ñ(8Ó(:Ó";�Ø—‘˜OÔ,à¨!¡¨i¸©lÐ :Ñ;¸qÓ@Ø  AÑ%�LØ ‘N‘Iàð ˜A‘, ×!3Ñ!3°AÑ!6Ó6¸9ÀQ¹<È,×J\ÑJ\Ð]^ÑJ_Õ;_ð &�#‹Jñ) ð* ˆr#   c                 óî   • [         R                  X R                  5       5      n[        UR	                  5       5      n[        UR                  5       5      n[        R                  " U5      nX4   nX$   nXV4$ )zå
Returns the start index and length of the longest diagonal in the given input.
Args:
    input_matrix (numpy.ndarray): The input matrix.
Returns:
    tuple: A tuple containing the start index and length of the longest diagonal.
)r¾   rÕ   ÚnonzeroÚlistÚvaluesÚkeysr�   Úargmax)rÍ   rÐ   Údiags_valuesÚ
diags_keysÚ	best_diagÚdiag_start_indexÚdiag_start_lengths          r    Ú_get_longest_diag_indexÚEAssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_index°  sk   € ô >×TÑTØ×.Ñ.Ó0ó
ˆô ˜EŸL™L›NÓ+ˆÜ˜%Ÿ*™*›,Ó'ˆ
Ü—I’I˜lÓ+ˆ	Ø%Ñ0ÐØ(Ñ3ÐØÐ2Ð2r#   c                 ó¼  • XR                   :H  n[        R                  " U5      (       d  [        R                  " U5      nUR	                  [
        5      nUR                  5       R                  5       (       d  g[        R                  U5      u  pEUS   U-   nUS   U-   nU R                  S   U-
  R                  5       nUSS2Xh-   S24   n	USS2XfU-   24   n
X‰U
4$ )ay  
Input:
    prompt: 2D array of shape (batch_size, prompt_length), represents the original prompt tokens
    prompt_plus_new_tokens: 2D array of shape (batch_size, prompt_length), represents the suffix of the original prompt, with additional new tokens.
Output:
    discrepancy_length: int, represents the number of tokens that need to be replaced from prompt
    new_tokens_only: 2D array of shape (batch_size, new_token_length), represents the new tokens that are not in prompt
    discrepancy_only: 2D array of shape (batch_size, discrepancy_length), represents the new tokens that are in prompt but not in prompt_plus_new_tokens
©NNNr   r   N)ÚTr3   Ú	is_tensorÚtensorrM   r7   ÚanyÚitemr¾   râ   rd   )ÚpromptÚprompt_plus_new_tokensÚcompare_matÚcompare_mat_intÚlongest_locationÚlongest_diag_lengthÚnew_token_start_indexÚdiscrepancy_with_oldÚdiscrepancy_lengthÚnew_tokens_onlyÚdiscrepancy_onlys              r    Ú_get_tokens_diagÚ>AssistedCandidateGeneratorDifferentTokenizers._get_tokens_diagÄ  sñ   € ð × 8Ñ 8Ñ8ˆÜ�Š˜{×+Ñ+ÜŸ,š, {Ó3ˆKà%Ÿ.™.¬Ó-ˆà×"Ñ"Ó$×)Ñ)×+Ñ+à#ä0]×0uÑ0uØó1
Ñ-Ðð !1°Ñ 3Ð6IÑ IÐØ/°Ñ2Ð5HÑHÐØ$Ÿl™l¨1™oÐ0DÑD×JÑJÓLÐØ0²Ð4IÑ4^Ñ4`Ð1`ÑaˆØ1ÚÐ$Ð?QÑ'QÐQÐQñ
Ðð "Ð4DÐDÐDr#   c                 óp   • UR                  USSS9nU" USSS9S   nUR                  UR                  5      $ )zä
Convert token IDs from one tokenizer to another.
Args:
    input_ids: The input token IDs.
    source_tokenizer: The source tokenizer.
    destination_tokenizer: The destination tokenizer.
Returns:
    The converted token IDs.
T©Úskip_special_tokensÚclean_up_tokenization_spacesÚpt©Úadd_special_tokensÚreturn_tensorsr   )ÚdecoderM   rI   )r   r   Úsource_tokenizerÚdestination_tokenizerÚtextÚdest_idss         r    Ú&convert_source_tokens_to_target_tokensÚTAssistedCandidateGeneratorDifferentTokenizers.convert_source_tokens_to_target_tokenså  sF   € ð  ×&Ñ& yÀdÐimÐ&ÐnˆÙ(¨À$ÐW[Ñ\Ð]hÑiˆØ�{‰{˜9×+Ñ+Ó,Ð,r#   r   c                 óè  • [        U R                  5      nUS:X  a  US4$ UR                  U R                  R                  5      nSnU R                  U5      u  pTXPl        [        [        X0R                  UR                  S   -
  5      S5      nU R                  XT5        U R                  XVU5      nU R                  R                  SS5        U R                  R                  " S0 UDU R                  D6nU R!                  XR"                  5      n	UR                  S   U l        UR&                  U R                  S'   UR"                  U l        U R$                  U	R                  S   :¼  a  US4$ U	S4$ )rz   r   Nr›   rK   r   rD   r+   )r7   rS   rM   r<   rI   Ú_prepare_assistant_input_idsrÅ   r‹   rœ   rj   rd   r|   r}   r`   Úpopr®   Ú_process_assistant_outputsr±   rÄ   rD   )
r   r   r   r   rŸ   Úassistant_input_idsrk   r€   rµ   Únew_target_idss
             r    r!   Ú<AssistedCandidateGeneratorDifferentTokenizers.get_candidatesø  se  € ô ˜T×6Ñ6Ó7ˆØ˜QÓØ˜d�?Ð"à—L‘L ×!5Ñ!5×!<Ñ!<Ó=ˆ	Øˆà/3×/PÑ/PÐQZÓ/[Ñ,ÐØ"5ÔäœS ×1KÑ1KÐNa×NgÑNgÐhjÑNkÑ1kÓlÐnoÓpˆà×#Ñ#Ð$7ÔIØ×7Ñ7Ð8KÐ]kÓlˆØ×Ñ×!Ñ!Ð"2°DÔ9à×/Ñ/×8Ò8Ñd¸?ÐdÈd×NcÑNcÑdÐØ×8Ñ8¸×D^ÑD^Ó_ˆð $-§?¡?°1Ñ#5ˆÔ Ø3C×3SÑ3Sˆ×ÑÐ/Ñ0Ø"2×"<Ñ"<ˆÔà×#Ñ# ~×';Ñ';¸AÑ'>Ó>Ø˜d�?Ð"à˜tÐ#Ð#r#   c                 ód  • U R                   U R                  S.nSnU R                  Gb^  U R                  U R                  :”  GaC  U R                  U R                  -
  nU R
                  " USS2US24   40 UD6nUR                  S   nU R                  SS2U* S24   nU R                  Xu5      u  p‰n
U R                  nU	b¬  US:”  az  U
R                  S   S:”  ag  XŠR                  S   :X  a  X«SS2U* S24'   OGXŠR                  S   :”  a5  XŠR                  S   -
  nUSS2SU* 24   nX«SS2U
R                  S   * S24'   UnU	R                  S   S:”  a  [        R                  " X¹/SS9nX³4$ [        R                  " Xµ/SS9n X³4$ U R
                  " U40 UD6nUR                  S   U l        X³4$ )zIConverts target input IDs to assistant input IDs, handling discrepancies.©r  r  r   Nr   r›   r¬   )
r¿   rÀ   rÅ   rÄ   rÆ   r  rd   rö   r3   r¯   )r   r   Úconvert_kwargsrŸ   Ústart_index_in_target_windowÚnew_assistant_idsÚprompt_use_lengthÚ
prompt_useró   rô   rõ   r  Údiscrepancy_length_diffs                r    r  ÚJAssistedCandidateGeneratorDifferentTokenizers._prepare_assistant_input_ids"  s  € ð !%× 5Ñ 5Ø%)×%=Ñ%=ñ
ˆð ˆà×"Ñ"Ò.°4×3KÑ3KÈd×NdÑNdÔ3dà+/×+CÑ+CÀd×F\ÑF\Ñ+\Ð(à $× KÒ KØš!Ð9Ñ:Ð:Ñ;ñ!Ø?Mñ!Ðð !2× 7Ñ 7¸Ñ :ÐØ×0Ñ0²Ð5FÐ4FÑ4GÐ1GÑHˆJàDH×DYÑDYØóEÑAÐÐ1Að #'×"9Ñ"9ÐàÑ*Ø%¨Ó)Ð.>×.DÑ.DÀQÑ.GÈ!Ó.KØ)×-CÑ-CÀAÑ-FÓFØGWªAÐ0BÐ/BÑ/CÐ,CÒDà+×.DÑ.DÀQÑ.GÓGØ2D×G]ÑG]Ð^_ÑG`Ñ2`Ð/Ø.AÂ!ÐE^ÐG^ÐF^ÐE^ÐB^Ñ._Ð+ØO_ªAÐ0@×0FÑ0FÀqÑ0IÐ/IÑ/KÐ,KÑLà&8�Oà"×(Ñ(¨Ñ+¨aÓ/Ü*/¯)ª)Ð5HÐ4ZÐ`bÑ*cÐ'ð #Ð3Ð3ô ',§i¢iÐ1DÐ0XÐ^`Ñ&aÑ#ð
 #Ð3Ð3ð #'×"MÒ"MÈiÑ"jÐ[iÑ"jÐØ'0§¡°qÑ'9ˆDÔ$à"Ð3Ð3r#   Úassistant_sequencesc                 ó  • [        [        R                  U R                  5      nUR                  S   nX@R
                  -
  nU R                  USS2US24   U R                  U R                  S9nUR                  S   nUSS2U* S24   nU R                  X†5      u  pšn	UnU
b*  U
R                  S   S:”  a  [        R                  " Xº/SS9nO[        R                  " X¶/SS9nU R                  b  USS2SU R                  24   nU$ )z7Processes assistant outputs to obtain target input IDs.r   Nr  r   r›   r¬   )r   r3   r4   rÅ   rd   rÇ   r  rÀ   r¿   rö   r¯   rm   )r   r   r  rÅ   Únum_prev_assistantÚstart_assistant_look_indexÚnew_target_ids_from_windowÚtarget_prompt_use_lengthÚtarget_prompt_useÚ_Útarget_new_tokens_onlyr  s               r    r
  ÚHAssistedCandidateGeneratorDifferentTokenizers._process_assistant_outputsP  s-  € ô "¤%×"2Ñ"2°D×4KÑ4KÓLÐØ/×5Ñ5°aÑ8ÐØ%7×:SÑ:SÑ%SÐ"à%)×%PÑ%PØ¢Ð#=Ñ#>Ð >Ñ?Ø!×5Ñ5Ø"&×"7Ñ"7ð &Qð &
Ð"ð
 $>×#CÑ#CÀAÑ#FÐ à%¢aÐ*BÐ)BÑ)CÐ&CÑDÐà'+×'<Ñ'<Ð=NÓ'kÑ$ˆ 1à"ˆà!Ñ-Ø%×+Ñ+¨AÑ.°Ó2Ü!&§¢¨NÐ+SÐY[Ñ!\�øô #ŸYšY¨Ð'SÐY[Ñ\ˆNà×%Ñ%Ñ1Ø+ªAÐ/K°×1KÑ1KÐ/KÐ,KÑLˆNàÐr#   )rÇ   rÀ   rÅ   rÄ   rÆ   r¿   r»   )r,   r-   r.   r/   r0   r3   r4   r¼   rX   r   rw   ÚstaticmethodrÕ   râ   rö   r  r5   r6   r!   r7   r  r
  r8   Ú__classcell__©r   s   @r    r¾   r¾   W  s^  ø† ñðP .2Ø<@ñZà×#Ñ#ðZð +ðZð 4ð	Zð
 7ðZð .ðZð ðZð —|‘| dÑ*ðZð #Ð#8Ñ9÷Zð Zð( ñ!ó ð!ðF ñ3ó ð3ð& ñEó ðEò@-ð&($¨×(8Ñ(8ð ($ÀuÈU×M]ÑM]Ð_d×_pÑ_pÐMpÑGqô ($ðT,4°e×6FÑ6Fð ,4È5ÐQV×QaÑQaÐcfÐQfÑKgô ,4ð\Ø×)Ñ)ðØ@E×@PÑ@Pðà	×	Ñ	÷ò r#   r¾   c                   ó2   ^ • \ rS rSrSrU 4S jrS rSrU =r$ )Ú_PruneReindexingLMHeadir  aP  
A class to prune and reindex the language model head.

This class prunes the language model head to only include the specified token IDs and reindexes the logits
to map back to the original vocabulary.

Args:
    original_lm_head (nn.Module): The original language model head.
    token_ids (list[int]): The list of token IDs to keep.
c                 óˆ   >• [         TU ]  5         [        X5      R                  UR                  R
                  5      U l        g rÂ   )rÃ   rw   r	   rM   ÚweightrJ   Úpruned_lm_head)r   Úoriginal_lm_headÚassistant_overlap_token_idsr   s      €r    rw   Ú_PruneReindexingLMHead.__init__~  s6   ø€ Ü‰ÑÔÜ0Ð1AÓ_×bÑbØ×#Ñ#×)Ñ)ó
ˆÕr#   c                 ó(   • U R                  U5      nU$ rÂ   ©r(  )r   Úhidden_statesÚpruned_logitss      r    ÚforwardÚ_PruneReindexingLMHead.forward„  s   € Ø×+Ñ+¨MÓ:ˆØÐr#   r-  )	r,   r-   r.   r/   r0   rw   r0  r8   r"  r#  s   @r    r%  r%  r  s   ø† ñ	õ
÷ð r#   r%  c                   ó~   ^ • \ rS rSrS\R
                  4U 4S jjrS\R                  S\R                  4S jr
SrU =r$ )Ú_MapInputEmbeddingi‰  Úoriginal_embeddingc                 ój   >• [         TU ]  5         Xl        UR                  U l        X l        SU l        g)a$  
Wraps an existing embedding layer and remaps token IDs before lookup.

Args:
    original_embedding (nn.Embedding): Pre-trained or existing embedding layer.
    assistant_overlap_token_ids (dict): Mapping from original token IDs to new token IDs.
                  Example: {old_id: new_id}
FN)rÃ   rw   r4  r'  r*  Úmap)r   r4  r*  r   s      €r    rw   Ú_MapInputEmbedding.__init__Š  s0   ø€ ô 	‰ÑÔØ"4ÔØ(×/Ñ/ˆŒØ+FÔ(Øˆ�r#   r   r   c                 óº   • U R                   (       a1  U R                  US      R                  S5      R                  S5      nO	SU l         UnU R                  U5      $ )z•
Args:
    input_ids (torch.LongTensor): Tensor of token IDs (batch_size, seq_len).

Returns:
    torch.FloatTensor: Corresponding input embeddings.
)r   r›   r   T)r6  r*  Ú	unsqueezer4  )r   r   Úmy_input_idss      r    r0  Ú_MapInputEmbedding.forward™  sU   € ð �8�8à×;Ñ;¸IÀeÑ<LÑM×WÑWÐXYÓZ×dÑdÐefÓg‰LàˆDŒHØ$ˆLà×&Ñ& |Ó4Ð4r#   )r*  r6  r4  r'  )r,   r-   r.   r/   ÚnnÚ	Embeddingrw   r3   r4   r6   r0  r8   r"  r#  s   @r    r3  r3  ‰  s7   ø† ð¨2¯<©<÷ ð5 ×!1Ñ!1ð 5°e×6GÑ6G÷ 5ò 5r#   r3  c                   ó  • \ rS rSr% Sr\" S5      * r\\S'   Sr\	\S'     SSS	S
S	S\	S\
S   S\4
S jjrS rS rS\\	   4S jrS\R$                  S\R$                  4S jrS\R(                  S\R(                  4S jrSrg)ÚAssistantToTargetTranslatori«  a°  
Translates token ids and logits between assistant and target model vocabularies. This class is used to handle
vocabulary mismatches when using different tokenizers for the assistant and target models in speculative decoding,
as introduced in the paper "Lossless Speculative Decoding Algorithms for Heterogeneous Vocabularies"
(https://huggingface.co/papers/2502.05202).
It maintains mappings between the two vocabularies and handles token/logit conversion.

Args:
    target_tokenizer (`PreTrainedTokenizerBase`):
        The tokenizer used by the target (main) model.
    assistant_tokenizer (`PreTrainedTokenizerBase`):
        The tokenizer used by the assistant model.
    target_vocab_size (`int`):
        The size of the target model's vocabulary. If not provided, will be inferred from the target tokenizer.
    assistant_model (Optional[PreTrainedModel], optional): The assistant model to be used. Defaults to None for backward compatibility.
    assistant_prune_lm_head (bool): Whether to prune the assistant model's language model
        head to match the target vocabulary. This is only applicable if `assistant_model` is provided.
        Defaults to False for backward compatibility.
ÚInfÚFILTER_VALUEr›   ÚSUPPRESS_TOKEN_IDNr¿   r   rÀ   Útarget_vocab_sizer<   r   Úassistant_prune_lm_headc                 ó@  • Xl         X l        Ub  UR                  OSU l        X0l        U R                  5       u  U l        U l        U R                  5       U l	        S U l
        U=(       a    US LU l        [        U R                  5      S:”  Ga  U R                  (       aÌ  UbÉ  [        R                  " [        U R                  R!                  5       5      [        R"                  U R                  S9U l        UR'                  5       n[)        X`R$                  5      nAUR+                  U5        UR-                  5       n[/        X€R$                  5      n	AUR1                  U	5        X�l        g [5        [7        U R                  5       U R                  5      /5      U l
        g g )NÚcpur   ©rJ   rI   )Ú_target_tokenizerÚ_assistant_tokenizerrI   Ú_assistant_model_devicerC  Ú"_get_assistant_to_target_input_idsÚ_assistant_to_target_input_idsÚtarget_to_assistant_input_idsÚ_get_suppress_input_idsÚ_suppress_input_idsÚlogits_processorsrD  rŠ   r3   rè   rÙ   rÚ   re   r*  Úget_output_embeddingsr%  Úset_output_embeddingsÚget_input_embeddingsr3  Úset_input_embeddingsÚmap_input_embeddingsr   r   )
r   r¿   rÀ   rC  r<   rD  r)  r(  Úoriginal_input_embeddingsrU  s
             r    rw   Ú$AssistantToTargetTranslator.__init__Ã  sk  € ð ;KÔØ=PÔ!ØAPÑA\ ×'=Ò'=ÐbgˆÔ$Ø&7Ôà×3Ñ3Ó5ñ 	PˆÔ+¨TÔ-Oð /3×.JÑ.JÓ.LˆÔ Ø=AˆÔØ'>×'^À?ÐZ^ÐC^ˆÔ$Üˆt×'Ñ'Ó(¨1Ô,à×+×+°Ñ0KÜ38·<²<Ü˜×;Ñ;×BÑBÓDÓEÜŸ*™*Ø×7Ñ7ñ4�Ô0ð
 $3×#HÑ#HÓ#JÐ Ü!7Ð8H×JjÑJjÓ!k�Ø$Ø×5Ñ5°nÔEà,;×,PÑ,PÓ,RÐ)Ü'9Ð:S×UuÑUuÓ'vÐ$Ø-Ø×4Ñ4Ð5IÔJØ,@Õ)ä)<Ü2°4×3OÑ3OÓ3QÐSW×SoÑSoÓpÐqó*�Õ&ð' -r#   c                 ó~   • U R                   (       a,  [        U R                  5      S:”  a  SU R                  l        ggg)a[  
Disables the mapping of input ids despite the assistant pruning for the language model head being enabled.

This method is required for the first forward pass of `_MapInputEmbedding` where input ids are already in the assistant vocabulary space. By disabling the mapping, it ensures that the input ids are processed correctly without remapping.

r   FN)rD  rŠ   rO  rU  r6  ©r   s    r    Úunmap_input_idsÚ+AssistantToTargetTranslator.unmap_input_idsì  s6   € ð ×'×'¬C°×0HÑ0HÓ,IÈAÓ,MØ,1ˆD×%Ñ%Õ)ð -NÐ'r#   c           	      óX  • U R                   R                  5       nU R                  R                  5       nSnU R                  USS9S   n[        U5      S:”  a¶  U R                   R	                  U5      S   S   nU R                  USS9S   n[        U5      S:”  as  U R                  R	                  U5      S   S   nXW:w  aM  UR                  5        VV	s0 s H0  u  p‰UR                  U5      (       a  UR                  XuS5      OUU	_M2     nnn	[        UR                  5       5      n
[        R                  " U
S-   4U R                  [        S9n0 nUR                  5        H#  u  p�UR                  U5      nUc  M  XëU'   XÜU'   M%     UR                  U R                   5      U4$ s  sn	nf )NÚ F)rþ   r   r   r   ©rJ   )rH  Ú	get_vocabrI  rŠ   Úconvert_ids_to_tokensrV   Ú
startswithÚreplacer‹   rÚ   r3   ÚfullrB  r7   rb   rM   rJ  )r   Útarget_vocabÚassistant_vocabÚ	space_strÚtarget_space_idsÚtarget_space_signÚassistant_space_idsÚassistant_space_signÚtokrÑ   Úmax_assistant_indexÚassistant_to_target_input_idsrM  Úassistant_idÚ	target_ids                  r    rK  Ú>AssistantToTargetTranslator._get_assistant_to_target_input_idsú  sÏ  € Ø×-Ñ-×7Ñ7Ó9ˆØ×3Ñ3×=Ñ=Ó?ˆàˆ	Ø×1Ñ1°)ÐPUÐ1ÐVÐWbÑcÐÜÐÓ  1Ó$Ø $× 6Ñ 6× LÑ LÐM]Ó ^Ð_`Ñ aÐbcÑ dÐà"&×";Ñ";¸IÐZ_Ð";Ð"`ÐalÑ"mÐÜÐ&Ó'¨!Ó+Ø'+×'@Ñ'@×'VÑ'VÐWjÓ'kÐlmÑ'nÐopÑ'qÐ$à$Ó<ð )8×(=Ñ(=Ô(?ô'ò )@™H˜Cð  #Ÿ~™~Ð.B×CÑCð  ŸK™KÐ(<ÐQRÔSà!$Øòñ )@ð $ñ 'ô " /×"8Ñ"8Ó":Ó;ÐÜ(-¯
ª
Ð4GÈ!Ñ4KÐ3MÈt×OeÑOeÔmpÑ(qÐ%Ø8:Ð%Ø!0×!6Ñ!6Ö!8ÑˆCØ$×(Ñ(¨Ó-ˆIØÓ$Ø>G¨lÑ;Ø;G¨iÓ8ñ	 "9ð
 -×/Ñ/°×0LÑ0LÓMÐOlÐlÐlùó#'s   Ã7F&r   c                 ób   • [         R                  " U R                  U R                  :H  5      S   $ )zP
Get the input ids that are in the assistant vocab but not in the target vocab.
r   )r3   ÚwhererL  rB  rY  s    r    rN  Ú3AssistantToTargetTranslator._get_suppress_input_ids  s*   € ô �{Š{˜4×>Ñ>À$×BXÑBXÑXÓYÐZ[Ñ\Ð\r#   Úassistant_candidate_idsc                 ó
  • [        US   5      UR                  S   -
  nUS:X  a  U$ USU* S24   nU R                  (       a  U R                  U   nU R                  U   n[
        R                  " X&R                  S5      4SS9$ )a3  
Return the target candidate ids that correspond to the assistant candidate ids.
Note that we have already the target ids for the prompt and we only need to find the target ids for the new tokens.
Moreover, assistant ids of the original prompt does not necessarily appear in _assistant_to_target_input_ids.
r   r   Nr¬   )rŠ   rd   rD  r*  rL  r3   r¯   r9  )r   r  Útarget_input_idsrt  Únum_new_tokensÚlast_candidate_idsÚtransformed_slices          r    Úget_target_idsÚ*AssistantToTargetTranslator.get_target_ids#  s™   € ô Ð4°QÑ7Ó8Ð;N×;TÑ;TÐUVÑ;WÑWˆØ˜QÓØ#Ð#ð "9¸¸^¸OÑ<LÐ9LÑ!MÐØ×+×+à%)×%EÑ%EÐFXÑ%YÐ"Ø $× CÑ CÐDVÑ WÐÜ—9’9Ð.×0KÑ0KÈAÓ0NÐOÐUVÑWÐWr#   Úassistant_logitsc                 ón  • / UR                   SS QU R                  P7n[        R                  " X R                  U R
                  S9nU R                  U R                  :g  nU R                  U   nU R                  (       a  XSU4'   U$ USSU R                  R                   S   24   nUSU4   USU4'   U$ )zC
Return the target logits that correspond to the assistant logits.
Nr›   ©rI   .r   )	rd   rC  r3   rc  rA  rJ  rL  rB  rD  )r   r|  Útarget_shapeÚtarget_logitsÚassistant_indices_maskÚtarget_logits_supported_indicesÚvalid_assistant_logitss          r    Úget_target_logitsÚ-AssistantToTargetTranslator.get_target_logits8  sÝ   € ð
 )_Ð*:×*@Ñ*@ÀÀ"Ð*EÐ(^Àt×G]ÑG]Ñ(^ˆÜ+0¯:ª:Ø×+Ñ+°D×4PÑ4Pñ,
ˆð "&×!DÑ!DÈ×H^ÑH^Ñ!^Ðà*.×*MÑ*MÐNdÑ*eÐ'à×'×'ØBR˜#Ð>Ð>Ñ?ð Ðð &6°cÐ;i¸T×=`Ñ=`×=fÑ=fÐghÑ=iÐ;iÐ6iÑ%jÐ"ØBXÐY\Ð^tÐYtÑBuˆM˜#Ð>Ð>Ñ?ØÐr#   )rJ  rL  rI  rO  rH  r*  rD  rP  rU  rM  rC  ©NF)r,   r-   r.   r/   r0   ÚfloatrA  r2   rB  r7   r   r1   rw   rZ  rK  rÙ   rN  r3   r4   rz  r6   r„  r8   r+   r#   r    r?  r?  «  sÉ   ‡ ññ( ! ›<˜-€L�%Ó'ØÐ�sÓð 8<Ø(-ñ'à3ð'ð 7ð'ð ð	'ð
 "Ð"3Ñ4ð'ð "&õ'òR2ò!mðF]¨¨c©ô ]ðXØNS×N^ÑN^ðXà	×	Ñ	ôXð*°%×2CÑ2Cð È×HYÑHY÷ r#   r?  c                   ó„   • \ rS rSrSr\R                  " 5       r\  SSSSSS\	S\
S	   S
\S\4S jj5       r\S 5       rSrg)ÚAssistantVocabTranslatorCacheiN  z›
Cache for `AssistantToTargetTranslator` instances. The instances are computed at
pre-processing time, and this cache allows us to avoid recomputing them.
Nr¿   r   rÀ   rC  r<   r   rD  r   c                 óÖ   • U R                   R                  U5      nUc#  [        R                  " 5       nX`R                   U'   UR                  U5      nUc  [	        UUUUU5      nXvU'   U$ rÂ   )Ú_cacherb   ÚweakrefÚWeakKeyDictionaryr?  )Úclsr¿   rÀ   rC  r<   rD  Úassistant_dictÚmappings           r    Úget_translatorÚ,AssistantVocabTranslatorCache.get_translatorV  sw   € ð Ÿ™Ÿ™Ð(8Ó9ˆØÑ!Ü$×6Ò6Ó8ˆNØ+9�J‰JÐ'Ñ(à ×$Ñ$Ð%8Ó9ˆØ‰?Ü1Ø Ø#Ø!ØØ'óˆGð 3:Ð.Ñ/àˆr#   c                 ó  • U R                    Vs/ s H	  ob  M  UPM     nnU H  nU R                   U	 M     U R                   R                  5        H$  nU Vs/ s H	  ob  M  UPM     nnU H  nX1	 M     M&     gs  snf s  snf )z’
Clean up dead references in the cache.
This removes entries where either the target_tokenizer or assistant_tokenizer
has been garbage collected.
N)r‹  rÚ   )rŽ  rs   Ú	dead_keysr�  s       r    ÚcleanupÚ%AssistantVocabTranslatorCache.cleanupq  sy   € ð %(§J¢JÓ>¢J˜S—S¡Jˆ	Ð>ÛˆCØ—
‘
˜3’ñ ð "Ÿj™j×/Ñ/Ö1ˆNÙ(6ÓFª Ÿ©ˆIÐFÛ �Ø"Ò'ó !ò 2ùò ?ùò Gs   �A:™A:ÁA?Á"A?r+   r†  )r,   r-   r.   r/   r0   rŒ  r�  r‹  Úclassmethodr7   r   r1   r?  r‘  r•  r8   r+   r#   r    r‰  r‰  N  s…   † ñð
 ×&Ò&Ó(€Fàð 8<Ø(-ñà3ðð 7ðð ð	ð
 "Ð"3Ñ4ðð "&ðð 
%ôó ðð4 ñ(ó ó(r#   r‰  c                   óV  ^ • \ rS rSrSr  SS\R                  SSSSS	SS
SS\S\S\R                  S-  S\
S   4U 4S jjjrS\R                  S\\R                  \R                  4   4S jrSS\R                  S\S\4U 4S jjjrS\R                  S\R                  4S jrSrU =r$ )Ú%UniversalSpeculativeDecodingGeneratori„  zç
`CandidateGenerator` class to be used for Universal Speculative Decoding (USD): speculative decoding with different tokenizers
for the assistant and main models. This class generates candidates through the use of a smaller model.
Nr   r<   r   r¿   r   rÀ   r=   r   r>   Úatm_translatorr?   r@   r   c
           
      óZ   >• Xpl         [        T
U ]	  UUUUUUUU	5        SU l        S U l        g )Nr   )Ú_atm_translatorrÃ   rw   Ú_target_seq_len_with_candidatesÚ_prev_assistant_ids)r   r   r<   r¿   rÀ   r=   r>   rš  r?   r@   r   s             €r    rw   Ú.UniversalSpeculativeDecodingGenerator.__init__Š  sB   ø€ ð  .ÔÜ‰ÑØØØØØØØØô		
ð 56ˆÔ,Ø<@ˆÕ r#   r   c                 óX  • UR                  U R                  R                  5      nU R                  U5      u  pEU R	                  U5      u  pgUS:X  a  US4$ U R                  XES9  U R                  XFU5      nSUS   l        SUS   l        U R                  R                  b  U R                  R                  US'   U R                  U5      u  U l        n	U R                  R                  XCU R                  5      n
U
R                  S   U l        U R                  R!                  U	5      nX«4$ )z[
Simplified version of get_candidates that uses the translator cache for token conversion.
r   N©r    Tr=   r@   r›   )rM   r<   rI   r  r{   r|   r}   rg   rf   rœ  rP  r~   rž  rz  rd   r�  r„  )r   r   r   rv  r  r    rk   r   r€   Úassistant_candidate_logitsÚtarget_candidate_idsÚtarget_candidate_logitss               r    r!   Ú4UniversalSpeculativeDecodingGenerator.get_candidates¦  s?  € ð %Ÿ<™<¨×(<Ñ(<×(CÑ(CÓDÐØ04×0QÑ0QÐRbÓ0cÑ-ÐØ)-×)CÑ)CÐDTÓ)UÑ&ˆà˜QÓØ˜d�?Ð"à×#Ñ#Ð$7Ð#Ñ[Ø×7Ñ7Ð8KÐ]kÓlˆð >BˆÐ+Ñ,Ô:ØGKˆÐ+Ñ,ÔDð ×Ñ×1Ñ1Ñ=Ø26×2FÑ2F×2XÑ2XˆOÐ.Ñ/Ø?C×?XÑ?XÐYhÓ?iÑ<ˆÔ Ð"<ð  $×3Ñ3×BÑBØ°4×3KÑ3Kó 
Ðð 0D×/IÑ/IÈ"Ñ/MˆÔ,Ø"&×"6Ñ"6×"HÑ"HÐIcÓ"dÐà#Ð<Ð<r#   r  r    c                 óT  >• U R                   cŽ  [        U R                  UR                  S   U R                  R
                  R                  5      U l        [        U R                  UR                  S   U R                  R
                  R                  5      U l        [        TU ]%  XS9$ )Nr›   r¡  )
rž  r£   r`   rd   r<   r[   r\   r¤   rÃ   r|   )r   r  r    r   s      €r    r|   Ú<UniversalSpeculativeDecodingGenerator._update_past_and_masksÆ  s™   ø€ Ø×#Ñ#Ñ+ô %<Ø×%Ñ%Ð':×'@Ñ'@ÀÑ'DÀd×FZÑFZ×FaÑFa×FtÑFtó%ˆDÔ!ô %:Ø×%Ñ%Ð':×'@Ñ'@ÀÑ'DÀd×FZÑFZ×FaÑFa×FtÑFtó%ˆDÔ!ô ‰wÑ-Ð.AÐ-ÐeÐer#   rv  c                 óJ  • UR                   S   nU R                  S:X  a  UnOSnUSS2U* S24   nSnU R                  S:”  a6  U R                  R                  R	                  US   R                  5       5      nUcS  U R                  R                  USSS9nU R                  USSS	9S
   R                  U R                  R                  5      nO+[        R                  " U//U R                  R                  S9nU R                  c  UnOTU R                  S-   U-
  nUS:”  a  U R                  SS2SU* 24   U l        [        R                  " U R                  U/SS9nUR                  [        R                   S9nU R                  R#                  5         U[%        US   5      4$ )z=
Simplified token conversion that only processes new tokens.
r›   r   r   NTrù   Frü   rý   r   r~  r¬   r^  )rd   r�  rœ  rM  rb   rê   r¿   r   rÀ   rM   r<   rI   r3   rè   rž  r¯   re   rZ  rŠ   )	r   rv  Útarget_seq_lenÚnew_token_countÚtarget_new_idsÚassistant_new_idsÚtarget_new_textr  Útokens_to_removes	            r    r  ÚBUniversalSpeculativeDecodingGenerator._prepare_assistant_input_idsÒ  sÄ  € ð
 *×/Ñ/°Ñ3ˆØ×/Ñ/°1Ó4Ø,‰OàˆOØ)ª!¨oÐ-=Ñ->Ð*>Ñ?ˆð !ÐØ×/Ñ/°!Ó3à $× 4Ñ 4× RÑ R× VÑ VÐWeÐfgÑWh×WmÑWmÓWoÓ pÐØÑ$Ø"×3Ñ3×:Ñ:Ø°DÐW[ð ;ð ˆOð !%× 8Ñ 8Ø°EÈ$ð !9ð !àñ!ç™2˜d×2Ñ2×9Ñ9Ó:ñ ô !&§¢Ð/@Ð.AÐ-BÈ4×K_ÑK_×KfÑKfÑ gÐð ×#Ñ#Ñ+Ø"3Ñà#×CÑCÀaÑGÈ.ÑXÐà !Ó#Ø+/×+CÑ+CÂAÐGYÐIYÐHYÐGYÐDYÑ+Z�Ô(Ü"'§)¢)¨T×-EÑ-EÐGXÐ,YÐ_aÑ"bÐØ1×4Ñ4¼5¿:¹:Ð4ÐFÐØ×Ñ×,Ñ,Ô.Ø"¤CÐ(9¸!Ñ(<Ó$=Ð=Ð=r#   )rœ  rž  r�  r`   r»   )r   )r,   r-   r.   r/   r0   r3   r4   r¼   r?  rX   r   rw   r5   r6   r!   r7   r1   r|   r  r8   r"  r#  s   @r    r™  r™  „  s  ø† ñð .2Ø<@ñAà×#Ñ#ðAð +ðAð 4ð	Að
 7ðAð .ðAð ðAð 4ðAð —|‘| dÑ*ðAð #Ð#8Ñ9÷Að Að8=¨×(8Ñ(8ð =ÀuÈU×M]ÑM]Ð_d×_pÑ_pÐMpÑGqô =ñ@
f¸%×:JÑ:Jð 
fÐ^að 
fÐjn÷ 
fð 
fð&>¸U×=MÑ=Mð &>ÐRW×RbÑRb÷ &>ò &>r#   r™  c                   ó  • \ rS rSrSr      SS\R                  S-  S\S\S\S\S	   S
\S-  4S jjr	S\R                  S\\R                  \R                  4   4S jrS\R                  S\R                  S\4S jrSrg)ÚPromptLookupCandidateGeneratoriû  aÕ  
`CandidateGenerator` class to be used for prompt lookup generation. This class generates candidates by looking up
likely continuations in the provided prompt (input_ids) itself.
Read the following blog post for more information: https://github.com/apoorvumang/prompt-lookup-decoding

Args:
    eos_token_id (`torch.Tensor`, *optional*):
        The token id of the end of sequence token.
    num_output_tokens (`int`, *optional*, defaults to 10):
        The number of tokens to be output as candidate tokens.
    max_matching_ngram_size (`int`, *optional*, defaults to 2):
        The maximum ngram size to be considered for matching in the prompt
    max_length (`int`, *optional*, defaults to 20):
        The number of total maximum tokens that can be generated. For decoder-only models that includes the
        prompt length. Defaults to 20, which is the max length used as default in generation config.
    logits_processor (`LogitsProcessorList`, *optional*):
        An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
        used to modify the prediction scores of the language modeling head applied at each generation step. In
        prompt lookup assisted generation, they are not used to manipulate probabilities, but rather to find
        forbidden tokens (p = -inf) and block them from being valid candidates.
    vocab_size (`int`, *optional*):
        The size of the vocabulary. Required if `logits_processor` is provided.
NrU   Únum_output_tokensÚmax_matching_ngram_sizerl   r@   r   Ú
vocab_sizec                 ó¢   • X l         X0l        X@l        Xl        XPl        X`l        U R                  S::  d  U R                   S::  a  [        S5      eg )Nr   z4Invalid max_matching_ngram_size or num_output_tokens)r²  r³  rl   rU   r@   r´  Ú
ValueError)r   rU   r²  r³  rl   r@   r´  s          r    rw   Ú'PromptLookupCandidateGenerator.__init__  sS   € ð "3ÔØ'>Ô$Ø$ŒØ(ÔØ 0ÔØ$Œà×'Ñ'¨1Ó,°×0FÑ0FÈ!Ó0KÜÐSÓTÐTð 1Lr#   r   r   c           
      ó  • UR                   u  p4U R                  US-   :X  a  US4$ SnSn[        [        U R                  US-
  5      SS5       GHè  nUR                  SUSS9nUSU* S24   n	X‰:H  R                  SS9n
U
R                  S	S
9S   nU GH–  nXÇ-   nXÐR                  -   n[        XäU R                  5      nXÞ:  d  M3  USXÞ24   nU R                  bë  Un[        R                  " X0R                  4UR                  [        R                  S9n[        U5       H‹  u  nnU R                  UU5      nUSU4   nU[!        S5      * [        R"                  " UR$                  5      R                  4;   a  USU n  O/[        R&                  " XSUS-    R)                  S5      4SS9nM�     UR                   S   S:X  a  GM3  S	n[        R*                  " XPR,                  5      n[        R                  " U5      nUR/                  5       S:”  a  US   R1                  5       nUSU n  O   U(       d  GMé    O   U(       a  Ub  [3        U5      S:X  a  US4$ UR)                  S5      n[        R&                  " X4SS9nUS4$ )al  
Fetches the candidates to be tried for the current input.

Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)

Return:
    `torch.LongTensor` of shape `(num_candidates, candidate_length)`: The candidate sequences to be tried.
r   NFr   r›   )Ú	dimensionÚsizeÚstepr   r¬   T)Úas_tuplerH   r@  )rd   rl   r²   rœ   r³  ÚunfoldÚallrØ   r²  r@   r3   rc   r´  rI   Úfloat32Ú	enumerater‡  ÚfinforJ   r¯   r9  ÚisinrU   Únumelrê   rŠ   )r   r   r   ÚbszÚinput_lengthÚ
chosen_idsÚmatch_foundÚ
ngram_sizeÚwindowsÚngram_tensorrq   Úmatch_indicesrÑ   rÒ   Úend_idxÚsequence_with_candidateÚfake_input_logitsÚcandidate_idxÚnew_candidate_tokenÚfake_output_logitsÚfake_candidate_logitsÚmaskÚmatch_indices_eosÚfirst_eos_indexÚcandidate_input_idss                            r    r!   Ú-PromptLookupCandidateGenerator.get_candidates'  sÀ  € ð &ŸO™OÑˆð �?‰?˜l¨QÑ.Ó.Ø˜d�?Ð"àˆ
ØˆÜ¤ D×$@Ñ$@À,ÐQRÑBRÓ SÐUVÐXZ×[ˆJà×&Ñ&°¸È!Ð&ÐLˆGð % Q¨¨© _Ñ5ˆLð Ñ.×3Ñ3¸Ð3Ð:ˆGð $ŸO™O°T˜OÐ:¸1Ñ=ˆMô
 %�ØÑ,�	Ø#×&<Ñ&<Ñ<�Ü˜g°T·_±_ÓE�àÕ&Ø!*¨1¨iÐ.?Ð+?Ñ!@�Jð ×,Ñ,Ñ8Ø2;Ð/Ü,1¯JªJØ §/¡/Ð2¸9×;KÑ;KÔSX×S`ÑS`ñ-Ð)ô CLÈJÖBWÑ>˜MÐ+>Ø15×1FÑ1FÐG^Ð`qÓ1rÐ.Ø4FÀqÐJ]ÐG]Ñ4^Ð1à4¼%À»,¸ÌÏÊÐTi×ToÑToÓHp×HtÑHtÐ8uÓuØ-7¸¸Ð-G 
Ù %ä:?¿)º)Ø%.Ð;N¸]ÈQÑ=NÐ0O×0YÑ0YÐZ[Ó0\Ð$]Ðcdñ;"Ò 7ñ CXð &×+Ñ+¨AÑ.°!Ó3Ú$à"&�Kô
 !Ÿ:š: j×2CÑ2CÓD�DÜ(-¯ª°dÓ(;Ð%Ø(×.Ñ.Ó0°1Ó4Ø*;¸AÑ*>×*CÑ*CÓ*E˜Ø%/Ð0@°Ð%A˜
Ùñ[ %÷\ ‰{Ùñ \öD ˜jÑ0´C¸
³OÀqÓ4HØ˜d�?Ð"ð  ×)Ñ)¨!Ó,ˆ
Ü#Ÿiši¨Ð(?ÀQÑGÐà" DÐ(Ð(r#   r$   r%   c                 ó   • g)r'   Nr+   r(   s       r    r)   Ú8PromptLookupCandidateGenerator.update_candidate_strategy…  s   € ð 	r#   )rU   r@   rl   r³  r²  r´  )Né
   r   é   NN)r,   r-   r.   r/   r0   r3   rX   r7   r   rw   r4   r5   r6   r!   r)   r8   r+   r#   r    r±  r±  û  sÏ   † ñð4 -1Ø!#Ø'(ØØ<@Ø!%ñUà—l‘l TÑ)ðUð ðUð "%ð	Uð
 ðUð #Ð#8Ñ9ðUð ˜$‘JõUð&\)¨×(8Ñ(8ð \)ÀuÈU×M]ÑM]Ð_d×_pÑ_pÐMpÑGqô \)ð|°5×3CÑ3Cð ÈU×M^ÑM^ð Ðmp÷ r#   r±  c                   óâ   ^ • \ rS rSrSr  SS\R                  SSSSS	\S
\R                  S-  S\	S   4U 4S jjjr
S\R                  S\\R                  \R                  4   4U 4S jjrSrU =r$ )ÚEarlyExitCandidateGeneratori–  aI  
`CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates
candidates through the use of **the model itself**, exiting early. Can only be used with models that support early
exit, e.g., `facebook/layerskip-llama3.2-1B`.

Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
    assistant_model (`PreTrainedModel`):
        The original model. This model must support early exit (i.e. is trained to compute logits in earlier
        layers).
    generation_config (`~generation.GenerationConfig`, *optional*):
        The generation configuration to be used as base parametrization for the generation call.
    logits_processor (`LogitsProcessorList`):
        An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
        used to modify the prediction scores of the language modeling head applied at each generation step.
    model_kwargs (`Dict`):
        The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
        model as well.
    inputs_tensor (`torch.Tensor`, *optional*):
        The model input tensor. In encoder-decoder models, this is the encoder input.
Nr   r<   r   r=   r   r>   r?   r@   r   c           	      ó‚   >• [         TU ]  UUUUUUS9  U R                  R                  U l        S U R                  l        g )N)r   r<   r=   r>   r?   r@   )rÃ   rw   r=   Úassistant_early_exit)r   r   r<   r=   r>   r?   r@   r   s          €r    rw   Ú$EarlyExitCandidateGenerator.__init__®  sM   ø€ ô 	‰ÑØØ+Ø/Ø%Ø'Ø-ð 	ñ 	
ð %)×$:Ñ$:×$OÑ$OˆÔ!Ø6:ˆ×ÑÕ3r#   r   c                 ó  >• [        U R                  U R                  R                  5      nUR                  R                  nU R
                  UR                  l        [        TU ]  U5      u  pVXCR                  l        XV4$ rÂ   )Úgetattrr<   Úbase_model_prefixr[   Únum_hidden_layersrß  rÃ   r!   )r   r   r   Ú
base_modelÚoriginal_num_hidden_layersr�   r‚   r   s          €r    r!   Ú*EarlyExitCandidateGenerator.get_candidatesÄ  sn   ø€ ä˜T×1Ñ1°4×3GÑ3G×3YÑ3YÓZˆ
Ø%/×%6Ñ%6×%HÑ%HÐ"Ø.2×.GÑ.Gˆ
×ÑÔ+Ü*/©'Ñ*@ÀÓ*KÑ'ˆØ.H×ÑÔ+ØÐ.Ð.r#   )rß  r»   )r,   r-   r.   r/   r0   r3   r4   r¼   rX   r   rw   r5   r6   r!   r8   r"  r#  s   @r    rÝ  rÝ  –  sž   ø† ñð: .2Ø<@ñ;à×#Ñ#ð;ð +ð;ð .ð	;ð
 ð;ð —|‘| dÑ*ð;ð #Ð#8Ñ9÷;ð ;ð,/¨×(8Ñ(8ð /ÀuÈU×M]ÑM]Ð_d×_pÑ_pÐMpÑGq÷ /õ /r#   rÝ  c                   ót  ^ • \ rS rSr% SrSr\\S'   SSS.r\	\
\4   \S'      SS\R                  S	S
S\R                  SSS\	S\R                   S-  S\S   S\\\   -  \R                   -  S-  4U 4S jjjrS\R                  S\	\
\4   S\S\S\S\\R                  \R.                  S-  4   4S jrSrU =r$ )Ú*SinglePositionMultiTokenCandidateGeneratoriÎ  a5  Candidate generator for predicting multiple draft tokens from a single token position using the MTP method.

The Multi-Token Prediction (MTP) method defines an assisted candidate generator with an assistant model that
autoregressively drafts multiple candidate tokens from a constant `position_ids` value, the last "seen" token, with
the goals of reducing assistant model compute, increasing drafted token acceptance rates, and increasing target
model throughput.

This capability is enabled by three concrete requirements for assistant models:

*   **Use KV cache sharing techniques for the entire assistant model** (see Gemma 4) to reduce attention computation
    in the assistant model. This method of cache sharing passes the `key_states` and `value_states` from the main
    model in a dictionary, allowing the assistant model to skip pre-fill entirely, and reducing attention
    computations (e.g., `k_proj`, `k_norm`, `v_proj`, and `v_norm` in the Gemma 4 architecture) as applicable to the
    main and assistant models' architectures. This architectural feature effectively locks the assistant into a
    constant `position_ids` value.
*   **Concatenate the embedding and hidden states for the seen last token** from the target model as the input to
    the assistant. This adaptation allows the assistant to retain rich context about the preceding (possibly
    drafted) tokens while working from a constant `position_ids` value. For the first token drafted after pre-fill,
    the last seen token will be the last token from the prompt. For subsequent drafting steps, the last seen token
    will be the last token generated by the assistant (within a drafting round) or the last token accepted by the
    target model (between drafting rounds).
*   **Use cross-attention** to allow Q from the assistant to attend to KV from the main model.

Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
    assistant_model (`PreTrainedModel`):
        The model to be used for generating candidates. This model should be smaller than the main model.
    target_model_input_embeddings (`torch.nn.Embedding`):
        The input embedding table from main model, used to get the embeddings from the last seen token.
    generation_config (`~generation.GenerationConfig`, *optional*):
        The generation configuration to be used as base parametrization for the generation call.
    model_kwargs (`dict`):
        The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
        model as well.
    inputs_tensor (`torch.Tensor`, *optional*):
        The model input tensor. In encoder-decoder models, this is the encoder input.
    logits_processor (`LogitsProcessorList`, *optional*):
        An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
        used to modify the prediction scores of the language modeling head applied at each generation step.
    eos_token_id (`int` or `list[int]` or `torch.Tensor`, *optional*):
        The token id of the end of sequence token. If not `None`, only the provided values will be used. If None,
        values will be inferred from the available `generation_config` and `assistant_generation_config`.
Tr   )Úoutput_hidden_statesÚreturn_shared_kv_statesÚmodel_kwargs_overridesNr   r<   r   Útarget_model_input_embeddingsr=   r   r>   r?   r@   r   rU   c	                 óž  >• SUR                   R                  ;  a#  [        SUR                   R                   S35      e[        T	U ]  XXEXg5        X0l        UGc  [        5       n[        U R                  R                  [        5      (       a&  UR                  U R                  R                  5        ON[        U R                  R                  [        5      (       a%  UR                  U R                  R                  5        [        U R                  R                  [        5      (       a&  UR                  U R                  R                  5        ON[        U R                  R                  [        5      (       a%  UR                  U R                  R                  5        U(       a,  [        R                   " [#        U5      [        R$                  S9OS U l	        g [        U[        R&                  5      (       dA  [        U[        5      (       a  U/n[        R                   " U[        R$                  S9U l	        g UR%                  5       U l	        g )NÚGemma4AssistantzAExpected assistant_model to be a Gemma4AssistantForCausalLM. Got z­ This candidate generator requires that the assistant model is able to work from a shared_kv_states dictionary. Currently, only the Gemma4AssistantForCausalLM supports this.r^  )r   r,   r¶  rÃ   rw   rí  rÊ   rW   r=   rU   r   rR   r7   rÌ   rP   r3   rè   rÙ   re   rX   )
r   r   r<   rí  r=   r>   r?   r@   rU   r   s
            €r    rw   Ú3SinglePositionMultiTokenCandidateGenerator.__init__  s©  ø€ ð  O×$=Ñ$=×$FÑ$FÓFÜØSÐTc×TmÑTm×TvÑTvÐSwð]ð]óð ô 	‰Ñ˜Ð5FÐVcÔvØ-JÔ*àÒÜ #£ˆLä˜$×0Ñ0×=Ñ=¼x×HÑHØ×#Ñ# D×$:Ñ$:×$GÑ$GÕHÜ˜D×2Ñ2×?Ñ?Ä×EÑEØ× Ñ  ×!7Ñ!7×!DÑ!DÔEä˜$×:Ñ:×GÑGÌ×RÑRØ×#Ñ# D×$DÑ$D×$QÑ$QÕRÜ˜D×<Ñ<×IÑIÌ3×OÑOØ× Ñ  ×!AÑ!A×!NÑ!NÔOæVb¤§¢¬T°,Ó-?ÄuÇzÁzÒ RÐhlˆDÕÜ˜L¬%¯,©,×7Ñ7Ü˜,¬×,Ñ,Ø ,˜~�Ü %§¢¨\ÄÇÁÑ LˆDÕà ,× 1Ñ 1Ó 3ˆDÕr#   Úmodel_outputsÚis_first_iterationÚn_last_matchesr   c                 óê  • U(       a  US4$ [        [        U R                  5      U R                  UR                  S   -
  S-
  5      nUS::  a  US4$ Ub"  [        US5      (       a  [        US5      (       d  [        S5      eUR                  S   nUR                  n	UR                  S   n
U	R                  5        VVs0 s H-  u  p¼X¼S   SS2SS2SU
2SS24   US   SS2SS2SU
2SS24   4_M/     n	nnUSS2XUS-   24   nUSS2SS24   n[        R                  " UR                  S   S-
  //[        R                  U R                  R                  S9n[        R                  " UR                  S   [        R                   UR                  S9n/ n/ n[#        U5       GHó  nU R%                  U5      n[        R&                  " UU/SS	9n[        R(                  " 5          U R                  UUR+                  S
5      UU	SS9nSSS5        WR,                  R/                  SS	9nUR0                  nUR3                  5       (       aœ  UR5                  S5      n[        R6                  " UU R8                  R:                  U5      nUR=                  [        R6                  " UR5                  S5      [        R>                  " UR,                  5      UR,                  5      5        OUR=                  UR,                  5        UR=                  U5        U R@                  c  GM~  [        RB                  " U[        RD                  " URG                  S5      U R@                  RI                  UR                  5      5      5      nURK                  5       (       d  GMô    O   [        R&                  " U[        R&                  " USS	9/SS	9n[        R&                  " USS	9nUU4$ s  snnf ! , (       d  f       GNä= f)z2Generate draft token candidates using the drafter.Nr   r   r.  Úshared_kv_statesz^`model_outputs` cannot be None, and they need to contain `hiden_states` and `shared_kv_states`r›   rG  r¬   rK   F)Úinputs_embedsrK   Úposition_idsrõ  Ú	use_cache)&rœ   r7   rS   rm   rd   Úhasattrr¶  r.  rõ  rV   r3   rè   re   r<   rI   Úzerosr1   r²   rí  r¯   Úno_gradrb   ÚlogitsrÜ   Úlast_hidden_stateré   r9  rr  r=   Úpad_token_idr�   Ú
zeros_likerU   Ú
logical_orrÂ  ÚsqueezerM   r¾  )r   r   r>   rñ  rò  ró  r   r   rý  rõ  Úcurrent_lengthÚkÚvÚlast_token_idr÷  Úsequence_stoppedÚdrafted_logitsÚdrafted_tokensr  Úlast_token_embeddingrö  ÚoutputsÚstoppedr�   r‚   s                            r    r!   Ú9SinglePositionMultiTokenCandidateGenerator.get_candidates.  s¡  € ö Ø˜d�?Ð"ô œS ×!:Ñ!:Ó;¸T×=WÑ=WÐZc×ZiÑZiÐjkÑZlÑ=lÐopÑ=pÓqˆØ˜QÓØ˜d�?Ð"ð Ñ!Ü˜=¨/×:Ñ:Ü˜=Ð*<×=Ñ=äØpóð ð +8×*EÑ*EÀbÑ*IÐØIV×IgÑIgÐð #Ÿ™¨Ñ+ˆà\l×\rÑ\rÔ\tô
Ú\tÑTXÐTUˆA�!‘’Qš˜?˜N˜?ªAÐ-Ñ.°°!±²Qº¸?¸N¸?ÊAÐ5MÑ0NÐOÒOÑ\tð 	ñ 
ð
 .ªa°ÐSTÑBTÐ1TÐ.TÑUÐØ!¢! R¡S &Ñ)ˆÜ—|’| i§o¡o°aÑ&8¸1Ñ&<Ð%=Ð$>ÄeÇjÁjÐY]×YmÑYm×YtÑYtÑuˆÜ Ÿ;š; y§¡°qÑ'9ÄÇÁÐT]×TdÑTdÑeÐð ˆØˆä�~×&ˆAØ#'×#EÑ#EÀmÓ#TÐ Ü!ŸIšIÐ';Ð=NÐ&OÐUWÑXˆMä—’•Ø×.Ñ.Ø"/Ø#/×#3Ñ#3Ð4DÓ#EØ!-Ø%5Ø#ð /ð �÷ !ð $ŸN™N×1Ñ1°bÐ1Ð9ˆMØ '× 9Ñ 9Ðð  ×#Ñ#×%Ñ%Ø*×4Ñ4°QÓ7�Ü %§¢¨G°T×5KÑ5K×5XÑ5XÐZgÓ h�Ø×%Ñ%Ü—K’K × 1Ñ 1°"Ó 5´u×7GÒ7GÈÏÉÓ7WÐY`×YgÑYgÓhõð ×%Ñ% g§n¡nÔ5à×!Ñ! -Ô0ð × Ñ Ô,Ü#(×#3Ò#3Ø$Ü—J’J˜}×4Ñ4°QÓ7¸×9JÑ9J×9MÑ9MÈm×NbÑNbÓ9cÓdó$Ð ð $×'Ñ'×)Ô)ÙñG 'ôL Ÿ	š	 9¬e¯iªi¸ÈAÑ.NÐ"OÐUVÑWˆÜ Ÿ9š9 ^¸Ñ;ÐØÐ.Ð.Ð.ùóm
÷$ !–ús   Â?4OÇ##O#Ï#
O2	)rU   rí  rå   )r,   r-   r.   r/   r0   r   r1   r2   rì  r¼   Ústrr   r3   r4   r<  r=  rX   r   r7   rÙ   rw   r
   r5   r6   r!   r8   r"  r#  s   @r    ré  ré  Î  s=  ø‡ ñ+ðZ $(Ð˜DÓ'ð !%Ø#'ñ.Ð˜D  c ™Nó ð .2Ø<@Ø>Bñ(4à×#Ñ#ð(4ð +ð(4ð (*§|¡|ð	(4ð
 .ð(4ð ð(4ð —|‘| dÑ*ð(4ð #Ð#8Ñ9ð(4ð ˜D ™I‘o¨¯©Ñ4°tÑ;÷(4ð (4ðT[/à×#Ñ#ð[/ð ˜3 ˜8‘nð[/ð #ð	[/ð
 !ð[/ð ð[/ð 
ˆu×Ñ ×!2Ñ!2°TÑ!9Ð9Ñ	:÷[/ò [/r#   ré  r>   Ú
new_lengthr\   r   c                 ó|  • U(       a  SOSnX0;  a  U $ X   nXR                   S   -
  nUS:  a  USS2SU24   X'   O<US:”  a6  [        R                  " XDR                  UR                   S   U45      /SS9X'   SU ;   a_  U S   nUS:  a  USS2SU24   U S'   U $ US:”  a<  USS2SS2SS2SS24   R	                  SUSS5      n[        R                  " Xg/SS9U S'   U $ S	U ;   aY  U S	   nUS:  a  USS2SU24   U S	'   U $ US:”  a8  USS2SS2SS24   R	                  SUS5      n[        R                  " Xg/SS9U S	'   U $ )
zNExpands or crops the model's mask for decoding purposes, to the defined lengthrG   rK   r   r   Nr›   r¬   Úcross_attention_maskÚimage_attention_mask)rd   r3   r¯   Únew_onesÚrepeat)r>   r  r\   Úmask_keyrÓ  Úmask_length_diffÚ
cross_maskÚnew_masks           r    r£   r£   Œ  s«  € ö ,>Ñ'ÐCS€HØÓ#ØÐàÑ!€DØ!§J¡J¨q¡MÑ1Ðà˜!ÓØ!%¢aÐ):Ð*:Ð):Ð&:Ñ!;ˆÒØ	˜AÓ	Ü!&§¢¨D·-±-ÀÇÁÈAÁÐP`Ð@aÓ2bÐ+cÐikÑ!lˆÑð  Ó-à!Ð"8Ñ9ˆ
Ø˜aÓØ3=ºaÐARÐBRÐARÐ>RÑ3SˆLÐ/Ñ0ð Ðð  Ó!Ø!¢! R¡Sª!ªQ ,Ñ/×6Ñ6°qÐ:JÈAÈqÓQˆHÜ38·9²9¸jÐ=SÐYZÑ3[ˆLÐ/Ñ0ð Ðð 
  <Ó	/à!Ð"8Ñ9ˆ
Ø˜aÓØ3=ºaÐARÐBRÐARÐ>RÑ3SˆLÐ/Ñ0ð
 Ðð	  Ó!Ø!¢! R¡Sª! )Ñ,×3Ñ3°AÐ7GÈÓKˆHÜ38·9²9¸jÐ=SÐYZÑ3[ˆLÐ/Ñ0àÐr#   c                 ó”  • U(       a  SOSnU R                  U5      c  U $ X   nXR                  S   -
  nUS:  a  USS2SU24   X'   U $ US:”  ax  S/UR                  5       S-
  -  S/-   n[        R                  " XTR
                  UR                  S9R                  " U6 USSS24   -   S-   n[        R                  " XG/SS	9nXpU'   U $ )
zVExpands or crops the model's position ids for decoding purposes, to the defined lengthÚdecoder_position_idsr÷  Nr›   r   r   rG  .r¬   )	rb   rd   r­   r3   ÚarangerJ   rI   Úviewr¯   )r>   r  r\   Úposition_keyÚ	positionsÚposition_length_diffÚrequired_dimÚnext_position_idss           r    r¤   r¤   °  sú   € ö .@Ñ)À^€LØ×Ñ˜Ó%Ñ-ØÐàÑ*€IØ%¯©¸Ñ(;Ñ;Ðà˜aÓØ%.ªqÐ2GÐ3GÐ2GÐ/GÑ%HˆÑ"ð Ðð 
 Ó	!à�s˜iŸm™m›o°Ñ1Ñ2°b°TÑ9ˆä�LŠLÐ-·_±_ÈY×M]ÑM]Ñ^×cÒcÐeqÐrØ˜˜R™S˜Ñ!ñ"àñð 	ô
 "ŸIšI yÐ&DÈ"ÑMÐØ%6�\Ñ"àÐr#   c                 ó   • U R                  S5      c  U $ U S   nUSS2S4   R                  S5      nXR                  S   -
  nUS:  a  USS2SU24   U S'   U $ US:”  a/  UR                  SU5      n[        R
                  " U S   U/SS9U S'   U $ )zXExpands or crops the model's token_type_ids for decoding purposes, to the defined lengthÚtoken_type_idsNr›   r   r   r¬   )rb   r9  rd   r  r3   r¯   )r>   r  r"  Úfinal_token_typeÚtype_length_diffÚtoken_type_copiess         r    r¥   r¥   Ê  sÈ   € à×ÑÐ(Ó)Ñ1ØÐð "Ð"2Ñ3€NØ%¢a¨ eÑ,×6Ñ6°rÓ:ÐØ!×$8Ñ$8¸Ñ$;Ñ;Ðà˜!ÓØ)7ºÐ;LÐ<LÐ;LÐ8LÑ)MˆÐ%Ñ&ð Ðð 
˜AÓ	Ø,×3Ñ3°AÐ7GÓHÐÜ).¯ª°LÐAQÑ4RÐTeÐ3fÐlnÑ)oˆÐ%Ñ&ØÐr#   )2rN   rŒ  Úcollections.abcr   Útypingr   r   r   r   Únumpyr�   r3   Útorch.nnr<  Úpytorch_utilsr	   Úutilsr
   r   Úconfiguration_utilsr   Úlogits_processr   r   r   Úsklearn.metricsr   Úmodeling_utilsr   Útokenization_utils_baser   r   r:   r¾   ÚModuler%  r3  r?  r‰  r™  r±  rÝ  ré  r¼   r  r7   r1   r£   r¤   r¥   r+   r#   r    Ú<module>r2     s†  ðó Û Ý $ß 5Ó 5ã Û Ý å .ß 5Ý 1ß hÑ hñ ×ÑÝ)æÝ0ÝAÝ5÷&
ñ &
ôRD/Ð!3ô D/ôNXÐ4Nô Xôv˜RŸY™Yô ô.5˜Ÿ™ô 5÷D`ñ `÷F3(ñ 3(ôlt>Ð,Yô t>ônXÐ%7ô Xôv5/Ð"<ô 5/ôp{/Ð1Kô {/ð|!¨$¨s°C¨x©.ð !Àcð !Ð_cð !ÐhlÐmpÐruÐmuÑhvô !ðH¨¨S°#¨X©ð ÀCð Ð]að ÐfjÐknÐpsÐksÑftô ð4¨$¨s°C¨x©.ð Àcð ÈdÐSVÐX[ÐS[Énõ r#   