
    qi                     d   d Z ddlZddlm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 dd	lmZmZmZ dd
lmZ ddlmZmZ ddlmZ ddlmZ ddlmZmZmZmZmZ ddl 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+  e)jX                  e-      Z.dej^                  de0de0fdZ1 G d dejd                        Z3 G d dejd                        Z4	 	 d<dejj                  dej^                  dej^                  dej^                  d ej^                  dz  d!e6dz  d"e6d#e$e&   fd$Z7 G d% d&ejj                        Z8 G d' d(e      Z9 G d) d*e      Z:e' G d+ d,e"             Z; G d- d.e;      Z< G d/ d0e;      Z=e' G d1 d2e;             Z> e'd34       G d5 d6e;e             Z? G d7 d8e;      Z@ G d9 d:e;e      ZAg d;ZBy)=zPyTorch Blenderbot model.    N)Callable)nn)CrossEntropyLoss   )initialization)ACT2FN)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)create_bidirectional_maskcreate_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringis_torchdynamo_compilinglogging   )BlenderbotConfig	input_idspad_token_iddecoder_start_token_idc                     | j                  | j                        }| ddddf   j                         |ddddf<   ||dddf<   |t        d      |j	                  |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)	new_zerosshapeclone
ValueErrormasked_fill_)r   r    r!   shifted_input_idss       d/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/blenderbot/modeling_blenderbot.pyshift_tokens_rightr+   4   s}     "++IOO<(CRC0668ae4adLMM""#4#<lK    c                   v     e Zd ZdZdedef fdZ	 d
dej                  dedej                  dz  f fd	Z	 xZ
S )$BlenderbotLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    num_embeddingsembedding_dimc                 &    t         |   ||       y N)super__init__)selfr/   r0   	__class__s      r*   r4   z-BlenderbotLearnedPositionalEmbedding.__init__I   s    7r,   Ninput_ids_shapepast_key_values_lengthposition_idsc                     |F|dd \  }}t        j                  |||z   t         j                  | j                  j                        }t
        |   |      S )z3`input_ids_shape` is expected to be [bsz x seqlen].N   )dtypedevice)torcharangelongweightr=   r3   forward)r5   r7   r8   r9   bszseq_lenr6   s         r*   rB   z,BlenderbotLearnedPositionalEmbedding.forwardL   s]     *2A.LC <<&(>(HPUPZPZcgcncncucuL w|,,r,   )r   N)__name__
