a
    d                     @   sR  d dl Z d dlZd dl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 eeZdZG dd dZG d	d
 d
ZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd  d eZ e!ej"e!d!d"d#Z#d$d% Z$e!ej"e!e!eee!  d&d'd(Z%G d)d* d*eZ&G d+d, d,eZ'G d-d. d.eZ(G d/d0 d0eZ)G d1d2 d2eZ*G d3d4 d4eZ+G d5d6 d6eZ,G d7d8 d8eZ-G d9d: d:eZ.G d;d< d<eeZ/G d=d> d>eZ0G d?d@ d@eZ1G dAdB dBeZ2G dCdD dDeZ3dS )E    N)CallableIterableListOptionalTupleUnion   )add_start_docstrings)
get_loggeraP  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
            search or log softmax for each vocabulary token when using beam search
        kwargs:
            Additional logits processor specific kwargs.

    Return:
        `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.

c                   @   s0   e Zd ZdZeeejejejdddZ	dS )LogitsProcessorzSAbstract base class for all logit processors that can be applied during generation.	input_idsscoresreturnc                 C   s   t | j ddS )z#Torch method for processing logits.H is an abstract class. Only classes inheriting this class can be called.NNotImplementedError	__class__selfr   r    r   o/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/generation/logits_process.py__call__6   s    
zLogitsProcessor.__call__N
__name__
__module____qualname____doc__r	   !LOGITS_PROCESSOR_INPUTS_DOCSTRINGtorch
LongTensorFloatTensorr   r   r   r   r   r   3   s   r   c                   @   s0   e Zd ZdZeeejejejdddZ	dS )LogitsWarperzjAbstract base class for all logit warpers that can be applied during generation with multinomial sampling.r   c                 C   s   t | j ddS )z Torch method for warping logits.r   Nr   r   r   r   r   r   A   s    
zLogitsWarper.__call__Nr   r   r   r   r   r"   >   s   r"   c                   @   s0   e Zd ZdZeeejejejdddZ	dS )LogitsProcessorLista  
    This class can be used to create a list of [`LogitsProcessor`] or [`LogitsWarper`] to subsequently process a
    `scores` input tensor. This class inherits from list and adds a specific *__call__* method to apply each
    [`LogitsProcessor`] or [`LogitsWarper`] to the inputs.
    r   c                    s   | D ]}t |jj}t|dkr|t fddt| dd  D shtdt|  d|j	 d|||fi  }q|||}q|S )Nr   c                 3   s   | ]}| v V  qd S Nr   ).0argkwargsr   r   	<genexpr>U       z/LogitsProcessorList.__call__.<locals>.<genexpr>z,Make sure that all the required parameters: z for z$ are passed to the logits processor.)
inspect	signaturer   
parameterslenalllistkeys
ValueErrorr   )r   r   r   r(   	processorZfunction_argsr   r'   r   r   P   s    &zLogitsProcessorList.__call__Nr   r   r   r   r   r#   I   s   r#   c                   @   sD   e Zd ZdZeeeee f dddZej	ej
ej
dddZdS )	MinLengthLogitsProcessora  
    [`LogitsProcessor`] enforcing a min-length by setting EOS probability to 0.

    Args:
        min_length (`int`):
            The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`.
        eos_token_id (`Union[int, List[int]]`):
            The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
    )
min_lengtheos_token_idc                 C   st   t |tr|dk r td| t |tr0|g}tdd |D rTtdd |D rdtd|  || _|| _d S )Nr   z6`min_length` has to be a non-negative integer, but is c                 S   s   g | ]}t |tqS r   
isinstanceintr%   ir   r   r   
<listcomp>q   r*   z5MinLengthLogitsProcessor.__init__.<locals>.<listcomp>c                 S   s   g | ]}|d k qS r   r   r:   r   r   r   r<   q   r*   =`eos_token_id` has to be a list of positive integers, but is )	r8   r9   r2   r/   anyloggerwarningr5   r6   )r   r5   r6   r   r   r   __init__k   s    
$z!MinLengthLogitsProcessor.__init__r   c                 C   s:   |j d }|| jk r6| jD ]}td |d d |f< q|S Ninf)shaper5   r6   floatr   r   r   cur_lenr;   r   r   r   r   w   s
    


