o
    Zh                    @   s,  d Z ddlZddlZddlZddlZddl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 dd	lmZ dd
lmZmZ ddlmZmZmZmZmZ ddlm Z  ddl!m"Z"m#Z#m$Z$m%Z% ddl&m'Z'm(Z( ddl)m*Z* e# rddl+m,Z, ddl-m.Z. e%/e0Z1de
j2de3de3fddZ4G dd dej5Z6G dd dej5Z7G dd dej8Z9de9iZ:G d d! d!ej8Z;G d"d# d#ej8Z<e"G d$d% d%e Z=G d&d' d'e=Z>G d(d) d)e=Z?e"G d*d+ d+e=Z@e"d,d-G d.d/ d/e=eZAG d0d1 d1e=ZBG d2d3 d3e=eZCg d4ZDdS )5zPyTorch Blenderbot model.    N)ListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)CacheEncoderDecoderCache)GenerationMixin)AttentionMaskConverter_prepare_4d_attention_mask)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)PreTrainedModel)auto_docstringis_torch_flex_attn_availableis_torchdynamo_compilinglogging   )'BlenderbotSmallForConditionalGenerationBlenderbotSmallModel   )BlenderbotConfig)	BlockMask)make_flex_block_causal_mask	input_idspad_token_iddecoder_start_token_idc                 C   sh   |  | j}| ddddf  |ddddf< ||dddf< |du r*td||dk| |S )z1
    Shift input ids one token to the right.
    Nr   r   z1self.model.config.pad_token_id has to be defined.i)Z	new_zerosshapeclone
ValueErrorZmasked_fill_)r    r!   r"   Zshifted_input_ids r'   a/var/www/auris/lib/python3.10/site-packages/transformers/models/blenderbot/modeling_blenderbot.pyshift_tokens_right?   s   (r)   c                       sP   e Zd ZdZdedef fddZ	ddejd	ed
eej	 f fddZ
  ZS )$BlenderbotLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    num_embeddingsembedding_dimc                    s   t  || d S N)super__init__)selfr+   r,   	__class__r'   r(   r/   T      z-BlenderbotLearnedPositionalEmbedding.__init__r   Ninput_ids_shapepast_key_values_lengthposition_idsc                    s@   |du r|dd \}}t j||| t j| jjd}t |S )z3`input_ids_shape` is expected to be [bsz x seqlen].Nr   )dtypedevice)torcharangelongweightr8   r.   forward)r0   r4   r5   r6   bszZseq_lenr1   r'   r(   r=   W   s   z,BlenderbotLearnedPositionalEmbedding.forwardr   N)__name__
__module____qualname____doc__intr/   r9   Sizer   Tensorr=   __classcell__r'   r'   r1   r(   r*   O   s    r*   c                
       sL   e Zd ZdZddedededee f fddZd	ej	f fd
dZ
  ZS )BlenderbotScaledWordEmbeddingz\
    This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
          ?r+   r,   padding_idxembed_scalec                    s   t  ||| || _d S r-   )r.   r/   rK   )r0   r+   r,   rJ   rK   r1   r'   r(   r/   i   s   
z&BlenderbotScaledWordEmbedding.__init__r    c                    s   t  || j S r-   )r.   r=   rK   )r0   r    r1   r'   r(   r=   m   r3   z%BlenderbotScaledWordEmbedding.forward)rI   )r@   rA   rB   rC   rD   r   floatr/   r9   rF   r=   rG   r'   r'   r1   r(   rH   d   s    $rH   c                       s   e Zd ZdZ						ddededed	ed
ededee dee f fddZ							dde
jdee
j dee dee
j dee
j dedee
j dee
jee
j eee
j  f fddZ  ZS )BlenderbotAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsdropout
is_decoderbias	is_causalconfig	layer_idxc	           	         s   t    || _|| _|| _|| | _|| _| j| | jkr*td| j d| d| jd | _|| _	|| _
|| _|d u rK| j	rKtd| jj d tj|||d| _tj|||d| _tj|||d| _tj|||d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      zInstantiating a decoder z without passing `layer_idx` is not recommended and will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.rS   )r.   r/   rO   rP   rQ   head_dimrU   r&   scalingrR   rT   rV   loggerwarning_oncer2   r@   r   Lineark_projv_projq_projout_proj)	r0   rO   rP   rQ   rR   rS   rT   rU   rV   r1   r'   r(   r/   u   s0   