__module____qualname____doc__intr4   r>   SizeTensorrB   __classcell__r6   s   @r*   r.   r.   D   sT    8s 83 8 qu	-$zz	-CF	-Z_ZfZfimZm	- 	-r,   r.   c            
       `     e Zd ZdZd
dededededz  f fdZdej                  f fd	Z	 xZ
S )BlenderbotScaledWordEmbeddingz\
    This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
    r/   r0   padding_idxembed_scaleNc                 6    t         |   |||       || _        y r2   )r3   r4   rQ   )r5   r/   r0   rP   rQ   r6   s        r*   r4   z&BlenderbotScaledWordEmbedding.__init__^   s    D&r,   r   c                 <    t         |   |      | j                  z  S r2   )r3   rB   rQ   )r5   r   r6   s     r*   rB   z%BlenderbotScaledWordEmbedding.forwardb   s    wy)D,<,<<<r,   )      ?)rE   rF   rG   rH   rI   floatr4   r>   rK   rB   rL   rM   s   @r*   rO   rO   Y   sE    's '3 'S '_dgk_k '= = =r,   rO   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|||z   }t        j
                  j                  |d      }t        j
                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )Nr#         r;   r   dimptrainingr   )
sizer>   matmul	transposer   
functionalsoftmaxr\   rd   
contiguous)
rV   rW   rX   rY   rZ   r[   r\   r]   attn_weightsattn_outputs
             r*   eager_attention_forwardrm   g   s     **R.D( <<s}}Q':;gEL!#n4==((2(>L==((6??([L,,|U3K''1-88:K$$r,   c                   Z    e Zd ZdZ	 	 	 	 	 	 ddedededededed	edz  d
edz  f fdZ	 	 	 	 	 dde	j                  de	j                  dz  dedz  de	j                  dz  dede	j                  dz  dee   dee	j                  e	j                  dz  ee	j                     dz  f   fdZ xZS )BlenderbotAttentionz=Multi-headed attention from 'Attention Is All You Need' paperN	embed_dim	num_headsr\   
is_decoderbias	is_causalconfig	layer_idxc	                    t         	|           || _        || _        || _        ||z  | _        || _        | j
                  |z  | j                  k7  rt        d| j                   d| d      | j
                  dz  | _        || _	        || _
        || _        |9| j                  r-t        j                  d| j                  j                   d       t!        j"                  |||      | _        t!        j"                  |||      | _        t!        j"                  |||      | _        t!        j"                  |||      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).r_   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   )r3   r4   rp   rq   r\   head_dimru   r'   r[   rr   rt   rv   loggerwarning_oncer6   rE   r   Lineark_projv_projq_projout_proj)
r5   rp   rq   r\   rr   rs   rt   ru   rv   r6   s
            r*   r4   zBlenderbotAttention.__init__   s$    	""!Y.MMI%$..8MdnnM]$YKr3  }}d*$""*4>>+B+B*C D, , ii	94@ii	94@ii	94@		)YTBr,   hidden_stateskey_value_statespast_key_valuesrZ   output_attentionscache_positionr]   returnc                    |du}|j                   dd \  }	}
|r|j                   d   n|
}|	|
d| j                  f}|	|d| j                  f} | j                  |      j                  | j	                  dd      }d}|St        |t              rA|j                  j                  | j                        }|r|j                  }n|j                  }n|}|r|n|}|rK|I|rGj                  | j                     j                  }|j                  | j                     j                  }n| j                  |      }| j!                  |      } |j                  | j	                  dd      } |j                  | j	                  dd      }|T|s|nd}j#                  ||| j                  d|i      \  }}|r)t        |t              rd|j                  | j                  <   t%        j&                  | j(                  j*                  t,              } || ||||f| j.                  sdn| j0                  | j2                  |d	|\  }}|j5                  |	|
d      j7                         }| j9                  |      }||fS )
z#Input shape: Batch x Time x ChannelNr#   r   r;   Fr   T        )r\   r[   r   )r%   ry   r   viewrg   
isinstancer   
is_updatedgetrv   cross_attention_cacheself_attention_cachelayerskeysvaluesr}   r~   updater   get_interfaceru   _attn_implementationrm   rd   r\   r[   reshaperj   r   )r5   r   r   r   rZ   r   r   r]   is_cross_attentionrC   tgt_lensrc_lenq_input_shapekv_input_shapequery_statesr   curr_past_key_valuescurrent_states
key_statesvalue_statesattention_interfacerl   rk   s                          r*   rB   zBlenderbotAttention.forward   s{     .T9 %**3B/W/A"((+wgr4==9wDMM: 7t{{=166FPPQRTUV
&/+>?,77;;DNNK
%+:+P+P(+:+O+O('6$-?)]/"=*-44T^^DIIJ/66t~~FMML^4J;;~6L(.9CCAqIJ,<,,n=GG1ML*7It+?+F+Fdnn?OQ_>`,(
L &*_FY*ZAEO..t~~>(?(M(MKK,,.E)
 %8
%
  $}}C$,,LL/
%
 
%
!\ "))#w;FFHmmK0L((r,   )r   FTFNN)NNNFN)rE   rF   rG   rH   rI   rU   boolr   r4   r>   rK   r	   r   r   tuplerB   rL   rM   s   @r*   ro   ro      s=   G  *. $%C%C %C 	%C
 %C %C %C !4'%C :%CT 15(,.2"'.2P)||P)  ,,-P) 	P)
 t+P)  P) t+P) -.P) 
