o
    Zhe                  
   @   s  d dl Z 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 e r9d dlmZ ddlmZ ddlmZ d	d
lmZmZmZ ercddlmZ ddlmZ d	dlmZ ddl m!Z! G dd dZ"G dd de"Z#G dd de#Z$G dd dej%Z&G dd dej%Z'G dd dZ(G dd dZ)G dd de$Z*G dd  d e"Z+G d!d" d"e#Z,d#d$ Z-d%ee.ef d&e/d'e0d(ee.ef fd)d*Z1d%ee.ef d&e/d(ee.ef fd+d,Z2dS )-    N)TYPE_CHECKINGAnyDictOptionalTuple   )prune_linear_layer)is_sklearn_available)	roc_curve)Cache)isin_mps_friendly   )LogitsProcessorListMinLengthLogitsProcessorSuppressTokensLogitsProcessor)PreTrainedModel)PreTrainedTokenizerBase)GenerationConfig)deprecate_kwargc                   @   sN   e Zd ZdZdejdeejeej f fddZ	dejdejde
fdd	Zd
S )CandidateGeneratorz`Abstract base class for all candidate generators that can be applied during assisted generation.	input_idsreturnc                 C      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    r   Z/var/www/auris/lib/python3.10/site-packages/transformers/generation/candidate_generator.pyget_candidates/      
z!CandidateGenerator.get_candidatesscoresnum_matchesc                 C   r   )  
        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"   r   r   r   update_candidate_strategy@   r    z,CandidateGenerator.update_candidate_strategyN)__name__
__module____qualname____doc__torch
LongTensorr   r   FloatTensorr   intr%   r   r   r   r   r   ,   s    $r   c                   @   s   e Zd ZdZ		d$dejddddded	eej d
dfddZ	dejde
ejeej f fddZdejdejdefddZdejde
eef fddZ	d%dejdededefddZdejdededefdd Zd!ede
ejeej f fd"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                 C   s  |j }||}|d ur||}|| _|jj| _|jj| _|j| jj_i }| D ]\}	}
|	dvrFt|
t	j
r?|
 |nt|
||	< q*d| v rT| sT|d= |jjrn|||jj|\}}}|||||j}n
d|v rx|d |d< || _|jjrd| _n"d|v rd| _| jdt	j|jd df|j t	jd	| jd
< nd| _|d ur|nt | _t|| _d| j_d| j_| j| j_d| j_| jj | _!d| j_ d | j_"| jD ]}t|t#rt$dqd | j_%t& r| jjjrt'| t(u rg | _)g | _*d S d S d S d S )N)encoder_outputspast_key_valuesZlogits_to_keepr4   Z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)+r7   tor/   r0   num_assistant_tokensassistant_confidence_thresholdeos_token_iditems
isinstancer*   TensordetachcopydeepcopykeysZ_supports_logits_to_keepconfigis_encoder_decoderZ_prepare_model_inputsZbos_token_idZ._prepare_encoder_decoder_kwargs_for_generationassistant_kwargsinput_ids_keygetZonesshapelongr   r3   return_dict_in_generateoutput_scoresZis_assistantZ
min_lengthmain_model_min_lengthmin_new_tokensr   
ValueErrorZcache_implementationr	   typer.   probsmatches)r   r   r/   r0   r1   r2   r3   r7   rG   keyvalueZmodel_input_name	processorr   r   r   __init__j   sx   




"







z#AssistedCandidateGenerator.__init__r   c                 C   sZ   | | jj}| |\}}|dkr|dfS | | | |||}| |\}}||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   N)r:   r/   r7   _calculate_new_tokens_update_past_and_masks_prepare_generation_args_generate_candidates)r   r   rO   max_new_tokensgeneration_argscandidate_idscandidate_logitsr   r   r   r      s   
z)AssistedCandidateGenerator.get_candidatesr!   r"   c                 C   s6  | j jjdv r"|t|d d kr|  jd7  _n	td| jd | _t r| j jjrt| t	u r| j
dg|  t| jt| j
krI| j
d t| jt| j
 }|dkr^| j| d= t| jdkrddh| j
rt| j
| j\}}}d| }|d|  }	t|	}
||
 }|| j j_dS dS dS dS dS dS )	r#   >   	heuristicZheuristic_transientr   r   g       @g      ?N      )r/   r0   Znum_assistant_tokens_schedulelenr;   maxr	   r<   rQ   r.   rS   extendrR   appendissubsetr
   npZargmin)r   r   r!   r"   Zexcess_lengthZfprZtprZ
thresholdsZfnrZcostsZoptimal_threshold_indexZbest_thresholdr   r   r   r%      s2   
z4AssistedCandidateGenerator.update_candidate_strategyc                 C   sD   |j d }tt| j| jj| d }tt|| j| d}||fS )zCCalculate the minimum and maximum number of new tokens to generate.r   r   )rJ   minr-   r;   r0   
max_lengthre   rN   )r   r   Znew_cur_lenr]   rO   r   r   r   rY     s   
z0AssistedCandidateGenerator._calculate_new_tokensr   r   remove_from_pkvnum_added_tokensc                 C   sz   | j dddu}|r;|jd d | }t| j| j d || | j d< t| j |jd | jjj| _ t| j |jd | _ |S )zLUpdate past key values and attention masks for subsequent generation rounds.r5   Nrj   r   )	rG   rI   rJ   _crop_past_key_valuesr/   _prepare_attention_maskrE   rF   _prepare_token_type_ids)r   r   rm   rn   Zhas_past_key_valuesZnew_cache_sizer   r   r   rZ   #  s   
z1AssistedCandidateGenerator._update_past_and_masksrO   r]   c              
   C   s   | j |d|d|d| jd| jiS )z*Prepare arguments for the generation call.rO   r]   r0   r3   )rH   r0   r3   )r   r   rO   r]   r   r   r   r[   4  s   z3AssistedCandidateGenerator._prepare_generation_argsr^   c           	      C   s   | j jdi || j}|j| jd< t rN| j jjrNt| tu rNt	j
|jdd}t	j|dd}|jdt|j df }|tt||f }| j|  t	j|jdd}|j}||fS )z7Generate candidate sequences using the assistant model.r5   r   dimrj   Nr   r   )r/   generaterG   r5   r	   r0   r<   rQ   r.   r*   catr!   Zsoftmax	sequencesrd   rangerR   rf   toliststack)	r   r^   assistant_outputZscores_tensorZscores_softmaxZidspr`   r_   r   r   r   r\   >  s   z/AssistedCandidateGenerator._generate_candidatesNN)r   r   )r&   r'   r(   r)   r*   r+   r   r   r@   rW   r   r,   r   r-   r%   rY   boolrZ   r[   r\   r   r   r   r   r.   S   s@    
$_:
&
r.   c                       s   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dZ	e
dd Ze
dd Ze
dd Zdd Zdejdeejeej f fddZdejdeejef fddZdejdejdejdejfd d!Z  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_tokenizerr0   r   r1   r2   r3   r   c	           	         sF   t  |||||| || _|| _d | _d | _|jj| _|jj| _d S N)	superrW   r   r   prev_target_ids_lenprev_assistant_idsr0   target_lookbehindassistant_lookbehind)	r   r   r/   r   r   r0   r1   r2   r3   r   r   r   rW   r  s   
z6AssistedCandidateGeneratorDifferentTokenizers.__init__c                 C   s   t  }i }|D ]f}t|}t| }||v rq|| d}|d7 }|d | jd k ri|d | jd k rit| }|| | |d |d f dkrV|d7 }|d7 }nn|d | jd k ri|d | jd k s6|||< q|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tuplerx   addrJ   )input_matrixZnonzero_idxvisiteddiagsidx	start_idxZtuple_start_idxZcur_diag_lenr   r   r   _get_longest_diag_dict  s(   

$

$

zDAssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_dictc                 C   sJ   t | |  }t| }t| }t|}|| }|| }||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valuesrD   ri   Zargmax)r   r   Zdiags_valuesZ
diags_keysZ	best_diagZdiag_start_indexZdiag_start_lengthr   r   r   _get_longest_diag_index  s   

zEAssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_indexc                 C   s   |j | k}t|st|}|t}|  sdS t	|\}}|d | }|d | }| j
d |  }|dd|| df }	|dd||| 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*   Z	is_tensortensorr:   r-   anyitemr~   r   rJ   )promptZprompt_plus_new_tokensZcompare_matZcompare_mat_intZlongest_locationZlongest_diag_lengthZnew_token_start_indexZdiscrepancy_with_olddiscrepancy_lengthnew_tokens_onlydiscrepancy_onlyr   r   r   _get_tokens_diag  s"   




z>AssistedCandidateGeneratorDifferentTokenizers._get_tokens_diagc                 C   s.   |j |dd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Zskip_special_tokensZclean_up_tokenization_spacesptadd_special_tokensZreturn_tensorsr   )batch_decoder:   r7   )r   r   source_tokenizerdestination_tokenizertextZdest_idsr   r   r   &convert_source_tokens_to_target_tokens  s   zTAssistedCandidateGeneratorDifferentTokenizers.convert_source_tokens_to_target_tokensr   c           	      C   s   t | j}|dkr|dfS || jj}d}| |\}}|| _tt|| j	|j
d  d}| || | |||}| jdd | jjdi || j}| ||j|}|j
d | _|j| jd< |j| _| j|j
d krr|dfS |dfS )rX   r   Nrj   r9   r   r5   r   )r-   r;   r:   r/   r7   _prepare_assistant_input_idsr   re   rk   rN   rJ   rZ   r[   rG   poprt   _process_assistant_outputsrv   r   r5   )	r   r   r]   rm   assistant_input_idsrO   r^   rz   new_target_idsr   r   r   r     s&   
z<AssistedCandidateGeneratorDifferentTokenizers.get_candidatesc                 C   s  | j | jd}d}| jdur| j| jkr| j| j }| j|dd|df fi |}|jd }| jdd| df }| ||\}}	}
| j}|	dur|dkr|
jd dkr||
jd krj|
|dd| df< n'||
jd kr||
jd  }|ddd| f }|
|dd|
jd  df< |}|	jd dkrtj	||	gdd}||fS tj	||gdd}||fS | j|fi |}|jd | _||fS )zIConverts target input IDs to assistant input IDs, handling discrepancies.r   r   r   Nr   rj   rr   )
r   r   r   r   r   r   rJ   r   r*   ru   )r   r   Zconvert_kwargsrm   Zstart_index_in_target_windowZnew_assistant_idsZprompt_use_lengthZ
prompt_user   r   r   r   Zdiscrepancy_length_diffr   r   r   r     sD   

