
    g              
       j   d dl Z d dlmZmZmZmZ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mZ erddlmZ dd	lmZ dd
lmZ  G d d          Z G d de          Z G d de          Z G d de          Zd Zdeeef         dededeeef         fdZdeeef         dedeeef         fdZ dS )    N)TYPE_CHECKINGAnyDictOptionalTuple   )DynamicCache)isin_mps_friendly   )LogitsProcessorListMinLengthLogitsProcessor)PreTrainedModel)PreTrainedTokenizerBase)GenerationConfigc                       e Zd ZdZdej        deej        eej                 f         fdZ	dej        dej        de
fdZdS )	CandidateGeneratorz`Abstract base class for all candidate generators that can be applied during assisted generation.	input_idsreturnc                 0    t          | j         d          )ag  
        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   s     g/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/generation/candidate_generator.pyget_candidatesz!CandidateGenerator.get_candidates$   s$     "~sss
 
 	
    scoresnum_matchesc                 0    t          | j         d          )  
        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_strategyz,CandidateGenerator.update_candidate_strategy5   s*     "~ + + +
 
 	
r   N)__name__
__module____qualname____doc__torch
LongTensorr   r   FloatTensorr   intr"    r   r   r   r   !   s        jj
(8 
U5CSU]^c^oUpCp=q 
 
 
 
"
53C 
UM^ 
mp 
 
 
 
 
 
r   r   c                       e Zd ZdZ	 	 ddej        ddddded	eej                 d
dfdZ	dej        de
ej        eej                 f         fdZdej        dej        defdZdS )AssistedCandidateGeneratorar  
    `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                    |j         }|                    |          }||                    |          }|| _        |j        j        | _        |j        j        | _        |j        | j        j        _        i }|                                D ]a\  }	}
|	dvrXt          |
t          j
                  r'|
                                                    |          nt          j        |
          ||	<   bd|                                v r|                                s|d= d|v r|d         |d<   n^|j        j        rC|                    ||j        j        |          \  }}}|                    ||||j                  }nd|v r|d         |d<   || _        |j        j        rd| _        ngd|v r\d| _        | j                            dt          j        |j        d         d	f|j         t          j        
                    | j        d<   nd| _        ||nt7                      | _        t          j        |          | _        d| j        _        d| j        _        | j        | j        _        d| j        _        | j        j         | _!        d| j        _         d | j        _"        | j        D ]&}t          |tF                    rtI          d          'd | j        _%        d S )N)encoder_outputsassistant_encoder_outputspast_key_valuesnum_logits_to_keepr5   r4   decoder_input_idsr   decoder_attention_maskr   r   )devicedtypeattention_maskTzPassing `MinLengthLogitsProcessor` when using `assisted_generation is disabled. Please pass in `min_length` into `.generate()` instead)&r:   tor.   r/   num_assistant_tokensassistant_confidence_thresholdeos_token_iditems
isinstancer'   Tensordetachcopydeepcopykeys_supports_num_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   r2   return_dict_in_generateoutput_scoresis_assistant
min_lengthmain_model_min_lengthmin_new_tokensr   
ValueErrorcache_implementation)r   r   r.   r/   r0   r1   r2   r:   rN   keyvaluemodel_input_name	processors                r   __init__z#AssistedCandidateGenerator.__init___   s,    !'LL((	$),,V44M  /$3$E$Z!.=.O.n+ ?P>\.; &,,.. 	 	JC]]]1;E5<1P1PjELLNN%%f---VZVcdiVjVj !%
  #3#8#8#:#:::?CoCoCqCq: !56&,662>?Z2[.//#6 	R@O@e@e@MO_A A=M+-=  /]]/1A?Cd    ,..2>?P2Q./ 0 !4 	-!4D"222!,D6:6K6O6O(
IOA.29;KSXS]^^^7 7D!"233 "-D 5E4P 0 0ViVkVk!%/@!A!A9=6/3,@D@c=.2+ &*%;%F",-)04-. 	 	I)%=>>  M   7;333r   r   c           
         |                     | j        j                  }|j        d         }t	          t          | j                  | j        j        |z
  dz
            }t          t	          || j
        |z
            d          }|dk    r|dfS | j                            dd          du}|ru|dz
  }t          | j        | j        d         |dz
            | j        d<   t          | j        || j        j        j                  | _        t#          | j        |          | _        | j        |d|d|d| j        d	| j        i} | j        j        di || j        }|j        | j        d<   t-          j        |j        d
          }	|j        }