zBlenderbotAttention.__init__hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionscache_positionreturnc                 C   sv  |du}|  \}	}
}| ||	d| j| jdd}|| j }|dur=t|tr;|j	
| j}|r7|j}n|j}n|}|rA|n|}|rX|durX|rX|j| j }|j| j }nE| |}| |}||	d| j| jdd}||	d| j| jdd}|dur|s|nd}|||| jd|i\}}|rd|j	| j< |	| j d| jf}|j| }|j| }|j| }| d}t||dd}|  |	| j |
|fkrtd|	| j |
|f d|   |dur|ddddddd|jd	 f }||	| j|
|| }||	| j |
|}tjj|dd
}|durN|  | jfkr3td| jf d|   |dddd||	| j|
| }||	| j |
|}|re||	| j|
|}||	| j |
|}nd}tjj|| j| jd}t||}|  |	| j |
| jfkrtd|	| j |
| jf d|   ||	| j|
| j}|dd}||	|
| j}| |}|||fS )z#Input shape: Batch x Time x ChannelNr#   r   r   rg   Tz$Attention weights should be of size z	, but is dimz/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size )sizer_   viewrP   rX   Z	transposerY   
isinstancer   
is_updatedgetrV   Zcross_attention_cacheself_attention_cacheZ	key_cacheZvalue_cacher]   r^   updatereshaper9   Zbmmr&   r$   r   
functionalZsoftmaxrQ   rn   rO   r`   )r0   ra   rb   rc   rd   re   rf   rg   Zis_cross_attentionr>   tgt_len_Zquery_statesrr   Zcurr_past_key_valueZcurrent_statesZ
key_statesZvalue_statesZ
proj_shapeZsrc_lenattn_weightsZattn_weights_reshapedZ
attn_probsZattn_outputr'   r'   r(   r=      s   "








&
"

zBlenderbotAttention.forward)rN   FTFNN)NNNNFN)r@   rA   rB   rC   rD   rL   boolr   r   r/   r9   rF   r
   r   r=   rG   r'   r'   r1   r(   rM   r   s`    	*	rM   eagerc                       sL   e Zd Zdef fddZ	ddejdejdejded	ejf
d
dZ  Z	S )BlenderbotEncoderLayerrU   c                    s   t    |j| _t|j | j|j|j|d| _t	
| j| _|j| _t|j | _|j| _t	| j|j| _t	|j| j| _t	
| j| _d S )N)rO   rP   rQ   rU   )r.   r/   d_modelrO   BLENDERBOT_ATTENTION_CLASSES_attn_implementationZencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normrQ   r	   activation_functionactivation_fnactivation_dropoutr\   Zencoder_ffn_dimfc1fc2final_layer_normr0   rU   r1   r'   r(   r/     s   
zBlenderbotEncoderLayer.__init__Fra   rd   re   rf   rh   c           
      C   s   |}|  |}| j||||d\}}}tjj|| j| jd}|| }|}| |}| | |}tjj|| j	| jd}| 
|}tjj|| j| jd}|| }|jtjkrht|jjd }tj|| |d}|f}	|rr|	|f7 }	|	S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )ra   rd   re   rf   rl   i  )minmax)r   r   r   rw   rQ   rn   r   r   r   r   r   r7   r9   Zfloat16finfor   clamp)
r0   ra   rd   re   rf   residualrz   ry   Zclamp_valueoutputsr'   r'   r(   r=   &  s0   



zBlenderbotEncoderLayer.forwardF)
r@   rA   rB   r   r/   r9   rF   r{   r=   rG   r'   r'   r1   r(   r}     s    r}   c                       s   e Zd Zddedee f fddZ									ddejd	eej d
eej deej deej deej dee	 dee
 dee
 deej dejfddZ  ZS )BlenderbotDecoderLayerNrU   rV   c              	      s   t    |j| _t|j | j|j|jdd||d| _|j	| _	t
