U
    di<                    @   s  d dl Z d dlZd dlZd dlmZ d dlmZmZmZ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 ddlmZmZmZmZmZmZ ddlm Z  dd	l!m"Z" dd
l#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZB ddlmCZCmDZDmEZEmFZF ddlGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZa ddlbmcZcmdZdmeZemfZfmgZgmhZhmiZi er.ddljmkZk ddllmmZm ddlnmoZo e3peqZre. rPd dlsmtZtmuZu eG dd de-ZveG dd de-ZweG dd de-ZxeG d d! d!e-ZyevZzevZ{evZ|ewZ}ewZ~ewZexZexZeyZeyZee~ezf Zeee|f Zeeef Zeeef Zee}e{f Zeevewf Zeexeyf Zeeef ZG d"d# d#Zd$d% Zd>d'd(Zejejejejeeejd)d*d+Zd?eeed,d-d.Zee-e	f eee e
ee-e	f  d/d0d1Ze
e- e e-d2d3d4Zd5ed6 d7dfejejeeeejd8d9d:Ze
e e	eejf ejejd;d<d=ZdS )@    N)	dataclass)TYPE_CHECKINGAnyCallableDictListOptionalTupleUnion)nn)
functional   )CacheDynamicCacheEncoderDecoderCacheOffloadedCacheQuantizedCacheConfigStaticCache)PretrainedConfig)is_deepspeed_zero3_enabled)is_fsdp_managed_module)CausalLMOutputWithPastSeq2SeqLMOutput)isin_mps_friendly)ExtensionsTrie)ModelOutputis_accelerate_availableis_hqq_availableis_optimum_quanto_availableis_quanto_availableis_torchdynamo_compilinglogging   )DisjunctiveConstraintPhrasalConstraint)
BeamScorerBeamSearchScorerConstrainedBeamSearchScorer)AssistedCandidateGenerator-AssistedCandidateGeneratorDifferentTokenizersCandidateGeneratorPromptLookupCandidateGenerator_crop_past_key_values_prepare_attention_mask_prepare_token_type_ids) NEED_SETUP_CACHE_CLASSES_MAPPINGQUANT_BACKEND_CLASSES_MAPPINGGenerationConfigGenerationMode)#EncoderNoRepeatNGramLogitsProcessor'EncoderRepetitionPenaltyLogitsProcessorEpsilonLogitsWarperEtaLogitsWarperExponentialDecayLengthPenaltyForcedBOSTokenLogitsProcessorForcedEOSTokenLogitsProcessorHammingDiversityLogitsProcessorInfNanRemoveLogitsProcessorLogitNormalizationLogitsProcessorListMinLengthLogitsProcessor!MinNewTokensLengthLogitsProcessorMinPLogitsWarperNoBadWordsLogitsProcessorNoRepeatNGramLogitsProcessor PrefixConstrainedLogitsProcessor RepetitionPenaltyLogitsProcessorSequenceBiasLogitsProcessor$SuppressTokensAtBeginLogitsProcessorSuppressTokensLogitsProcessorTemperatureLogitsWarperTopKLogitsWarperTopPLogitsWarperTypicalLogitsWarper.UnbatchedClassifierFreeGuidanceLogitsProcessor)ConfidenceCriteriaEosTokenCriteriaMaxLengthCriteriaMaxTimeCriteriaStoppingCriteriaStoppingCriteriaListStopStringCriteria)PreTrainedModel)PreTrainedTokenizerBase)BaseStreamer)AlignDevicesHookadd_hook_to_modulec                   @   s   e Zd ZU dZdZejed< dZe	e
ej  ed< dZe	e
ej  ed< dZe	e
e
ej   ed< dZe	e
e
ej   ed< dZe	e
e
e
ej    ed< dS )	GenerateDecoderOnlyOutputaw  
    Outputs of decoder-only generation models, when using non-beam methods.

    Args:
        sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
            if all batches finished early due to the `eos_token_id`.
        scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
            Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
            Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
        attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
        hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
        past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
            Returns the model cache, used to speed up decoding. Different models have a different cache format, check
            the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
    N	sequencesscoreslogits
attentionshidden_statespast_key_values)__name__
__module____qualname____doc__rZ   torch
LongTensor__annotations__r[   r   r	   FloatTensorr\   r]   r^   r_    rh   rh   A/tmp/pip-unpacked-wheel-bm_b0l5e/transformers/generation/utils.pyrY   v   s   
rY   c                   @   s   e Zd ZU dZdZejed< dZe	e
ej  ed< dZe	e
ej  ed< dZe	e
ej  ed< dZe	e
ej  ed< dZe	e
e
ej   ed< dZe	e
e
ej   ed	< dZe	e
e
ej   ed
< dZe	e
e
e
ej    ed< dS )GenerateEncoderDecoderOutputaI  
    Outputs of encoder-decoder generation models, when using non-beam methods.

    Args:
        sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
            if all batches finished early due to the `eos_token_id`.
        scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
            Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
            Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
        encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
            sequence_length, sequence_length)`.
        encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`.
        decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
        cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
        decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
        past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Returns the model cache, used to speed up decoding. Different models have a different cache format, check
            the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
    NrZ   r[   r\   encoder_attentionsencoder_hidden_statesdecoder_attentionscross_attentionsdecoder_hidden_statesr_   )r`   ra   rb   rc   rZ   rd   re   rf   r[   r   r	   rg   r\   rk   rl   rm   rn   ro   r_   rh   rh   rh   ri   rj      s   
#rj   c                   @   s   e Zd ZU dZdZejed< dZe	ej
 ed< dZe	eej
  ed< dZe	eej
  ed< dZe	ej ed< dZe	eeej
   ed< dZe	eeej
   ed	< dZe	eeeej
    ed
< dS )GenerateBeamDecoderOnlyOutputa
  
    Outputs of decoder-only generation models, when using beam methods.

    Args:
        sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
            if all batches finished early due to the `eos_token_id`.
        sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
            Final beam scores of the generated `sequences`.
        scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
            Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
            of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
            Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
            with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
            Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
        beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
            Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
            `(batch_size*num_return_sequences, sequence_length)`.
        attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
        hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
        past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
            Returns the model cache, used to speed up decoding. Different models have a different cache format, check
            the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
    NrZ   sequences_scoresr[   r\   beam_indicesr]   r^   r_   )r`   ra   rb   rc   rZ   rd   re   rf   rq   r   rg   r[   r	   r\   rr   r]   r^   r_   rh   rh   rh   ri   rp      s   
 rp   c                   @   s  e Zd ZU dZdZejed< dZe	ej
 ed< dZe	eej
  ed< dZe	eej
  ed< dZe	ej ed< dZe	eej
  ed< dZe	eej
  ed	< dZe	eeej
   ed
< dZe	eeej
   ed< dZe	eeej
   ed< dZe	eeeej
    ed< dS ) GenerateBeamEncoderDecoderOutputa  
    Outputs of encoder-decoder generation models, when using beam methods.

    Args:
        sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
            if all batches finished early due to the `eos_token_id`.
        sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
            Final beam scores of the generated `sequences`.
        scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
            Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
            of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
            Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
            with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
            Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
        beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
            Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
            `(batch_size*num_return_sequences, sequence_length)`.
        encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
            sequence_length, sequence_length)`.
        encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)`.
        decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, num_heads, generated_length,
            sequence_length)`.
        cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
        decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
        past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
            Returns the model cache, used to speed up decoding. Different models have a different cache format, check
            the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
    NrZ   rq   r[   r\   rr   rk   rl   rm   rn   ro   r_   )r`   ra   rb   rc   rZ   rd   re   rf   rq   r   rg   r[   r	   r\   rr   rk   rl   rm   rn   ro   r_   rh   rh   rh   ri   rs      s   
*rs   c                   @   sD  e Zd ZdZdpejee eej eej eej dddZ	dqeej
 eej
 eeeej
f  eej
ee eeej
f f dddZdreej
 eej
 eeeej
f  ejdd	d
Zej
eej
 eej
 ejdddZej
ee eeeef dddZdseeeeej
f ej
ejeejeeej
f f dddZedteeeej eejeeef f dddZedddZdueeeef eeeeef dddZdd  Zeejej
d!ed"d"eed#	d$d%Z dveeeje!eej
ge"e f ee eeeeef  eej
 eej
 ed&
d'd(Z#dweee$ ed" e$d)d*d+Z%e&ee$f e&ee$f e&ee$f d,d-d.Z'dxej
eej
 eej
 eej
d/d0d1Z(d2d3 Z)d4d5 Z*eeef d6d7d8Z+d9d: Z,d;d< Z-ee eeeef d=d>d?Z.d@dA Z/eeeejedBdCdDZ0edEdFdGZ1eed!eeejedHdIdJZ2edEdKdLZ3dyeee ee&ejef  dMdNdOZ4e5 dzeej
 ee ee ee$ ee!eej
ge"e f  ee ed! edP eej
 eej
 e&e6ejf dQdRdSZ7d{eeejee ee edTdUdVZ8d|ejed" ejdWdXdYZ9eje&ee"e f ee$eedPe&e:ejf dZd[d\Z;e5 ejee$eeedP e&e:ejf d]d^d_Z<ejee$eeedP e&e:ejf d]d`daZ=dbdc Z>eje?ee$eee&e@ejf dddedfZAeje?ee$eedgdhdiZBejeCee$eee&e@ejf djdkdlZDejeee$eeedP e&e:ejf dmdndoZEdS )}GenerationMixina  
    A class containing all functions for auto-regressive text generation, to be used as a mixin in [`PreTrainedModel`].

    The class exposes [`~generation.GenerationMixin.generate`], which can be used for:
        - *greedy decoding* if `num_beams=1` and `do_sample=False`
        - *contrastive search* if `penalty_alpha>0` and `top_k>1`
        - *multinomial sampling* if `num_beams=1` and `do_sample=True`
        - *beam-search decoding* if `num_beams>1` and `do_sample=False`
        - *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`
        - *diverse beam-search decoding* if `num_beams>1` and `num_beam_groups>1`
        - *constrained beam-search decoding* if `constraints!=None` or `force_words_ids!=None`
        - *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`

    To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
    N)	input_idsr_   attention_maskinputs_embedscache_positionc                 K   s  i }| j r||d< nB|dkrV|dk	r6|d d jd nd}tj||jd tj|jd}|dk	r||d< |dk	s|d |jd kr|dd|jd  df }n$|jd |jd kr|dd|f }| jjrd	nd
}	| jjs"|dk	r|d dkrd||	< ||d< n|jtj	d||	< d|d< n|jtj	d||	< |dk	r|
ddkrdtt| jj kr| dd }
|
|dkd |
|d< dD ]R}|
|}|dk	r|r|dd|jd  df }|jtj	d}|||< qt|tr|jdkr|d dk	r.|d j\}}}|d j}n||	 j\}}||	 j}t| | jd}|dkrlt| dd}nt|dd}|dkrt| jj d n"|||| | j|||| j|d	}|dk	r||d< | D ]\}}||kr|||< q|dd |S )a  
        Prepare the model inputs for generation. In includes operations like computing the 4D attention mask or
        slicing inputs given the existing cache.

        See the forward pass in the model documentation for expected arguments (different models might have different
        requirements for e.g. `past_key_values`). This function should work as is for most LLMs.
        rx   Nr   r   r"   dtypedevicer_   decoder_input_idsru   rw   )Zmemory_formatposition_ids)r~   token_type_idsZ5_prepare_4d_causal_attention_mask_with_cache_positiona   has no `_prepare_4d_causal_attention_mask_with_cache_position` method defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're writing code, see Llama for an example implementation. If you're a user, please report this issue on GitHub.)sequence_lengthZtarget_lengthrz   r{   rx   
batch_sizeconfigr_   rv   labels) _supports_cache_classshaperd   arangelongr{   r   is_encoder_decodercloneZcontiguous_formatgetsetinspect	signatureforward
parameterskeyscumsumZmasked_fill_
isinstancer   ndimgetattrbase_model_prefixloggerwarning_once	__class__r`   Zget_max_cache_shaperz   itemspop)selfru   r_   rv   rw   rx   kwargsmodel_inputspast_lengthZinput_ids_keyr~   model_input_namemodel_inputr   r   _r{   
base_modelZcausal_mask_creation_functionkeyvaluerh   rh   ri   prepare_inputs_for_generation\  s    







    


z-GenerationMixin.prepare_inputs_for_generation)inputsbos_token_idmodel_kwargsreturnc              
      s.  | j jr*t| dr*| jj| jkr*| jj n| j  fdd| D }| d}|dk	r|dk	rtd| d  d| d  d		n|dk	r|} d