zJAssistedCandidateGeneratorDifferentTokenizers._prepare_assistant_input_idsassistant_sequencesr   c                 C   s   | j jd }|| j }| j|dd|df | j| jd}|jd }|dd| df }| ||\}	}
}	|}|
durM|
jd dkrLtj||
gdd}n	tj||gdd}t	| j
drh|ddd| j
jf }|S )z7Processes assistant outputs to obtain target input IDs.r   Nr   r   rj   rr   rl   )r   rJ   r   r   r   r   r   r*   ru   hasattrr0   rl   )r   r   r   r   Znum_prev_assistantZstart_assistant_look_indexZnew_target_ids_from_windowZtarget_prompt_use_lengthZtarget_prompt_use_Ztarget_new_tokens_onlyr   r   r   r   r   J  s&   

zHAssistedCandidateGeneratorDifferentTokenizers._process_assistant_outputsr|   )r&   r'   r(   r)   r*   r+   r   r   r@   rW   staticmethodr   r   r   r   r   r,   r   r-   r   r   __classcell__r   r   r   r   r~   Q  sN    (	
#

 $*.r~   c                       s(   e Zd ZdZ fddZdd Z  ZS )_PruneReindexingLMHeadal  
    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                    s$   t    t|||jj| _d S r   )r   rW   r   r:   weightr8   pruned_lm_head)r   original_lm_headassistant_overlap_token_idsr   r   r   rW   w  s   