z!MinLengthLogitsProcessor.__call__Nr   r   r   r   r9   r   r   rB   r   r    r!   r   r   r   r   r   r4   `   s   
r4   c                   @   sF   e Zd ZdZeeeeee f dddZej	ej
ej
dddZdS )	!MinNewTokensLengthLogitsProcessora  
    [`LogitsProcessor`] enforcing a min-length of new tokens by setting EOS (End-Of-Sequence) token probability to 0.

    Args:
        prompt_length_to_skip (`int`):
            The input tokens length.
        min_new_tokens (`int`):
            The minimum *new* tokens length below which the score of `eos_token_id` is set to `-float("Inf")`.
        eos_token_id (`Union[int, List[int]]`):
            The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
    )prompt_length_to_skipmin_new_tokensr6   c                 C   s   d|fd|ffD ].\}}t |tr*|dk rtd| d| qt |trP|g}tdd |D rttdd |D rtd	|  || _|| _|| _	d S )
NrL   rM   r   `z'` has to be a positive integer, but is c                 S   s   g | ]}t |tqS r   r7   r:   r   r   r   r<      r*   z>MinNewTokensLengthLogitsProcessor.__init__.<locals>.<listcomp>c                 S   s   g | ]}|d k qS r=   r   r:   r   r   r   r<      r*   r>   )
r8   r9   r2   r/   r?   r@   rA   rL   rM   r6   )r   rL   rM   r6   Zarg_name	arg_valuer   r   r   rB      s    
$z*MinNewTokensLengthLogitsProcessor.__init__r   c                 C   s@   |j d | j }|| jk r<| jD ]}td |d d |f< q |S rC   )rF   rL   rM   r6   rG   )r   r   r   Znew_tokens_lengthr;   r   r   r   r      s
    

z*MinNewTokensLengthLogitsProcessor.__call__NrJ   r   r   r   r   rK      s   rK   c                   @   s6   e Zd ZdZedddZejejejdddZ	dS )	TemperatureLogitsWarperz
    [`LogitsWarper`] for temperature (exponential scaling output probability distribution).

    Args:
        temperature (`float`):
            The value used to module the logits distribution.
    temperaturec                 C   s*   t |tr|dks td| || _d S )Nr   z:`temperature` has to be a strictly positive float, but is )r8   rG   r2   rR   )r   rR   r   r   r   rB      s    z TemperatureLogitsWarper.__init__r   c                 C   s   || j  }|S r$   rQ   r   r   r   r   r      s    
z TemperatureLogitsWarper.__call__N)
r   r   r   r   rG   rB   r   Tensorr!   r   r   r   r   r   rP      s   rP   c                   @   s6   e Zd ZdZedddZejejejdddZ	dS )	 RepetitionPenaltyLogitsProcessora#  
    [`LogitsProcessor`] enforcing an exponential penalty on repeated sequences.

    Args:
        repetition_penalty (`float`):
            The parameter for repetition penalty. 1.0 means no penalty. See [this
            paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
    )penaltyc                 C   s*   t |tr|dks td| || _d S )Nr   6`penalty` has to be a strictly positive float, but is )r8   rG   r2   rU   )r   rU   r   r   r   rB      s    z)RepetitionPenaltyLogitsProcessor.__init__r   c                 C   s>   t |d|}t |dk || j || j }|d|| |S N   r   )r   gatherwhererU   scatter_r   r   r   Zscorer   r   r   r      s    z)RepetitionPenaltyLogitsProcessor.__call__N)
r   r   r   r   rG   rB   r   r    r!   r   r   r   r   r   rT      s   	rT   c                   @   s:   e Zd ZdZeejdddZejejejdddZ	dS )	'EncoderRepetitionPenaltyLogitsProcessoraq  
    [`LogitsProcessor`] enforcing an exponential penalty on tokens that are not in the original input.

    Args:
        hallucination_penalty (`float`):
            The parameter for hallucination penalty. 1.0 means no penalty.
        encoder_input_ids (`torch.LongTensor`):
            The encoder_input_ids that should not be repeated within the decoder ids.
    )rU   encoder_input_idsc                 C   s4   t |tr|dks td| d| | _|| _d S )Nr   rV   rX   )r8   rG   r2   rU   r^   )r   rU   r^   r   r   r   rB      s    
