
    fTh                        S r SSKrSSKrSSKrSSKrSSKJrJrJrJ	r	  SSK
r
SSKr
SSK
Jr  SSKJr  SSKJr  SSKJrJr  SS	KJr  SS
KJrJr  SSKJrJrJrJrJr  SSKJ r   SSK!J"r"J#r#J$r$J%r%  SSK&J'r'J(r(  SSK)J*r*  \#" 5       (       a  SSK+J,r,  SSK-J.r.  \%R^                  " \05      r1S\
Rd                  S\3S\34S jr4 " S S\Rj                  5      r6 " S S\Rj                  5      r7 " S S\Rp                  5      r9S\90r: " S S \Rp                  5      r; " S! S"\Rp                  5      r<\" " S# S$\ 5      5       r= " S% S&\=5      r> " S' S(\=5      r?\" " S) S*\=5      5       r@\"" S+S,9 " S- S.\=\5      5       rA " S/ S0\=5      rB " S1 S2\=\5      rC/ S3QrDg)4z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                     U R                  U R                  5      nU SS2SS24   R                  5       USS2SS24'   X#SS2S4'   Uc  [        S5      eUR	                  US:H  U5        U$ )z)
Shift input ids one token to the right.
Nr   r   z1self.model.config.pad_token_id has to be defined.i)	new_zerosshapeclone
ValueErrormasked_fill_)r!   r"   r#   shifted_input_idss       j/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/blenderbot/modeling_blenderbot.pyshift_tokens_rightr-   ?   sz     "++IOO<(CRC0668ae4adLMM""#4#<lK    c                      ^  \ rS rSrSrS\S\4U 4S jjr SS\R                  S\S\	\R                     4U 4S	 jjjrS
rU =r$ )$BlenderbotLearnedPositionalEmbeddingO   zF
This module learns positional embeddings up to a fixed maximum size.
num_embeddingsembedding_dimc                 $   > [         TU ]  X5        g N)super__init__)selfr2   r3   	__class__s      r,   r7   -BlenderbotLearnedPositionalEmbedding.__init__T   s    7r.   input_ids_shapepast_key_values_lengthposition_idsc                    > UcB  USS u  pE[         R                  " X"U-   [         R                  U R                  R                  S9n[
        TU ]  U5      $ )z3`input_ids_shape` is expected to be [bsz x seqlen].Nr   )dtypedevice)torcharangelongweightr@   r6   forward)r8   r;   r<   r=   bszseq_lenr9   s         r,   rE   ,BlenderbotLearnedPositionalEmbedding.forwardW   sX     *2A.LC <<&(HPUPZPZcgcncncucuL w|,,r.    r   N)__name__
__module____qualname____firstlineno____doc__intr7   rA   Sizer   TensorrE   __static_attributes____classcell__r9   s   @r,   r0   r0   O   sT    8s 83 8 tx	-$zz	-CF	-ZbchcocoZp	- 	-r.   r0   c            
       r   ^  \ rS rSrSrSS\S\S\S\\   4U 4S jjjrS\	R                  4U 4S	 jjrS
rU =r$ )BlenderbotScaledWordEmbeddingd   zT
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
r2   r3   padding_idxembed_scalec                 2   > [         TU ]  XU5        X@l        g r5   )r6   r7   rZ   )r8   r2   r3   rY   rZ   r9   s        r,   r7   &BlenderbotScaledWordEmbedding.__init__i   s    D&r.   r!   c                 <   > [         TU ]  U5      U R                  -  $ r5   )r6   rE   rZ   )r8   r!   r9   s     r,   rE   %BlenderbotScaledWordEmbedding.forwardm   s    wy)D,<,<<<r.   rZ   )      ?)rK   rL   rM   rN   rO   rP   r   floatr7   rA   rR   rE   rS   rT   rU   s   @r,   rW   rW   d   sJ    's '3 'S '_ghm_n ' '= = =r.   rW   c                     ^  \ rS rSrSr      SS\S\S\S\S\S\S	\\	   S
\\   4U 4S jjjr
      SS\R                  S\\R                     S\\   S\\R                     S\\R                     S\S\\R                     S\\R                  \\R                     \\\R                        4   4S jjrSrU =r$ )BlenderbotAttentionr   z=Multi-headed attention from 'Attention Is All You Need' paper	embed_dim	num_headsdropout