z_PruneReindexingLMHead.__init__c                 C   s   |  |}|S r   )r   )r   Zhidden_statesZpruned_logitsr   r   r   forward}  s   
z_PruneReindexingLMHead.forward)r&   r'   r(   r)   rW   r   r   r   r   r   r   r   k  s    r   c                       s:   e Zd Zdejf fddZdejdejfddZ	  Z
S )_MapInputEmbeddingoriginal_embeddingc                    s(   t    || _|j| _|| _d| _dS )aT  
        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   r   r   r   map)r   r   r   r   r   r   rW     s
   
	
z_MapInputEmbedding.__init__r   r   c                 C   s6   | j r| j|d  dd}nd| _ |}| |S )z
        Args:
            input_ids (torch.LongTensor): Tensor of token IDs (batch_size, seq_len).

        Returns:
            torch.FloatTensor: Corresponding input embeddings.
        )r   rj   r   T)r   r   	unsqueezer   )r   r   Zmy_input_idsr   r   r   r     s
   
z_MapInputEmbedding.forward)r&   r'   r(   nnZ	EmbeddingrW   r*   r+   r,   r   r   r   r   r   r   r     s    r   c                   @   s   e Zd ZU dZed Zeed< dZeed< e	ddd			
	d"dddddede
ded defddZdd Zdd Zdee fddZdejdejfddZdejdejfd d!Zd
S )#AssistantToTargetTranslatora  
    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://www.arxiv.org/abs/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_device (str, optional): The device on which the assistant model is loaded.
                Defaults to "cpu".
        assistant_model_device (`str`, defaults to "cpu"): The device where the assistant model is located. Used for placing tensors.
        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.
    ZInfFILTER_VALUErj   SUPPRESS_TOKEN_IDassistant_model_device4.53versioncpuNFr   r   r   target_vocab_sizer/   r   assistant_prune_lm_headc                 C   s   || _ || _|d u r|n|j| _|| _|  \| _| _|  | _	d | _
|o(|d u| _t| j	dkrw| jritjt| j tj| jd| _| }t|| j}~|| | }	t|	| j}
~	||
 |
| _d S tt|  | jg| _
d S d S )Nr   )r8   r7   )_target_tokenizer_assistant_tokenizerr7   _assistant_model_devicer   "_get_assistant_to_target_input_ids_assistant_to_target_input_idstarget_to_assistant_input_ids_get_suppress_input_idsZ_suppress_input_idslogits_processorsr   rd   r*   r   r   r   rK   r   Zget_output_embeddingsr   Zset_output_embeddingsZget_input_embeddingsr   Zset_input_embeddingsmap_input_embeddingsr   r   )r   r   r   r   r   r/   r   r   r   Zoriginal_input_embeddingsr   r   r   r   rW     s<   






z$AssistantToTargetTranslator.__init__c                 C   s   | j r	d| j_dS dS )as  
        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.

        FN)r   r   r   r   r   r   r   unmap_input_ids  s   z+AssistantToTargetTranslator.unmap_input_idsc                    s  | j  }| j }d}| j |ddd }t|dkrN| j |d d | j|ddd }t|dkrN| j|d d   krN fdd| D }t| }tj	|d f| j