|
|	fS )Z  
        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   r   Nr6   rY   max_new_tokensr/   r2   dimr+   )r=   r.   r:   rR   minr*   r>   r/   
max_lengthmaxrX   rN   rP   _crop_past_key_values_prepare_attention_maskrI   rJ   _prepare_token_type_idsrO   r2   generater6   r'   stackr   	sequences)r   r   new_cur_lenrd   rY   has_past_key_valuesnew_cache_sizeassistant_generation_kwargsassistant_outputcandidate_logitscandidate_idss              r   r   z)AssistedCandidateGenerator.get_candidates   s    LL!5!<==	  ob)S!:;;T=S=^al=lop=pqqS1Kk1YZZ\]^^Qd?" #3778I4PPX\\ 		`(1_N7L$d&;<M&NP^abPb8 8D!"34 %<%{D4H4O4b% %D! %<D<QS^$_$_D! 	nn!7 5'
# 94/8pp;VpZ^Zopp 4D3S/0 !;'7'>AFFF(2...r   r   r   c                     | j         j        j        dv rI|t          | j                  k    r| xj        dz  c_        dS t          d| j        dz
            | _        dS dS )r    >   	heuristicheuristic_transientg       @g      ?N)r.   r/   num_assistant_tokens_scheduler*   r>   ri   r!   s       r   r"   z4AssistedCandidateGenerator.update_candidate_strategy   s}      1O T
 
 
 c$";<<<<))S0)))),/T5NQT5T,U,U)))
 
r   NN)r#   r$   r%   r&   r'   r(   r   r   rC   r`   r   r)   r   r*   r"   r+   r   r   r-   r-   H   s        8 1526V; V;#V; +V; .	V;
 V;  -V; 0V; V; V; V;p5/(8 5/U5CSU]^c^oUpCp=q 5/ 5/ 5/ 5/nV53C VUM^ Vmp V V V V V Vr   r-   c                        e Zd ZdZ	 	 ddej        ddddddd	d
dedeej                 ddf fdZ	e
d             Ze
d             Ze
d             Zd Zdej        deej        eej                 f         fdZ xZS )-AssistedCandidateGeneratorDifferentTokenizersa  
    `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   r0   r1   r2   r   c	                     t                                          ||||||           || _        || _        d | _        d | _        d| _        d| _        d S )N
   )superr`   r~   r   prev_tokensprev_assistant_idstarget_lookbehindassistant_lookbehind)
r   r   r.   r~   r   r/   r0   r1   r2   r   s
            r   r`   z6AssistedCandidateGeneratorDifferentTokenizers.__init__)  s`     	O5FVceuvvv 0#6 "&!#$&!!!r   c                 Z   t                      }i }|D ]}t          j        |          }t          |                                          }||v r=|                    |           d}|dz  }|d         | j        d         k     r|d         | j        d         k     rt          |                                          }|                    |           | |d         |d         f         dk    r|dz  }|dz  }nn.|d         | j        d         k     r|d         | j        d         k     |||<   |S )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   )setr'   clonetupletolistaddrR   )input_matrixnonzero_idxvisiteddiagsidx	start_idxtuple_start_idxcur_diag_lens           r   _get_longest_diag_dictzDAssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_dict=  sG    %% 	& 	&CC((I#I$4$4$6$677O'))KK(((LNIA,!3A!6669Q<,J\]^J_;_;_"'	(8(8(:(:";";O,,,	!il :;q@@ A%LNII A,!3A!6669Q<,J\]^J_;_;_ &E#JJr   c                 0   t                               | |                                           }t          |                                          }t          |                                          }t          j        |          }||         }||         }||fS )a  
        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valuesrG   npargmax)r   r   diags_values
diags_keys	best_diagdiag_start_indexdiag_start_lengths          r   _get_longest_diag_indexzEAssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_indexa  s     >TT,..00
 
 ELLNN++%**,,''