|j | _|j| _t| j| _t|j | j|j|jd||d| _t| j| _t| j|j| _t|j| j| _t| j| _d S )NT)rO   rP   rQ   rR   rT   rU   rV   )rQ   rR   rU   rV   )r.   r/   r~   rO   r   r   Zdecoder_attention_headsr   r   rQ   r	   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normr\   Zdecoder_ffn_dimr   r   r   )r0   rU   rV   r1   r'   r(   r/   Y  s6   
	zBlenderbotDecoderLayer.__init__FTra   rd   encoder_hidden_statesencoder_attention_maskre   cross_attn_layer_head_maskrc   rf   	use_cacherg   rh   c                 C   s   |}|  |}| j||||||
d\}}}tjj|| j| jd}|| }d}|durN|}| |}| j||||||d\}}}tjj|| j| jd}|| }|}| |}| 	| 
|}tjj|| j| jd}| |}tjj|| j| jd}|| }|f}|r|||f7 }|	r||f7 }|S )a8  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            encoder_hidden_states (`torch.FloatTensor`):
                cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
            encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
                size `(decoder_attention_heads,)`.
            past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
                cache in the correct position and to infer the complete sequence length.
        )ra   rc   rd   re   rf   rg   rl   N)ra   rb   rd   re   rc   rf   )r   r   r   rw   rQ   rn   r   r   r   r   r   r   r   )r0   ra   rd   r   r   re   r   rc   rf   r   rg   r   Zself_attn_weightsZcross_attn_weightsr   r'   r'   r(   r=   x  sN   "




zBlenderbotDecoderLayer.forwardr-   )	NNNNNNFTN)r@   rA   rB   r   r   rD   r/   r9   rF   r
   r{   r=   rG   r'   r'   r1   r(   r   X  sD    "	
r   c                   @   s   e Zd ZeZdZdZdZdZdd Z	e
dd Z	ddeejd	f d
ejdejdedef
ddZedejdededejdejdefddZdS )BlenderbotPreTrainedModelmodelTc                 C   s   | j j}t|tjr"|jjjd|d |jd ur |jj	  d S d S t|tj
rC|jjjd|d |jd urA|jj|j 	  d S d S t|tjrX|jjd |jj	  d S d S )NrN   )meanstdrI   )rU   Zinit_stdrq   r   r\   r<   dataZnormal_rS   Zzero_	EmbeddingrJ   r   Zfill_)r0   moduler   r'   r'   r(   _init_weights  s   

z'BlenderbotPreTrainedModel._init_weightsc                 C   s@   | j j}tjg ddddd|gg| jd}||||d}|S )N)r      
      r   r         r   r8   )rd   r    decoder_input_ids)rU   r!   r9   Ztensorr8   ne)r0   Z	pad_tokenr    dummy_inputsr'   r'   r(   r     s   "z&BlenderbotPreTrainedModel.dummy_inputsFrd   r   input_tensorrg   past_key_valuesrf   c                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )NZflash_attention_2rN   Zflex_attentionr   FZsdpa)inputs_embedsr5   Zis_trainingr   r#   )sequence_lengthtarget_lengthr7   rg   
batch_size)cudaZxpuZnpu)rU   r   anyrq   r9   rF   r   get_seq_lengthZis_compileabler   Z_ignore_causal_mask_sdparn   r7   r$   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr8   typer   r   Z_unmask_unattended)r0   rd   r   rg   r   rf   Zpast_seen_tokensZusing_compilable_cacher7   r   r   causal_mask	min_dtyper'   r'   r(   _update_causal_mask  sT   




z-BlenderbotPreTrainedModel._update_causal_maskr   r   r7   r   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   )Z
fill_valuer7   r8   r   )Zdiagonalr   r#   r   )rk   r9   r   r   fullr8   Ztriur:   rv   expandr%   r$   toZmasked_fill)rd   r   r   r7   rg   r   kwargsr   r   Zmask_lengthZpadding_maskr'   r'   r(   r   5  s,    $
6  zOBlenderbotPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_positionNr   )r@   rA   rB   r   Zconfig_classbase_model_prefixZsupports_gradient_checkpointingZ_supports_cache_classZ_supports_static_cacher   propertyr   r   r9   rF   r
   r{   r   staticmethodrD   r7   r   r'   r'   r'   r(   r     sF    

Dr   c                       sJ   e Zd ZdZd	dedeej f fddZ							d
ddZ	  Z
S )BlenderbotEncoderz
    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
    [`BlenderbotEncoderLayer`].

    Args:
        config: BlenderbotConfig
        embed_tokens (nn.Embedding): output embedding
    NrU   embed_tokensc                    s   t     j| _ j| _ j} j| _ j| _	 j