u||U\\D0%2E2LL	MP)r,   ro   c            	       |     e Zd Zdef fdZ	 ddej                  dej                  dedej                  fdZ xZ	S )	BlenderbotEncoderLayerru   c                 h   t         |           |j                  | _        t	        | j                  |j
                  |j                  |      | _        t        j                  | j                        | _
        |j                  | _        t        |j                     | _        |j                  | _        t        j                   | j                  |j"                        | _        t        j                   |j"                  | j                        | _        t        j                  | j                        | _        y )N)rp   rq   r\   ru   )r3   r4   d_modelrp   ro   encoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normr\   r   activation_functionactivation_fnactivation_dropoutr|   encoder_ffn_dimfc1fc2final_layer_normr5   ru   r6   s     r*   r4   zBlenderbotEncoderLayer.__init__  s    ,nn44,,	
 %'LL$@!~~#F$>$>?"(";";99T^^V-C-CD99V33T^^D "T^^ <r,   r   rZ   r   r   c                    |}| j                  |      }| j                  |||      \  }}t        j                  j	                  || j                  | j
                        }||z   }|}| j                  |      }| j                  | j                  |            }t        j                  j	                  || j                  | j
                        }| j                  |      }t        j                  j	                  || j                  | j
                        }||z   }|j                  t        j                  k(  rEt        j                  |j                        j                  dz
  }t        j                   || |      }||f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.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r   rZ   r   rb   i  )minmax)r   r   r   rh   r\   rd   r   r   r   r   r   r<   r>   float16finfor   clamp)r5   r   rZ   r   residualrk   clamp_values          r*   rB   zBlenderbotEncoderLayer.forward  sP    !11-@&*nn')/ '5 '
#|
 --mt||VZVcVc-d =0 --m<**488M+BC--mt?V?Vaeanan-o/--mt||VZVcVc-d =0%--/++m&9&9:>>EK!KKK<[YMl**r,   )F)
rE   rF   rG   r   r4   r>   rK   r   rB   rL   rM   s   @r*   r   r     sL    =/ =, #(	%+||%+ %+  	%+
 
%+r,   r   c                       e Zd Zddededz  f fdZ	 	 	 	 	 	 	 ddej                  dej                  dz  dej                  dz  dej                  dz  d	edz  d
e	dz  de	dz  dej                  dz  dej                  fdZ
 xZS )BlenderbotDecoderLayerNru   rv   c           	         t         |           |j                  | _        t	        | j                  |j
                  |j                  dd||      | _        |j                  | _        t        |j                     | _        |j                  | _        t        j                  | j                        | _        t	        | j                  |j
                  |j                  d||      | _        t        j                  | j                        | _        t        j$                  | j                  |j&                        | _        t        j$                  |j&                  | j                        | _        t        j                  | j                        | _        y )NT)rp   rq   r\   rr   rt   ru   rv   )r\   rr   ru   rv   )r3   r4   r   rp   ro   decoder_attention_headsr   r   r\   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normr|   decoder_ffn_dimr   r   r   )r5   ru   rv   r6   s      r*   r4   zBlenderbotDecoderLayer.__init__?  s    ,nn44,,
 ~~#F$>$>?"(";";$&LL$@!/NN**,,
 (*||DNN'C$99T^^V-C-CD99V33T^^D "T^^ <r,   r   rZ   encoder_hidden_statesencoder_attention_maskr   r   	use_cacher   r   c	                 ,   |}	| j                  |      }| j                  |||||      \  }}
t        j                  j	                  || j                  | j
                        }|	|z   }d}|g|}	| j                  |      }| j                  |||||      \  }}t        j                  j	                  || j                  | j
                        }|	|z   }|}	| j                  |      }| j                  | j                  |            }t        j                  j	                  || j                  | j
                        }| j                  |      }t        j                  j	                  || j                  | j
                        }|	|z   }|f}|r||
|fz  }|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.
            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.
            past_key_values (`Cache`): 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.
        )r   r   rZ   r   r   rb   N)r   r   rZ   r   r   )r   r   r   rh   r\   rd   r   r   r   r   r   r   r   )r5   r   rZ   r   r   r   r   r   r   r   self_attn_weightscross_attn_weightsoutputss                r*   rB   zBlenderbotDecoderLayer.forward^  s   8 !11-@ ,0>>'+)/) ,: ,