td	}i }| D ]\}	}
||	}|d ur{|||
< |
||< qf|| j|fS )
N F)r   r   r   c                    s.   i | ]\}}|  r| d n||qS r   )
startswithreplace).0tokr   Zassistant_space_signZtarget_space_signr   r   
<dictcomp>  s    zRAssistantToTargetTranslator._get_assistant_to_target_input_ids.<locals>.<dictcomp>r   r8   )r   Z	get_vocabr   rd   Zconvert_ids_to_tokensr>   re   r   r*   fullr   r-   rI   r:   r   )r   Ztarget_vocabZassistant_vocabZ	space_strZtarget_space_idsZassistant_space_idsZmax_assistant_indexZassistant_to_target_input_idsr   r   Zassistant_idZ	target_idr   r   r   r     s.   

	
z>AssistantToTargetTranslator._get_assistant_to_target_input_idsr   c                 C   s   t | j| jkd S )z`
        Get the input ids that are in the assistant vocab but not in the target vocab.
        r   )r*   wherer   r   r   r   r   r   r     s   z3AssistantToTargetTranslator._get_suppress_input_idsassistant_candidate_idsc                 C   sf   t |d |jd  }|dkr|S |d| df }| jr"| j| }| j| }tj||dfddS )aS  
        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   Nrr   )rd   rJ   r   r   r   r*   ru   r   )r   r   target_input_idsr   Znum_new_tokensZlast_candidate_idsZtransformed_slicer   r   r   get_target_ids  s   	

z*AssistantToTargetTranslator.get_target_idsassistant_logitsc                 C   s   g |j dd | jR }tj|| j| jd}| j| jk}| j| }| jr-||d|f< |S |dd| jj d f }|d|f |d|f< |S )zS
        Return the target logits that correspond to the assistant logits.
        Nrj   r7   .r   )	rJ   r   r*   r   r   r   r   r   r   )r   r   Ztarget_shapeZtarget_logitsZassistant_indices_maskZtarget_logits_supported_indicesZvalid_assistant_logitsr   r   r   get_target_logits4  s   

z-AssistantToTargetTranslator.get_target_logitsr   NF)r&   r'   r(   r)   floatr   __annotations__r   r-   r   strr   r}   rW   r   r   r   r   r*   r+   r   r,   r   r   r   r   r   r     s<   
 
,
#
r   c                   @   sf   e Zd ZdZe Zeeddd			ddd	d
d	de	de
ded dedefddZedd ZdS )AssistantVocabTranslatorCachez
    Cache for `AssistantToTargetTranslator` instances. The instances are computed at
    pre-processing time, and this cache allows us to avoid recomputing them.
    r   r   r   r   NFr   r   r   r   r/   r   r   r   c           	      C   sV   | j |}|d u rt }|| j |< ||}|d u r)t||||||}|||< |S r   )_cacherI   weakrefWeakKeyDictionaryr   )	clsr   r   r   r   r/   r   assistant_dictmappingr   r   r   get_translatorR  s    

z,AssistantVocabTranslatorCache.get_translatorc                 C   sT   dd | j D }|D ]}| j |= q
| j  D ]}dd |D }|D ]}||= q!qdS )z
        Clean up dead references in the cache.
        This removes entries where either the target_tokenizer or assistant_tokenizer
        has been garbage collected.
        c                 S      g | ]}|d u r|qS r   r   r   rT   r   r   r   
<listcomp>x      z9AssistantVocabTranslatorCache.cleanup.<locals>.<listcomp>c                 S   r   r   r   r   r   r   r   r   ~  r   N)r   r   )r   Z	dead_keysrT   r   r   r   r   cleanupp  s   
z%AssistantVocabTranslatorCache.cleanupr   )r&   r'   r(   r)   r   r   r   classmethodr   r-   r   r   r}   r   r   r   r   r   r   r   r   J  s2    
r   c                       s   e Zd ZdZ		ddejddddddd	d
dededeej	 ddf fddZ
dejdeejeej f fddZddejdedef fddZdejdejfddZ  ZS )%UniversalSpeculativeDecodingGeneratorz
    `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   r0   r   r1   atm_translatorr2   r3   r   c
           
   
      s0   || _ t ||||||||	 d| _d | _d S )Nr   )_atm_translatorr   rW   _target_seq_len_with_candidates_prev_assistant_ids)