r!t|nd}|d ur+|| _nt j|| j|d| _t j|| _t fddt jD | _t j| _d| _|   d S )NrI   rK   c                    s   g | ]}t  qS r'   )r}   ).0ry   rU   r'   r(   
<listcomp>  s    z.BlenderbotEncoder.__init__.<locals>.<listcomp>F)r.   r/   rQ   Zencoder_layerdrop	layerdropr~   r!   rJ   max_position_embeddingsZmax_source_positionsscale_embeddingmathsqrtr   rH   
vocab_sizer*   embed_positionsr   
ModuleListrangeZencoder_layerslayersr   
layer_normgradient_checkpointing	post_init)r0   rU   r   rO   rK   r1   r   r(   r/   x  s(    zBlenderbotEncoder.__init__c                 C   sN  |dur|n| j j}|dur|n| j j}|dur|n| j j}|dur*|dur*td|durA| || | }|d|d }n|durN| dd }ntd|du r[| |}| 	|}	||	 }
t
jj|
| j| jd}
|duryt||j}|r}dnd}|rdnd}|dur| d t| jkrtdt| j d	| d  d
t| jD ]X\}}|r||
f }d}| jrtg }|| jk rd}|rd}n-| jr| jr| |j|
||dur|| nd|}n||
||dur|| nd|d}|d }
|r||d f }q| |
}
|r||
f }|s tdd |
||fD S t|
||dS )a~  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

                [What are input IDs?](../glossary#input-ids)
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        NzDYou cannot specify both input_ids and inputs_embeds at the same timer#   z5You have to specify either input_ids or inputs_embedsrl   r'   r   z&The head_mask should be specified for  layers, but it is for .FT)NN)re   rf   r   c                 s       | ]	}|d ur|V  qd S r-   r'   r   vr'   r'   r(   	<genexpr>  s    z,BlenderbotEncoder.forward.<locals>.<genexpr>last_hidden_statera   
attentions)rU   rf   output_hidden_statesuse_return_dictr&   Z%warn_if_padding_and_no_attention_maskro   rp   r   r   r   rw   rQ   rn   r   r7   lenr   	enumerater9   randr   r   _gradient_checkpointing_func__call__r   tupler   )r0   r    rd   	head_maskr   rf   r   return_dictZinput_shapeZ	embed_posra   Zencoder_statesZall_attentionsidxZencoder_layerZto_dropdropout_probabilitylayer_outputsr'   r'   r(   r=     s   .







zBlenderbotEncoder.forwardr-   )NNNNNNN)r@   rA   rB   rC   r   r   r   r   r/   r=   rG   r'   r'   r1   r(   r   n  s    	r   c                       sr   e Zd ZdZddedeej f fddZdd Z	d	d
 Z
													ddeej fddZ  ZS )BlenderbotDecoderz
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BlenderbotDecoderLayer`]

    Args:
        config: BlenderbotConfig
        embed_tokens (nn.Embedding): output embedding
    NrU   r   c                    s   t     j| _ j| _ j| _ j| _ j	rt
 jnd}|d ur)|| _nt j j| j|d| _t j j| _t fddt jD | _t j| _d| _|   d S )NrI   r   c                    s   g | ]}t  |d qS ))rV   )r   )r   ir   r'   r(   r   8  s    z.BlenderbotDecoder.__init__.<locals>.<listcomp>F)r.   r/   rQ   Zdecoder_layerdropr   r!   rJ   r   Zmax_target_positionsr   r   r   r~   r   rH   r   r*   r   r   r   r   Zdecoder_layersr   r   r   r   r   )r0   rU   r   rK   r1   r   r(   r/   $  s*   zBlenderbotDecoder.__init__c                 C      | j S r-   r   r0   r'   r'   r(   get_input_embeddings@     z&BlenderbotDecoder.get_input_embeddingsc                 C   
   || _ d S r-   r   r0   valuer'   r'   r(   set_input_embeddingsC     
z&BlenderbotDecoder.set_input_embeddingsrg   c           "      C   s  |
dur|
n| j j}
|dur|n| j j}|	dur|	n| j j}	|dur$|n| j j}| jr7| jr7|	r7td d}	|du |duA rCt	d|durP|
d|jd }|du rY| |}d}|	rnt|tsnd}td t|}| dd \}}|dur| nd}|du rtj||| |jd	}|du rt s|| }tj|||jd	}t|tr|jn|}| |||||
}|dur|durt||j|d
}| j||f||d}|| }tjj || j | jd}|rdnd}|
rdnd}|
r|durdnd}d}t!||gddgD ]+\}}|dur,| d t"| j#kr,t	d| dt"| j# d| d  dqt$| j#D ]\}}|r?||f7 }| jrPt%g }|| j&k rPq3| jr{| jr{| '|j(|||||duri|| nd|durs|| ndd|
|	|} n ||||||dur|| nd|dur|| nd||
|	|d
} | d }|	r| |
rdnd }|
r|| d f7 }|dur|| d f7 }q3| )|}|r||f7 }|	r|nd}!|r|* }!|st+dd ||!|||fD S t,||!|||dS )aS  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

                [What are input IDs?](../glossary#input-ids)
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                of the decoder.
            encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
                Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
                selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0,
                1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

            cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
                cross-attention on hidden heads. Mask values selected in `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

            past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
                Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
                shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
                shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

                Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
                cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
                cache in the correct position and to infer the complete sequence length.
        NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer#   TzPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.r   r   )rx   )r6   rl   r'   r   cross_attn_head_maskzThe `z` should be specified for r   r   )	rd   r   r   re   r   rc   rf   r   rg   r   r   r   c                 s   r   r-   r'   r   r'   r'   r(   r   1  s    z,BlenderbotDecoder.forward.<locals>.<genexpr>)r   r   ra   r   cross_attentions)-rU   rf   r   r   r   r   rn   rZ   warningr&   rp   r$   r   rq   r
   r[   r   Zfrom_legacy_cachero   r   r9   r:   r8   r   Zonesrt   r   r   r7   r   r   rw   rQ   zipr   r   r   r   r   r   r   r   Zto_legacy_cacher   r   )"r0   r    rd   r   r   r   r   r   r   r   rf   r   r   rg   Zreturn_legacy_cacher   Z
seq_lengthr5   Zmask_seq_lengthZself_attn_cacher   r6   ra   Zall_hidden_statesZall_self_attnsZall_cross_attentionsZnext_decoder_cacheZ	attn_maskZ	mask_namer   Zdecoder_layerr   r   Z
next_cacher'   r'   r(   r=   F  s   U

	







zBlenderbotDecoder.forwardr-   )NNNNNNNNNNNNN)r@   rA   rB   rC   r   r   r   r   r/   r   r   r9   rF   r=   rG   r'   r'   r1   r(   r     s*    r   c                &       sR  e Zd ZddgZdef fddZedeee	e
jf  f fddZd	d
 Zdd Zdd Zdd Ze																d%deej deej deej deej deej deej deej deeeef  deeej  deej deej dee dee dee d ee d!eej d"eeej ef f"d#d$Z  ZS )&BlenderbotModeldecoder.embed_tokens.weightencoder.embed_tokens.weightrU   c                    sl   t  | |j|j}}|jrt|jnd}t||j||d| _	t
|| j	| _t|| j	| _|   d S )NrI   r   )r.   r/   r!   r   r   r   r   r~   rH   sharedr   encoderr   decoderr   )r0   rU   rJ   r   rK   r1   r'   r(   r/   C  s   zBlenderbotModel.__init__pretrained_model_name_or_pathc                    <   |dkrt dt t|S tt| j|g|R i |S )Nfacebook/blenderbot-90MzThe checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical checkpoint `facebook/small_blenderbot-90M` with `BlenderbotSmallModel.from_pretrained('facebook/small_blenderbot-90M')` instead.)warningswarnFutureWarningr   from_pretrainedr.   r   clsr   Z
model_argsr   r1   r'   r(   r  O  s   
zBlenderbotModel.from_pretrainedc                 C   r   r-   )r   r   r'   r'   r(   r   \  r   z$BlenderbotModel.get_input_embeddingsc                 C   s   || _ | j | j_| j | j_d S r-   )r   r   r   r   r   r'   r'   r(   r   _  s   
z$BlenderbotModel.set_input_embeddingsc                 C   r   r-   )r   r   r'   r'   r(   get_encoderd  r   zBlenderbotModel.get_encoderc                 C   r   r-   r   r   r'   r'   r(   get_decoderg  r   zBlenderbotModel.get_decoderNr    rd   r   decoder_attention_maskr   decoder_head_maskr   encoder_outputsr   r   decoder_inputs_embedsr   rf   r   r   rg   rh   c                 C   s  |dur|n| j j}|dur|n| j j}|dur|n| j j}|dur$|n| j j}|du r9| j||||
|||d}n$|r]t|ts]t|d t|dkrN|d ndt|dkrY|d ndd}| j	|||d ||||	||||||d}|sw|| S t
|j|j|j|j|j|j|j|jdS )	a  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            Blenderbot uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
            `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).
        decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.
        cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
            1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, BlenderbotModel

        >>> model = BlenderbotModel.from_pretrained("facebook/blenderbot-400M-distill")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")

        >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
        >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids  # Batch size 1
        >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_input_ids)

        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 6, 1280]
        ```N)r    rd   r   r   rf   r   r   r   r   r   r   r    rd   r   r   r   r   r   r   r   rf   r   r   rg   )r   r   decoder_hidden_statesdecoder_attentionsr   encoder_last_hidden_stater   encoder_attentions)rU   rf   r   r   r   r   rq   r   r   r   r   r   r   ra   r   r   )r0   r    rd   r   r  r   r  r   r  r   r   r  r   rf   r   r   rg   Zdecoder_outputsr'   r'   r(   r=   j  s`   :
zBlenderbotModel.forward)NNNNNNNNNNNNNNNN)r@   rA   rB   _tied_weights_keysr   r/   classmethodr   r   strosPathLiker  r   r   r  r
  r   r9   
LongTensorrF   r   r   r   FloatTensorr{   r   r=   rG   r'   r'   r1   r(   r   ?  sz    "	
r   z\
    The Blenderbot Model with a language modeling head. Can be used for summarization.
    )Zcustom_introc                (       s  e Zd ZdZdgZg dZdef fddZede	e
eejf  f fdd	Zd
d Zdd Z	d1dede	e dedejf fddZdeddfddZdd Zdd Ze																	d2de	ej de	ej de	ej de	ej d e	ej d!e	ej d"e	ej d#e	e
eef  d$e	eej   d%e	ej d&e	ej  d'e	ej d(e	e d)e	e d*e	e d+e	e d,e	ej de
eej  e!f f$d-d.Z"e#d/d0 Z$  Z%S )3"BlenderbotForConditionalGenerationr   final_logits_bias)r   r   lm_head.weightrU   c                    sX   t  | t|| _| dtd| jjjf t	j
|j| jjjdd| _|   d S )Nr  r   FrW   )r.   r/   r   r   register_bufferr9   zerosr   r+   r   r\   r~   lm_headr   r   r1   r'   r(   r/     s
   
z+BlenderbotForConditionalGeneration.__init__r   c                    r   )Nr  zThe checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical checkpoint `facebook/small_blenderbot-90M` with `BlenderbotSmallForConditionalGeneration.from_pretrained('facebook/small_blenderbot-90M')` instead.)r  r  r  r   r  r.   r  r  r1   r'   r(   r    s   

z2BlenderbotForConditionalGeneration.from_pretrainedc                 C   
   | j  S r-   )r   r  r   r'   r'   r(   r    r   z.BlenderbotForConditionalGeneration.get_encoderc                 C   r!  r-   )r   r
  r   r'   r'   r(   r
    r   z.BlenderbotForConditionalGeneration.get_decoderNTnew_num_tokenspad_to_multiple_ofmean_resizingrh   c                    s&   t  |||}| |jjd  |S )Nr   )r.   resize_token_embeddings_resize_final_logits_biasr<   r$   )r0   r"  r#  r$  new_embeddingsr1   r'   r(   r%    s   z:BlenderbotForConditionalGeneration.resize_token_embeddingsc                 C   sj   | j jd }||kr| j d d d |f }ntjd|| f| j jd}tj| j |gdd}| d| d S )Nr#   r   r   rj   r  )r  r$   r9   r  r8   catr  )r0   r"  Zold_num_tokensZnew_biasZ
extra_biasr'   r'   r(   r&    s   z<BlenderbotForConditionalGeneration._resize_final_logits_biasc                 C   r   r-   r   r   r'   r'   r(   get_output_embeddings  r   z8BlenderbotForConditionalGeneration.get_output_embeddingsc                 C   r   r-   r)  r0   r'  r'   r'   r(   set_output_embeddings  r   z8BlenderbotForConditionalGeneration.set_output_embeddingsr    rd   r   r  r   r  r   r  r   r   r  labelsr   rf   r   r   rg   c                 C   s  |dur|n| j j}|dur)|rtd d}|du r)|du r)t|| j j| j j}| j|f||||||||	|
||||||d}| |d | j	 }d}|durat
 }||d| j j|d}|sw|f|dd  }|duru|f| S |S t|||j|j|j|j|j|j|jd	S )	a  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            Blenderbot uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
            `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).
        decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.
        cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
            1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example conversation:

        ```python
        >>> from transformers import AutoTokenizer, BlenderbotForConditionalGeneration

        >>> mname = "facebook/blenderbot-400M-distill"
        >>> model = BlenderbotForConditionalGeneration.from_pretrained(mname)
        >>> tokenizer = AutoTokenizer.from_pretrained(mname)
        >>> UTTERANCE = "My friends are cool but they eat too many carbs."
        >>> print("Human: ", UTTERANCE)
        Human:  My friends are cool but they eat too many carbs.

        >>> inputs = tokenizer([UTTERANCE], return_tensors="pt")
        >>> reply_ids = model.generate(**inputs)
        >>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
        Bot: That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?

        >>> REPLY = "I'm not sure"
        >>> print("Human: ", REPLY)
        Human: I'm not sure

        >>> NEXT_UTTERANCE = (
        ...     "My friends are cool but they eat too many carbs.</s> <s>That's unfortunate. "
        ...     "Are they trying to lose weight or are they just trying to be healthier?</s> "
        ...     "<s> I'm not sure."
        ... )
        >>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="pt")
        >>> next_reply_ids = model.generate(**inputs)
        >>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
        Bot:   I see. Well, it's good that they're trying to change their eating habits.
        ```
        NzJThe `use_cache` argument is changed to `False` since `labels` is provided.F)rd   r   r  r  r   r  r   r   r   r  r   rf   r   r   rg   r   r#   r   )	losslogitsr   r  r  r   r  r   r  )rU   r   rZ   r   r)   r!   r"   r   r   r  r   rp   r   r   r   r  r  r   r  r   r  )r0   r    rd   r   r  r   r  r   r  r   r   r  r-  r   rf   r   r   rg   r   Z	lm_logitsZmasked_lm_lossloss_fctoutputr'   r'   r(   r=     s^   O