(( --mt||VZVcVc-d =0 " ,$H 88GM040A0A+!65 /"3 1B 1-M- MM11-4<<Z^ZgZg1hM$}4M !--m<**488M+BC--mt?V?Vaeanan-o/--mt||VZVcVc-d =0 ")+=>>Gr,   r2   )NNNNFTN)rE   rF   rG   r   rI   r4   r>   rK   r	   r   rB   rL   rM   s   @r*   r   r   >  s    =/ =C$J =D /3596:(,).!%.2H||H t+H  %||d2	H
 !&t 3H H  $;H $;H t+H 
Hr,   r   c                   R     e Zd ZU eed<   dZdZdZdZdZ	dZ
 fdZed        Z xZS )BlenderbotPreTrainedModelru   modelTc                     t         |   |       t        |t              r t	        j
                  |j                         y y r2   )r3   _init_weightsr   "BlenderbotForConditionalGenerationinitzeros_final_logits_bias)r5   rV   r6   s     r*   r   z'BlenderbotPreTrainedModel._init_weights  s3    f%f@AKK001 Br,   c                     | j                   j                  }t        j                  g ddddd|gg| j                        }|j                  |      ||d}|S )N)r      
      r;   r         r;   r=   )rZ   r   decoder_input_ids)ru   r    r>   tensorr=   ne)r5   	pad_tokenr   dummy_inputss       r*   r   z&BlenderbotPreTrainedModel.dummy_inputs  sZ    KK,,	LL"2Q2q)4L!MVZVaVab	'll95"!*

 r,   )rE   rF   rG   r   __annotations__base_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraphr   propertyr   rL   rM   s   @r*   r   r     sE    &*#N!2
  r,   r   c                   <     e Zd ZdZdef fdZ	 	 	 	 	 	 ddZ x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
    ru   c                    t         |   |       |j                  | _        |j                  | _        |j
                  }|j                  | _        |j                  | _	        |j                  rt        j                  |      nd}t        |j                  || j                  |      | _        t!        |j                  |      | _        t%        j&                  t)        |j*                        D cg c]  }t-        |       c}      | _        t%        j0                  |j
                        | _        d| _        | j7                          y c c}w )NrT   rQ   F)r3   r4   r\   encoder_layerdrop	layerdropr   r    rP   max_position_embeddingsmax_source_positionsscale_embeddingmathsqrtrO   
vocab_sizeembed_tokensr.   embed_positionsr   
ModuleListrangeencoder_layersr   r   r   
layer_normgradient_checkpointing	post_init)r5   ru   rp   rQ   _r6   s        r*   r4   zBlenderbotEncoder.__init__  s     ~~11NN	!..$*$B$B!.4.D.Ddii	*#9y$*:*:
  D** 
 mmUSYShShMi$j%;F%C$jk,,v~~6&+# %ks   -Ec                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }||t	        d      |8| j                  ||       |j                         }|j                  d|d         }n!||j                         dd }nt	        d      || j                  |      }| j                  |      }	||	z   }
t        j                  j                  |
| j                  | j                        }
t        | j                   ||      }|rdnd}|rdnd}t        | j                         D ]b  \  }}|r||
fz   }d}| j                  r&t#        j$                  g       }|| j&                  k  rd	}|rd
}n ||
||      }|d   }
|sZ||d   fz   }d | j)                  |
      }
|r||
fz   }|st+        d |
||fD              S t-        |
||      S )a8  
        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)
            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_embedsrb   )ru   inputs_embedsrZ    FT)NN)r   r   r   c              3   &   K   | ]	  }||  y wr2   r   .0vs     r*   	<genexpr>z,BlenderbotEncoder.forward.<locals>.<genexpr>R  s     eqWXWdes   last_hidden_stater   