z0EncoderRepetitionPenaltyLogitsProcessor.__init__r   c                 C   sB   t |d| j}t |dk || j || j }|d| j| |S rW   )r   rY   r^   rZ   rU   r[   r\   r   r   r   r      s    z0EncoderRepetitionPenaltyLogitsProcessor.__call__N)
r   r   r   r   rG   r   r    rB   r!   r   r   r   r   r   r]      s   
r]   c                   @   sF   e Zd ZdZed dfeeedddZejej	ej	ddd	Z
d
S )TopPLogitsWarperaD  
    [`LogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.

    Args:
        top_p (`float`):
            If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
            higher are kept for generation.
        filter_value (`float`, *optional*, defaults to `-float("Inf")`):
            All filtered values will be set to this float value.
        min_tokens_to_keep (`int`, *optional*, defaults to 1):
            Minimum number of tokens that cannot be filtered.
    InfrX   )top_pfilter_valuemin_tokens_to_keepc                 C   s<   t |}|dk s|dkr&td| || _|| _|| _d S )Nr   g      ?z.`top_p` has to be a float > 0 and < 1, but is )rG   r2   ra   rb   rc   )r   ra   rb   rc   r   r   r   rB      s    zTopPLogitsWarper.__init__r   c                 C   sr   t j|dd\}}|jddjdd}|d| j k}| jdkrRd|d| j d f< |d||}||| j}|S )NFZ
descendingrD   ZdimrX   r   .)	r   sortsoftmaxcumsumra   rc   scattermasked_fillrb   )r   r   r   sorted_logitssorted_indicescumulative_probssorted_indices_to_removeindices_to_remover   r   r   r     s    
zTopPLogitsWarper.__call__Nr   r   r   r   rG   r9   rB   r   r    r!   r   r   r   r   r   r_      s   	r_   c                   @   sF   e Zd ZdZed dfeeedddZejej	ej	ddd	Z
d
S )TopKLogitsWarpera  
    [`LogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.

    Args:
        top_k (`int`):
            The number of highest probability vocabulary tokens to keep for top-k-filtering.
        filter_value (`float`, *optional*, defaults to `-float("Inf")`):
            All filtered values will be set to this float value.
        min_tokens_to_keep (`int`, *optional*, defaults to 1):
            Minimum number of tokens that cannot be filtered.
    r`   rX   )top_krb   rc   c                 C   s6   t |tr|dkr td| t||| _|| _d S )Nr   z6`top_k` has to be a strictly positive integer, but is )r8   r9   r2   maxrr   rb   )r   rr   rb   rc   r   r   r   rB   $  s    zTopKLogitsWarper.__init__r   c                 C   s<   t | j|d}|t||d d k }||| j}|S )NrD   r   .rD   N)minrr   sizer   topkrj   rb   )r   r   r   rr   ro   r   r   r   r   +  s    zTopKLogitsWarper.__call__Nrp   r   r   r   r   rq     s   rq   c                   @   sH   e Zd ZdZded dfeeedddZejej	ej	dd	d
Z
dS )TypicalLogitsWarpera"  
    [`LogitsWarper`] that performs typical decoding. See [Typical Decoding for Natural Language
    Generation](https://arxiv.org/abs/2202.00666) for more information.

    Args:
        mass (`float`):
            Value of typical_p between 0 and 1 inclusive, defaults to 0.9.
        filter_value (`float`, *optional*, defaults to `-float("Inf")`):
            All filtered values will be set to this float value.
        min_tokens_to_keep (`int`, *optional*, defaults to 1):
            Minimum number of tokens that cannot be filtered.
    g?r`   rX   )massrb   rc   c                 C   s<   t |}|dkr|dk s&td| || _|| _|| _d S )Nr   rX   z2`typical_p` has to be a float > 0 and < 1, but is )rG   r2   rb   ry   rc   )r   ry   rb   rc   r   r   r   rB   A  s    zTypicalLogitsWarper.__init__r   c                 C   s   t jjj|dd}t |}|| jddd }t | | }t j|dd\}}|d|}	|	j	ddj
dd}
|
| jk jdd}d||dk < ||d|ddk}| jdkrd|d	d | jf< |d||}||| j}|S )
NrD   re   T)ZkeepdimFrd   rX   r   .)r   nn
functionallog_softmaxexpZnansumabsrf   rY   rg   rh   ry   sumviewrc   ri   rj   rb   )r   r   r   
normalizedpentZshifted_scoresZsorted_scoresrl   rk   rm   Zlast_indrn   ro   r   r   r   r   J  s    