z*BlenderbotForConditionalGeneration.forwardc                    sB   d}| D ]}|t  fdd|d d D |dd   f7 }q|S )Nr'   c                 3   $    | ]}| d  |jV  qdS r?   Zindex_selectr   r8   r   Z
past_statebeam_idxr'   r(   r        " zDBlenderbotForConditionalGeneration._reorder_cache.<locals>.<genexpr>r   r   r   r6  Zreordered_pastZ
layer_pastr'   r5  r(   _reorder_cache  s   
z1BlenderbotForConditionalGeneration._reorder_cache)NT)NNNNNNNNNNNNNNNNN)&r@   rA   rB   r   Z_keys_to_ignore_on_load_missingr  r   r/   r  r   r   r  r  r  r  r  r
  rD   r{   r   r   r%  r&  r*  r,  r   r9   r  rF   r   r   r   r  r   r=   r   r:  rG   r'   r'   r1   r(   r    s    	"		
 r  c                       s(   e Zd ZdZ fddZdd Z  ZS )BlenderbotDecoderWrapperz
    This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
    used in combination with the [`EncoderDecoderModel`] framework.
    c                    s   t  | t|| _d S r-   )r.   r/   r   r   r   r1   r'   r(   r/     s   z!BlenderbotDecoderWrapper.__init__c                 O   s   | j |i |S r-   r	  )r0   argsr   r'   r'   r(   r=     s   z BlenderbotDecoderWrapper.forward)r@   rA   rB   rC   r/   r=   rG   r'   r'   r1   r(   r;    s    r;  c                "       s  e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
e														d$deej deej deej deej deej deej deeej  deej deej dee dee dee dee deej deeef fd d!Zed"d# Z  ZS )%BlenderbotForCausalLMr  c                    sN   t |}d|_d|_t | t|| _tj	|j
|jdd| _|   d S )NTFrW   )copydeepcopyrR   Zis_encoder_decoderr.   r/   r;  r   r   r\   Zhidden_sizer   r   r   r   r1   r'   r(   r/     s   