krd|kr| j jsdtt	
| jj k}|std| jj d| j|||d|d
< n|dk	rtd|d d } | |||}| |fS )zT
        This function extracts the model-specific `inputs` for generation.
        encoderc                    s&   i | ]\}}|d k	s| kr||qS Nrh   ).0kvZ
input_namerh   ri   
<dictcomp>  s
        z9GenerationMixin._prepare_model_inputs.<locals>.<dictcomp>Nz
`inputs`: z` were passed alongside z0 which is not allowed. Make sure to either pass z or z=...ru   rw   zAYou passed `inputs_embeds` to `.generate()`, but the model class z doesn't have its forwarding implemented. See the GPT2 implementation for an example (https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!r   zMYou passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.)r   r   hasattrr   main_input_namer   r   
ValueErrorr   r   r   r   r   r   r   r`   *_maybe_initialize_input_ids_for_generation)r   r   r   r   Zinputs_kwargZhas_inputs_embeds_forwardingrh   r   ri   _prepare_model_inputs  sF    
  
z%GenerationMixin._prepare_model_inputsc                 C   s   |dk	r|S | d}| jjrP|dk	rP|j dd }tj|tj| jdd S d}|	 D ]}t
|tjr\|jd } q|q\d|krtj|dftj| jdS |dkrtd	tj|dftj| jd| S )
z3Initializes input ids for generation, if necessary.Nencoder_outputsr|   ry   ir"   r   rw   zB`bos_token_id` has to be defined when no `input_ids` are provided.)r   r   r   Zlast_hidden_statesizerd   onesr   r{   valuesr   Tensorr   r   )r   r   r   r   r   r   r   r   rh   rh   ri   r     s     

z:GenerationMixin._maybe_initialize_input_ids_for_generation)r   pad_token_ideos_token_idr   c                 C   s   t j|jd d t j|jd}|d kr*|S t|jdkoH|jt jt jfk}|sR|S |d k	oht||d	 }|d kpt||d	  }|| }|
| }	|	| ||   }
|
S )Nr   ry   elementsZtest_elements)rd   r   r   r   r{   lenrz   intr   anyne)r   r   r   r   Zdefault_attention_maskZis_input_idsZis_pad_token_in_inputsZ&is_pad_token_not_equal_to_eos_token_idZcan_infer_attention_maskZattention_mask_from_paddingrv   rh   rh   ri   &_prepare_attention_mask_for_generation9  s"     z6GenerationMixin._prepare_attention_mask_for_generation)inputs_tensorr   generation_configr   c                    s   |   }t| dr6t|dr&d|j_nt|tdd dddgfdd	| D }tt	|j
j d
 kpvd k}|s fdd	| D }|j|d< |j|d< |d k	r|n| j}d|d< |||< |f ||d< |S )Nhf_device_map_hf_hookT)io_same_devicedecoder_Z
cross_attn	use_cachec                    s,   i | ]$\ }t  fd dD s |qS )c                 3   s   | ]}  |V  qd S r   )
startswithr   pargumentrh   ri   	<genexpr>l  s     z\GenerationMixin._prepare_encoder_decoder_kwargs_for_generation.<locals>.<dictcomp>.<genexpr>r   )r   r   )irrelevant_prefixr   ri   r   i  s    zRGenerationMixin._prepare_encoder_decoder_kwargs_for_generation.<locals>.<dictcomp>r   r   c                    s   i | ]\}}| kr||qS rh   rh   )r   r   r   )encoder_signaturerh   ri   r   q  s      output_attentionsoutput_hidden_statesreturn_dictr   )Zget_encoderr   r   r   rX   rW   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   encoder_kwargsZencoder_accepts_wildcardrh   )r   r   ri   ._prepare_encoder_decoder_kwargs_for_generationV  s,    







z>GenerationMixin._prepare_encoder_decoder_kwargs_for_generation)r   r   r   decoder_start_token_idr{   r   c                 C   sv  |dk	rd|kr| d}n d|kr8|dkr8| d}nd}|dkrJ| j}|jdkr|jd |kr|td| d|jd  |dd}ntj|dftj|d	| }|dkr|}nd
| j	j
 ks| jjdkrd
| jjj krn| jjdkrn~|dddf |dddf k  rntj||gdd}d|krn|d }tjt|ddddf |fdd}||d< ||fS )zGPrepares `decoder_input_ids` for generation with encoder-decoder modelsNr}   ru   r"   r   z1`decoder_start_token_id` expected to have length z	 but got r|   ry   Zdonutzvision-encoder-decoder)Zwhisperdimdecoder_attention_mask)r   r{   r   r   r   viewrd   r   r   r   r`   lowerr   Z
model_typer   allitemcat	ones_like)r   r   r   r   r   r{   r}   r   rh   rh   ri   )_prepare_decoder_input_ids_for_generation  sF    

*
z9GenerationMixin._prepare_decoder_input_ids_for_generationr"   F)expand_sizer   ru   r   c                    sl    dkr||fS  fdd}|dk	r2|j  dd}||}|rd|ddkrTtd||d |d< ||fS )	zIExpands tensors from [batch_size, ...] to [batch_size * expand_size, ...]r"   c                    sH   | D ]>}|dkr| | d k	rt | | tjr| | j dd| |< q| S )Nrx   r   r   )r   rd   r   repeat_interleave)Zdict_to_expandr   r   rh   ri   _expand_dict_for_generation  s    
zRGenerationMixin._expand_inputs_for_generation.<locals>._expand_dict_for_generationNr   r   r   zMIf `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.)r   r   r   )r   r   ru   r   r   rh   r   ri   _expand_inputs_for_generation  s    

z-GenerationMixin._expand_inputs_for_generation)outputsc                 C   sR   d }d}d|kr|j }n2d|kr(|j}n"d|kr8|j}nd|krJ|j}d}||fS )Nr_   memspast_buckets_statescache_params)r_   r   r   r   )r   r   r_   
cache_namerh   rh   ri   _extract_past_from_model_output  s    z/GenerationMixin._extract_past_from_model_output)r   r   r   num_new_tokensr   c                 C   sP  |  |\}}|||< t|dd d k	r0|j|d< d|krh|d }tj||d d df dgdd|d< |sd|kr|d }tj|||jd dfgdd|d< n6d|kr|d }	tj|	|	|	jd dfgdd|d< |d	d
r|d dd  | |d< nJ|	d}
tj
|
d d |
d | d |
jd|
j}t|
|f|d< |S )Nstater   r|   r   rv   r   r"   r   r   Trx   rz   )r   r   r   rd   r   	unsqueezenew_onesr   r   r   r   rz   tor{   )r   r   r   r   r   r   cacher   rv   r   Zpast_positionsZnew_positionsrh   rh   ri   #_update_model_kwargs_for_generation  s@    
( 


  z3GenerationMixin._update_model_kwargs_for_generationc                 C   s   t d| jj d| j d S )NzGMake sure that a `_reorder_cache` function is correctly implemented in z to enable beam search for )NotImplementedErrorr   ra   )r   r_   beam_idxrh   rh   ri   _reorder_cache  s    zGenerationMixin._reorder_cacherT   rU   )	r   ru   r   assistant_modellogits_processortarget_tokenizerassistant_tokenizerr   r   c	              
   C   sr   t dd |||fD }	|jdk	r<t|j|j|j|jd}
n2|	rZt||||||||d}
nt||||||d}
|
S )zU
        Returns the candidate generator to be used in `assisted_generation`
        c                 s   s   | ]}|d k	V  qd S r   rh   )r   r   rh   rh   ri   r   ,  s     z;GenerationMixin._get_candidate_generator.<locals>.<genexpr>N)r   Znum_output_tokensmax_matching_ngram_size
max_length)ru   r   r   r   r   r   r   r   )ru   r   r   r   r   r   )r   Zprompt_lookup_num_tokensr+   _eos_token_tensorr   r   r)   r(   )r   r   ru   r   r   r   r   r   r   Zdifferent_tokenizerscandidate_generatorrh   rh   ri   _get_candidate_generator  s8    
z(GenerationMixin._get_candidate_generator)
r   input_ids_seq_lengthencoder_input_idsprefix_allowed_tokens_fnr   r{   r   negative_prompt_idsnegative_prompt_attention_maskr   c
              	   C   s   t  }
|jdk	r6|jdkr6|
t|j| ||	|jd |jdk	rR|
t|jd |jdk	r|jdkr|
t|j|j	|j
d |jdk	r|jdkrt|jdkr|
t|j|d	 ntd
t |jdk	r|jdkr|
t|jd |jdk	r|jdkr|
t|j |jdk	rZ|jdkrZt|jdkrN|
t|j| ntdt |jdk	rz|
t|j|j |jdk	r|jdk	r|jdkr|
t|j|j|d |jdk	r|jdk	r|jdkr|
t||j|j|d |dk	r|
t||j	|j
  |j dk	r2|
t!|j  |j"dk	rV|
t#|j$|j"|d |j%dkrn|
t&  |j'dk	r|
t(|j'|j| |j)dk	r|
t*|j)|d |j+dk	r|}|dks|j dkr|n|d }|
t,|j+||d |j-dk	rt.d|j/dk	r0|
|j/0| j1j2| | 3|
|}
|j4r|j	dkrt5|jt6rnt|jd }n&t5|jt7j8r|jjd d }nd}nd}|j9dk	r|j9dkr|
t:|j9 |j;dk	r|j;dkr|
t<|j;|d |j=dk	r|j=dk r|
t>|j=|d |j?dk	r:|
t@|j?|d |jAdk	rf|jAdk rf|
tB|jA|d |jCdk	rd|jC  k rdk rn n|
tD|jC|d |jEdk	rd|jE  k rdk rn n|
tF|jE||d |jGdkr|
tH  |
S )z
        This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]
        instances used to modify the scores of the language model head.
        Nr"   )Zunconditional_idsZunconditional_attention_maskr   sequence_bias        )diversity_penalty	num_beamsnum_beam_groups      ?r   )penaltyr  zyPassing `encoder_repetition_penalty` requires some form of `input_ids` to be passed to `generate`, ignoring the argument.)r  r   z{Passing `encoder_no_repeat_ngram_size` requires some form of `input_ids` to be passed to `generate`, ignoring the argument.r{   TzYou have explicitly specified `forced_decoder_ids`. Please remove the `forced_decoder_ids` argument in favour of `input_ids` or `decoder_input_ids` respectively.)top_kmin_tokens_to_keep)top_pr  )min_pr  )Zmassr  )epsilonr  )r  r  r{   )Ir=   Zguidance_scaleappendrL   r   r
  rE   r  r:   r  r  Zencoder_repetition_penaltyr   r   r4   warningswarnUserWarningZrepetition_penaltyrD   Zno_repeat_ngram_sizerB   Zencoder_no_repeat_ngram_sizer3   Zbad_words_idsrA   r  
min_lengthr>   min_new_tokensr?   rC   Zforced_bos_token_idr8   Zforced_eos_token_idr9   r   Zremove_invalid_valuesr;   Z exponential_decay_length_penaltyr7   Zsuppress_tokensrG   Zbegin_suppress_tokensrF   Zforced_decoder_idsr   Zwatermarking_configZconstruct_processorr   
vocab_size_merge_criteria_processor_list	do_sampler   listrd   r   ZtemperaturerH   r  rI   r  rJ   r  r@   Z	typical_prK   Zepsilon_cutoffr5   Z
eta_cutoffr6   Zrenormalize_logitsr<   )r   r   r  r  r  r   r{   r   r  r  Z
processorsZbegin_indexr  rh   rh   ri   _get_logits_processorK  s   	


* *  z%GenerationMixin._get_logits_processor)r   stopping_criteria	tokenizerr   c                 K   s   t  }|jd k	r2t| jdd }|t|j|d |jd k	rN|t|jd |jd k	r||d krht	d|t
|j|d |jd k	r|t|jd |jr|jd k	r|jdkr|t|jd | ||}|S )	Nmax_position_embeddings)r   r$  )max_timea  There are one or more stop strings, either in the arguments to `generate` or in the model's generation config, but we could not locate a tokenizer. When generating with stop strings, you must pass the model's tokenizer to the `tokenizer` argument of `generate`.)stop_stringsr#  )r   r   )assistant_confidence_threshold)rR   r   r   r   r  rO   r%  rP   r&  r   rS   r  rN   Zis_assistantr'  rM   r  )r   r   r"  r#  r   criteriar$  rh   rh   ri   _get_stopping_criteria0  s<    




z&GenerationMixin._get_stopping_criteria)default_listcustom_listr   c                 C   s   t |dkr|S |D ]h}|D ]^}t|t|krt|tr>dnd}td| dt| d| d| d| d	| d
| dqq|| |S )Nr   zstopping criteriazlogits processorz	A custom z	 of type z with values zS has been passed to `.generate()`, but it has already been created with the values z. z has been created by passing the corresponding arguments to generate or by the model's config default values. If you just want to change the default values of zO consider passing them as arguments to `.generate()` instead of using a custom .)r   typer   rQ   r   extend)r   r*  r+  defaultZcustomZobject_typerh   rh   ri   r  W  s    2
z.GenerationMixin._merge_criteria_processor_list)rZ   r[   rr   normalize_logitsr   c                 C   s6  |dkr<t |d jd dd|j}|dt|}t |	t|d
dd}|r|	d| jj|jd }t jjj|dd}|	d|jd }|dk }d|  d }| ddd|f }|ddd|f }d||< || jj }|jd | }|dd|df | }	|d|	}
d|
|< |
S )a  
        Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was
        used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.

        Parameters:
            sequences (`torch.LongTensor`):
                The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or
                shorter if all batches finished early due to the `eos_token_id`.
            scores (`tuple(torch.FloatTensor)`):
                Transition scores for each vocabulary token at each generation step. Beam transition scores consisting
                of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
                Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
                with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
            beam_indices (`torch.LongTensor`, *optional*):
                Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
                `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at
                generate-time.
            normalize_logits (`bool`, *optional*, defaults to `False`):
                Whether to normalize the logits (which, for legacy reasons, may be unnormalized).

        Return:
            `torch.Tensor`: A `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing
                the transition scores (logits)

        Examples:

        ```python
        >>> from transformers import GPT2Tokenizer, AutoModelForCausalLM
        >>> import numpy as np

        >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
        >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
        >>> tokenizer.pad_token_id = tokenizer.eos_token_id
        >>> inputs = tokenizer(["Today is"], return_tensors="pt")

        >>> # Example 1: Print the scores for each token generated with Greedy Search
        >>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
        >>> transition_scores = model.compute_transition_scores(
        ...     outputs.sequences, outputs.scores, normalize_logits=True
        ... )
        >>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
        >>> # encoder-decoder models, like BART or T5.
        >>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
        >>> generated_tokens = outputs.sequences[:, input_length:]
        >>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
        ...     # | token | token string | log probability | probability
        ...     print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
        |   262 |  the     | -1.414 | 24.33%
        |  1110 |  day     | -2.609 | 7.36%
        |   618 |  when    | -2.010 | 13.40%
        |   356 |  we      | -1.859 | 15.58%
        |   460 |  can     | -2.508 | 8.14%

        >>> # Example 2: Reconstruct the sequence scores from Beam Search
        >>> outputs = model.generate(
        ...     **inputs,
        ...     max_new_tokens=5,
        ...     num_beams=4,
        ...     num_return_sequences=4,
        ...     return_dict_in_generate=True,
        ...     output_scores=True,
        ... )
        >>> transition_scores = model.compute_transition_scores(
        ...     outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
        ... )
        >>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
        >>> # Tip 1: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
        >>> # use case, you might want to recompute it with `normalize_logits=True`.
        >>> # Tip 2: the output length does NOT include the input length
        >>> output_length = np.sum(transition_scores.numpy() < 0, axis=1)
        >>> length_penalty = model.generation_config.length_penalty
        >>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)
        >>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
        True
        ```Nr   r|   r"   r   )rd   r   r   r   r   r{   expandr   stackZreshape	transposer   r  r   r   log_softmaxr   summaxr   gather)r   rZ   r[   rr   r0  Zbeam_indices_maskZmax_beam_lengthZbeam_sequence_indicesZcut_idxindicesZtransition_scoresrh   rh   ri   compute_transition_scoresl  s&    T$z)GenerationMixin.compute_transition_scoresc                 C   s8   t  s4|  s4ddddg}td| jj d| ddS )	z
        Confirms that the model class is compatible with generation. If not, raises an exception that points to the
        right class to use.
        ZForCausalLMZForConditionalGenerationZForSpeechSeq2SeqZForVision2SeqzThe current model class (z) is not compatible with `.generate()`, as it doesn't have a language model head. Classes that support generation often end in one of these names: r,  N)r    Zcan_generate	TypeErrorr   r`   )r   Z$terminations_with_generation_supportrh   rh   ri   _validate_model_class  s    z%GenerationMixin._validate_model_classc                    s    d krd S j jrb j jsbdddgfddt j D t fddD }|sbtdd	}j  j j  jkr|d k	rtd