zTypicalLogitsWarper.__call__Nrp   r   r   r   r   rx   3  s    	rx   c                   @   sF   e Zd ZdZed dfeeedddZejej	ej	ddd	Z
d
S )EpsilonLogitsWarpera  
    [`LogitsWarper`] that performs epsilon-sampling, i.e. restricting to tokens with `prob >= epsilon`. Takes the
    largest min_tokens_to_keep tokens if no tokens satisfy this constraint. See [Truncation Sampling as Language Model
    Desmoothing](https://arxiv.org/abs/2210.15191) for more information.

    Args:
        epsilon (`float`):
            If set to > 0, only the most tokens with probabilities `epsilon` or higher are kept for generation.
        filter_value (`float`, *optional*, defaults to `-float("Inf")`):
            All filtered values will be set to this float value.
        min_tokens_to_keep (`int`, *optional*, defaults to 1):
            Minimum number of tokens that cannot be filtered.
    r`   rX   epsilonrb   rc   c                 C   sZ   t |}|dks|dkr&td| t|}|dk rDtd| || _|| _|| _d S )Nr   rX   z7`epsilon_cutoff` has to be a float > 0 and < 1, but is C`min_tokens_to_keep` has to be a strictly positive integer, but is )rG   r2   r9   r   rb   rc   r   r   rb   rc   r   r   r   rB   r  s    zEpsilonLogitsWarper.__init__r   c                 C   sV   |j dd}|| jk }t| j|d}||t||d d k @ }||| j}|S )NrD   re   r   rt   )	rg   r   ru   rc   rv   r   rw   rj   rb   )r   r   r   probabilitiesro   rr   r   r   r   r     s    
zEpsilonLogitsWarper.__call__Nrp   r   r   r   r   r   c  s   r   c                   @   sF   e Zd ZdZed dfeeedddZejej	ej	ddd	Z
d
S )EtaLogitsWarpera  
    [`LogitsWarper`] that performs eta-sampling, i.e. calculates a dynamic cutoff `eta := min(epsilon, sqrt(epsilon,
    e^-entropy(probabilities)))` and restricts to tokens with `prob >= eta`. Takes the largest min_tokens_to_keep
    tokens if no tokens satisfy this constraint. See [Truncation Sampling as Language Model
    Desmoothing](https://arxiv.org/abs/2210.15191) for more information.

    Args:
        min_tokens_to_keep (`int`, *optional*, defaults to 1):
            Minimum number of tokens that cannot be filtered.r`   rX   r   c                 C   s`   t |}|dks|dkr&td| t|}|dk rDtd| t|| _|| _|| _d S )Nr   rX   z3`eta_cutoff` has to be a float > 0 and < 1, but is r   )rG   r2   r9   r   Ztensorr   rb   rc   r   r   r   r   rB     s    zEtaLogitsWarper.__init__r   c                 C   s   |j dd}tjj|d }t| jt| jt|  d }||k }t| j	|
d}||t||d d k @ }||| j}|S )NrD   re   )Zlogits).Nr   rt   )rg   r   distributionsZCategoricalentropyru   r   sqrtr}   rc   rv   rw   rj   rb   )r   r   r   r   r   etaro   rr   r   r   r   r     s    &zEtaLogitsWarper.__call__Nrp   r   r   r   r   r     s   
r   )
ngram_sizeprev_input_ids	num_hyposc                    s   dd t |D }t |D ]b}||   || }t fddt | D  D ].}t|d d }||g |d g ||< qLq|S )Nc                 S   s   g | ]}i qS r   r   r%   _r   r   r   r<     r*   z_get_ngrams.<locals>.<listcomp>c                    s   g | ]} |d  qS r$   r   r:   Z
gen_tokensr   r   r<     r*   rD   )rangetolistziptupleget)r   r   r   generated_ngramsidxZgenerated_ngramZngramZprev_ngram_tupler   r   r   _get_ngrams  s    r   c                 C   s,   |d | }t |||  }| |g S )NrX   )r   r   r   )Zbanned_ngramsr   r   rI   Z	start_idxZ	ngram_idxr   r   r   _get_generated_ngrams  s    r   )r   r   r   rI   r   c                    sJ    d k rdd t |D S t| fddt |D }|S )z6Copied from fairseq for no_repeat_ngram in beam_searchrX   c                 S   s   g | ]}g qS r   r   r   r   r   r   r<     r*   z-_calc_banned_ngram_tokens.<locals>.<listcomp>c                    s"   g | ]}t | |  qS r   )r   r%   Zhypo_idxrI   r   r   r   r   r   r<     s   )r   r   )r   r   r   rI   banned_tokensr   r   r   _calc_banned_ngram_tokens  s    r   c                   @   s6   e Zd ZdZedddZejejejdddZ	dS )	NoRepeatNGramLogitsProcessora5  
    [`LogitsProcessor`] that enforces no repetition of n-grams. See
    [Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345).

    Args:
        ngram_size (`int`):
            All ngrams of size `ngram_size` can only occur once.
    )r   c                 C   s*   t |tr|dkr td| || _d S )Nr   z;`ngram_size` has to be a strictly positive integer, but is )r8   r9   r2   r   )r   r   r   r   r   rB     s    z%NoRepeatNGramLogitsProcessor.__init__r   c                 C   sL   |j d }|j d }t| j|||}t|D ]\}}td |||f< q,|S )Nr   rD   rE   )rF   r   r   	enumeraterG   )r   r   r   Znum_batch_hypothesesrI   banned_batch_tokensr;   r   r   r   r   r     s    

z%NoRepeatNGramLogitsProcessor.__call__N
r   r   r   r   r9   rB   r   r    r!   r   r   r   r   r   r     s   	r   c                   @   s:   e Zd ZdZeejdddZejejejdddZ	dS )	#EncoderNoRepeatNGramLogitsProcessora  
    [`LogitsProcessor`] that enforces no repetition of encoder input ids n-grams for the decoder ids. See
    [ParlAI](https://github.com/facebookresearch/ParlAI/blob/master/parlai/core/torch_generator_agent.py#L1350).

    Args:
        encoder_ngram_size (`int`):
            All ngrams of size `ngram_size` can only occur within the encoder input ids.
        encoder_input_ids (`int`):
            The encoder_input_ids that should not be repeated within the decoder ids.
    )encoder_ngram_sizer^   c                 C   s^   t |tr|dkr td| || _t|jdkr>|d}|jd | _t||| j| _	d S )Nr   zC`encoder_ngram_size` has to be a strictly positive integer, but is rX   )
r8   r9   r2   r   r.   rF   	unsqueeze
batch_sizer   r   )r   r   r^   r   r   r   rB      s    
z,EncoderNoRepeatNGramLogitsProcessor.__init__r   c                    sb   |j d }|j j d   fddt|D }t|D ]\}}td |||f< qB|S )Nr   rD   c                    s*   g | ]"}t j|  | j qS r   )r   r   r   r   rI   r   	num_beamsr   r   r   r<     s   z@EncoderNoRepeatNGramLogitsProcessor.__call__.<locals>.<listcomp>rE   )rF   r   r   r   rG   )r   r   r   r   r   r;   r   r   r   r   r     s    


z,EncoderNoRepeatNGramLogitsProcessor.__call__N)
r   r   r   r   r9   r   r    rB   r!   r   r   r   r   r   r     s   r   c                   @   s   e Zd ZdZeee  eeee f dddZej	ej
ej
dddZej
ejdd	d
Zee ee edddZeee  ee dddZejeee  ejdddZdS )NoBadWordsLogitsProcessoraI  
    [`LogitsProcessor`] that enforces that specified sequences will never be sampled.

    Args:
        bad_words_ids (`List[List[int]]`):
            List of list of token ids that are not allowed to be generated. In order to get the token ids of the words
            that should not appear in the generated text, use `tokenizer(bad_words, add_prefix_space=True,
            add_special_tokens=False).input_ids`.
        eos_token_id (`Union[int, List[int]]`):
            The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
    )bad_words_idsr6   c                    s  t |trt|dkr&td| dtdd |D rHtd| dtdd |D rjtd| d d u rvg  t  tr g tt fd	d
|}g | _g | _	|D ].}t|dkr| j
|d  q| j	
| qd | _| j	D ] }t|dkrtd| dqd S )Nr   z3`bad_words_ids` has to be a non-empty list, but is .c                 s   s   | ]}t |t V  qd S r$   )r8   r0   r%   Zbad_word_idsr   r   r   r)   -  r*   z5NoBadWordsLogitsProcessor.__init__.<locals>.<genexpr>z2`bad_words_ids` has to be a list of lists, but is c                 s   s    | ]}t d d |D V  qdS )c                 s   s(   | ] }t |ttjf p|d k V  qdS )r   N)r8   r9   npinteger)r%   Ztoken_idr   r   r   r)   0  r*   z?NoBadWordsLogitsProcessor.__init__.<locals>.<genexpr>.<genexpr>N)r?   r   r   r   r   r)   /  s   zKEach list in `bad_words_ids` has to be a list of positive integers, but is c                    s   t  fddD S )Nc                    s   g | ]} |gkqS r   r   r:   Zbad_token_seqr   r   r<   =  r*   zHNoBadWordsLogitsProcessor.__init__.<locals>.<lambda>.<locals>.<listcomp>)r/   r   r6   r   r   <lambda>=  r*   z4NoBadWordsLogitsProcessor.__init__.<locals>.<lambda>rX   zBanned words token sequences z cannot have an empty list)r8   r   r.   r2   r?   r9   r0   filterbad_words_id_length_1"bad_words_id_length_greater_than_1appendstatic_bad_words_mask)r   r   r6   wordbanned_token_seqr   r   r   rB   *  s6    


z"NoBadWordsLogitsProcessor.__init__r   c                 C   sB   | j d u r$t| jdkr$| || _ | | }| ||}|S )Nr   )r   r.   r   _calc_static_bad_word_mask_calc_banned_bad_words_idsr   $_set_scores_to_inf_for_banned_tokens)r   r   r   Zdynamic_banned_tokensr   r   r   r   M  s
    z"NoBadWordsLogitsProcessor.__call__)r   r   c                 C   s0   t |jd }d|| j< |d|j S rW   )r   zerosrF   r   r   todevicebool)r   r   r   r   r   r   r   V  s    
z4NoBadWordsLogitsProcessor._calc_static_bad_word_mask)prev_tokenstokensr   c                 C   s>   t |dkrdS t |t |kr$dS |t | d  |kS d S )Nr   TF)r.   )r   r   r   r   r   r   _tokens_match[  s
    z'NoBadWordsLogitsProcessor._tokens_match)r   r   c                 C   sN   g }|D ]@}g }| j D ]&}| ||d d r||d  q|| q|S NrD   )r   r   r   )r   r   r   Zprev_input_ids_sliceZbanned_tokens_slicer   r   r   r   r   e  s    
z4NoBadWordsLogitsProcessor._calc_banned_bad_words_ids)r   r   r   c           	      C   s   g }t |D ]B\}}|D ]4}||jd kr:|||g qtd| d qq|sb| jdu rb|S |rtt|}tj	||j
d}tj	| || |j
  }| jdurt|| j}n| j}||td }|S dS )a  
        Modifies the scores in place by setting the banned token positions to `-inf`. Banned token is expected to be a
        list of list of banned tokens to ban in the format [[batch index, vocabulary position],...

        Args:
            scores: logits distribution of shape (batch size, vocabulary size)
            banned_tokens: list of list of tokens to ban of length (batch_size)
        rX   z#An invalid bad word ID is defined: zG. This ID is not contained in the vocabulary, and is therefore ignored.N)r   rE   )r   rF   r   r@   errorr   r   Zonesr.   r    r   sparsetrv   r   Zto_denser   Z
bitwise_orrj   rG   )	r   r   r   Zbanned_mask_listr   Zbatch_banned_tokenstokenindicesZbanned_maskr   r   r   r   q  s,    


z>NoBadWordsLogitsProcessor._set_scores_to_inf_for_banned_tokensN)r   r   r   r   r   r9   r   rB   r   r    r!   r   Z
BoolTensorr   r   r   r   r   rS   r   r   r   r   r   r     s   $#	
r   c                   @   sJ   e Zd ZdZeeejgee f edddZ	ej
ejejdddZdS )	 PrefixConstrainedLogitsProcessora  
    [`LogitsProcessor`] that enforces constrained generation and is useful for prefix-conditioned constrained
    generation. See [Autoregressive Entity Retrieval](https://arxiv.org/abs/2010.00904) for more information.

    Args:
        prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`):
            This function constraints the beam search to allowed tokens only at each step. This function takes 2
            arguments `inputs_ids` and the batch ID `batch_id`. It has to return a list with the allowed tokens for the
            next generation step conditioned on the previously generated tokens `inputs_ids` and the batch ID
            `batch_id`.
    )prefix_allowed_tokens_fnr   c                 C   s   || _ || _d S r$   )_prefix_allowed_tokens_fn