attentions)ru   r   output_hidden_statesuse_return_dictr'   %warn_if_padding_and_no_attention_maskre   r   r   r   r   rh   r\   rd   r   	enumerater   r>   randr   r   r   r   )r5   r   rZ   r   r   r  return_dictr]   input_shape	embed_posr   encoder_statesall_attentionsidxencoder_layerto_dropdropout_probabilitylayer_outputss                     r*   rB   zBlenderbotEncoder.forward  s0   P 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--mt||VZVcVc-d2;;')
  40d"+DKK"8 	FC#!/=2B!BG}}&+jjn#&7"G , -!"&7! !.a 0 !/=3C2E!E-	F2 6+}.>>Ne]NN$Seee+>Vd
 	
r,   )NNNNNN)rE   rF   rG   rH   r   r4   rB   rL   rM   s   @r*   r   r     s/    / 8 !m
r,   r   c                   f     e Zd ZdZdef fdZ	 	 	 	 	 	 	 	 	 	 	 ddej                  dz  fdZ x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
    ru   c           	         t         |   |       |j                  | _        |j                  | _        |j
                  | _        |j                  | _        |j                  rt        j                  |j                        nd}t        |j                  |j                  | j                  |      | _        t!        |j                  |j                        | _        t%        j&                  t)        |j*                        D cg c]  }t-        ||       c}      | _        t%        j0                  |j                        | _        d| _        | j7                          y c c}w )NrT   r   )rv   F)r3   r4   r\   decoder_layerdropr   r    rP   r   max_target_positionsr   r   r   r   rO   r   r   r.   r   r   r   r   decoder_layersr   r   r   r   r   r   )r5   ru   rQ   ir6   s       r*   r4   zBlenderbotDecoder.__init__a  s    ~~11!..$*$B$B!393I3Idii/s9v~~t/?/?[
  D**NN 
 mmBGH]H]B^_Q#Fa8_
 ,,v~~6&+# `s   ?ENr   c                    ||n| j                   j                  }|	|	n| j                   j                  }	||n| j                   j                  }|
|
n| j                   j                  }
|du |duz  rt        d      |$|}|j                  }|j                  d|d         }n-| |j                         dd }|dddddf   }nt        d      || j                  |      }| j                  r%| j                  r|rt        j                  d       d}|rd|b|| j                   j                  r4t        t!        | j                         t!        | j                               nt!        | j                         }|j                         dd \  }}||j#                         nd}|%t%        j&                  |||z   |j(                  	      }|1t+               s'||z   }t%        j,                  |||j(                  	      }t/        |t              r|j0                  n|}t3        | j                   ||||
      }t5        | j                   |||      }| j7                  ||f||      }||z   }t8        j:                  j=                  || j<                  | j                        }|	rdnd}|rdnd}|r|dnd}t?        | j@                        D ]k  \  }}|	r||fz  }| j                  r%t%        jB                  g       }|| jD                  k  r? |||||||||      }|d   }|sW||d   fz  }|c||d   fz  }m | jG                  |      }|	r||fz  }|
stI        d |||||fD              S tK        |||||      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)
            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)
            past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
                It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

                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.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer#   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsz[`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`...F)ru   r   r   )ru   r   rZ   r   r   )ru   r   rZ   r   )r9   rb   r   )r   r   r   r   r   r   r;   c              3   $   K   | ]  }|| 
 y wr2   r   r   s     r*   r  z,BlenderbotDecoder.forward.<locals>.<genexpr>4  s      = s   )r  r   r   r  cross_attentions)&ru   r   r  r   r  r'   r%   r   re   r   r   rd   rz   r{   is_encoder_decoderr   r
   get_seq_lengthr>   r?   r=   r   onesr   r   r   r   r   r   rh   r\   r
  r   r  r   r   r   r   )r5   r   rZ   r   r   r   r   r   r   r  r  r   r]   inputr  