zBlenderbotForCausalLM.__init__c                 C   s
   | j jjS r-   r   r   r   r   r'   r'   r(   r     r   z*BlenderbotForCausalLM.get_input_embeddingsc                 C   s   || j j_d S r-   r@  r   r'   r'   r(   r     s   z*BlenderbotForCausalLM.set_input_embeddingsc                 C   r   r-   r)  r   r'   r'   r(   r*    r   z+BlenderbotForCausalLM.get_output_embeddingsc                 C   r   r-   r)  r+  r'   r'   r(   r,    r   z+BlenderbotForCausalLM.set_output_embeddingsc                 C   s   || j _d S r-   r   r   )r0   r   r'   r'   r(   set_decoder  s   z!BlenderbotForCausalLM.set_decoderc                 C   s   | j jS r-   rA  r   r'   r'   r(   r
    s   z!BlenderbotForCausalLM.get_decoderNr    rd   r   r   r   r   r   r   r-  r   rf   r   r   rg   rh   c                 C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}| jj|||||||||
||||d}| |d }d}|	durU|	|j}	t	 }||
d| j j|	
d}|sk|f|dd  }|duri|f| S |S t|||j|j|j|jdS )a  
        cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, BlenderbotForCausalLM

        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
        >>> model = BlenderbotForCausalLM.from_pretrained("facebook/blenderbot-400M-distill", add_cross_attention=False)
        >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)

        >>> logits = outputs.logits
        >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
        >>> list(logits.shape) == expected_shape
        True
        ```Nr  r   r#   r   )r.  r/  r   ra   r   r   )rU   rf   r   r   r   r   r   r   r8   r   rp   r   r   r   ra   r   r   )r0   r    rd   r   r   r   r   r   r   r-  r   rf   r   r   rg   r   r/  r.  r0  r1  r'   r'   r(   r=     sH   .zBlenderbotForCausalLM.forwardc                    s.   d}| D ]}|t  fdd|D f7 }q|S )Nr'   c                 3   r2  r?   r3  r4  r5  r'   r(   r   :  r7  z7BlenderbotForCausalLM._reorder_cache.<locals>.<genexpr>r8  r9  r'   r5  r(   r:  5  s   z$BlenderbotForCausalLM._reorder_cache)NNNNNNNNNNNNNN)r@   rA   rB   r  r/   r   r   r*  r,  rB  r
  r   r   r9   r  rF   r  r   r{   r   r   r   r=   r   r:  rG   r'   r'   r1   r(   r=    sr    	

Yr=  )r=  r  r   r   )ErC   r>  r   r  r  typingr   r   r   r   r9   Ztorch.utils.checkpointr   Ztorch.nnr   Zactivationsr	   Zcache_utilsr
   r   Z
generationr   Zmodeling_attn_mask_utilsr   r   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   utilsr   r   r   r   Zblenderbot_smallr   r   Zconfiguration_blenderbotr   Z!torch.nn.attention.flex_attentionr   Zintegrations.flex_attentionr   Z
get_loggerr@   rZ   rF   rD   r)   r   r*   rH   ModulerM   r   r}   r   r   r   r   r   r  r;  r=  __all__r'   r'   r'   r(   <module>   sf   
 Ew  .  &  J 