is_decoderbias	is_causalconfig	layer_idxc	                 t  > [         T	U ]  5         Xl        X l        X0l        X-  U l        Xpl        U R
                  U-  U R                  :w  a  [        SU R                   SU S35      eU R
                  S-  U l        X@l	        X`l
        Xl        Uc>  U R                  (       a-  [        R                  SU R                  R                   S35        [         R"                  " XUS9U l        [         R"                  " XUS9U l        [         R"                  " XUS9U l        [         R"                  " XUS9U l        g )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.ri   )r6   r7   re   rf   rg   head_dimrk   r)   scalingrh   rj   rl   loggerwarning_oncer9   rK   r   Lineark_projv_projq_projout_proj)
r8   re   rf   rg   rh   ri   rj   rk   rl   r9   s
            r,   r7   BlenderbotAttention.__init__u   s    	""!.MMI%$..8MdnnM]$YKr3  }}d*$""*4>>+B+B*C D, , ii	4@ii	4@ii	4@		)TBr.   hidden_stateskey_value_statespast_key_valueattention_masklayer_head_maskoutput_attentionscache_positionreturnc                 
   USLnUR                  5       u  pnU R                  U5      R                  U	SU R                  U R                  5      R                  SS5      nXR                  -  nUb]  [        U[        5      (       aF  UR                  R                  U R                  5      nU(       a  UR                  nOUR                  nOUnU(       a  UOUnU(       a=  Ub:  W(       a3  WR                  U R                     nUR                  U R                     nOU R!                  U5      nU R#                  U5      nUR                  U	SU R                  U R                  5      R                  SS5      nUR                  U	SU R                  U R                  5      R                  SS5      nUbN  U(       d  UOSnWR%                  UUU R                  SU05      u  nnU(       a  SUR                  U R                  '   XR                  -  SU R                  4nUR&                  " U6 nUR&                  " U6 nUR&                  " U6 nUR                  S5      n[(        R*                  " UUR                  SS5      5      nUR                  5       XR                  -  U
U4:w  a.  [-        SXR                  -  U
U4 SUR                  5        35      eUb]  USS2SS2SS2SUR.                  S	   24   nUR                  XR                  U
U5      U-   nUR                  XR                  -  U
U5      n[0        R2                  R5                  USS
9nUb  UR                  5       U R                  4:w  a*  [-        SU R                  4 SUR                  5        35      eUR                  SSSS5      UR                  XR                  U
U5      -  nUR                  XR                  -  U
U5      nU(       a=  UR                  XR                  U
U5      nUR                  XR                  -  U
U5      nOSn[0        R2                  R7                  UU R6                  U R8                  S9n[(        R*                  " UU5      nUR                  5       XR                  -  XR                  4:w  a7  [-        SXR                  -  XR                  4 SUR                  5        35      eUR                  XR                  XR                  5      nUR                  SS5      nUR'                  XU R:                  5      nU R=                  U5      nUUU4$ )z#Input shape: Batch x Time x ChannelNr%   r   r   r   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 )sizerv   viewrf   ro   	transposerp   
isinstancer   
is_updatedgetrl   cross_attention_cacheself_attention_cache	key_cachevalue_cachert   ru   updatereshaperA   bmmr)   r'   r   
functionalsoftmaxrg   r   re   rw   )r8   ry   rz   r{   r|   r}   r~   r   is_cross_attentionrF   tgt_len_query_statesr   curr_past_key_valuecurrent_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                           r,   rE   BlenderbotAttention.forward   s    .T9',,.a {{=166sBPTP]P]^hhijlmn#ll2%.*=>>+66::4>>J
%*8*N*N'*8*M*M'&4#-?)]."<,66t~~FJ.::4>>JL^4J;;~6L#b$..$--PZZ[\^_`J',,S"dnndmmT^^_`bcdL)7It+>+E+Ednn?OQ_>`,(
L &@DN--dnn=NN*B>
#++Z8''4
#++Z8//!$yyz/C/CAq/IJ3#7'"JJ6nn8LgW^7_6` a %%'(* 
 %+Aq!5Kz7G7G7K5K,KLN',,S..'7SVddL',,S>>-A7GTL}},,\r,B&##%$..):: Et~~FWEX Y',,./1  +//2q!<|?P?PQTVdVdfmov?wwL',,S>>-A7GTL
 %1$5$5c>>7T[$\!055cNN6JGU\]L$(!]]**<4<<RVR_R_*`
ii
L9#"6!OO2C..4H'S`S`3a2b c$$&') 
 "&&sNNG]]S!++Aq1 "))#GmmK01>AAr.   )rk   rg   re   ro   rj   rh   rt   rl   rf   rw   rv   rp   ru   )        FTFNN)NNNNFN)rK   rL   rM   rN   rO   rP   ra   boolr   r   r7   rA   rR   r   r   rE   rS   rT   rU   s   @r,   rc   rc   r   sZ   G  -1#'%C%C %C 	%C
 %C %C %C )*%C C=%C %CT 48*.1526"'15pB||pB #5<<0pB !	pB
 !.pB "%,,/pB  pB !.pB 
u||Xell3XeELL>Q5RR	SpB pBr.   rc   eagerc                      ^  \ rS rSrS\4U 4S jjr SS\R                  S\R                  S\R                  S\S\R                  4
S	 jjr	S
r
U =r$ )BlenderbotEncoderLayeri  rk   c                   > [         TU ]  5         UR                  U l        [        UR
                     " U R                  UR                  UR                  US9U l        [        R                  " U R                  5      U l        UR                  U l        [        UR                     U l        UR                   U l        [        R"                  " U R                  UR$                  5      U l        [        R"                  " UR$                  U R                  5      U l        [        R                  " U R                  5      U l        g )N)re   rf   rg   rk   )r6   r7   d_modelre   BLENDERBOT_ATTENTION_CLASSES_attn_implementationencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normrg   r
   activation_functionactivation_fnactivation_dropoutrs   encoder_ffn_dimfc1fc2final_layer_normr8   rk   r9   s     r,   r7   BlenderbotEncoderLayer.__init__  s    5f6Q6QRnn44,,	
 %'LL$@!~~#F$>$>?"(";";99T^^V-C-CD99V33T^^D "T^^ <r.   ry   r|   r}   r~   r   c                    UnU R                  U5      nU R                  UUUUS9u  pn[        R                  R	                  XR                  U R
                  S9nXQ-   nUnU R                  U5      nU R                  U R                  U5      5      n[        R                  R	                  XR                  U R
                  S9nU R                  U5      n[        R                  R	                  XR                  U R
                  S9nXQ-   nUR                  [        R                  :X  aC  [        R                  " UR                  5      R                  S-
  n[        R                   " X* US9nU4n	U(       a  X4-  n	U	$ )aW  
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.
)ry   r|   r}   r~   r   i  )minmax)r   r   r   r   rg   r   r   r   r   r   r   r?   rA   float16finfor   clamp)
r8   ry   r|   r}   r~   residualr   r   clamp_valueoutputss
             r,   rE   BlenderbotEncoderLayer.forward&  sV   $ !11-@)-')+/	 *8 *
&Q --m||VZVcVc-d 0 --m<**488M+BC--m?V?Vaeanan-o/--m||VZVcVc-d 0%--/++m&9&9:>>EK!KK<[YM "&Gr.   )	r   r   rg   re   r   r   r   r   r   F)rK   rL   rM   rN   r   r7   rA   rR   r   rE   rS   rT   rU   s   @r,   r   r     s_    =/ =. #(.||. . 	.
  . 
. .r.   r   c                   `  ^  \ rS rSrSS\S\\   4U 4S jjjr         SS\R                  S\\R                     S\\R                     S\\R                     S	\\R                     S
\\R                     S\\
   S\\   S\\   S\\R                     S\R                  4S jjrSrU =r$ )BlenderbotDecoderLayeriX  rk   rl   c           
      T  > [         TU ]  5         UR                  U l        [        UR
                     " U R                  UR                  UR                  SSUUS9U l        UR                  U l	        [        UR                     U l        UR                  U l        [        R                  " U R                  5      U l        [        UR
                     " U R                  UR                  UR                  SUUS9U l        [        R                  " U R                  5      U l        [        R&                  " U R                  UR(                  5      U l        [        R&                  " UR(                  U R                  5      U l        [        R                  " U R                  5      U l        g )NT)re   rf   rg   rh   rj   rk   rl   )rg   rh   rk   rl   )r6   r7   r   re   r   r   decoder_attention_headsr   r   rg   r
   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrs   decoder_ffn_dimr   r   r   )r8   rk   rl   r9   s      r,   r7   BlenderbotDecoderLayer.__init__Y  s6   5f6Q6QRnn44,,
 ~~#F$>$>?"(";";$&LL$@!89T9TUNN**,,
 (*||DNN'C$99T^^V-C-CD99V33T^^D "T^^ <r.   ry   r|   encoder_hidden_statesencoder_attention_maskr}   cross_attn_layer_head_maskr{   r~   	use_cacher   r   c           	          UnU R                  U5      nU R                  UUUUUU
S9u  pn[        R                  R	                  XR                  U R
                  S9nX-   nSnUb`  UnU R                  U5      nU R                  UUUUUUS9u  pn[        R                  R	                  XR                  U R
                  S9nX-   nUnU R                  U5      nU R                  U R                  U5      5      n[        R                  R	                  XR                  U R
                  S9nU R                  U5      n[        R                  R	                  XR                  U R
                  S9nX-   nU4nU(       a  XU4-  nU	(       a  X4-  nU$ )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.
    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.
)ry   r{   r|   r}   r~   r   r   N)ry   rz   r|   r}   r{   r~   )r   r   r   r   rg   r   r   r   r   r   r   r   r   )r8   ry   r|   r   r   r}   r   r{   r~   r   r   r   self_attn_weightscross_attn_weightsr   s                  r,   rE   BlenderbotDecoderLayer.forwardx  s   D !11-@ <@>>'))+/) <J <
8. --m||VZVcVc-d 0 " ,$H 88GM AE@Q@Q+!65 :-"3 AR A=M~ MM11-<<Z^ZgZg1hM$4M !--m<**488M+BC--m?V?Vaeanan-o/--m||VZVcVc-d 0 "+=>>G((Gr.   )r   r   rg   re   r   r   r   r   r   r   r   r5   )	NNNNNNFTN)rK   rL   rM   rN   r   r   rP   r7   rA   rR   r   r   rE   rS   rT   rU   s   @r,   r   r   X  s   =/ =HSM = =D 268<9=26=A*.,1$(15T||T !.T  (5	T
 !) 6T "%,,/T %-U\\$:T !T $D>T D>T !.T 
T Tr.   r   c                      \ rS rSr\rSrSrSrSr	S r
\S 5       r SS\\R                  S4   S\R                  S	\R                  S
\S\4
S jjr\S\R                  S\S\S\R*                  S	\R                  S\4S j5       rSrg)BlenderbotPreTrainedModeli  modelTc                    U R                   R                  n[        U[        R                  5      (       aW  UR
                  R                  R                  SUS9  UR                  b%  UR                  R                  R                  5         g g [        U[        R                  5      (       ad  UR
                  R                  R                  SUS9  UR                  b2  UR
                  R                  UR                     R                  5         g g [        U[        R                  5      (       aJ  UR
                  R                  R                  S5        UR                  R                  R                  5         g g )Nr   )meanstdr`   )rk   init_stdr   r   rs   rD   datanormal_ri   zero_	EmbeddingrY   r   fill_)r8   moduler   s      r,   _init_weights'BlenderbotPreTrainedModel._init_weights  s   kk""fbii((MM&&CS&9{{&  &&( '--MM&&CS&9!!-""6#5#56<<> .--MM$$S)KK""$ .r.   c                     U R                   R                  n[        R                  " / SQSSSSU//U R                  S9nUR                  U5      UUS.nU$ )N)r      
      r   r         r   r@   )r|   r!   decoder_input_ids)rk   r"   rA   tensorr@   ne)r8   	pad_tokenr!   dummy_inputss       r,   r   &BlenderbotPreTrainedModel.dummy_inputs  sZ    KK,,	LL"2Q2q)4L!MVZVaVab	'll95"!*

 r.   r|   r   input_tensorr   past_key_valuesr~   c           	         U R                   R                  S:X  a  Ub  US:H  R                  5       (       a  U$ g U R                   R                  S:X  a,  [        U[        R
                  5      (       a  [        U5      nU$ Ub  UR                  5       OSnUb  UR                  OSnU R                   R                  S:X  a5  U(       d.  U(       d'  [        R                  " UUUU R                  S9(       a  g UR                  nUR                  S   n	U(       a  UR                  5       n
O5[        U[        R
                  5      (       a  UR                  S	   OXi-   S-   n
U R                  UU	U
UUUR                  S   S
9nU R                   R                  S:X  aZ  UbW  UR                   R"                  S;   a=  U(       d6  [        R$                  " U5      R&                  n[        R(                  " X5      nU$ )Nflash_attention_2r   flex_attentionr   Fsdpa)inputs_embedsr<   is_trainingr   r%   )sequence_lengthtarget_lengthr?   r   
batch_size)cudaxpunpu)rk   r   anyr   rA   rR   r    get_seq_lengthis_compileabler   _ignore_causal_mask_sdpar   r?   r'   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr@   typer   r   _unmask_unattended)r8   r|   r   r   r   r~   past_seen_tokensusing_compilable_cacher?   r   r   causal_mask	min_dtypes                r,   _update_causal_mask-BlenderbotPreTrainedModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K.K%%;;++/??.%,,77!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell;; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCK[Kr.   r   r   r?   r   c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n[        R                  " X4XUR
                  S9nUS:w  a  [        R                  " USS9nU[        R                  " X$R
                  S9UR                  SS5      :  -  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                  S   n	USS2SS2SS2SU	24   U SS2SSSS24   R                  UR
                  5      -   n
U
S:H  n
USS2SS2SS2SU	24   R                  X5      USS2SS2SS2SU	24'   U$ )	a  
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   )
fill_valuer?   r@   r   )diagonalr   r%   r   )r   rA   r   r   fullr@   triurB   r   expandr(   r'   tomasked_fill)r|   r   r   r?   r   r   kwargsr  r  mask_lengthpadding_masks              r,   r  OBlenderbotPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_position5  s}   > %.*<*<*>!*C(K* ' E*..I** 0Y\j\q\qK !##jjqA5<<>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c 6Aq!\k\12 r.   rI   Nr   )rK   rL   rM   rN   r   config_classbase_model_prefixsupports_gradient_checkpointing_supports_cache_class_supports_static_cacher   propertyr   r   rA   rR   r   r   r  staticmethodrP   r?   r  rS   rI   r.   r,   r   r     s    #L&*# !%  " #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4r.   r   c                   n   ^  \ rS rSrSrSS\S\\R                     4U 4S jjjr	       S	S jr
SrU =r$ )
BlenderbotEncoderin  z
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
[`BlenderbotEncoderLayer`].

Args:
    config: BlenderbotConfig
    embed_tokens (nn.Embedding): output embedding
rk   embed_tokensc                   > [         TU ]  U5        UR                  U l        UR                  U l        UR
                  nUR                  U l        UR                  U l	        UR                  (       a  [        R                  " U5      OSnUb  X l        O$[        UR                  X0R                  US9U l        [!        UR                  U5      U l        [$        R&                  " [)        UR*                  5       Vs/ s H  n[-        U5      PM     sn5      U l        [$        R0                  " UR
                  5      U l        SU l        U R7                  5         g s  snf )Nr`   r_   F)r6   r7   rg   encoder_layerdrop	layerdropr   r"   rY   max_position_embeddingsmax_source_positionsscale_embeddingmathsqrtr%  rW   
vocab_sizer0   embed_positionsr   
ModuleListrangeencoder_layersr   layersr   
layer_normgradient_checkpointing	post_init)r8   rk   r%  re   rZ   r   r9   s         r,   r7   BlenderbotEncoder.__init__x  s    ~~11NN	!..$*$B$B!.4.D.Ddii	*## , =!!9.>.>K!D  D** 
 mmUSYShShMi$jMi%;F%CMi$jk,,v~~6&+# %ks   :Ec                    Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUb  Ub  [	        S5      eUb7  U R                  X5        UR                  5       nUR                  SUS   5      nO"Ub  UR                  5       SS nO[	        S5      eUc  U R                  U5      nU R                  U5      n	XI-   n
[        R                  R                  XR                  U R                  S9n
Ub  [        X$R                  5      nU(       a  SOSnU(       a  SOSnUb`  UR                  5       S   [!        U R"                  5      :w  a6  [	        S[!        U R"                  5       S	UR                  5       S    S
35      e[%        U R"                  5       H  u  pU(       a  X4-   nSnU R                  (       a(  [&        R(                  " / 5      nUU R*                  :  a  SnU(       a  SnO^U R,                  (       a8  U R                  (       a'  U R/                  UR0                  U
UUb  X=   OSU5      nOU" U
UUb  X=   OSUS9nUS   n
U(       d  M  UUS   4-   nM     U R3                  U
5      n
U(       a  X4-   nU(       d  [5        S XU4 5       5      $ [7        XUS9$ )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_embedsr   rI   r   z&The head_mask should be specified for  layers, but it is for .FT)NN)r}   r~   r   c              3   .   #    U  H  oc  M  Uv   M     g 7fr5   rI   .0vs     r,   	<genexpr>,BlenderbotEncoder.forward.<locals>.<genexpr>  s     e$Sq$Ss   	last_hidden_statery   
attentions)rk   r~   output_hidden_statesuse_return_dictr)   %warn_if_padding_and_no_attention_maskr   r   r%  r/  r   r   rg   r   r   r?   lenr3  	enumeraterA   randr(  r5  _gradient_checkpointing_func__call__r4  tupler   )r8   r!   r|   	head_maskr   r~   rD  return_dictinput_shape	embed_posry   encoder_statesall_attentionsidxencoder_layerto_dropdropout_probabilitylayer_outputss                     r,   rE   BlenderbotEncoder.forward  s   \ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]  ]%>cdd"66yQ#..*K!r;r?;I&',,.s3KTUU  --i8M((5	%1--m||VZVcVc-d %7H[H[\N30d  ~~"c$++&66 <S=M<N O!(+,A/  #,DKK"8C#!/2B!BG}}&+jjn#&7"G ,..4==$($E$E%..%&+4+@d)%M %2%&;D;PVZ*;	%M !.a 0  !/=3C2E!EA #9F 6+.>>Ne]N$Seee+Vd
 	
r.   )	rg   r/  r%  r5  r4  r(  r3  r*  rY   r5   )NNNNNNN)rK   rL   rM   rN   rO   r   r   r   r   r7   rE   rS   rT   rU   s   @r,   r$  r$  n  sM    / x?U  > !C
 C
r.   r$  c                      ^  \ rS rSrSrSS\S\\R                     4U 4S jjjr	S r
S r             SS\\R                     4S	 jjrS
rU =r$ )BlenderbotDecoderi  z
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BlenderbotDecoderLayer`]

Args:
    config: BlenderbotConfig
    embed_tokens (nn.Embedding): output embedding
rk   r%  c           
        > [         TU ]  U5        UR                  U l        UR                  U l        UR
                  U l        UR                  U l        UR                  (       a   [        R                  " UR                  5      OSnUb  X l        O/[        UR                  UR                  U R                  US9U l        [!        UR                  UR                  5      U l        [$        R&                  " [)        UR*                  5       Vs/ s H  n[-        XS9PM     sn5      U l        [$        R0                  " UR                  5      U l        SU l        U R7                  5         g s  snf )Nr`   r_   )rl   F)r6   r7   rg   decoder_layerdropr(  r"   rY   r)  max_target_positionsr+  r,  r-  r   r%  rW   r.  r0   r/  r   r0  r1  decoder_layersr   r3  r   r4  r5  r6  )r8   rk   r%  rZ   ir9   s        r,   r7   BlenderbotDecoder.__init__$  s    ~~11!..$*$B$B!393I3Idii/s# , =!!6>>43C3CQ\!D  D**NN 
 mmBGH]H]B^_B^Q#F8B^_
 ,,v~~6&+# `s   E)c                     U R                   $ r5   r%  r8   s    r,   get_input_embeddings&BlenderbotDecoder.get_input_embeddings@  s       r.   c                     Xl         g r5   rb  r8   values     r,   set_input_embeddings&BlenderbotDecoder.set_input_embeddingsC  s    !r.   r   c                 *	   U
b  U
OU R                   R                  n
Ub  UOU R                   R                  nU	b  U	OU R                   R                  n	Ub  UOU R                   R                  nU R
                  (       a/  U R                  (       a  U	(       a  [        R                  S5        Sn	USL USL-  (       a  [        S5      eUb  UR                  SUR                  S   5      nUc  U R                  U5      nSnU	(       aB  [        U[        5      (       d-  Sn[        R                  S5        [         R"                  " U5      nUR%                  5       SS u  nnUb  UR'                  5       OSnUc#  [(        R*                  " UUU-   UR,                  S	9nUc4  [/        5       (       d%  UU-   n[(        R0                  " UUUR,                  S	9n[        U[         5      (       a  UR2                  OUnU R5                  UUUUU
5      nUb  Ub  [7        XHR8                  US
9nU R;                  UU4UUS9nUU-   n[<        R>                  RA                  UU R@                  U R                  S9nU(       a  SOSnU
(       a  SOSnU
(       a  Ub  SOSnSn[C        XV/SS/5       Hn  u  nnUc  M  UR%                  5       S   [E        U RF                  5      :w  d  M7  [        SU S[E        U RF                  5       SUR%                  5       S    S35      e   [I        U RF                  5       H  u  nnU(       a  UU4-  nU R                  (       a(  [(        RJ                  " / 5      nUU RL                  :  a  ML  U R
                  (       aG  U R                  (       a6  U RO                  URP                  UUUUUb  UU   OSUb  UU   OSSU
U	U5      n OU" UUUUUb  UU   OSUb  UU   OSUU
U	US9
n U S   nU	(       a  U U
(       a  SOS   nU
(       d  M  UU S   4-  nUc  M  UU S   4-  nGM      U RS                  U5      nU(       a  UU4-  nU	(       a  UOSn!U(       a  URU                  5       n!U(       d  [W        S UU!UUU4 5       5      $ [Y        UU!UUUS9$ )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)
    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   )r   )r=   r   rI   rM  cross_attn_head_maskzThe `z` should be specified for r9  r:  )	r|   r   r   r}   r   r{   r~   r   r   r	   r   r   c              3   0   #    U  H  nUc  M  Uv   M     g 7fr5   rI   r<  s     r,   r?  ,BlenderbotDecoder.forward.<locals>.<genexpr>1  s      mA ms   	)rB  r   ry   rC  cross_attentions)-rk   r~   rD  r   rE  r5  r   rq   warningr)   r   r'   r%  r   r   rr   r   from_legacy_cacher   r  rA   rB   r@   r   onesr   r  r   r?   r/  r   r   rg   ziprG  r3  rH  rI  r(  rJ  rK  r4  to_legacy_cacherL  r   )"r8   r!   r|   r   r   rM  rl  r   r   r   r~   rD  rN  r   return_legacy_cacher   
seq_lengthr<   mask_seq_lengthself_attn_cacher  r=   ry   all_hidden_statesall_self_attnsall_cross_attentionsnext_decoder_cache	attn_mask	mask_namerS  decoder_layerrV  rW  
next_caches"                                     r,   rE   BlenderbotDecoder.forwardF  s   j 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]&&4==p "	 -t";<stt !r9??2+>?I  --i8M $Z??"&\
 2CCOTO!.!3!3!5cr!:
JETE`!?!?!Afg!"\\&(>(KTaThThN !*B*D*D4zAO"ZZ
OML`L`aN /+>?? 00  	
 ..
 !,1G1S%?&(;(;Z&"
 ++$&<> , 
 &4--mt||VZVcVc-d #7BD0d&7<Q<]rdh! %((IKYoKp$q Iy$>>#A&#dkk*::$	{*DSEUDV W%NN,Q/03  %r #,DKK"8C#!m%55!}}&+jjn#&7**t}} $ A A!**!)*&/&;IcN1E1Q(-W[%"! !.!#.*?+A7@7LYs^RV5I5U,S1[_#2&7'#1! *!,M%28I1q%Q"  =#3"55(4(]1-=,??(_ #9d 6  -!11+4'$
(88:J '5FXlm  
 9+&+%1
 	
r.   )	rg   r/  r%  r5  r4  r(  r3  r]  rY   r5   )NNNNNNNNNNNNN)rK   rL   rM   rN   rO   r   r   r   r   r7   rd  ri  rA   rR   rE   rS   rT   rU   s   @r,   rZ  rZ    s}    / x?U  8!"
 "#!!15v
 !.v
 v
r.   rZ  c            &       ~  ^  \ rS rSrSS/rS\4U 4S jjr\S\\	\
\R                  4      4U 4S jj5       rS rS	 rS
 rS r\                SS\\R(                     S\\R*                     S\\R(                     S\\R(                     S\\R*                     S\\R*                     S\\R*                     S\\	\\4      S\\\R2                        S\\R*                     S\\R2                     S\\   S\\   S\\   S\\   S\\R*                     S\	\\R2                     \4   4"S jj5       rSrU =r$ ) BlenderbotModeli?  decoder.embed_tokens.weightencoder.embed_tokens.weightrk   c                 r  > [         TU ]  U5        UR                  UR                  p2UR                  (       a   [
        R                  " UR                  5      OSn[        X1R                  X$S9U l	        [        XR                  5      U l        [        XR                  5      U l        U R                  5         g )Nr`   r_   )r6   r7   r"   r.  r+  r,  r-  r   rW   sharedr$  encoderrZ  decoderr6  )r8   rk   rY   r.  rZ   r9   s        r,   r7   BlenderbotModel.__init__C  s~     "("5"5v7H7HZ393I3Idii/s3JP[u(=(= 	r.   pretrained_model_name_or_pathc                    > US:X  a1  [         R                  " S[        5        [        R                  " U5      $ [
        [        U ]  " U/UQ70 UD6$ )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_pretrainedr6   r  clsr  
model_argsr  r9   s       r,   r  BlenderbotModel.from_pretrainedO  sV    (,EEMMd 	 (778UVV_c:;Xp[epioppr.   c                     U R                   $ r5   )r  rc  s    r,   rd  $BlenderbotModel.get_input_embeddings\  s    {{r.   c                 |    Xl         U R                   U R                  l        U R                   U R                  l        g r5   )r  r  r%  r  rg  s     r,   ri  $BlenderbotModel.set_input_embeddings_  s'    $(KK!$(KK!r.   c                     U R                   $ r5   )r  rc  s    r,   get_encoderBlenderbotModel.get_encoderd      ||r.   c                     U R                   $ r5   r  rc  s    r,   get_decoderBlenderbotModel.get_decoderg  r  r.   r!   r|   r   decoder_attention_maskrM  decoder_head_maskrl  encoder_outputsr   r   decoder_inputs_embedsr   r~   rD  rN  r   r   c                    Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUc  U R                  UUUU
UUUS9nORU(       aK  [        U[        5      (       d6  [        US   [        U5      S:  a  US   OS[        U5      S:  a  US   OSS9nU R                  UUUS   UUUU	UUUUUUS9nU(       d  UU-   $ [        UR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                  S9$ )	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!   r|   rM  r   r~   rD  rN  r   r   r   rA  r!   r|   r   r   rM  rl  r   r   r   r~   rD  rN  r   )rB  r   decoder_hidden_statesdecoder_attentionsro  encoder_last_hidden_stater   encoder_attentions)rk   r~   rD  r   rE  r  r   r   rG  r  r   rB  r   ry   rC  ro  )r8   r!   r|   r   r  rM  r  rl  r  r   r   r  r   r~   rD  rN  r   decoder_outputss                     r,   rE   BlenderbotModel.forwardj  s   t 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]""ll#-#+"3%9' + O O_!M!M-"1!"4474H14Loa0RV14_1E1I?1-tO ,,'1"1!"4#1'!5+//!5#) ' 
  "_44!-??+;;"1"?"?.99,==&5&G&G"1"?"?.99	
 		
r.   )r  r  r  )NNNNNNNNNNNNNNNN)rK   rL   rM   rN   _tied_weights_keysr   r7   classmethodr   r   strosPathLiker  rd  ri  r  r  r   rA   
LongTensorrR   r   r   r   FloatTensorr   r   rE   rS   rT   rU   s   @r,   r  r  ?  s   79VW
/ 
 
qHU3PRP[P[K[E\<] 
q 
q0
  15158<=A,0487;CG=A04=A$(,0/3&*15#o
E,,-o
 !.o
 $E$4$45	o

 !))9)9 :o
 ELL)o
 $ELL1o
 'u||4o
 "%(>"?@o
 "$u'8'8"9:o
  -o
  ((9(9:o
 D>o
 $D>o
 'tno
  d^!o
" !.#o
$ 
uU&&');;	<%o
 o
r.   r  z\
    The Blenderbot Model with a language modeling head. Can be used for summarization.
    )custom_introc            (       
  ^  \ rS rSrSrS/r/ SQrS\4U 4S jjr\	S\
\\\R                  4      4U 4S jj5       rS	 rS
 r S(S\S\
\   S\S\R*                  4U 4S jjjrS\SS4S jrS rS r\                 S)S\
\R8                     S\
\R:                     S\
\R8                     S\
\R8                     S\
\R:                     S\
\R:                     S\
\R:                     S\
\\\4      S\
\ \RB                        S\
\R:                     S\
\RB                     S\
\R8                     S \
\   S!\
\   S"\
\   S#\
\   S$\
\R:                     S\\\RB                     \"4   4$S% jj5       r#\$S& 5       r%S'r&U =r'$ )*"BlenderbotForConditionalGenerationi  r   final_logits_bias)r  r  lm_head.weightrk   c                 v  > [         TU ]  U5        [        U5      U l        U R	                  S[
        R                  " SU R                  R                  R                  45      5        [        R                  " UR                  U R                  R                  R                  SS9U l        U R                  5         g )Nr  r   Frn   )r6   r7   r  r   register_bufferrA   zerosr  r2   r   rs   r   lm_headr6  r   s     r,   r7   +BlenderbotForConditionalGeneration.__init__  s     $V,
0%++q$**BSBSBbBb>c2deyy1B1B1Q1QX]^ 	r.   r  c                    > US:X  a1  [         R                  " S[        5        [        R                  " U5      $ [
        [        U ]  " U/UQ70 UD6$ )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  r6   r  r  s       r,   r  2BlenderbotForConditionalGeneration.from_pretrained  s_    (,EEMMw 	 ;JJKhii7M)
,6
:@
 	
r.   c                 6    U R                   R                  5       $ r5   )r   r  rc  s    r,   r  .BlenderbotForConditionalGeneration.get_encoder      zz%%''r.   c                 6    U R                   R                  5       $ r5   )r   r  rc  s    r,   r  .BlenderbotForConditionalGeneration.get_decoder  r  r.   Nnew_num_tokenspad_to_multiple_ofmean_resizingr   c                 x   > [         TU ]  XU5      nU R                  UR                  R                  S   5        U$ )Nr   )r6   resize_token_embeddings_resize_final_logits_biasrD   r'   )r8   r  r  r  new_embeddingsr9   s        r,   r  :BlenderbotForConditionalGeneration.resize_token_embeddings  s<     8]jk&&~'<'<'B'B1'EFr.   c                 ,   U R                   R                  S   nX::  a  U R                   S S 2S U24   nON[        R                  " SX-
  4U R                   R                  S9n[        R
                  " U R                   U/SS9nU R                  SU5        g )Nr%   r   r   r   r  )r  r'   rA   r  r@   catr  )r8   r  old_num_tokensnew_bias
extra_biass        r,   r  <BlenderbotForConditionalGeneration._resize_final_logits_bias  s    //55b9+--a..@AHa)H%IRVRhRhRoRopJyy$"8"8*!E1MH0(;r.   c                     U R                   $ r5   r  rc  s    r,   get_output_embeddings8BlenderbotForConditionalGeneration.get_output_embeddings  r  r.   c                     Xl         g r5   r  r8   r  s     r,   set_output_embeddings8BlenderbotForConditionalGeneration.set_output_embeddings      %r.   r!   r|   r   r  rM  r  rl  r  r   r   r  labelsr   r~   rD  rN  r   c                    Ub  UOU R                   R                  nUbX  U(       a  [        R                  S5        SnUc7  Uc4  [	        XR                   R
                  U R                   R                  5      nU R                  UUUUUUUUU	U
UUUUUUS9nU R                  US   5      U R                  -   nSnUbF  [        5       nU" UR                  SU R                   R                  5      UR                  S5      5      nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  UR                   UR"                  UR$                  UR&                  UR(                  S9	$ )	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)r|   r   r  r  rM  r  rl  r   r   r  r   r~   rD  rN  r   r   r%   r   )	losslogitsr   r  r  ro  r  r   r  )rk   rE  rq   rp  r-   r"   r#   r   r  r  r   r   r.  r   r   r  r  ro  r  r   r  )r8   r!   r|   r   r  rM  r  rl  r  r   r   r  r  r   r~   rD  rN  r   r   	lm_logitsmasked_lm_lossloss_fctoutputs                          r,   rE   *BlenderbotForConditionalGeneration.forward  s   ^ &1%<k$++B]B]klI (-B-J$6KK44dkk6X6X%! **)/+#9/!5+'"7/!5#)!  
$ LL,t/E/EE	')H%innR9O9O&PRXR]R]^`RabN\GABK/F3A3M^%.YSYY#33")"?"?&99$55&-&G&G")"?"?&99

 
	
r.   c                 b   ^ SnU  H%  nU[        U4S jUS S  5       5      USS  -   4-  nM'     U$ )NrI   c              3   x   >#    U  H/  oR                  S TR                  UR                  5      5      v   M1     g7frJ   index_selectr  r@   r=  
past_statebeam_idxs     r,   r?  DBlenderbotForConditionalGeneration._reorder_cache.<locals>.<genexpr>  s1     rcqU_--aZ=N=N1OPPcq   7:r   rL  r   r  reordered_past
layer_pasts    `  r,   _reorder_cache1BlenderbotForConditionalGeneration._reorder_cache  sO    )JrcmnpopcqrrQR.! N * r.   r  r   )NT)NNNNNNNNNNNNNNNNN)(rK   rL   rM   rN   r  _keys_to_ignore_on_load_missingr  r   r7   r  r   r   r  r  r  r  r  r  rP   r   r   r   r  r  r  r  r   rA   r  rR   r   r   r   r  r   rE   r"  r  rS   rT   rU   s   @r,   r  r    s     ':&;#i/  
HU3PRP[P[K[E\<] 
 
(( dh!7?}\`	 < < <&  15158<=A,0487;CG=A04=A-1$(,0/3&*15%@
E,,-@
 !.@
 $E$4$45	@

 !))9)9 :@
 ELL)@
 $ELL1@
 'u||4@
 "%(>"?@@
 "$u'8'8"9:@
  -@
  ((9(9:@
 ))*@
 D>@
 $D>@
  'tn!@
" d^#@
$ !.%@
& 
uU&&'8	9'@
 @
D  r.   r  c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )BlenderbotDecoderWrapperi  z
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                 D   > [         TU ]  U5        [        U5      U l        g r5   )r6   r7   rZ  r  r   s     r,   r7   !BlenderbotDecoderWrapper.__init__  s     (0r.   c                 &    U R                   " U0 UD6$ r5   r  )r8   argsr  s      r,   rE    BlenderbotDecoderWrapper.forward  s    ||T,V,,r.   r  )	rK   rL   rM   rN   rO   r7   rE   rS   rT   rU   s   @r,   r  r    s    
1- -r.   r  c            "         ^  \ rS rSrS/rU 4S jrS rS rS rS r	S r
S	 r\              SS
\\R                     S\\R                      S\\R"                     S\\R"                     S\\R                      S\\R                      S\\\R"                        S\\R"                     S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\\4   4S jj5       r\S 5       rSrU =r$ )BlenderbotForCausalLMi  r  c                 
  > [         R                  " U5      nSUl        SUl        [        TU ]  U5        [        U5      U l        [        R                  " UR                  UR                  SS9U l        U R                  5         g )NTFrn   )copydeepcopyrh   is_encoder_decoderr6   r7   r  r   r   rs   hidden_sizer.  r  r6  r   s     r,   r7   BlenderbotForCausalLM.__init__  sf    v& $)! -f5
yy!3!3V5F5FUS 	r.   c                 B    U R                   R                  R                  $ r5   r   r  r%  rc  s    r,   rd  *BlenderbotForCausalLM.get_input_embeddings  s    zz!!...r.   c                 8    XR                   R                  l        g r5   r  rg  s     r,   ri  *BlenderbotForCausalLM.set_input_embeddings  s    */

'r.   c                     U R                   $ r5   r  rc  s    r,   r  +BlenderbotForCausalLM.get_output_embeddings  r  r.   c                     Xl         g r5   r  r  s     r,   r  +BlenderbotForCausalLM.set_output_embeddings  r  r.   c                 $    XR                   l        g r5   r   r  )r8   r  s     r,   set_decoder!BlenderbotForCausalLM.set_decoder  s    $

r.   c                 .    U R                   R                  $ r5   r  rc  s    r,   r  !BlenderbotForCausalLM.get_decoder  s    zz!!!r.   r!   r|   r   r   rM  rl  r   r   r  r   r~   rD  rN  r   r   c                    Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nU R                  R                  UUUUUUUUU
UUUUS9nU R                  US   5      nSnU	ba  U	R                  UR                  5      n	[        5       nU" UR                  SU R                   R                  5      U	R                  S5      5      nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  UR                  UR                   S9$ )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   ry   rC  ro  )rk   r~   rD  rE  r   r  r  r  r@   r   r   r.  r   r   ry   rC  ro  )r8   r!   r|   r   r   rM  rl  r   r   r  r   r~   rD  rN  r   r   r  r  r  r  s                       r,   rE   BlenderbotForCausalLM.forward  s[   \ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] **$$)"7#9!5+'/!5#) % 
  gaj)YYv}}-F')HFKKDKK,B,BCV[[QS_UDY,F'+'7D7V#CVC0#33!//))$55
 	
r.   c                 P   ^ SnU  H  nU[        U4S jU 5       5      4-  nM     U$ )NrI   c              3   x   >#    U  H/  oR                  S TR                  UR                  5      5      v   M1     g7frJ   r  r  s     r,   r?  7BlenderbotForCausalLM._reorder_cache.<locals>.<genexpr>:  s1     ncmU_--aZ=N=N1OPPcmr  r  r  s    `  r,   r  $BlenderbotForCausalLM._reorder_cache5  s8    )Jncmnn N * r.   r  )NNNNNNNNNNNNNN)rK   rL   rM   rN   r  r7   rd  ri  r  r  r  r  r   r   rA   r  rR   r  r   r   r   r   r   rE   r"  r  rS   rT   rU   s   @r,   r  r    s   *+
/0&%"  1515=A>B,07;=A59-1$(,0/3&*59W
E,,-W
 !.W
  ((9(9:	W

 !)):): ;W
 ELL)W
 'u||4W
 "$u'8'8"9:W
   1 12W
 ))*W
 D>W
 $D>W
 'tnW
 d^W
 !!1!12W
  
u77	8!W
 W
r  r.   r  )r  r  r  r   )ErO   r  r,  r  r  typingr   r   r   r   rA   torch.utils.checkpointr   torch.nnr   activationsr
   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   r   r   modeling_utilsr   utilsr   r   r   r   blenderbot_smallr   r   configuration_blenderbotr   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr    
get_loggerrK   rq   rR   rP   r-   r   r0   rW   Modulerc   r   r   r   r   r$  rZ  r  r  r  r  __all__rI   r.   r,   <module>r,     s       	  / /    % ! 5 )  .  ] 6  !!;J 
		H	%%,, c [^  -2<< -*
=BLL 
=ZB")) ZBz !()<= ARYY AJtRYY tn [ [ [|j
1 j
Za
1 a
H	 Z
/ Z
 Z
z 
E)BO E
ER-8 -B5 BJr.   