| dn |d ks|d krtd| dd S )NZencoder_attention_headsZencoder_ffn_dimZencoder_layersc                    s   g | ]}| kr|qS rh   rh   r   attr)attributes_to_checkrh   ri   
<listcomp>  s      z7GenerationMixin._validate_assistant.<locals>.<listcomp>c                 3   s&   | ]}t j|t  j|kV  qd S r   )r   r   r<  )r   r   rh   ri   r     s    z6GenerationMixin._validate_assistant.<locals>.<genexpr>zThe main model and the assistant don't have compatible encoder-dependent input shapes. Ensure you load the assistant with the correct encoder-decoder class, e.g. `AutoModelForSpeechSeq2Seq` for Whisper.zc(see https://huggingface.co/docs/transformers/en/generation_strategies#universal-assisted-decoding)z`assistant_tokenizer` is not required when the main and assistant models use the same tokenizer. Please omit `assistant_tokenizer` from `generate()` r,  zThe main and assistant moedels have different tokenizers. Please provide `tokenizer` and `assistant_tokenizer` to `generate()` )r   r   dirr   r   get_text_configr  )r   r   r#  r   Z	are_equalZdoc_referencerh   )r   r>  r   ri   _validate_assistant  s.    


z#GenerationMixin._validate_assistantr   c                 C   s  t |ddtr*| js*t| jj d| jjrHdD ]}|	|d q6g }t
t| jj}d|ksnd|kr|t
t| jjO }| jjrTt| | jd}t| dd}|dkr|dk	rt|dd}|dk	rt
t|jj}||O }t| dd}|dkr|dk	rt|dd}|dk	r@t
t|jj}	|d	d
 |	D O }d|krT|dhO }| D ](\}}
|
dk	r\||kr\|| q\|rtd| ddS )zXValidates model kwargs for generation. Generate argument typos will also be caught here.r_   Nz does not support an instance of `Cache` as `past_key_values`. Please check the model documentation for supported cache formats.)r}   r   r   r   decoderc                 S   s   h | ]}d | qS )r   rh   )r   xrh   rh   ri   	<setcomp>E  s     z9GenerationMixin._validate_model_kwargs.<locals>.<setcomp>Zassistant_encoder_outputsz8The following `model_kwargs` are not used by the model: zG (note: typos in the generate arguments will also show up in this list))r   r   r   r   r   r   r`   r   r   r   r   r   r   r   r   r   r   r   r   r  )r   r   r   Zunused_model_argsZ
model_argsr   r   Zencoder_model_argsrC  Zdecoder_model_argsr   rh   rh   ri   _validate_model_kwargs  sD    




z&GenerationMixin._validate_model_kwargsc              	   C   s  t  r
dS |r8|jdkr8|jdkr8td|j dt ||jkrp| jjrNdnd}td| d| d	|j d
d}|r|d|j d7 }|j	dk	r|j	|jkrtd|j	 d|j d| t |j
dk	r|j
| }||jkrtd|j
 d| d|j d| t dS )z=Performs validation related to the resulting generated lengthN   z0Using the model-agnostic default `max_length` (=zz) to control the generation length. We recommend setting `max_new_tokens` to control the maximum length of the generation.r}   ru   zInput length of z is z, but `max_length` is set to z}. This can lead to unexpected behavior. You should consider increasing `max_length` or, better yet, setting `max_new_tokens`.z Generation will stop at the defined maximum length. You should decrease the minimum length and/or increase the maximum length.z" Note that `max_length` is set to z, its default value.z-Unfeasible length constraints: `min_length` (z.) is larger than the maximum possible length (z).z1Unfeasible length constraints: `min_new_tokens` (z$), when added to the prompt length (z/), is larger than the maximum possible length ()r    max_new_tokensr   r  r  r  r   r   r   r  r  )r   r   input_ids_lengthhas_default_max_lengthZinput_ids_stringZmin_length_error_suffixr  rh   rh   ri   _validate_generated_lengthU  sD    

z*GenerationMixin._validate_generated_lengthc                 C   s   |j dk	rB|s4|jdk	r4td|j  d|j d |j | |_n2|dkrt||jd krt| jjst| j|jd 8  _|jdk	r|std|j d|j d	 |j| |_n6|dkr||jd kr| jjst	|j|jd  d
|_|S )z]Prepared max and min length in generation configs to avoid clashes between similar attributesNzBoth `max_new_tokens` (=z) and `max_length`(=z) seem to have been set. `max_new_tokens` will take precedence. Please refer to the documentation for more information. (https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)rw   r"   zBoth `min_new_tokens` (=z) and `min_length`(=z) seem to have been set. `min_new_tokens` will take precedence. Please refer to the documentation for more information. (https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)r   )
rH  r   r   warningr   r   r   r  r  r6  )r   r   rJ  has_default_min_lengthr   rI  r   rh   rh   ri   _prepare_generated_length  s6    

z)GenerationMixin._prepare_generated_length)r   r   r   c                 K   s   d}|dkrpt  sf| jjrf| jjt| jkrft| j dkrft	| j}|| jkrft
dt || _| j}d}t  st|}|jf |}|s|jdkr| jj|_|jdkr| jj|_|jdkr| jj|_|jdkr| jj|_n|}||fS )z
        Prepares the base generation config, then applies any generation configuration options from kwargs. This
        function handles retrocompatibility with respect to configuration files.
        FNr   a?  You have modified the pretrained model configuration to control generation. This is a deprecated strategy to control generation and will be removed in v5. Please use and modify the model generation configuration (see https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )T)r    r   Z_from_model_configZ_original_object_hashhashr   r   Z&_get_non_default_generation_parametersr1   Zfrom_model_configr  r  r  copydeepcopyupdater   r   r   r   )r   r   r   Zusing_model_generation_configZnew_generation_configr   rh   rh   ri   _prepare_generation_config  sB    	








z*GenerationMixin._prepare_generation_configc                 C   s  d|kr>| j js>tj|d ddddf tjddd }ndd|kr|| j jr|tj|d ddddf tjddd }n&tj|dddf tjddd }d}|ddk	r|d }d}t|ts|d d j	d }nt
|d	r| dk	r| }t s||d }||d
< |S )zbCalculates `cache_position` for the pre-fill stage based on `input_ids` and optionally past lengthrw   r   Nr   r"   Zdecoder_inputs_embedsr_   r   get_seq_lengthrx   )r   r   rd   r   Zint64r   r   r   r   r   r   rT  r    )r   ru   r   rx   r   r   rh   rh   ri   _get_initial_cache_position  s$    .*&
z+GenerationMixin._get_initial_cache_position)cache_implementationr   max_cache_lenr{   r   c                    s  t | }jjp|ddk	}tdr:|r4jjnj}|dkrPtjj|}td ppt	|| pp|j
|k}	|dkr|	p|j|k }	|rtdr|	pjjj|d d jd k}	|	rtjdr҈jj}
nt sj}
n jj}
dtt d	fd
d}d}tdrDdd j D d   fddj D }||}j ||||
|d}|f |_|r| }|d d jd |d< tj|f |_n
j  jS )z
        Sets a cache for `generate`, that will persist across calls. A new cache will only be initialized a
        new `generate` call requires a larger cache or uses a different batch size.

        Returns the resulting cache object.
        r   N_cachesliding_windowmambar   r"   _pre_quantization_dtypeexecution_device_mapc                    s    d krd S t  dkr:d kr: fddtjjD S i } D ]<}tjjD ]*}d| d| dkrR | ||<  qBqRqBtjjD ]}||krtd| dq|S )Nr"    c                    s   i | ]}| d  qS )r^  rh   r   idxr\  rh   ri   r   E  s      zLGenerationMixin._get_cache.<locals>.get_layer_device_map.<locals>.<dictcomp>r,  zlayer z! has not been mapped to a device.)r   ranger   num_hidden_layersRuntimeError)r]  layer_device_maplayerr`  r   r\  ri   get_layer_device_mapA  s    z8GenerationMixin._get_cache.<locals>.get_layer_device_mapr   c                 S   s   g | ]}|d kr|qS )cpuZdiskrh   )r   drh   rh   ri   r?  V  s      z.GenerationMixin._get_cache.<locals>.<listcomp>c                    s"   i | ]\}}||d kr n|qS rh  rh   )r   namer{   )main_devicerh   ri   r   W  s    z.GenerationMixin._get_cache.<locals>.<dictcomp>)r   r   rW  r{   rz   rd  rW  )N)r/   r   r   r   r   rX  self_attention_cacheminrY  r   r   rW  cross_attention_cacher   r[  r    rz   get_output_embeddingsZweightr   dictr   r   r   rA  rP  r   reset)r   rV  r   rW  r{   r   Z	cache_clsrequires_cross_attention_cacheZcache_to_checkZneed_new_cacheZcache_dtyperg  r]  rd  Zcache_kwargsr   rh   )rl  r   ri   