batch_size
seq_lengthr8   mask_seq_lengthself_attn_cachecausal_maskr9   r   all_hidden_statesall_self_attnsall_cross_attentionsr  decoder_layerr  r  s                                 r*   rB   zBlenderbotDecoder.forwardz  s   H 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B] -t";<stt"E++K!r;r?;I&',,.s3K!!Q(+Edee  --e4M&&4==##q "	 0 )48V8V $L$DlZ^ZeZeFfg!5  "/!3!3!5cr!:
JETE`!?!?!Afg!"\\&(>(KTaThThN !*B*D4zAO"ZZ
OML`L`aN /+>? 00  	 );;'))+
 ";;;'1"7	"
 ++$&<> , 
 &4--mt||VZVcVc-d #7BD0d&7<Q<]rdh"+DKK"8 	@C#!m%55!}}&+jjn#&7)%'= /"3#-	M *!,M =#3"55(4(]1-=,??(3	@8 6  -!11 ':K^]qr  
 9+++%1
 	
r,   )NNNNNNNNNNN)
rE   rF   rG   rH   r   r4   r>   rK   rB   rL   rM   s   @r*   r  r  X  sR    / 6 "#!.2E
 t+E
r,   r  c                       e Zd ZdddZdef fdZd Zd Ze	 	 	 	 	 	 	 	 	 	 	 	 	 dde	j                  dz  d	e	j                  dz  d
e	j                  dz  de	j                  dz  deez  dz  dedz  de	j                  dz  de	j                  dz  dedz  dedz  dedz  dedz  de	j                  dz  dee	j                     ez  fd       Z xZS )BlenderbotModelzshared.weight)zencoder.embed_tokens.weightzdecoder.embed_tokens.weightru   c                 J   t         |   |       |j                  |j                  }}|j                  rt        j                  |j                        nd}t        ||j                  ||      | _	        t        |      | _        t        |      | _        | j                          y )NrT   r   )r3   r4   r    r   r   r   r   r   rO   sharedr   encoderr  decoderr   )r5   ru   rP   r   rQ   r6   s        r*   r4   zBlenderbotModel.__init__I  s}     "("5"5v7H7HZ393I3Idii/s3JP[itu(0(0 	r,   c                     | j                   S r2   )r0  r5   s    r*   get_input_embeddingsz$BlenderbotModel.get_input_embeddingsU  s    {{r,   c                 ~    || _         | j                   | j                  _        | j                   | j                  _        y r2   )r0  r1  r   r2  r5   rY   s     r*   set_input_embeddingsz$BlenderbotModel.set_input_embeddingsX  s)    $(KK!$(KK!r,   Nr   rZ   r   decoder_attention_maskencoder_outputsr   r   decoder_inputs_embedsr   r   r  r  r   r   c                    |
|
n| j                   j                  }
||n| j                   j                  }|	|	n| j                   j                  }	||n| j                   j                  }|| j                  ||||
||      }nI|rGt        |t              s7t        |d   t        |      dkD  r|d   ndt        |      dkD  r|d   nd      }| j                  |||d   ||||	|
|||      }|s||z   S t        |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                        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.

        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   rZ   r   r   r  r  r   r   r;   r  r   rZ   r   r   r   r   r   r   r  r  r   )r  r   decoder_hidden_statesdecoder_attentionsr  encoder_last_hidden_stater   encoder_attentions)ru   r   r  r   r  r1  r   r   lenr2  r   r  r   r   r  r  )r5   r   rZ   r   r9  r:  r   r   r;  r   r   r  r  r   r]   decoder_outputss                   r*   rB   zBlenderbotModel.forward]  s   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]""ll#-+"3%9' + O O_!M-"1!"4474H14Loa0RV14_1E1I?1-tO ,,'1"1!"4#1+//!5#) ' 
 "_44!-??+;;"1"?"?.99,==&5&G&G"1"?"?.99	
 		
r,   )NNNNNNNNNNNNN)rE   rF   rG   _tied_weights_keysr   r4   r5  r8  r   r>   
LongTensorrK   r   r   r	   FloatTensorr   r   rB   rL   rM   s   @r*   r.  r.  B  sw    (7'6

/ 
0
  .2.259:>:>(,-1:>!%)-,0#'.2d
##d*d
 t+d
 !++d2	d

 !& 0 04 7d
 047d
 d
 ||d*d
  %0047d
 $;d
  $;d
 #Tkd
 D[d
 t+d
  
u  	!$6	6!d
 d
r,   r.  z\
    The Blenderbot Model with a language modeling head. Can be used for summarization.
    )custom_introc            !           e Zd ZdZdgZddiZdef fdZ	 dded	edz  d
e	de
j                  f fdZdeddfdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddej                   dz  dej"                  dz  dej                   dz  dej                   dz  deez  dz  dedz  dej"                  dz  dej*                  dz  dej                   dz  de	dz  de	dz  de	dz  de	dz  dej"                  dz  deej*                     ez  fd       Z xZS )r   r   r   lm_head.weightzmodel.shared.weightru   c                 x   t         |   |       t        |      | _        | j	                  dt        j                  d| j                  j                  j                  f             t        j                  |j                  | j                  j                  j                  d      | _        | j                          y )Nr   r   Frx   )r3   r4   r.  r   register_bufferr>   zerosr0  r/   r   r|   r   lm_headr   r   s     r*   r4   z+BlenderbotForConditionalGeneration.__init__  s     $V,
0%++q$**BSBSBbBb>c2deyy1B1B1Q1QX]^ 	r,   Nnew_num_tokenspad_to_multiple_ofmean_resizingr   c                 z    t         |   |||      }| j                  |j                  j                  d          |S )Nr   )r3   resize_token_embeddings_resize_final_logits_biasrA   r%   )r5   rN  rO  rP  new_embeddingsr6   s        r*   rR  z:BlenderbotForConditionalGeneration.resize_token_embeddings  s?     8I[]jk&&~'<'<'B'B1'EFr,   c                 6   | j                   j                  d   }||k  r| j                   d d d |f   }nSt        j                  d||z
  f| j                   j                        }t        j
                  | j                   |gd      }| j                  d|       y )Nr#   r   r   r`   r   )r   r%   r>   rL  r=   catrK  )r5   rN  old_num_tokensnew_bias