_num_beams)r   r   r   r   r   r   rB     s    z)PrefixConstrainedLogitsProcessor.__init__r   c              	   C   sl   t |tj }t|d| j|jd D ]8\}}t|D ]&\}}d||| j | | ||f< q:q*|| S )NrD   r   )	r   Z	full_likemathrE   r   r   r   rF   r   )r   r   r   maskZbatch_idZ	beam_sentZbeam_idsentr   r   r   r     s
    ""z)PrefixConstrainedLogitsProcessor.__call__N)r   r   r   r   r   r9   r   rS   r   rB   r    r!   r   r   r   r   r   r     s   "r   c                   @   s@   e Zd ZdZeeedddZejej	ejeej	dddZ
dS )	HammingDiversityLogitsProcessora  
    [`LogitsProcessor`] that enforces diverse beam search. Note that this logits processor is only effective for
    [`PreTrainedModel.group_beam_search`]. See [Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence
    Models](https://arxiv.org/pdf/1610.02424.pdf) for more details.

    Args:
        diversity_penalty (`float`):
            This value is subtracted from a beam's score if it generates a token same as any beam from other group at a
            particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
        num_beams (`int`):
            Number of beams used for group beam search. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more
            details.
        num_beam_groups (`int`):
            Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
            See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
    )diversity_penaltyr   num_beam_groupsc                 C   sx   t |tr|dkstd|| _t |tr2|dk r:td|| _t |trR|dk rZtd||krjtd|| | _d S )N        z=`diversity_penalty` should be a float strictly larger than 0.r   z8`num_beams` should be an integer strictly larger than 1.z>`num_beam_groups` should be an integer strictly larger than 1.z8`beam_groups` has to be smaller or equal to `num_beams`.)r8   rG   r2   _diversity_penaltyr9   r   _num_sub_beams)r   r   r   r   r   r   r   rB     s    z(HammingDiversityLogitsProcessor.__init__)r   r   current_tokensbeam_group_idxr   c                 C   s   |j d | j }|| j }t|| j | j}|| }|j d }	|dkrJ|S t|D ]\}