_get_cache  s\    	




zGenerationMixin._get_cache)r   c                 C   s&   | j o$d| jj ko$d| jj kS )a  
        Return `True` if current model can use a `DynamicCache` instance when initializing the `past_key_values`.
        This is mostly the same as `_supports_cache_class` attribute, but add exception for `Jamba` model which
        uses its own `HybridMambaAttentionDynamicCache` and do not need to initialize the Cache in advance in
        order to save memory (because no back and forth `to_legacy_cache` and `from_legacy_cache` will be performed
        for `HybridMambaAttentionDynamicCache`).
        jambaZzamba)r   r   r`   r   rf  rh   rh   ri   _supports_default_dynamic_cachen  s
    	z/GenerationMixin._supports_default_dynamic_cache)r   r   r   r   max_cache_lengthr{   r   c                 C   s  d| j j krdnd}| jjp,|ddk	}||}	|	dk	r|jdk	rZtd| dt|	t	r| 
 r|szt|	nt|	||< dS |jdkrdS | 
 s|jdk	rtd	|j d
t dS |dk	r|jdk	rtd|j d d|_|jdk	r|jtkrP|jdkr&| js&td| j|jt|j|j| |||d||< n|jdkr| jsltd|jdk	r~|jnt }
t|
j }|
jdkrt st  st!dn|
jdkrt" st!d||
||< n|jdkrt# ||< n|st ntt t ||< dS )z
        Prepares the cache for generation (if applicable), given `generate`'s parameterization. If a cache is
        instantiated, writes it to `model_kwargs`, under the name expected by the model.
        rZ  r_   r   r   NzMPassing both `cache_implementation` (used to initialize certain caches) and `zB` (a Cache object) is unsupported. Please use only one of the two.FzThis model does not support `Cache` instances, it only supports the legacy cache format (tuple of tuples). `cache_implementation` (set to z) will be ignored.zRAn assistant model is provided, using a dynamic cache instead of a cache of type='z'.staticzThis model does not support `cache_implementation='static'`. Please check the following issue: https://github.com/huggingface/transformers/issues/28981)rV  r   rW  r{   r   Z	quantizedzThis model does not support the quantized cache. If you want your model to support quantized cache, please open an issue and tag @zucchini-nlp.ZquantozYou need to install optimum-quanto in order to use KV cache quantization with optimum-quanto backend. Please install it via  with `pip install optimum-quanto`ZHQQzYou need to install `HQQ` in order to use KV cache quantization with HQQ backend. Please install it via  with `pip install hqq`Z	offloaded)$r   r`   r   r   r   r   rV  r   r   tuplerv  r   from_legacy_cacher   r   r  r  r  r   r   r/   Z_supports_static_cachert  r6  r  num_return_sequencesZ_supports_quantized_cachecache_configr   r0   backendr   r   ImportErrorr   r   )r   r   r   r   r   rw  r{   r   rs  user_defined_cacher|  Zcache_classrh   rh   ri   _prepare_cache_for_generation|  s    







z-GenerationMixin._prepare_cache_for_generationc                 C   s   dt t| jj kS )z
        Return True if the current model supports the keyword argument `num_logits_to_keep` in forward()
        to save memory. Checking it in this way allows to avoid using a new model attribute.
        num_logits_to_keep)r   r   r   r   r   r   rf  rh   rh   ri   _supports_num_logits_to_keep  s    z,GenerationMixin._supports_num_logits_to_keep)r   kwargs_has_attention_maskr{   c           	         sh  d fdd	}||j |d}||j|d}||j|d}||j|d} jjr^|dk	rZ|n|}|dk	rz|jdkrz|d}|dkr|dk	rt s|dk	r|st	
d t	
d| d |d } jjr|dkrtd	t sL|dk	rt||d
 r|dk	r|st	d |dk	rLt|s:|dk  rLt	
d| d ||_||_||_||_dS )a  
        Prepares the special tokens for generation, overwriting the generation config with their processed versions
        converted to tensor.

        Note that `generation_config` is changed in place and stops being serializable after this method is called.
        That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
        function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
        Nc                    sF   | d kr| S |d k	r|n j }t| tjr4| |S tj| |tjdS )Nr{   rz   )r{   r   rd   r   r   tensorr   )tokenr{   rf  rh   ri   _tensor_or_none  s    
z@GenerationMixin._prepare_special_tokens.<locals>._tensor_or_noner  r   zThe attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.z)Setting `pad_token_id` to `eos_token_id`:z for open-end generation.z\`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation.r   zThe attention mask is not set and cannot be inferred from input because pad token is same as eos token. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.z;`eos_token_id` should consist of positive integers, but is zq. Your generation will not stop until the maximum length is reached. Depending on other flags, it may even crash.)N)r   r   r   r   r   r   r   r   r    r   rL  r   r   r   r   rd   Zis_floating_pointZ_bos_token_tensorr  _pad_token_tensor_decoder_start_token_tensor)	r   r   r  r{   r  Zbos_token_tensorZeos_token_tensorZpad_token_tensorZdecoder_start_token_tensorrh   rf  ri   _prepare_special_tokens  sV    	



	z'GenerationMixin._prepare_special_tokensrV   )r   r   r   r"  r  synced_gpusr   streamerr  r  r   c           +         s  |    |dd}|dd}| j f|\ }| |  | ||| |dkrpt sdt| ont	 dk}|dk	r||nt
 }|dk	r|nt }dtt| jj k}d|k}|dddk	}| | j|\}}}|jd }|j}| j ||d | jjs`t s` jdk	r`|dkr`t|jd	kr`t|ddd
f  jkdkr`t d | jjsz|dkrzd _!|s|r|r| "| j j#|d< n,|r|dkrt|d jd	krt$d| jjrd|kr| %||| }| jjr| j&||| j'|jd\}}n|dkr*|n|d} j(rH| )||}|dk	r`|*|+  |jd
 }|ddko j,dk	}|ddko j-dk	}| j. |||||d | / rd|krd|d< | 0 || d| j1j23 krdnd}||} j,}|jd |kr:|dkr:| jjs:||jd 7 }| 4 |||||  5|}|dk	rv j6dkrvt$dt s| jj7|jj7krt89d|jj7 d| jj7 d| jj7 dt: | j; |||||j||	|