Il++	%i0(3!222r   c                    |j         | k    }t          j        |          st          j        |          }|                    t
                    }|                                                                sdS t          	                    |          \  }}|d         |z   }|d         |z   }| j
        d         |z
                                  }|dd||z   df         }	|dd|||z   f         }
||	|
fS )a  
        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)Tr'   	is_tensortensorr=   r*   anyitemr}   r   rR   )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_diagz>AssistedCandidateGeneratorDifferentTokenizers._get_tokens_diagu  s    -.&8{++ 	4,{33K%..--""$$))++ 	$##0]0u0u1
 1
-- !1 36I I/25HH$l1o0DDJJLL04IL^4^4`4`1`a1AA$'<?Q'QQQ
 "?4DDDr   c                     |                     |dd          } ||dd          d         }|                    |j                  S )a$  
        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   )batch_decoder=   r:   )r   r   source_tokenizerdestination_tokenizertextdest_idss         r   &convert_source_tokens_to_target_tokenszTAssistedCandidateGeneratorDifferentTokenizers.convert_source_tokens_to_target_tokens  sR      ,,YDos,tt(($W[\\\]hi{{9+,,,r   r   c           
      R   t          | j                  }|dk    r|dfS |                    | j        j                  }| j        | j        d}d}| j        Z| j        j	        d         | j
        k    r>| j        j	        d         | j
        z
  } | j        |dd|df         fi |}|j	        d         }| j        dd| df         }t                              ||          \  }	}
}| j        }|
|	dk    rx|j	        d         dk    rg|	|j	        d         k    r||dd|	 df<   nG|	|j	        d         k    r6|	|j	        d         z
  }|ddd| f         }||dd|j	        d          df<   |	}|
j	        d         dk    rt          j        ||
gd          }n.t          j        ||gd          }n | j        |fi |}|| _        || _        |j	        d         }t#          t%          || j        |z
            d          }| j                            dd          du}|rx|dz
  |z
  }t-          | j        | j        d         |dz
            | j        d<   t/          | j        || j        j        j                  | _        t5          | j        |          | _        | j        |d|d	|d
| j        d| j        i}| j                            dd            | j        j        di || j        }| j        j	        d         }|| j         z
  }|                     |j!        dd|df         | j        | j                  }|j	        d         }|dd| df         }t                              ||          \  }}}|}|*|j	        d         dk    rt          j        ||gd          }nt          j        ||gd          }|| _        tE          | j        d          r|ddd| j        j#        f         }|j$        | j        d<   |j!        | _        |j	        d         |j	        d         k    r|dfS |dfS )rb   r   N)r   r   r   rc   re   r6   rY   rd   r/   r2   r<   rh   r+   )%r*   r>   r=   r.   r:   r~   r   r   prev_target_idsrR   r   r   r   r}   r   r'   catri   rg   rX   rN   rP   rj   rk   rI   rJ   rl   rO   r/   r2   poprm   r   ro   hasattrrh   r6   )r   r   rd   convert_kwargsremove_from_pkvstart_index_in_target_windownew_assistant_idsprompt_use_length
prompt_user   r   r   assistant_input_idsdiscrepancy_length_diffrp   rY   rq   rr   rs   rt   num_prev_assistantstart_assistant_look_indexnew_target_ids_from_windowtarget_prompt_use_lengthtarget_prompt_use_target_new_tokens_onlynew_target_idss                               r   r   z<AssistedCandidateGeneratorDifferentTokenizers.get_candidates  sa    T677Qd?"LL!5!<==	 $ 5%)%=
 
 
 'D,@,Fq,IDLb,b,b+/+?+Ea+H4Ka+a( K K!!!9:::;! !?M! ! !2 7 :05F4F4G4G1GHJ >NNz[lmm B1A #'"9*%)).>.DQ.G!.K.K)-=-CA-FFFGW+AAA0B/B/C/C,CDD+.>.DQ.GGG2DGWG]^_G`2`/.A!!!E^G^F^E^B^._+O_+AAA0@0Fq0I/I/K/K,KL&8O"(+a//*/)5H/4Z`b*c*c*c' ',i1DFW0X^`&a&a&a## #N$"Mi"j"j[i"j"j#,D "5)/3S1Kk1YZZ\]^^ #3778I4PPX\\ 		`(1_>N7L$d&;<M&NP^abPb8 8D!"34 %<%{D4H4O4b% %D! %<D<QS^$_$_D!  3nn!7 5'
# 	!!"2D99984/8pp;VpZ^Zopp!4:1=%7$:S%S"%)%P%P&qqq*D*E*E'EF!5"&"7 &Q &
 &
"
 $>#CA#F %aaa*B)B)C)C&CD'T'e'e9(
 (
$!1 #!-%+A.22!&N<R+SY[!\!\!\ #Y8R'SY[\\\N(4)<88 	T+AAA/R1G1R/R,RSN 4D3S/0+5 ?1!5a!888d?"t##r   r{   )r#   r$   r%   r&   r'   r(   r   r   rC   r`   staticmethodr   r   r   r   r   r)   r   __classcell__)r   s   @r   r}   r}     sX        P 1526' '#' +' 4	'
 7' .' '  -' 0' ' ' ' ' '( ! ! \!F 3 3 \3& E E \E@- - -&E$(8 E$U5CSU]^c^oUpCp=q E$ E$ E$ E$ E$ E$ E$ E$r   r}   c            	           e Zd ZdZ	 	 	 	 ddej        dededefd	Zd
ej        de	ej        e
ej                 f         fdZd
ej        dej        defdZdS )PromptLookupCandidateGeneratora
  
    `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:
        max_matching_ngram_size (`int`):
            The maximum ngram size to be considered for matching in the prompt
        num_output_tokens (`int`):
            The number of tokens to be output as candidate tokens.
        max_length (`int`):
            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.
    Nr      r@   num_output_tokensmax_matching_ngram_sizerh   c                     || _         |r|nd| _        || _        || _        | j        dk    s| j         dk    rt	          d          d S )Nr   r   z4Invalid max_matching_ngram_size or num_output_tokens)r   r   rh   r@   rZ   )r   r@   r   r   rh   s        r   r`   z'PromptLookupCandidateGenerator.__init__A  sb     "3BY'`'>'>_`$$('1,,0F!0K0KSTTT 1L0Kr   r   r   c                 L   |                     d          }| j        |dz   k    r|dfS d}d}t          t          | j        |dz
            dd          D ]}|                    d|d          }|d| df         }||k                        d          }|                    d	
          d         }	|	D ]}
|
|z   }|| j        z   }t          ||| j                  }||k     ru|d||f         }d	}t          || j
                  }t          j        |          }|                                dk    r$|d                                         }|d|         } n|r n	|t          |          dk    r|dfS |                    d          }t          j        ||fd          }|dfS )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 `(num_candidates, candidate_length)`: The candidate sequences to be tried.
        r   NFr   rc   )	dimensionsizestepr   re   T)as_tuple)r   rh   rangerg   r   unfoldallr   r   r
   r@   r'   numelr   len	unsqueezer   )r   r   input_length
chosen_idsmatch_found
ngram_sizewindowsngram_tensormatchesmatch_indicesr   r   end_idxmaskmatch_indices_eosfirst_eos_indexcandidate_input_idss                    r   r   z-PromptLookupCandidateGenerator.get_candidatesP  s    !~~a(( ?lQ...d?"
D$@,QRBR S SUVXZ[[ !	 !	J&&!&LLG %Q_5L ,.333::G $OOTO::1=M %  *,	#d&<<g|T_EEw&&!*1i.?+?!@J"&K
 -Z9JKKD(-d(;(;%(..00144*;A*>*C*C*E*E%/0@0@%A
E '   ZA!5!5d?"  ))!,,
#iJ(?QGGG"D((r   r   r   c                     dS )r    Nr+   r!   s       r   r"   z8PromptLookupCandidateGenerator.update_candidate_strategy  s	     	r   )Nr   Nr   )r#   r$   r%   r&   r'   rC   r*   r`   r(   r   r   r)   r   r"   r+   r   r   r   r   1  s         " &*!#'+U UlU U "%	U
 U U U U>)(8 >)U5CSU]^c^oUpCp=q >) >) >) >)@53C UM^ mp      r   r   c           
         g }| j         j        rt          t          |                    D ]o}|                    ||         d         ddddd|ddf         ||         d         ddddd|ddf         ||         d         ||         d         f           pt          |          }nd| j        j                                        v s2| j         j	        d| j         j	        d                                         v r| j         j
        r;t          t          |                    D ]}||         ddd|ddf         ||<   n)t          t          |                    D ]}||         ddddd|ddf         ||<    nt          |t                    r|                    |           n|t          t          |                    D ]}||         g g fk    rT|                    ||         d         ddddd|ddf         ||         d         ddddd|ddf         f           d|                    ||         d         ||         d         f           t          |          }|S )z9Crops the past key values up to a certain maximum length.r   Nr   r      