||
| j |
| j |  }tj||	d|j}||
| |
d |   | j	| 8  < qR|S )Nr   rD   )Z	minlengthrX   )
rF   r   r   ru   r   r   Zbincountr   r   r   )r   r   r   r   r   r   Zgroup_start_idxZgroup_end_idxZ
group_sizeZ
vocab_sizeZ	batch_idxZprevious_group_tokensZtoken_frequencyr   r   r   r     s    	

(z(HammingDiversityLogitsProcessor.__call__Nrp   r   r   r   r   r     s   r   c                   @   s6   e Zd ZdZedddZejejejdddZ	dS )	ForcedBOSTokenLogitsProcessorz
    [`LogitsProcessor`] that enforces the specified token as the first generated token.

    Args:
        bos_token_id (`int`):
            The id of the token to force as the first generated token.
    bos_token_idc                 C   s
   || _ d S r$   r   )r   r   r   r   r   rB     s    z&ForcedBOSTokenLogitsProcessor.__init__r   c                    sZ   |j d }|dkrV|j d }td |d d  fddt|D f< d|d d  jf< |S )NrD   rX   rE   c                    s   g | ]}| j kr|qS r   r   r:   r   r   r   r<   	  r*   z:ForcedBOSTokenLogitsProcessor.__call__.<locals>.<listcomp>r   )rF   rG   r   r   )r   r   r   rI   