d	}| j<f  ||d|} j!|d< |t=j>kr j?dkr&t$d  j? d!|dkr8t$d"|d sJt$d# j@d$kr^t$d%| jArxt$d&| j1j2 | jB |||||||d'} | jC|f| || ||d(|}!nt|t=jDkr| jArt$d)| j1j2 | jE|f jF|| ||d*|}!n(|t=jGkr\|d s t$d+| jAr:t$d,| j1j2 | jH|f|| ||d-|}!n|t=jIt=jJfkr| jKf | j?| jjd.|\}}| jL|f|| ||d-|}!nx|t=jMt=jNfkr*tO| j6|j jP jQ j? j,d/}"| jKf | j6| jjd.|\}}| jR||"f|| |d0|}!n |t=jSkrtO| j6|j jP jQ j? jT j,d1}"| jKf | j6| jjd.|\}}| jU||"f|| |d0|}!n|t=jVkr*g }# jWdk	r jW}# jXdk	rƇ fd2d3}$tY jXtZrt jXdkr|$   jXD ]}%tY|%d tZrvtY|%tZr2t|%dkr8|$  t[d4d5 |%D rR|$  t[d6d5 |%D rl|$  t\|%}&nBtY|%tZrt|%dkr|$  t[d7d5 |%D r|$  t]|%}&|#^|& qt_|#| j6|j jP jQ j? j,d8}'| jKf | j6| jjd.|\}}| j`|f|'|| |d9|}! jad:k	rt stb|!drtb|!jcd;r|!jcjddk	r ja}(|dk	})t7|!jctekptY|!jctfot7|!jcjgtekot7|!jcjhtek}*|)s|*rtid< d}(|(r|!jcd |!_c|!S )=a   

        Generates sequences of token ids for models with a language modeling head.

        <Tip warning={true}>

        Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
        model's default generation configuration. You can override any `generation_config` by passing the corresponding
        parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.

        For an overview of generation strategies and code examples, check out the [following
        guide](../generation_strategies).

        </Tip>

        Parameters:
            inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):
                The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
                method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
                should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
                `input_ids`, `input_values`, `input_features`, or `pixel_values`.
            generation_config ([`~generation.GenerationConfig`], *optional*):
                The generation configuration to be used as base parametrization for the generation call. `**kwargs`
                passed to generate matching the attributes of `generation_config` will override them. If
                `generation_config` is not provided, the default will be used, which has the following loading
                priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
                configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
                default values, whose documentation should be checked to parameterize generation.
            logits_processor (`LogitsProcessorList`, *optional*):
                Custom logits processors that complement the default logits processors built from arguments and
                generation config. If a logit processor is passed that is already created with the arguments or a
                generation config an error is thrown. This feature is intended for advanced users.
            stopping_criteria (`StoppingCriteriaList`, *optional*):
                Custom stopping criteria that complements the default stopping criteria built from arguments and a
                generation config. If a stopping criteria is passed that is already created with the arguments or a
                generation config an error is thrown. If your stopping criteria depends on the `scores` input, make
                sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is
                intended for advanced users.
            prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
                If provided, this function constraints the beam search to allowed tokens only at each step. If not
                provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
                `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
                on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
                for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
                Retrieval](https://arxiv.org/abs/2010.00904).
            synced_gpus (`bool`, *optional*):
                Whether to continue running the while loop until max_length. Unless overridden, this flag will be set
                to `True` if using `FullyShardedDataParallel` or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoid
                deadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults to `False`.
            assistant_model (`PreTrainedModel`, *optional*):
                An assistant model that can be used to accelerate generation. The assistant model must have the exact
                same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistant model
                is much faster than running generation with the model you're calling generate from. As such, the
                assistant model should be much smaller.
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
            negative_prompt_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                The negative prompt needed for some processors such as CFG. The batch size must match the input batch
                size. This is an experimental feature, subject to breaking API changes in future versions.
            negative_prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Attention_mask for `negative_prompt_ids`.
            kwargs (`Dict[str, Any]`, *optional*):
                Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be
                forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
                specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.

        Return:
            [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
            or when `config.return_dict_in_generate=True`) or a `torch.LongTensor`.

                If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
                [`~utils.ModelOutput`] types are:

                    - [`~generation.GenerateDecoderOnlyOutput`],
                    - [`~generation.GenerateBeamDecoderOnlyOutput`]

                If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
                [`~utils.ModelOutput`] types are:

                    - [`~generation.GenerateEncoderDecoderOutput`],
                    - [`~generation.GenerateBeamEncoderDecoderOutput`]
        r#  Nr   r"   rv   r   r   r  r   r|   zA decoder-only architecture is being used, but right-padding was detected! For correct generation results, please set `padding_side='left'` when initializing the tokenizer.rw   Tru   z1`attention_mask` passed to `generate` must be 2D.)r   r   r   r   r{   r   r  )r   rJ  rM  r   r   rI  r  rZ  r_   r   zZ`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1.z~You are calling .generate() with the `input_ids` being on a device type different than your model's device. `input_ids` is on z, whereas the model is on z. You may experience unexpected behaviors or slower generation. Please make sure that you have put `input_ids` to the correct device by calling for example input_ids = input_ids.to('z ') before running `.generate()`.)	r   r  r  r  r   r{   r   r  r  )r   r"  r#  r   zFnum_return_sequences has to be 1 when doing assisted generate, but is r,  z6assisted generate is only supported for batch_size = 1z+assisted generate requires `use_cache=True`)rx  ZhybridrY  z=assisted generate is not supported with Static cache classes`zCassisted generation is not supported with stateful models, such as )r   ru   r   r   r   r   r   r   )r  r   r"  r   r  r  z=dola decoding is not supported with stateful models, such as )dola_layersr   r"  r   r  r  z,Contrastive search requires `use_cache=True`zBcontrastive search is not supported with stateful models, such as )r   r"  r   r  r  )ru   r   r   )r   r  r{   length_penaltydo_early_stoppingnum_beam_hyps_to_keepr   )r   r"  r   r  )r   r  r{   r  r  r  r  r   c                      s   t d j dd S )Nzo`force_words_ids` has to either be a `List[List[List[int]]]` or `List[List[int]]` of positive integers, but is r,  )r   force_words_idsrh   r   rh   ri   	typeerror  s    z+GenerationMixin.generate.<locals>.typeerrorc                 s   s   | ]}t |t V  qd S r   )r   r   r   Z	token_idsrh   rh   ri   r   	  s     z+GenerationMixin.generate.<locals>.<genexpr>c                 s   s    | ]}t d d |D V  qdS )c                 s   s"   | ]}t |t p|d k V  qdS r   Nr   r   r   Ztoken_idrh   rh   ri   r   	  s     z5GenerationMixin.generate.<locals>.<genexpr>.<genexpr>Nr   r  rh   rh   ri   r   	  s   c                 s   s"   | ]}t |t p|d k V  qdS r  r  r  rh   rh   ri   r   	  s     )constraintsr   r  r{   r  r  r  r   )constrained_beam_scorerr   r"  r   r  Fto_legacy_cachea  From v4.47 onwards, when a model cache is to be returned, `generate` will return a `Cache` instance instead by default (as opposed to the legacy tuple of tuples format). If you want to keep returning the legacy format, please set `return_legacy_cache=True`.)jr;  r   rS  rF  rP  rB  r   r   distZget_world_sizer=   rR   r   r   r   r   r   r   r   r   r   r   r{   r  r   r   r    r  r   rd   r5  r   rL  r   r   r  r   r   r   r  Ztoken_healingheal_tokensputri  r   r  rN  r  rK  r   r`   r   r  Zget_generation_moder  r-  r  r  r  r!  r)  r2   ZASSISTED_GENERATIONr{  rV  Z_is_statefulr  _assisted_decodingZDOLA_GENERATION_dola_decodingr  ZCONTRASTIVE_SEARCH_contrastive_searchZSAMPLEZGREEDY_SEARCHr   _sampleZBEAM_SAMPLEZBEAM_SEARCHr&   r  Zearly_stopping_beam_searchZGROUP_BEAM_SEARCHr  _group_beam_searchZCONSTRAINED_BEAM_SEARCHr  r  r   r   r   r#   r$   r  r'   _constrained_beam_searchZreturn_legacy_cacher   r_   r  r   r   rm  ro  r   )+r   r   r   r   r"  r  r  r   r  r  r  r   r#  r   r   Zaccepts_attention_maskZrequires_attention_maskr  r   r   r   r{   ru   rI  rJ  rM  r   r  rw  Zgeneration_modeZprepared_logits_processorZprepared_stopping_criteriar  resultbeam_scorerZfinal_constraintsr  Zword_ids
constraintr  Zshould_convert_cacheZis_user_defined_cacheZis_default_cache_typerh   r  ri   generateK  s   d  

  
   



     
"  
























zGenerationMixin.generate)this_peer_finishedr  r{   cur_lenr   r   c                 C   s^   t  r||k S |rNt|rdnd|}tj|tjjd | dkrVdS n|rVdS dS dS )z
        Returns whether there are still unfinished sequences in the device. The existence of unfinished sequences is
        fed through `this_peer_finished`. ZeRO stage 3-friendly.
        r  r  )opFTN)	r    rd   r  r   r  Z
all_reduceZReduceOpZSUMr   )r   r  r  r{   r  r   Zthis_peer_finished_flagrh   rh   ri   _has_unfinished_sequencesR	  s    z)GenerationMixin._has_unfinished_sequences)ru   r#  r   c                    s  dkrt djj }}t }td|d}dd j|ddD }|d	dd
j|j	}t
||k||}| dkr|S |dddf  }dd   fdd|D }	tt||	D ]\}
\}}||
 }t
||k rq҇fdd|j|dD }t|dkr$q||f  d7  < |j|d |dd }| dkr^qt|||k dkr|||d< | j|d|d||
< q|S )a  
        Generates sequences of token ids for models with a language modeling head.
        Parameters:
            input_ids (`torch.LongTensor`): The sequence used as a prompt for the generation.
            tokenizer (`PreTrainedTokenizerBase`, *optional*): The tokenizer used to decode the input ids.
        Return:
            `torch.LongTensor` where each sequence has its tail token replaced with its appropriate extension.
        Nzs When generating with token healing, you must pass the model's tokenizer to the `tokenizer` argument of `generate`.r"   )rH  r   c                 S   s   g | ]}|  qS rh   )stripr   rh   rh   ri   r?  	  s     z/GenerationMixin.heal_tokens.<locals>.<listcomp>T)Zskip_special_tokenspt)Zreturn_tensorspaddingr   r|    c                 3   s    | ]} |d  V  qdS )r  N)decodereplace)r   tZ	space_tokr#  rh   ri   r   	  s     z.GenerationMixin.heal_tokens.<locals>.<genexpr>c                    s   i | ]}  |fd qS )g      $@)convert_tokens_to_ids)r   Zalt_tok)r#  rh   ri   r   	  s    
 z/GenerationMixin.heal_tokens.<locals>.<dictcomp>)prefixr  r	  r  )r   r   r   r   Z	get_vocabr1   Zbatch_decoderu   r   r{   rd   whereZnumeltolistZconvert_ids_to_tokensr  	enumeratezipr   r   
extensionsr   rR  r  r   )r   ru   r#  r   r   Z
vocab_trier   ZpromptsZtail_idsZ	tail_toks	batch_idxZtail_idZtail_tokZ	batch_idsZseq_biasZtrimmed_idsrh   r  ri   r  q	  sN    

zGenerationMixin.heal_tokens)ru   r  r   r"  r   r  r  r   c           &   	      sP  | j jrtd|j}	|j}
|j}|j}|j}|j}t	dd |D }|j
}|rX|rXdnd}|rh|rhdnd}|rx|
rxdnd}|r|
rdnd}|r|rdnd}|jd }tj|tj|jd}| ||}d}| j  j | j jsd}n" d	krd	}n d	krd
}nd}t|trb|dkrb| d	 kr2|g}n. dkrPtt| d	 d	ntt|dd	}nrt|tr|dkr dkrtt d	  d	ntt d  d	}n(t|tṙ fdd|D }ntd|  }|dkrtd| j|||jdr| j|f|}| f |d|
dd}|jdddddf    }|jdddddf  }i } |D ]2}!||j|! dddddf  |j| |!< qn| j!||| j jd}|r|rƐqt"|| |}"|" |j}"|||"}#|rl|r||#f7 }|r||f7 }|
rH|| j jr(|j#fn|j$f7 }| j jrH||j%f7 }|rl|| j jrb|j&fn|jf7 }|rt'j(j)|#dd}$tj*|$d
d+d
}%ntj,|#dd}%|r|%| |	d
|   }%tj-||%dddf gdd}|dk	r|.|%/  |||| @ }|0 dk}q|dk	r(|1  |rHt2||||||3ddS |S dS )a
  
        Generates sequences of token ids for models with a language modeling head using **dola decoding** and can be
        used for decoder-only text models.
        The method is based on the paper "DoLa: Decoding by Contrasting Layers Improves Factuality in Large Language
        Models" (https://arxiv.org/abs/2309.03883) in ICLR 2024.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            dola_layers (`Union[str, List[int]]`):
                The candidate layers used in contrasting layers of DoLa. It can be either 1) 'low' or 'high', which
                means the lower part or higher part of the model layers, respectively, or 2) a list of layer indices
                to be used for candidate layers. The 0-th layer is the word embedding layer of the model.
            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.
            stopping_criteria (`StoppingCriteriaList`, *optional*):
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
                Whether to continue running the while loop until max_length (needed to avoid deadlocking with
                `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
            model_kwargs:
                Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
                If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
            [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]
            or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
            [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
            `model.config.is_encoder_decoder=True`.
        z8DoLa decoding is only available for decoder-only models.c                 s   s   | ]}t |d V  qdS r   Nr   r   r(  rh   rh   ri   r   
  s     z1GenerationMixin._dola_decoding.<locals>.<genexpr>rh   Nr   ry   Fr   r"   low(   rG  highc                    s   g | ]}| k r|qS rh   rh   r   iZfinal_layerrh   ri   r?  7
  s      z2GenerationMixin._dola_decoding.<locals>.<listcomp>z?dola_layers must be either 'low', 'high' or a list of integers.zCDoLa is not supported for models that don't have output embeddings.r  T)r   r   r   r|   r   r   Znum_samplesr_   rZ   r[   r\   r]   r^   r_   )4r   r   r   r  r   r   output_scoresoutput_logitsreturn_dict_in_generater   r  r   rd   r   r   r{   rU  rA  rb  Ztie_word_embeddingsr   strr   ra  rp  r  r   r\   detachr   floatr^   r   r   _dola_select_contrastrm   r]   rn   ro   r   r   softmaxmultinomialsqueezeargmaxr   r  ri  r6  endrY   r   )&r   ru   r  r   r"  r   r  r  r   r   r   r   r  r  r  has_eos_stopping_criteriar  r[   
raw_logitsrm   rn   ro   r   unfinished_sequencesr  Zstart_layercandidate_premature_layersZlm_headr   r   Zfinal_layer_next_token_logitsfinal_logitscandidate_premature_logitsZcandidate_premature_layernext_token_logitsnext_token_scoresprobsnext_tokensrh   r  ri   r  	  s    2



$  





	zGenerationMixin._dola_decoding)ru   r   r"  r   r  r  r   c           =         s	  t dd |D }|j |j}	|j}
|j}|j}|j}|j}|j}|j	}|rT|rTdnd}|rd|rddnd}|rt|rtdnd}|r|rdnd}|r|rdnd}|r| j
jr|r|d dnd}|r|d dnd}|jd }tj|tj|jd	}| ||}tj|tjd
}| j
jr6d|kr>|d dk	r>|d }n|d }|j dd}d}| j|||jdr|ddkst|d ttfr|d  dkrd|d< | j|f|}| f |dd|d}| j
jr|jd }n
|jd }|jdddddf   }| |j}| j!||| j
jd}|sJ| j"f  | j
jd|\} }|d}!|!dkrrt#| j$j% dn@t|!d t&tj'fr|!d d jd |krt#| j$j% d|||}"t(j)j*|"dd}#tj+|#d d\}$}%|rd|r||f7 }|r||"f7 }|r@|| j
jr |j,fn|j-f7 }| j
jr@||j.f7 }|rd|| j
jrZ|jfn|jf7 }~|s|d }&t|&t/st|&trt|&j0t/r|&1  nJg }'|&D ]8}(g })|(D ]}*|)2|*j dd q|'2t&|) qt&|'}&|&|d< |rg }+t3 D ]},| j|%dd|,f 4ddf|}-| f |-dd|d}t|d t/sxt|d trt|d j0t/rd|d< |d 5d |+2| q
t6|+| j
7 }n,| j|%4ddf|}-| f |-dd|d}~-| j
jr|jd }.|j}/n|jd }.|j}/|jdddddf  }0|j dd}1t8|1|.|$||	 }2tj9||:|jd dfgdd}|2 d}2t; fddt<|2D }3|%t3t=|%|2f }4t>t?|.j@dd }.|.t3||2ddf }.tj9||.Adgdd}d}5|/D ]4}(t>t?|( t3||2ddf }(|5|(f7 }5q|rn| j|%dd|2f 4ddf|}6| f |6dddd}7|7d }8n| B|\} }8t|8t/st|8trt|8j0t/r|8C|3 nHg }'|8D ]6}(g })|(D ]}*|)2|*|3df  q|'2t&|) qt&|'}8t>t?|0 t3||2ddf }| |j}| j
jrd}9d}:|r|j.D ]4}(t>tj?|( ddt3||2df }(|9|(f7 }9qD|j,D ]4}(t>tj?|( ddt3||2df }(|:|(f7 }:qtD|8|5|:pd|9pdd}nZd};|r|j-D ]4}(t>tj?|( ddt3||2df }(|;|(f7 };qtE|8|5|;p(dd }| j!||| j
jd}|rR|rRqP|rl|4| |
d|   }4tj9||4dddf gdd}|dk	r|F|4G  |||| @ }|H dk}qP|dk	r|I  |	r|ddk		rt|d t/	st|d t	r,t|d j0t/	r,|d 5d nZg }!|d D ]@}(g }<|(D ]"}*|<2|*dddddf  	qD|!2t&|< 	q8t&|!|d< | j
j	rtJ|||||||||dd!	S tK||||||dd"S n|S dS )#a  
        Generates sequences of token ids for models with a language modeling head using **contrastive search** and can
        be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            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.
            stopping_criteria (`StoppingCriteriaList`):
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
                Whether to continue running the while loop until max_length (needed to avoid deadlocking with
                `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
            model_kwargs:
                Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
                If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
            [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]
            or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
            [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
            `model.config.is_encoder_decoder=True`.
        c                 s   s   | ]}t |d V  qdS r  r  r  rh   rh   ri   r   
  s     z6GenerationMixin._contrastive_search.<locals>.<genexpr>rh   Nr   r]   r^   r   ry   r   r   rv   r   Fr  r_   Tr   )r   r   r   r|   r  )r   r   zQ does not support caching and therefore **can't** be used for contrastive search.z| does not have a standard cache format and therefore **can't** be used for contrastive search without further modifications.)r   r   r"   ri  c                    s   g | ]\}}||   qS rh   rh   )r   r  rD  r  rh   ri   r?    s     z7GenerationMixin._contrastive_search.<locals>.<listcomp>.)r_   ro   rm   rn   )r_   r^   r]   	rZ   r[   r\   rk   rl   rm   rn   ro   r_   r  )Lr   r  penalty_alphar  r   r   r  r  r  