extra_biass        r*   rS  z<BlenderbotForConditionalGeneration._resize_final_logits_bias  s    //55b9^+--a..@AHa.)H%IRVRhRhRoRopJyy$"8"8*!E1MH0(;r,   r   rZ   r   r9  r:  r   r   r;  labelsr   r   r  r  r   c                    ||n| j                   j                  }|	R|
rt        j                  d       d}
|7|5t	        |	| j                   j
                  | j                   j                        }| j                  |||||||||
||||      }| j                  |d         | j                  z   }d}|	Ft               } ||j                  d| j                   j                        |	j                  d            }|s|f|dd z   }||f|z   S |S t        |||j                  |j                  |j                   |j"                  |j$                  |j&                  |j(                  	      S )	a4  
        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.
        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)rZ   r   r:  r9  r   r   r;  r   r   r  r  r   r   r#   r   )	losslogitsr   r>  r?  r  r@  r   rA  )ru   r  rz   warningr+   r    r!   r   rM  r   r   r   r   r   r   r>  r?  r  r@  r   rA  )r5   r   rZ   r   r9  r:  r   r   r;  rZ  r   r   r  r  r   r]   r   	lm_logitsmasked_lm_lossloss_fctoutputs                        r*   rB   z*BlenderbotForConditionalGeneration.forward  s   N &1%<k$++B]B]klI (-B-J$6DKK44dkk6X6X%! **)/+#9+'"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,   )NT)NNNNNNNNNNNNNN)rE   rF   rG   r   _keys_to_ignore_on_load_missingrD  r   r4   rI   r   r   	EmbeddingrR  rS  r   r>   rE  rK   r   r   r	   rF  r   rB   rL   rM   s   @r*   r   r     s     ':&;#//  ae!7:TzY]	< < <  .2.259:>:>(,-1:>*.!%)-,0#'.2u