gptbigcode)rI   rJ   r   r   appendr   r   r#   lowerarchitecturesmulti_queryrB   r	   crop)modelr6   rh   new_pastr   s        r   rj   rj     s   H|& "*_--.. 	 	COO#C(+AAAqqq+:+qqq,@A#C(+AAAqqq+:+qqq,@A#C(+#C(+	     //	17799	9	9".<5<C]^_C`CfCfChCh3h3h<# 	RS1122 O O'6s';AAA{
{AAA<M'N$$O S1122 R R'6s';AAAqqq+:+qqq<P'Q$$R	O\	2	2 *Z((((		$_--.. 		T 		TCs#Bx//',Q/111kzk1110DE',Q/111kzk1110DE    !5a!8/#:Nq:Q RSSSS//r   r0   
new_lengthrJ   r   c                    |rdnd}|| vr| S | |         }||j         d         z
  }|dk     r|ddd|f         | |<   nA|dk    r;t          j        ||                    |j         d         |f          gd          | |<   d| v rl| d         }|dk     r|ddd|f         | d<   n|dk    rE|ddddddddf                             d|dd          }t          j        ||gd          | d<   nkd	| v rg| d	         }|dk     r|ddd|f         | d	<   nG|dk    rA|ddddddf                             d|d          }t          j        ||gd          | d	<   | S )
zNExpands or crops the model's mask for decoding purposes, to the defined lengthr9   r<   r   r   Nrc   re   cross_attention_maskimage_attention_mask)rR   r'   r   new_onesrepeat)r0   r   rJ   mask_keyr   mask_length_diff
cross_masknew_masks           r   rk   rk     s    ,>S''CSH|##!D!DJqM1!!%aaa):*:):&:!;X	A		!&D$--AP`@a2b2b+cik!l!l!lX --!"89
a3=aaaARBRAR>R3SL/00!!!!!!RSS!!!QQQ,/66q:JAqQQH389j(=SYZ3[3[3[L/0	<	/	/!"89
a3=aaaARBRAR>R3SL/00!!!!!!RSS!!!),33A7GKKH389j(=SYZ3[3[3[L/0r   c                 4   d| vs| d         | S | d         }|dddf                              d          }||j        d         z
  }|dk     r|ddd|f         }n=|dk    r7|                    d|          }t          j        | d         |gd          | d<   | S )zXExpands or crops the model's token_type_ids for decoding purposes, to the defined lengthtoken_type_idsNrc   r   r   re   )r   rR   r  r'   r   )r0   r   r  final_token_typetype_length_difftoken_type_copiess         r   rl   rl     s    |++|<L/M/U!"23N%aaae,66r::!N$8$;;!'+<,<+<(<=	A		,33A7GHH).LAQ4RTe3fln)o)o)o%&r   )!rE   typingr   r   r   r   r   numpyr   r'   cache_utilsr	   pytorch_utilsr
   logits_processr   r   modeling_utilsr   tokenization_utils_baser   configuration_utilsr   r   r-   r}   r   rj   strr*   boolrk   rl   r+   r   r   <module>r     s5     < < < < < < < < < < < < < <      & & & & & & - - - - - - I I I I I I I I  6000000AAAAAA555555$
 $
 $
 $
 $
 $
 $
 $
N}V }V }V }V }V!3 }V }V }V@f$ f$ f$ f$ f$4N f$ f$ f$R	m m m m m%7 m m m`& & &R!$sCx. !c !_c !hlmprumuhv ! ! ! !H$sCx. c dSVX[S[n      r   