low_memoryr   r   r   r   rd   r   r   r{   rU  r   r   r  r   r   r   rT  r   ro   r^   r\   r   r  r   r   r   r   r   r`   ry  r   r   r   r  topkrm   r]   rn   r   rm  Zbatch_repeat_interleaver  ra  r   Zcropstack_model_outputsrA  _ranking_fastr   r   r  r  r   r2  splitr  r   r   Zbatch_select_indicesr   r   r  ri  r6  r  rj   rY   )=r   ru   r   r"  r   r  r  r   r  r  r   r   r   r  r  r  
sequentialr  r[   rm   rn   ro   rk   rl   r   r  cosine_matrix_maskr  r   r   Zlast_hidden_statesZlogit_for_next_stepr   r_   Zprocessed_logit_for_next_stepZ
next_probsZtop_k_probsZ	top_k_idsZpastZnew_key_valuesre  r   r   Zall_outputsr  Znext_model_inputsnext_hiddenZfull_hidden_statesr\   context_hiddenselected_idxZaugmented_idxr  Znext_decoder_hidden_statesZnext_model_inputZselected_outputsZnext_past_key_valuesZnext_step_cross_attentionsZnext_step_decoder_attentionsZnext_step_attentionsZlayer_past_key_valuesrh   r  ri   r  
  s    ,


   


  







"

	


      
$


$

$
$
$

 
	z#GenerationMixin._contrastive_searchc           "      K   sT  |j }|j}	|j}
|j}|j}|j}|j}tdd |D }|j}|rN|rNdnd}|r^|r^dnd}|rn|	rndnd}|r~|	r~dnd}|r|
rdnd}|r| j	j
r|	r|d dnd}|
r|d dnd}|j\}}d}tj|tj|jd	}| ||}| j|||j||d
r| j|f|}||	r0d|	ini  ||
rHd|
ini  | f |ddi}| j||| j	j
d}|r|rq|j dddddf  }||j}|||}|r<|r||f7 }|r||f7 }|	r|| j	j
r|jfn|jf7 }| j	j
r||jf7 }|
r<|| j	j
r2|jfn|jf7 }|rhtj j!|dd} tj"| dd#d}!ntj$|dd}!|r|!| |d|   }!tj%||!dddf gdd}|dk	r|&|!'  |||| @ }|( dk}|d7 }~q|dk	r |)  |rL| j	j
r0t*|||||||||dd	S t+||||||ddS n|S dS )a  
        Generates sequences of token ids for models with a language modeling head using **multinomial sampling** and
        can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            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.
            stopping_criteria (`StoppingCriteriaList`):
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
                Whether to continue running the while loop until max_length (needed to avoid deadlocking with
                `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
            model_kwargs:
                Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
                an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
            [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or `torch.LongTensor`:
            A `torch.LongTensor` containing the generated tokens (default behaviour) or a
            [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
            `model.config.is_encoder_decoder=True`.
        c                 s   s   | ]}t |d V  qdS r  r  r  rh   rh   ri   r   d  s     z*GenerationMixin._sample.<locals>.<genexpr>rh   Nr   r]   r^   Fry   )r{   r  r   r   r   r   Tr  r|   r   r"   r  r   r_   r  r  ),r  r   r   r  r  r  r   r   r  r   r   r   r   rd   r   r   r{   rU  r  r   rR  r   r\   r   r  r   rm   r]   rn   ro   r^   r   r   r  r  r  r  r   r  ri  r6  r  rj   rY   )"r   ru   r   r"  r   r  r  r   r   r   r   r  r  r  r   r  r  r[   r  rm   rn   ro   rk   rl   r   r  r  r  r   r   r  r  r  r  rh   rh   ri   r  2  s    +
     






	zGenerationMixin._samplec                 C   st   | j j }t|ttfr(| ||}nHd|krft|ttfsNt	d| d| ||}t
|}n
|| |S )aC  
        Temporary function to handle the different types of cache reordering processes while we roll out `Cache`.

        TODO: standardize cache formats and make all models compatible with `Cache`. It would remove the need
        for this function, with `Cache.reorder_cache` being the sole remaining code path
        Z
gptbigcodez'Using an unsupported cache format with zG. Currently, it only supports the legacy tuple format or `DynamicCache`)r   r`   r   r   ry  r   r   r   r   r   rz  Zreorder_cache)r   r_   r   Zmodel_classrh   rh   ri   _temporary_reorder_cache  s    