num_tokensr   r   r   r     s    

(z&ForcedBOSTokenLogitsProcessor.__call__Nr   r   r   r   r   r     s   r   c                   @   sD   e Zd ZdZeeeee f dddZej	ej
ej
dddZdS )	ForcedEOSTokenLogitsProcessora  
    [`LogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached.

    Args:
        max_length (`int`):
            The maximum length of the sequence to be generated.
        eos_token_id (`Union[int, List[int]]`):
            The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a
            list to set multiple *end-of-sequence* tokens.
    )
max_lengthr6   c                 C   s    || _ t|tr|g}|| _d S r$   )r   r8   r9   r6   )r   r   r6   r   r   r   rB     s    
z&ForcedEOSTokenLogitsProcessor.__init__r   c                    sj   |j d }| jd krf|j d }td |d d  fddt|D f<  jD ]}d|d d |f< qP|S )NrD   rX   rE   c                    s   g | ]}| j vr|qS r   r   r:   r   r   r   r<   $  r*   z:ForcedEOSTokenLogitsProcessor.__call__.<locals>.<listcomp>r   )rF   r   rG   r   r6   )r   r   r   rI   r   r;   r   r   r   r      s    

(
z&ForcedEOSTokenLogitsProcessor.__call__NrJ   r   r   r   r   r     s   r   c                   @   s(   e Zd ZdZejejejdddZdS )InfNanRemoveLogitsProcessorz
    [`LogitsProcessor`] that removes all `nan` and `inf` values to avoid the generation method to fail. Note that using
    the logits processor should only be used if necessary since it can slow down the generation method.
    r   c                 C   s*   d|||k< t |jj||tdk< |S )Nr   rE   )r   ZfinfoZdtypers   rG   r   r   r   r   r   0  s    z$InfNanRemoveLogitsProcessor.__call__N)r   r   r   r   r   r    r!   r   r   r   r   r   r   *  s   r   c                   @   sN   e Zd ZdZeeef eeee f edddZ	e
je
je
jdddZdS )	ExponentialDecayLengthPenaltya  
    [`LogitsProcessor`] that exponentially increases the score of the eos_token_id after regulation_start has been
    reached.

    Args:
        exponential_decay_length_penalty (`tuple(int, float)`):
            This tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty
            starts and `decay_factor` represents the factor of exponential decay
        eos_token_id (`Union[int, List[int]]`):
            The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
        input_ids_seq_length (`int`):
            The length of the input sequence.
    ) exponential_decay_length_penaltyr6   input_ids_seq_lengthc                 C   s2   |d | | _ |d | _t|tr(|g}|| _d S )Nr   rX   )regulation_startregulation_factorr8   r9   r6   )r   r   r6   r   r   r   r   rB   I  s
    

z&ExponentialDecayLengthPenalty.__init__r   c                 C   sR   |j d }|| jkrN| jD ]2}|d d |f t| j|| j  |d d |f< q|S r   )rF   r   r6   powr   rH   r   r   r   r   U  s
    


0z&ExponentialDecayLengthPenalty.__call__N)r   r   r   r   r   r9   rG   r   r   rB   r   rS   r!   r   r   r   r   r   r   :  s   
r   c                   @   s(   e Zd ZdZejejejdddZdS )LogitNormalizationa  
    [`LogitsWarper`] and [`LogitsProcessor`] for normalizing the scores using log-softmax. It's important to normalize
    the scores during beam search, after applying the logits processors or warpers, since the search algorithm used in
    this library doesn't do it (it only does it before, but they may need re-normalization) but it still supposes that
    the scores are normalized when comparing the hypotheses.
    r   c                 C   s   |j dd}|S )NrD   re   )r|   r   r   r   r   r   e  s    zLogitNormalization.__call__N)r   r   r   r   r   rS   r   r   r   r   r   r   ]  s   r   c                   @   s    e Zd ZdZdd Zdd ZdS )$SuppressTokensAtBeginLogitsProcessora  
    [`SuppressTokensAtBeginLogitsProcessor`] supresses a list of tokens as soon as the `generate` function starts
    generating using `begin_index` tokens. This should ensure that the tokens defined by `begin_suppress_tokens` at not
    sampled at the begining of the generation.
    c                 C   s   t || _|| _d S r$   )r0   begin_suppress_tokensbegin_index)r   r   r   r   r   r   rB   q  s    
z-SuppressTokensAtBeginLogitsProcessor.__init__c                 C   s,   |j d | jkr(td |d d | jf< |S )NrX   rE   )rF   r   rG   r   r   r   r   r   r   u  s    z-SuppressTokensAtBeginLogitsProcessor.__call__Nr   r   r   r   rB   r   r   r   r   r   r   j  s   r   c                   @   s    e Zd ZdZdd Zdd ZdS )SuppressTokensLogitsProcessorzThis processor can be used to suppress a list of tokens. The processor will set their log probs to `-inf` so that they
    are not sampled.c                 C   s   t || _d S r$   )r0   suppress_tokens)r   r   r   r   r   rB     s    z&SuppressTokensLogitsProcessor.__init__c                 C   s   t d |d d | jf< |S )NrE   )rG   r   r   r   r   r   r     s    z&SuppressTokensLogitsProcessor.__call__Nr   r   r   r   r   r   |  s   r   c                   @   s.   e Zd ZdZeee  dddZdd ZdS )ForceTokensLogitsProcessora  This processor takes a list of pairs of integers which indicates a mapping from generation indices to token
    indices that will be forced before sampling. The processor will set their log probs to `inf` so that they are
    sampled at their corresponding index.)force_token_mapc                 C   s   t || _d S r$   )dictr   )r   r   r   r   r   rB     s    z#ForceTokensLogitsProcessor.__init__c                 C   sN   |j d }| j|d }|d urJtd |d d d d f< d|d d |f< |S )NrD   rE   r   )rF   r   r   rG   )r   r   r   Zgeneration_idxcurrent_tokenr   r   r   r     s    
z#ForceTokensLogitsProcessor.__call__N)r   r   r   r   r   r9   rB   r   r   r   r   r   r     s   r   c                   @   s    e Zd ZdZdd Zdd ZdS )WhisperTimeStampLogitsProcessora{  
    Whisper specific Processor. This processor can be used to force a list of tokens. The processor will set their log
    probs to `inf` so that they are sampled at their corresponding index.

    Args:
        generate_config (`GenerateConfig`):
            The generate config used to generate the output. The following parameters are required:
                eos_token_id (`int`, *optional*, defaults to 50257):
                    The id of the *end-of-sequence* token.
                no_timestamps_token_id (`int`, *optional*, defaults to 50363):
                    The id of the `"<|notimestamps|>"` token.
                max_initial_timestamp_index (`int`, *optional*, defaults to 1):
                    Used to set the maximum value of the initial timestamp. This is used to prevent the model from
                    predicting timestamps that are too far in the future.
    c                 C   sZ   |j | _ |j| _|jd | _t|jd | _|jd d | jkrN|  jd8  _|j| _d S )NrX   r   rD   )r6   no_timestamps_token_idtimestamp_beginr.   Zforced_decoder_idsr   max_initial_timestamp_index)r   Zgenerate_configr   r   r   rB     s    z(WhisperTimeStampLogitsProcessor.__init__c                 C   s  t d |d d | jf< |jd | jd kr\t d |d d d d f< d|d d | jf< |S t|jd D ]}t||| jd f  }t|dko|d | jk}t|dk p|d | jk}|r|rt d ||| jd f< nt d ||d | j	f< |jd | jkrj| j
d urj| j| j
 }t d |d d |d d f< qjtjjj|  dd}t|jd D ]X}||| jd f jdd}	||d | jf  }
|	|
kr`t d ||d | jf< q`|S )NrE   rX   r   rD   r   re   )rG   r   rF   r   r   r   r0   r   r.   r6   r   r   rz   r{   r|   Z	logsumexprs   )r   r   r   kseqZlast_was_timestampZpenultimate_was_timestampZlast_allowedZlogprobsZtimestamp_logprobZmax_text_token_logprobr   r   r   r     s.     
z(WhisperTimeStampLogitsProcessor.__call__Nr   r   r   r   r   r     s   
r   )4r+   r   typingr   r   r   r   r   r   numpyr   r   utilsr	   Zutils.loggingr
   r   r@   r   r   r"   r0   r#   r4   rK   rP   rT   r]   r_   rq   rx   r   r   r9   rS   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sR    ''0+)

) <#