r   r   r/   r   r   r0   r1   r   r2   r3   r   r   r   rW     s   
z.UniversalSpeculativeDecodingGenerator.__init__r   c                 C   s   | | jj}| |\}}| |\}}|dkr|dfS | j||d | |||}d|d _d|d _| j	j
durA| j	j
|d< | |\| _}| j	||| j}	|	jd | _| j	|}
|	|
fS )zk
        Simplified version of get_candidates that uses the translator cache for token conversion.
        r   Nrn   Tr0   r3   rj   )r:   r/   r7   r   rY   rZ   r[   rM   rL   r   r   r\   r   r   rJ   r   r   )r   r   r   r   rn   rO   r]   r^   Zassistant_candidate_logitsZtarget_candidate_idsZtarget_candidate_logitsr   r   r   r     s$   

z4UniversalSpeculativeDecodingGenerator.get_candidatesr   r   rn   c                    s6   | j d u rt| j|jd | jjj| _t j||dS )Nrj   r   )	r   rp   rG   rJ   r/   rE   rF   r   rZ   )r   r   rn   r   r   r   rZ     s
   
z<UniversalSpeculativeDecodingGenerator._update_past_and_masksr   c           	      C   s$  |j d }| jdkr|}nd}|dd| df }d}| jdkr,| jj|d  }|du rI| jj|ddd}| j|ddd	d
 	| j
j}ntj|gg| j
jd}| jdu r\|}n"| jd | }|dkrt| jddd| f | _tj| j|gdd}|j	tjd}| j  |t|d fS )zM
        Simplified token conversion that only processes new tokens.
        rj   r   r   NTr   Fr   r   r   r   rr   r   )rJ   r   r   r   rI   r   r   r   r   r:   r/   r7   r*   r   r   ru   rK   r   rd   )	r   r   Ztarget_seq_lenZnew_token_countZtarget_new_idsZassistant_new_idsZtarget_new_textr   Ztokens_to_remover   r   r   r     s:   





zBUniversalSpeculativeDecodingGenerator._prepare_assistant_input_idsr|   r   )r&   r'   r(   r)   r*   r+   r   r   r   r@   rW   r   r,   r   r-   r}   rZ   r   r   r   r   r   r   r     s4    	
$ 	r   c                	   @   s|   e Zd ZdZ				ddeej dedee defd	d
Zdej	de
ej	eej f fddZdej	dejdefd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.
    N
      r=   num_output_tokensmax_matching_ngram_sizerl   c                 C   s@   || _ |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   rl   r=   rP   )r   r=   r   r   rl   r   r   r   rW     s   z'PromptLookupCandidateGenerator.__init__r   r   c                 C   sT  | d}| j|d kr|dfS d}d}tt| j|d ddD ]i}|jd|dd}|d| df }||kjdd}|jd	d
d }	|	D ]?}
|
| }|| j }t||| j}||k r|d||f }d	}t	|| j
}t|}| dkr|d  }|d| } nqE|r nq |du st|dkr|dfS |d}tj||fd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   rj   )	dimensionsizestepr   rr   T)as_tuple)r  rl   rw   rk   r   Zunfoldallr   r   r   r=   r*   Znumelr   rd   r   ru   )r   r   Zinput_lengthZ
chosen_idsZmatch_foundZ
ngram_sizewindowsZngram_tensorrS   Zmatch_indicesr   r   Zend_idxmaskZmatch_indices_eosZfirst_eos_indexZcandidate_input_idsr   r   r   r     s@   



z-PromptLookupCandidateGenerator.get_candidatesr!   r"   c                 C   s   dS )r#   Nr   r$   r   r   r   r%   V  s   z8PromptLookupCandidateGenerator.update_candidate_strategy)Nr   Nr   )r&   r'   r(   r)   r   r*   r@   r-   rW   r+   r   r,   r   r%   r   r   r   r   r     s"    
$@r   c                       sp   e Zd ZdZ		ddejddddded	eej d
df fddZ	dejde
ejeej f f fddZ  ZS )EarlyExitCandidateGeneratora  
    `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   r0   r   r1   r2   r3   r   c                    s.   t  j||||||d | jj| _d | j_d S )N)r   r/   r0   r1   r2   r3   )r   rW   r0   assistant_early_exit)r   r   r/   r0   r1   r2   r3   r   r   r   rW     s   	

z$EarlyExitCandidateGenerator.__init__r   c                    sB   t | j| jj}|jj}| j|j_t |\}}||j_||fS r   )getattrr/   Zbase_model_prefixrE   Znum_hidden_layersr	  r   r   )r   r   Z
base_modelZoriginal_num_hidden_layersr_   r`   r   r   r   r     s   
z*EarlyExitCandidateGenerator.get_candidatesr|   )r&   r'   r(   r)   r*   r+   r   r   r@   rW   r   r,   r   r   r   r   r   r   r  g  s$    0r  c              
   C   s  g }t |tr|| |S | jjrVtt|D ]7}||| d ddddd|ddf || d ddddd|ddf || d || d f qt|}|S d| j	j
 v sn| jjdurd| jjd  v r| jjrtt|D ]}|| ddd|ddf ||< qx|S tt|D ]}|| ddddd|ddf ||< q|S |durtt|D ]E}|| g g fkr||| d ddddd|ddf || d ddddd|ddf f q||| d || d f qt|}|S )z9Crops the past key values up to a certain maximum length.r   Nr   r   rc   Z
gptbigcode)r?   r   croprE   rF   rw   rd   rg   r   r   r&   lowerZarchitecturesZmulti_query)modelr5   rl   Znew_pastr   r   r   r   ro     sF   

"&&

 $*
&& ro   r1   
new_lengthrF   r   c                 C   sz  |rdnd}|| vr| S | | }||j d  }|dk r(|ddd|f | |< n|dkr?tj|||j d |fgdd| |< d| v r| d }|dk rY|ddd|f | d< | S |dkr~|ddddddddf d|dd}tj||gdd| d< | S d	| v r| d	 }|dk r|ddd|f | d	< | S |dkr|ddddddf d|d}tj||gdd| d	< | S )
zNExpands or crops the model's mask for decoding purposes, to the defined lengthr6   r9   r   r   Nrj   rr   Zcross_attention_maskZimage_attention_mask)rJ   r*   ru   Znew_onesrepeat)r1   r  rF   Zmask_keyr  Zmask_length_diffZ
cross_maskZnew_maskr   r   r   rp     s6   &,
$rp   c                 C   s   d| vs
| d du r| S | d }|dddf  d}||jd  }|dk r2|ddd|f }| S |dkrI|d|}tj| d |gdd| d< | S )zXExpands or crops the model's token_type_ids for decoding purposes, to the defined lengthtoken_type_idsNrj   r   r   rr   )r   rJ   r  r*   ru   )r1   r  r  Zfinal_token_typeZtype_length_diffZtoken_type_copiesr   r   r   rq     s   rq   )3rB   r   typingr   r   r   r   r   numpyri   r*   Ztorch.nnr   Zpytorch_utilsr   utilsr	   Zsklearn.metricsr
   Zcache_utilsr   r   Zlogits_processr   r   r   Zmodeling_utilsr   Ztokenization_utils_baser   Zconfiguration_utilsr   Zutils.deprecationr   r   r.   r~   Moduler   r   r   r   r   r   r  ro   r   r-   r}   rp   rq   r   r   r   r   <module>   sF   '   " '9tp8*)*$