z(GenerationMixin._temporary_reorder_cache)ru   r  r   r"  r   r  r   c           0         s  |j }|j}	|j}
|j}|j}|j}|j}|j}|j}t	|j
}|j}|j\}}||}|| |krtd||  d| d|r|rdnd}|r|rdnd}|r|rtdd t|D nd|r|
rdnd}|r|
rdnd}|r|rdnd}|r4jjr4|
r|d d	nd}|r0|d d
nd}tj||ftj|jd}d|ddddf< ||| f}d}|jd }j|||jdrj|f|}||
rd|
ini  ||rd|ini  |r<tfdddD rtdjj dt |||j! d} fdd| D }!t"|!j! }"nf |ddi}"j#|"|jjd}|rz|rz|d }q~|"j$dddddf %  }#|#&|j}#t'j(j)|#dd}$|||$}%|%|dddf *|% }$|r^|r||%f7 }|r ||#f7 }|
r:|jjr|"j+fn|"j,f7 }jjr:||"j-f7 }|r^|jjrT|"j.fn|"j/f7 }|$jd }&|$|||& }$|	dk	r|	jd nd}'t0dd|' | }(|rt'j(j1|$dd})tj2|)|(d }*t3|$d|*}$tj4|$ddd!\}$}+t3|*d|+}*ntj5|$|(dddd"\}$}*tj6|*|&d#d$},|*|& }*|j7||$|*|,||	|d%}-|-d& }|-d' }.|-d(  tj8| ddf |.9dgdd}~"|d)ddk	r:|d)  |d)< |r|rt fd*dtt	D |d }|j;st<|||r~d}q~|j=|||*|,||	|j>|d+	}/|r|s,d|/d,< jjrft?|/d- |/d, |||/d. ||||||d)d/S t@|/d- |/d, |||/d. |||d)d0S n|/d- S dS )1a  
        Generates sequences of token ids for models with a language modeling head using **beam search decoding** and
        can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            beam_scorer (`BeamScorer`):
                An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
                sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
            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.
            stopping_criteria (`StoppingCriteriaList`:
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
                Whether to continue running the while loop until max_length (needed to avoid deadlocking with
                `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
            model_kwargs:
                Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
                an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
            [`generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
            [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
            `model.config.is_encoder_decoder=True`.
        )Batch dimension of `input_ids` should be 	, but is r,  rh   Nc                 s   s   | ]
}d V  qdS rh   Nrh   r   r   rh   rh   ri   r   @  s     z/GenerationMixin._beam_search.<locals>.<genexpr>r   r]   r^   ry       er"   Fr|   r  r   r   c                 3   s   | ]}| j j kV  qd S r   )r   r`   r   )r   Z
model_namerf  rh   ri   r   `  s   )ZfsmtZreformerZctrlZgpt_bigcodeZ	transo_xlZxlnetZcpmru  zCurrently generation for zh is not supported for `low_memory beam_search`. Please open an issue on GitHub if you need this feature.)
split_sizefull_batch_sizer   c                    s   g | ]} f |d diqS )r   Trh   )r   Zinputs_per_sub_batchrf  rh   ri   r?  x  s    z0GenerationMixin._beam_search.<locals>.<listcomp>r   Tr  r   r   r   r  )
descendingr   r   largestsortedfloorZrounding_moder   r   rr   decoder_prompt_lennext_beam_scoresnext_beam_tokensnext_beam_indicesr_   c                 3   s$   | ]} |   | f V  qd S r   rh   r  r   rr   rh   ri   r     s     r   r   r   rr   r  sequence_scoresrZ   rr   rZ   rq   r[   r\   rr   rk   rl   rm   rn   ro   r_   rZ   rq   r[   r\   rr   r]   r^   r_   )Ar  r  r   r   r  r  r  r  r  r   
_beam_hypsr  r   rU  r   ry  ra  r   r   r   rd   zerosr  r{   r   r  r   rR  r   rc  r   r`   _split_model_inputsrA  r  r   r\   r   r   r   r   r4  	expand_asrm   r]   rn   ro   r^   r6  r  r  r7  sortr  divprocessr   r   r  is_doner   finalizer   rs   rp   )0r   ru   r  r   r"  r   r  r   r   r   r   r   r  r  r  r  r  r   r  batch_beam_sizer  r[   r  rm   rn   ro   rk   rl   beam_scoresr  r  r   Zinputs_per_sub_batchesZoutputs_per_sub_batchr   r  r  next_token_scores_processedr  n_eos_tokensZn_tokens_to_keepr  r  Z_indicesnext_indicesbeam_outputsbeam_next_tokenssequence_outputsrh   )r   rr   r   ri   r    sZ   +

 


  




    
$  
zGenerationMixin._beam_search)ru   r  r   r"  r   r  c           4         s  |j }|j}	|j}
|j}|j}|j}|j}|j|j}| t	|j
| |j}|j\}}| ||}|r|rfddt|D nd |krtd  d| d|r|rdnd}|r|rdnd}|r|
rdnd}|r|
rdnd}|r|rdnd}|rH| jjrH|
r,|d d	nd}|rD|d d
nd}tjfdtj|d}d|ddddf< | f}d}|jd }| j|||jdrtj |j|d}tj tj|d}| j|f|}||
rd|
ini  ||rd|ini  | f |ddi} | j| || jjd}|rP|rP|d }q|rtt| jdddddf }!|r| jdddddf   }"|"!|j}"t|D ], }#t"|# }$|$|# }%g }&tD ]& |&# fddt|#|$D  q||& }'| j|&dddf  }(|(!|j}(t$j%j&|(dd})|)jd }*||'|)|d}+|+||& 'd })|)(|+})|r|+|!|&< |)|%|* })|	dk	r|	jd nd},tj)|)t*dd|, |% dddd\})}-tj+|-|*dd}.|-|* }-dk	rt,dnd}/|j-|'|)|-|.||	|/|d	}0|0d ||&< |0d  }1|0d! |rn|rnt.fd"d#tt	d D < |' ||&< tj/|'ddf |1'dgdd}'|'dddf ||&< tj+|%dd |# |%  ||&< q|r^|r||!f7 }|r ||"f7 }|
r:|| jjr| j0fn| j1f7 }| jjr:|| j2f7 }|r^|| jjrT| j3fn| j4f7 }tj/||'dgdd}~ |d$ddk	r| 5|d$ ||d$< |d }|j6st7|||rd}qdk	rt,dnd}2|j8|||-|.||	|j9|2|d%	}3|rv|sd|3d&< | jjrJt:|3d' |3d& |||3d( ||||||d$d)S t;|3d' |3d& |||3d( |||d$d*S n|3d' S dS )+a	  
        Generates sequences of token ids for models with a language modeling head using **diverse beam search
        decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            beam_scorer (`BeamScorer`):
                An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
                sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
            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.
            stopping_criteria (`StoppingCriteriaList`):
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
                Whether to continue running the while loop until max_length (needed to avoid deadlocking with
                `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
            model_kwargs:
                Additional model specific kwargs that will be forwarded to the `forward` function of the model. If
                model is an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
            [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
            [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
            `model.config.is_encoder_decoder=True`.
        c                    s&   g | ]}t d d t  D qS )c                 s   s   | ]
}d V  qdS r  rh   r  rh   rh   ri   r   Q  s     z@GenerationMixin._group_beam_search.<locals>.<listcomp>.<genexpr>)ry  ra  r  )r   num_sub_beamsrh   ri   r?  Q  s     z6GenerationMixin._group_beam_search.<locals>.<listcomp>Nr  r  r,  rh   r   r]   r^   r  ry   r   Fr|   r  r   r   r   Tr  r"   c                    s   g | ]}  | qS rh   rh   r_  )r  r  rh   ri   r?    s     r   )current_tokensbeam_group_idxr   r  r  r  )r   r   rr   Zgroup_indexr  r  r  r  c                 3   s(   | ] }  |  | f V  qd S r   rh   r  )r  r   rr   rh   ri   r     s    z5GenerationMixin._group_beam_search.<locals>.<genexpr>r_   r   r  rZ   rr   r  r  )<r  r  r   r   r  r  r  r  r  r   r  r{   r   rU  ra  r   r   r   r   rd   fullr  r   r  r  rz   r   r   rR  r   Z
zeros_liker\   r   r   rn  r.  r   r   r4  r   r  r  r6  r	  r5  r
  ry  r   rm   r]   rn   ro   r^   r  r  r   r  r   rs   rp   )4r   ru   r  r   r"  r   r  r   r   r   r   r   r  r  r  r  r{   r  r  r[   r  rm   rn   ro   rk   rl   r  r  r  r  Zreordering_indicesr   r   Zprocessed_scoreZraw_logit_scoreZgroup_start_idxZgroup_end_idxZ
group_sizeZbatch_group_indicesZgroup_input_idsr  r  r  r  r  r  r  Zprocess_beam_indicesr  r  Zfinal_beam_indicesr  rh   )r  r   r  r   rr   r  r  ri   r    sx   +

 
   
    
$



 
z"GenerationMixin._group_beam_search)ru   r  r   r"  r   r  r   c           *         s  |j }|j}	|j}
|j}|j}|j}|j}t|j}|j	}|j
\}}| ||}|| |krvtd||  d| d|r|rdnd}|r|rdnd}|r|rtdd t|D nd|r|
rdnd}|r|
rdnd}|r|rdnd}|r(| jjr(|
r|d d	nd}|r$|d d
nd}tj||ftj|jd}d|ddddf< ||| f}d}|j
d }| j|||jdr.| j|f|}||
rd|
ini  ||rd|ini  | f |ddi}| j||| jjd}|r|r|d }qr|jdddddf   }||j}tjj |dd} ||| }!|!|dddf !|! } |  }"|r|r|| f7 }|r||f7 }|
r|| jjr|j"fn|j#f7 }| jjr||j$f7 }|r|| jjr|j%fn|j&f7 }| j
d }#| |||# } |	dk	r|	j
d nd}$tj'| t(dd|$ | dddd\} }%|%|# ) }&|%|# }%|j*|| |%|&|"||	|d	}'|'d }|'d }(|'d  tj+| ddf |(,dgdd}~|dddk	r| -|d  |d< |r|rt fddttD |d }|j.s&t/|||rrd}qr|j0|||%|&||	|j1|d 	})|r|s`d|)d!< | jjrt2|)d" |)d! |||)d# ||||||dd$S t3|)d" |)d! |||)d# |||dd%S n|)d" S dS )&ar	  
        Generates sequences of token ids for models with a language modeling head using **constrained beam search
        decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            constrained_beam_scorer (`ConstrainedBeamSearchScorer`):
                A derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
                sorted during generation, while satisfying a list of positive constraints. For more information, the
                documentation of [`ConstrainedBeamSearchScorer`] should be read.
            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.
            stopping_criteria (`StoppingCriteriaList`):
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
                Whether to continue running the while loop until max_length (needed to avoid deadlocking with
                `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
            model_kwargs:
                Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
                an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
            [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
            [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
            `model.config.is_encoder_decoder=True`.
        r  r  r,  rh   Nc                 s   s   | ]
}d V  qdS r  rh   r  rh   rh   ri   r   z  s     z;GenerationMixin._constrained_beam_search.<locals>.<genexpr>r   r]   r^   ry   r  r"   Fr|   r  r   r   r   Tr  r   r   r   r  r  r  r  r  r_   c                 3   s$   | ]} |   | f V  qd S r   rh   r  r  rh   ri   r     s     r   r  rZ   rr   r  r  )4r  r  r   r   r  r  r  r   r  r  r   rU  r   ry  ra  r   r   r   rd   r  r  r{   r   r  r   rR  r   r\   r   r   r   r   r4  r  rm   r]   rn   ro   r^   r  r6  r   r
  r   r   r  r  r   r  r   rs   rp   )*r   ru   r  r   r"  r   r  r   r   r   r   r   r  r  r  r   r  r  r  r[   r  rm   rn   ro   rk   rl   r  r  r  r   r   r  r  r  Zscores_for_all_vocabr  r  r  r  r  r  r  rh   r  ri   r  7  s*   ,

 
  




    
$  
z(GenerationMixin._constrained_beam_search)ru   r  r   r"  r   r  r  r   c           +         s  |j }	|j}
|j}|j}|j}|j}|r0|r0dnd}|r@|r@dnd}|rP|
rPdnd}|r`|
r`dnd}|rp|rpdnd}|r| jjr|
r|d dnd}|r|d dnd}|j	d }t
j|t
j|jd}| ||}d}d	}| j|||jd
r|j	d }||\}}|dk	r || j}|j	d |j	d  }||d}t|}t||j	d | jj}t||j	d }d|krt
j|d t
j||| |jt
jdfdd|d< | j|f|} d| kr|d | d< | |
rd|
ini  | |rd|ini  | f | }!|!jdd| d df    |j   t|dkrt|d D ]H}"||ddd||" f  dd|"ddf  dd|"ddf< qT|	r|dk	rt||| |\}#}$n|	r
 jdd}%t
j |%dddddf dd!ddddf }&n j"dd}&|dd|df }'|'|&ddddf k j#dddk $ }$|rl|$|krl|$d8 }$|&ddd|$d f }#t
j||#fdd}|dk	r|%|#&  |j	d }(|(d })t'| |!j(|)|!_(|)| |$ | j*|!|| jj|$d d}|r|rq|r|$d }*|r8|t+ fddt|*D 7 }|r\|t+fddt|*D 7 }|rf|(n|*}*|
r| jjrt,||!j-||*}t,||!j.||*d	d}n$|!j/d dk	rt,||!j/||*d	d}|r| jjrt,||!j0||*}nt,||!j1||*}|||| @ }|2 dk}d}q|dk	r*|3  t4|drR|j5j6j7dkrR|j8|j5j6_8|r| jjrt9|||||||||dd	S t:||||||ddS n|S dS )a
  
        Generates sequences of token ids for models with a language modeling head using **greedy decoding** or
        **sample** (depending on `do_sample`), assisted by candidate sequences. Assisted generation is an example of a
        candidate decoding strategy. Can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text
        models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            candidate_generator (`CandidateGenerator`):
                A derived instance of [`CandidateGenerator`] that defines how candidate sequences are generated. For
                more information, the documentation of [`CandidateGenerator`] should be read.
            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.
            stopping_criteria (`StoppingCriteriaList`):
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
                Whether to continue running the while loop until max_length (needed to avoid deadlocking with
                `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
            model_kwargs:
                Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
                If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
            [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
            [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
            `model.config.is_encoder_decoder=True`.
        rh   Nr   r]   r^   r   ry   FTr  r|   r"   rx   r  r   r  r   r   r  )r   r   c                 3   s$   | ]} d d |d d f V  qd S r   rh   r  )
new_logitsrh   ri   r     s     z5GenerationMixin._assisted_decoding.<locals>.<genexpr>c                 3   s$   | ]} d d |d d f V  qd S r   rh   r  )r  rh   ri   r     s     )is_decoder_attentionr   	heuristicr_   r  r  );r  r   r   r  r  r  r   r   r   r   rd   r   r   r{   rU  r  Zget_candidatesr   rP  r-   r.   r   r   r   rR  r\   r  r   r   ra  _speculative_samplingr  r  r  r  r   r5  r  ri  r,   r_   Zupdate_candidate_strategyr   ry  _split_model_outputsrn   rm   r]   ro   r^   r6  r  r   r   r   Znum_assistant_tokens_scheduleZnum_assistant_tokensrj   rY   )+r   ru   r  r   r"  r   r  r  r   r  r   r   r  r  r  r[   r  rm   rn   ro   rk   rl   r   r  r  Zis_first_iterationr  candidate_input_idscandidate_logitscandidate_lengthis_done_candidateZcandidate_kwargsr   r   r  valid_tokens	n_matchesr  Zselected_tokensZcandidate_new_tokensZnew_cur_lenZnew_cache_sizeZnewly_added_lengthrh   )r  r  ri   r  &  sD   1




  



 F
4*


   
      

	z"GenerationMixin._assisted_decoding)NNNN)NNN)NNN)N)r"   FN)Fr"   )NNNN)N)NF)NN)