##d*u
 t+u
 !++d2	u

 !& 0 04 7u
 047u
 u
 ||d*u
  %0047u
   4'u
 $;u
  $;u
 #Tku
 D[u
 t+u
" 
u  	!O	3#u
 u
r,   r   c                   (     e Zd ZdZ fdZd Z x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                 d    t         |   |       t        |      | _        | j	                          y r2   )r3   r4   r  r2  r   r   s     r*   r4   z!BlenderbotDecoderWrapper.__init__j  s&     (0r,   c                 &     | j                   |i |S r2   )r2  )r5   argsr]   s      r*   rB   z BlenderbotDecoderWrapper.forwardo  s    t||T,V,,r,   )rE   rF   rG   rH   r4   rB   rL   rM   s   @r*   rf  rf  d  s    

-r,   rf  c                       e Zd ZddiZ fdZd Zd Ze	 	 	 	 	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dedz  dej                  dz  dej                  dz  dedz  dedz  dedz  dedz  dej                  dz  deej                  z  deez  fd       Z xZS )BlenderbotForCausalLMrI  z!model.decoder.embed_tokens.weightc                     d|_         d|_        t        |   |       t	        |      | _        t        j                  |j                  |j                  d      | _
        | j                          y )NTFrx   )rr   r   r3   r4   rf  r   r   r|   hidden_sizer   rM  r   r   s     r*   r4   zBlenderbotForCausalLM.__init__y  sX     $)! -f5
yy!3!3V5F5FUS 	r,   c                 B    | j                   j                  j                  S r2   r   r2  r   r4  s    r*   r5  z*BlenderbotForCausalLM.get_input_embeddings  s    zz!!...r,   c                 :    || j                   j                  _        y r2   ro  r7  s     r*   r8  z*BlenderbotForCausalLM.set_input_embeddings  s    */

'r,   Nr   rZ   r   r   r   r   rZ  r   r   r  r  r   logits_to_keepr   c                    |	|	n| j                   j                  }	|
|
n| j                   j                  }
||n| j                   j                  }| j                  j                  ||||||||	|
||      }|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|a|j                  |j                        }t               } ||j                  d| j                   j                        |j                  d            }|s|f|dd z   }||f|z   S |S t        |||j                   |j"                  |j$                  |j&                        S )ah  
        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")
        >>> 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   r   r  r  )ru   r   r  r  r   r2  r   rI   slicerM  tor=   r   r   r   r   r   r   r  r  )r5   r   rZ   r   r   r   r   rZ  r   r   r  r  r   rq  r]   r   r   slice_indicesr]  r\  ra  rb  s                         r*   rB   zBlenderbotForCausalLM.forward  s   R 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] **$$)"7#9+'/!5#) % 
  
8B>SV8W~ot4]kmA}a,?@AYYv}}-F')HFKKDKK,B,BCV[[QS_UDY,F'+'7D7V#CVC0#33!//))$55
 	
r,   )NNNNNNNNNNNNr   )rE   rF   rG   rD  r4   r5  r8  r   r>   rE  rK   rF  r	   r   rI   r   r   rB   rL   rM   s   @r*   rk  rk  t  se   =	/0  .2.2:>;?(,26*.!%)-,0#'26-.S
##d*S
 t+S
  %0047	S

 !& 1 1D 8S
 S
 ((4/S
   4'S
 $;S
  $;S
 #TkS
 D[S
 ((4/S
 ell*S
  
2	2!S
 S
r,   rk  )rk  r   r.  r   )Nr   )CrH   r   collections.abcr   r>   r   torch.nnr    r   r   activationsr   cache_utilsr	   r
   r   
generationr   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   configuration_blenderbotr   
get_loggerrE   rz   rK   rI   r+   rd  r.   rO   ModulerU   rm   ro   r   r   r   r   r  r.  r   rf  rk  __all__r   r,   r*   <module>r     s       $   % & ! C C ) J B 9  G &  7 
		H	%%,, c [^  -2<< -*
=BLL 
=( !%II%<<% 
% <<	%
 LL4'% T\% % '(%:z)")) z)|8+7 8+xh7 hV   4Q
1 Q
hg
1 g
T 
/ 
 
D 
V
)BO V

V
t-8 - j
5 j
Zr,   