NNNNNNNNNN)NN)N)Fr`   ra   rb   rc   rd   re   r   r   rg   r   r   r   r  r	   r   r   r   r1   r   r   r   r{   r   staticmethodboolr   r   r   r   r   r=   r*   r  r   r   r!  rR   r)  r
   r  r9  r;  rB  rF  rK  rN  rS  rU  rt  rv  r  r  r  Zno_gradGenerateOutputr  r  r  GenerateNonBeamOutputr  r  r  r  r%   GenerateBeamOutputr  r  r'   r  r  rh   rh   rh   ri   rt   K  s         B   "
/ ;   "  

,4     j )


  z<13 
>   [t
  T                   W U    1    ' rrt   c                 C   s  | dd| df }|j dd}|ddt||f dd}|j dd}|ddt||f dd}	|	| }
t|
}||
k}| jdddk  }|r||kr|d8 }|ddd|d f }n|jd }|dd|ddf }||k r.|dd|ddf }tj|| dd}|	|  n|}tj
|ddddddf }|dkrtj|ddd|f |fdd}n|}||fS )a  
    Applies sampling as in the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf, algorithm 1). Returns
    the selected tokens, as well as the number of candidate matches.

    NOTE: Unless otherwise stated, the variable names match those in the paper.
    Nr|   r   r   r"   )rn  r  )r  rd   r   r  Z	rand_liker   r5  r   clampZdiv_r  r   )r  r  r   r  r!  Znew_candidate_input_idsqZq_ir   Zp_iZprobability_ratioZr_iZis_acceptedr#  r"  gammaZ
p_n_plus_1Z
q_n_plus_1Zp_primer  rh   rh   ri   r  1  s0      


 
$r  Fc           	      C   s   t | dkrbd}|D ]2}|r |n|jd }||dd|d|f f7 }q| |f7 } |d7 }||8 }t|D ]R}d}|D ]:}|r|| n|jd }||d||d d|f f7 }qv| |f7 } qj| S )z
    Given the (decoder/cross attentions)/(decoder hidden states) for multiple generated tokens, splits it into a tuple
    where each member corresponds to a single generated token.
    r   rh   r|   .Nr"   )r   r   ra  )	r   Znew_outputsr  Z	added_lenr  Z	new_tuplere  Zlast_dim_sizer  rh   rh   ri   r  i  s    
"r  )r  r  next_top_k_probsr  alpha
beam_widthr   c                 C   s   | | j ddd }||j ddd }t||ddd}|j|jd}d| t|jj }|| }tj	|dd\}	}
|
d}d| | ||	  }tt||}|j	dd\}
}|S )	a  
    Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as described
    in the paper "A Contrastive Framework for Neural Text Generation". Returns the index of the best candidate for each
    row in the batch.
    r   T)r   Zkeepdimr"   r|   r   r   r  )Znormrd   matmulr3  r  r   rz   Zfinforn  r6  r   r2  r  )r  r  r,  r  r-  r.  Znorm_context_hiddenZnorm_next_hiddenZcosine_matrixZdegeneration_penaltyr   Zcontrastive_scorer  rh   rh   ri   r    s    
r  )r  rb  r  c                    s    dkrdg|  S t  tjr> fddtd|D S t  ts^t  trlt  jtrl ||S t  trt  d tr fddtd|D S  fddtd|D S nt	dt
  dS )a  
    Takes care of three cases:
    1. data is a tensor: e.g. last_hidden_state, pooler_output etc. split them on the batch_size dim
    2. data is a tuple: e.g. hidden_states, attentions etc. Keep the tuple as it is and split each tensor in it and
       return a list of tuples
    3. data is a tuple of tuples, e.g. past_key_values. Keep the tuple as it is and split each tuple in it and
       return a list of tuples of tuples
    (see documentation of ModelOutput)
    Nc                    s   g | ]} ||  qS rh   rh   r  datar  rh   ri   r?    s     z_split.<locals>.<listcomp>r   c                    s$   g | ] t  fd dD qS )c                 3   s&   | ]}t  fd d|D V  qdS )c                 3   s   | ]}|    V  qd S r   rh   )r   r  r  r  rh   ri   r     s     z._split.<locals>.<listcomp>.<genexpr>.<genexpr>Nry  )r   Zinner_tupler2  rh   ri   r     s     $_split.<locals>.<listcomp>.<genexpr>r3  r   r0  r  ri   r?    s   c                    s$   g | ] t  fd dD qS )c                 3   s   | ]}|    V  qd S r   rh   )r   Z
sub_tensorr2  rh   ri   r     s     r4  r3  r5  r0  r6  ri   r?    s   Unexpected attribute type: )r   rd   r   ra  r   r   rm  Zbatch_splitry  r:  r-  )r1  r  rb  r  rh   r0  ri   _split  s&    





r8  )r   r  r  r   r   c                    sH  dkrg  S t  dkr2tdkrBtdtdrVj n }fdd|D }fdd|D }d	d
dgfdd|D | jfddt D }fdd|D  d
krtd
 | fddt	|D }dkr0fdd|D } fdd|D }|S )a  
    Split a ModelOutput object (or its subclasses) or Dict into a list of same-class objects based on a specified split
    size. The input object is dict when it was prepared for forward pass and ModelOutput when it was returned from
    previous forward pass.
    Nr   z3`full_batch_size` must be divisible by `split_size`z:`split_size` must be smaller or equal to `full_batch_size`__dataclass_fields__c                    s   g | ]}| kr|qS rh   rh   r   r   r   rh   ri   r?    s      z'_split_model_inputs.<locals>.<listcomp>c                    s&   g | ]}t  | ts|d kr|qS )rx   r   r%  r:  r;  rh   ri   r?    s       rx   r   r  c                    s&   g | ]}t | ts| kr|qS rh   r<  r:  )keys_to_ignorer   rh   ri   r?    s       c                    s&   g | ]  fd dD qS )c                    s$   i | ]}|t |   qS rh   )r8  r:  )r  r  r   rb  r  rh   ri   r     s      z2_split_model_inputs.<locals>.<listcomp>.<dictcomp>rh   r5  )r  r   non_bool_keysrb  r  r6  ri   r?    s   c                    s   i | ]}| | qS rh   rh   r:  r;  rh   ri   r     s      z'_split_model_inputs.<locals>.<dictcomp>c                    s    g | ]\}}|d  | iqS )r   rh   )r   r  
data_split)encoder_outputs_splitrh   ri   r?    s    c                    s   g | ]}|d  d  iqS )r  rh   r   r?  r;  rh   ri   r?    s    c                    s   g | ]}f | qS rh   rh   rA  )	bool_datamodel_output_clsrh   ri   r?    s    )
r-  r   r   r9  r   rA  rb  ra  r  r  )r   r  r  r   r   Z	bool_keysZdata_split_listZsplit_model_inputsrh   )	rB  r@  r  r=  r   rC  r>  rb  r  ri   r    sH    




   


r  )model_outputsr   r   c                    sp   st dtd | jtfddD s@t dfdd  fdd	j D }f |S )
z
    Stack a list of ModelOutput objects (or its subclasses) along the batch_size dimension. The function infers the
    specific ModelOutput subclass from the list provided.
    zInput list is empty.r   c                 3   s   | ]}t | V  qd S r   )r   )r   obj)rC  rh   ri   r     s     z&stack_model_outputs.<locals>.<genexpr>z4All elements in the list should be of the same type.c                    s  t dd  D rdS t d tjr4tj ddS t d trPtj dS t d trltj dS t d trt d d trt fddt	t
 d D S t fddt	t
 d D S n2t d ttfrt S td	t d  dS )
z5
        Reverse of `_split` function above.
        c                 s   s   | ]}|d kV  qd S r   rh   )r   r1  rh   rh   ri   r     s     z7stack_model_outputs.<locals>._concat.<locals>.<genexpr>Nr   r   rb  c                 3   s6   | ]. t  fd dttd d D V  qdS )c                 3   s,   | ]$ t j fd dD ddV  qdS )c                    s   g | ]}|   qS rh   rh   r<  )r  jrh   ri   r?  *  s     zLstack_model_outputs.<locals>._concat.<locals>.<genexpr>.<genexpr>.<listcomp>r   r   Nrd   r   r5  )r1  r  )rG  ri   r   *  s     zAstack_model_outputs.<locals>._concat.<locals>.<genexpr>.<genexpr>r   N)ry  ra  r   r5  r1  r6  ri   r   )  s   c                 3   s*   | ]" t j fd dD ddV  qdS )c                    s   g | ]}|  qS rh   rh   r<  r6  rh   ri   r?  .  s     zBstack_model_outputs.<locals>._concat.<locals>.<genexpr>.<listcomp>r   r   NrH  r5  rI  r6  ri   r   .  s     r7  )r   r   rd   r   r   r   Zfrom_batch_splitsr   ry  ra  r   r   r  r  r:  r-  rI  rF  rI  ri   _concat  s"    $
z$stack_model_outputs.<locals>._concatc                    s$   i | ]   fd dD qS )c                    s   g | ]}t | qS rh   )r   )r   Zmodel_outputr   rh   ri   r?  7  s     z2stack_model_outputs.<locals>.<dictcomp>.<listcomp>rh   r5  )rJ  rD  rK  ri   r   6  s    z'stack_model_outputs.<locals>.<dictcomp>)r   r-  rA  rb  r   r9  r   )rD  r   Zconcatenated_datarh   )rJ  rC  rD  rb  ri   r    s    
r  g?ZInfgMbP)r[   baseline_scoresrelative_topfilter_valuer  r   c                 C   s   | j dd}|j dd}tj|dd\}}	|d|d f }
tj|ddj}|t| }t|
|}|d}||||k < ||||k < ||fS )a]  
    Reference: https://github.com/XiangLi1999/ContrastiveDecoding/blob/170e9142e92159c1237d731e240f5eb14aabf428/transformers/src/transformers/generation_logits_process.py#L235
    Apply filtering to only keep tokens with a probability above a certain threshold. The threshold is defined as `relative_top` * max probability in the distribution.
    r|   r   T)r  .r"   )	r4  rd   r  r6  r   nplogrn  r   )r[   rL  rM  rN  Zbase_filter_valuer  Zscores_normalizedZbaseline_scores_normalizedZsorted_logitsZsorted_indicesZ
min_threshZ	probs_maxZprobs_threshrh   rh   ri   _relative_top_filter?  s    
rQ  )r  r  r  r   c                    s2  t | dkr2 | d  }t||\}}|| }|S tj fdd| D dd}tj|dd}tj|dd}d|d d d d d f |  }tj|dd}	tj|dd}
tj|	d d d d d f |dd	d}tj|
|dd	d}d||  }|d}| t	|
    } | }t||\}}|| }|S )
Nr"   r   c                    s   g | ]} | qS rh   rh   r  r  rh   ri   r?  d  s     z)_dola_select_contrast.<locals>.<listcomp>r   r|   g      ?none)Z	reduction)r   rQ  rd   r2  Fr  r4  Zkl_divZmeanr   r  ri  r   )r  r  r  Zbase_logitsr\   Zstacked_premature_layersZsoftmax_mature_layerZsoftmax_premature_layersZavg_distZlog_softmax_mature_layerZlog_softmax_premature_layersZkl1Zkl2Zjs_divsZpremature_layerrh   rR  ri   r  X  s(    (
r  )F)N)rP  r   r  Zdataclassesr   typingr   r   r   r   r   r   r	   r
   ZnumpyrO  rd   Ztorch.distributedZdistributedr  r   Ztorch.nnr   rT  Zcache_utilsr   r   r   r   r   r   Zconfiguration_utilsr   Zintegrations.deepspeedr   Zintegrations.fsdpr   Zmodeling_outputsr   r   Zpytorch_utilsr   Ztokenization_utilsr   utilsr   r   r   r   r   r    r!   Zbeam_constraintsr#   r$   Zbeam_searchr%   r&   r'   r  r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   Zlogits_processr3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   r"  rM   rN   rO   rP   rQ   rR   rS   Zmodeling_utilsrT   Ztokenization_utils_baserU   Z	streamersrV   Z
get_loggerr`   r   Zaccelerate.hooksrW   rX   rY   rj   rp   rs   ZGreedySearchDecoderOnlyOutputZ"ContrastiveSearchDecoderOnlyOutputZSampleDecoderOnlyOutputZ%ContrastiveSearchEncoderDecoderOutputZ GreedySearchEncoderDecoderOutputZSampleEncoderDecoderOutputZBeamSearchDecoderOnlyOutputZBeamSampleDecoderOnlyOutputZBeamSearchEncoderDecoderOutputZBeamSampleEncoderDecoderOutputZGreedySearchOutputZSampleOutputZBeamSearchOutputZBeamSampleOutputZContrastiveSearchOutputr'  r(  r&  rt   r  r  rg   re   r  r   r  r8  r  r  rQ  r  rh   rh   rh   ri   <module>   s   ( $	$	p$
#/+:                                8
%
   B: