
    g                    "   d Z ddlmZmZmZmZ ddlZddlZddlmZ ddl	m
Z
mZmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZmZmZ ddlmZ ddlmZmZmZmZm Z m!Z!m"Z" ddl#m$Z$  e            rddl%m&Z&  e!j'        e(          Z)dZ*dZ+g dZ,dZ-dZ.dZ/ G d dej0                  Z1 G d dej2                  Z3 G d de3          Z4 G d de3          Z5e3e4e5dZ6 G d d ej2                  Z7d!Z8 ed"e8           G d# d$e                      Z9d%Z: G d& d'e9          Z; ed"e8           G d( d)e9                      Z< G d* d+e9e          Z= ed,e8           G d- d.e9                      Z> ed/e8           G d0 d1e9                      Z?dS )2zPyTorch OPT model.    )ListOptionalTupleUnionN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)GenerationMixin)!_prepare_4d_causal_attention_mask*_prepare_4d_causal_attention_mask_for_sdpa)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPast)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )	OPTConfig)_flash_attention_forwardzfacebook/opt-350mr   )r      i   zArthurZ/opt-350m-dummy-scg\(\?z	'LABEL_0'c                   j     e Zd ZdZdedef fdZ	 	 ddej        ded	eej                 f fd
Z	 xZ
S )OPTLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    num_embeddingsembedding_dimc                 j    d| _         t                                          || j         z   |           d S N   )offsetsuper__init__)selfr"   r#   	__class__s      `/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/opt/modeling_opt.pyr)   z&OPTLearnedPositionalEmbedding.__init__H   s3     $+5}EEEEE    r   Nattention_maskpast_key_values_lengthposition_idsc                     |>t          j        |d          }||z  dz
                                  }|dd|df         }t                                          || j        z             S )z3`input_ids_shape` is expected to be [bsz x seqlen].Nr   dim)torchcumsumlongr(   forwardr'   )r*   r.   r/   r0   r+   s       r,   r7   z%OPTLearnedPositionalEmbedding.forwardN   sq      <A>>>L(>9A=CCEEL'+A+B+B(BCLww|dk9:::r-   r   N)__name__
__module____qualname____doc__intr)   r4   
LongTensorr   r7   __classcell__r+   s   @r,   r!   r!   C   s         Fs F3 F F F F F F '(37	; ;(; !$; u/0	; ; ; ; ; ; ; ; ; ;r-   r!   c                   j    e Zd ZdZ	 ddedef fdZdej        de	de	d	ej        fd
Z
	 	 	 	 	 	 ddej        deej                 deeej                          deej                 deej                 dedeej                 d	eej        eej                 eeej                          f         fdZ xZS )OPTAttentionz=Multi-headed attention from 'Attention Is All You Need' paperFconfig
is_decoderc                    t                                                       || _        |j        | _        |j        | _        |j        | _        |j	        | _	        | j        | j        z  | _
        d| _        | j
        | j        z  | j        k    r t          d| j         d| j         d          | j
        dz  | _        || _        t          j        | j        | j        | j	                  | _        t          j        | j        | j        | j	                  | _        t          j        | j        | j        | j	                  | _        t          j        | j        | j        | j	                  | _        d S )NTz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      ࿩bias)r(   r)   rC   hidden_size	embed_dimnum_attention_heads	num_headsattention_dropoutdropoutenable_biashead_dim	is_causal
ValueErrorscalingrD   r   Lineark_projv_projq_projout_proj)r*   rC   rD   kwargsr+   s       r,   r)   zOPTAttention.__init__b   sH    	+3/!-$.8MDN*t~==8dn 8 8%)^8 8 8   }d*$iTEUVVViTEUVVViTEUVVV	$.$.tGWXXXr-   tensorseq_lenbszreturnc                     |                     ||| j        | j                                      dd                                          S )Nr   r&   )viewrK   rO   	transpose
contiguous)r*   rY   rZ   r[   s       r,   _shapezOPTAttention._shape   s<    {{3GGQQRSUVWWbbdddr-   Nhidden_stateskey_value_statespast_key_valuer.   layer_head_maskoutput_attentionsr0   c                 d   |du}|                                 \  }	}
}|                     |          | j        z  }|r||d         }|d         }n>|rU|                     |                     |          d|	          }|                     |                     |          d|	          }n||                     |                     |          d|	          }|                     |                     |          d|	          }t          j        |d         |gd          }t          j        |d         |gd          }nT|                     |                     |          d|	          }|                     |                     |          d|	          }| j        r||f}|	| j	        z  d| j
        f} |                     ||
|	          j        | } |j        | } |j        | }|                     d          }t          j        ||                    dd                    }|                                 |	| j	        z  |
|fk    r2t          d|	| j	        z  |
|f d|                                            ||                                 |	d|
|fk    r+t          d	|	d|
|f d|                                            |                    |	| j	        |
|          |z   }t          j        |t          j        t          j        |j                  j        |j        
                    }|                    |	| j	        z  |
|          }|j        t          j        k    rJt,          j                            |dt          j                                      t          j                  }n!t,          j                            |d          }||                                 | j	        fk    r-t          d| j	        f d|                                            |                    dddd          |                    |	| j	        |
|          z  }|                    |	| j	        z  |
|          }|r=|                    |	| j	        |
|          }|                    |	| j	        z  |
|          }nd}t,          j                            || j        | j                  }t          j        ||          }|                                 |	| j	        z  |
| j
        fk    r5t          d|	| j	        |
| j
        f d|                                            |                    |	| j	        |
| j
                  }|                    dd          }|                    |	|
| j                  }|                     |          }|||fS )#Input shape: Batch x Time x ChannelNr   r   r&   r2   z$Attention weights should be of size z	, but is z!Attention mask should be of size device)r3   dtypez/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size ) sizerV   rR   ra   rT   rU   r4   catrD   rK   rO   r^   bmmr_   rQ   maxrY   finforl   minrk   float16r   
functionalsoftmaxfloat32torM   ro   reshaperI   rW   )r*   rb   rc   rd   r.   re   rf   r0   is_cross_attentionr[   tgt_len_query_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                        r,   r7   zOPTAttention.forward   s    .T9',,..Wa {{=11DL@ 	L."<'*J)!,LL 	LT[[1A%B%BBLLJ;;t{{3C'D'Db#NNLL'T[[%?%?SIIJ;;t{{='A'A2sKKLN1$5z#BJJJJ 9nQ&7%FANNNLL T[[%?%?SIIJ;;t{{='A'A2sKKL? 	8 ),7NDN*B>
Ct{{<#>>CZP$Z_j1
(|(*5//!$$yz/C/CAq/I/IJJ3#7'"JJJ*dn8LgW^7_ * * %%''* *  
 %""$$a'(BBB ta'8Rtt]k]p]p]r]rtt   (,,S$.'7SSVddL 9el5;|7I+J+J+NWcWjkkk L (,,S4>-A7GTTL ..=002U]0[[^^_d_lmmLL=0020FFL&##%%$.)::: 1t~FW 1 1',,..1 1   +//2q!<<|?P?PQTVZVdfmov?w?wwL',,S4>-A7GTTL 	)
 %1$5$5c4>7T[$\$\!055cDN6JGU\]]LL$(!]**<4<RVR_*``
i
L99#"6!OOO)CRVR_3` ) )$$&&) )  
 "&&sDNGT]SS!++Aq11 "))#wGGmmK001>AAr-   )FNNNNFN)r9   r:   r;   r<   r   boolr)   r4   Tensorr=   ra   r   r   r7   r?   r@   s   @r,   rB   rB   _   s       GG
 !Y YY Y Y Y Y Y Y:eU\ eC ec eel e e e e 488<1526"'/3xB xB|xB #5<0xB !u|!45	xB
 !.xB "%,/xB  xB u|,xB 
u|Xel3XeEL>Q5RR	SxB xB xB xB xB xB xB xBr-   rB   c                   0    e Zd ZdZ fdZ	 	 	 	 	 	 ddej        deej                 deeej                          deej                 d	eej                 d
e	deej                 deej        eej                 eeej                          f         fdZ
 xZS )OptFlashAttention2aB  
    OPT flash attention module. This module inherits from `OPTAttention` as the weights of the module stays untouched.
    The only required change would be on the forward pass where it needs to correctly call the public API of flash
    attention and deal with padding tokens in case the input contains any of them.
    c                 b     t                      j        |i | t                       | _        d S N)r(   r)   r   _flash_attn_uses_top_left_mask)r*   argsrX   r+   s      r,   r)   zOptFlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r-   NFrb   rc   rd   r.   re   rf   r0   r\   c                    |du}|                                 \  }	}
}
|                     |          }|r||d         }|d         }n>|rU|                     |                     |          d|	          }|                     |                     |          d|	          }n||                     |                     |          d|	          }|                     |                     |          d|	          }t          j        |d         |gd          }t          j        |d         |gd          }nT|                     |                     |          d|	          }|                     |                     |          d|	          }| j        r||f}|j        d         }|j        d         }|	                    |	|| j
        | j                  }|                    dd          	                    |	|| j
        | j                  }|                    dd          	                    |	|| j
        | j                  }| j        r| j        nd}|j        }|t
          j        k    rt          j                    rt          j                    }n3t'          | j        d	          r| j        j        }n| j        j        j        }t.                              d
| d           |                    |          }|                    |          }|                    |          }t5          |||||||| j        | j        	  	        }|                    |	|| j
        | j        z            }|                     |          }|sd}|||fS )rh   Nr   r   ri   r&   r2           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .)r0   rM   rP   use_top_left_mask)rp   rV   ra   rT   rU   r4   rq   rD   shaper^   rK   rO   r_   ro   rM   rl   ry   is_autocast_enabledget_autocast_gpu_dtypehasattrrC   r   weightloggerwarning_oncerz   r   rP   r   r{   rW   )r*   rb   rc   rd   r.   re   rf   r0   r|   r[   r~   r   r   r   query_lengthr}   attn_dropoutinput_dtypetarget_dtyper   r   s                        r,   r7   zOptFlashAttention2.forward  s    .T9!&&((	Q {{=11 	L."<'*J)!,LL 	LT[[1A%B%BBLLJ;;t{{3C'D'Db#NNLL'T[[%?%?SIIJ;;t{{='A'A2sKKLN1$5z#BJJJJ 9nQ&7%FANNNLL T[[%?%?SIIJ;;t{{='A'A2sKKL? 	8 ),7N#)!,"2& $((lDNDMZZ))!Q//44S'4>SWS`aa
#--a3388gt~W[Wdee'+}=t||#
 #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L.% n"A

 

 

 !, 3 3Ct~X\XeGe f fmm$9::  	)$(!1>AAr-   r   )r9   r:   r;   r<   r)   r4   r   r   r   r   r7   r?   r@   s   @r,   r   r      s/        X X X X X 488<1526"'/3fB fB|fB #5<0fB !u|!45	fB
 !.fB "%,/fB  fB u|,fB 
u|Xel3XeEL>Q5RR	SfB fB fB fB fB fB fB fBr-   r   c                   *    e Zd ZdZ	 	 	 	 	 	 ddej        deej                 deeej                          deej                 deej                 d	ed
eej                 deej        eej                 eeej                          f         f fdZ	 xZ
S )OPTSdpaAttentiona@  
    OPT sdpa attention module. This module inherits from `OPTAttention` as the weights of the module stays untouched.
    The only required change would be on the forward pass where it needs to correctly call the public API of sdpa
    attention and deal with padding tokens in case the input contains any of them.
    NFrb   rc   rd   r.   re   rf   r0   r\   c           	      n   |s|At                               d           t                                          ||||||          S |d u}|                                \  }	}
}|                     |          | j        z  }|                     |d|	          }|r||d         }|d         }n>|rU|                     |                     |          d|	          }|                     | 	                    |          d|	          }n||                     |                     |          d|	          }|                     | 	                    |          d|	          }t          j        |d         |gd          }t          j        |d         |gd          }nT|                     |                     |          d|	          }|                     | 	                    |          d|	          }| j        r||f}|}||d d d d d d d |j        d         f         }||
dk    rd	nd
}t          j        j                            ||||| j        r| j        nd|d          }|                    dd                                          }|                    |	|
d          }|                     |          }|d |fS )NzOPTModel is using SDPA attention, which currently does not support output_attentions=True.failing back to eager attention. remove warning using attn_implementation="eager".)rb   r.   re   rd   rf   rc   ri   r   r   r&   r2   r   TFr   g      ?)	attn_mask	dropout_prP   scale)r   r   r(   r7   rp   rV   rR   ra   rT   rU   r4   rq   rD   r   r   rw   scaled_dot_product_attentionro   rM   r_   r`   r^   rW   )r*   rb   rc   rd   r.   re   rf   r0   r|   r[   q_lenr~   r   r   r   causal_maskrP   r   r+   s                     r,   r7   zOPTSdpaAttention.forward}  s     	 ;e  
 77??+- /-"3!1 #    .T9%**,,UA{{=11DL@{{<S99  	L."<'*J)!,LL 	LT[[1A%B%BBLLJ;;t{{3C'D'Db#NNLL'T[[%?%?SIIJ;;t{{='A'A2sKKLN1$5z#BJJJJ 9nQ&7%FANNNLL T[[%?%?SIIJ;;t{{='A'A2sKKL? 	8 ),7N %%%aaaAAA/E1A"1E/E&EFK (/EAIIDD5	h)FF!&*m<dll  G 
 
 "++Aq11<<>>!&&sE266mmK00D.00r-   r   )r9   r:   r;   r<   r4   r   r   r   r   r7   r?   r@   s   @r,   r   r   v  s         488<1526"'/3X1 X1|X1 #5<0X1 !u|!45	X1
 !.X1 "%,/X1  X1 u|,X1 
u|Xel3XeEL>Q5RR	SX1 X1 X1 X1 X1 X1 X1 X1 X1 X1r-   r   )eagerflash_attention_2sdpac                   *    e Zd Zdef fdZ	 	 	 	 	 	 ddej        deej                 deej                 deeej                          d	ee	         d
ee	         deej
                 deej        eeej        ej        f                  f         fdZ xZS )OPTDecoderLayerrC   c                 @   t                                                       |j        | _        t	          |j                 |d          | _        |j        | _        |j        | _        t          |j
                 | _        t          j        | j        |j                  | _        t          j        | j        |j        |j                  | _        t          j        |j        | j        |j                  | _        t          j        | j        |j                  | _        d S )NT)rC   rD   elementwise_affinerF   )r(   r)   rH   rI   OPT_ATTENTION_CLASSES_attn_implementation	self_attndo_layer_norm_beforerM   r   activation_functionactivation_fnr   	LayerNormlayer_norm_elementwise_affineself_attn_layer_normrS   ffn_dimrN   fc1fc2final_layer_normr*   rC   r+   s     r,   r)   zOPTDecoderLayer.__init__  s    +.v/JKSYfjkkk$*$?!~#F$>?$&LNv/S%
 %
 %
! 9T^V^&BTUUU9V^T^&BTUUU "T^PVPt u u ur-   NFrb   r.   re   rd   rf   	use_cacher0   r\   c                    |}| j         r|                     |          }|                     ||||||          \  }}	}
t          j                            || j        | j                  }||z   }| j         s|                     |          }|j        }|                    d|	                    d                    }|}| j         r| 
                    |          }|                     |          }|                     |          }|                     |          }t          j                            || j        | j                  }||z                       |          }| j         s| 
                    |          }|f}|r||	fz  }|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`, *optional*): 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`, *optional*): 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.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
        )rb   rd   r0   r.   re   rf   rm   ri   )r   r   r   r   rw   rM   ro   r   r{   rp   r   r   r   r   r^   )r*   rb   r.   re   rd   rf   r   r0   residualself_attn_weightspresent_key_valuehidden_states_shapeoutputss                r,   r7   zOPTDecoderLayer.forward  s   4 ! $ 	E 55mDDM ?Cnn')%)+/ ?M ?
 ?
;(*; --mt|VZVc-dd =0 ( 	E 55mDDM ,1%--b-2D2DR2H2HII  $ 	A 11-@@M//**=99//--mt|VZVc-dd!M1778KLL ( 	A 11-@@M " 	,)++G 	,)++Gr-   )NNNFFN)r9   r:   r;   r   r)   r4   r   r   r   r   r>   FloatTensorr7   r?   r@   s   @r,   r   r     s%       vy v v v v v v( 26268<,1$)37M M|M !.M "%,/	M
 !u|!45M $D>M D>M u/0M 
u (51BEDU1U+V"WW	XM M M M M M M Mr-   r   aH  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`OPTConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zQThe bare OPT Model outputting raw hidden-states without any specific head on top.c                   .    e Zd ZeZdZdZdgZdZdZ	d Z
dS )OPTPreTrainedModelmodelTr   c                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rS|j        j                            d|           |j        -|j        j        |j                 	                                 d S d S d S )Nr   )meanstd)rC   init_std
isinstancer   rS   r   datanormal_rG   zero_	Embeddingpadding_idx)r*   moduler   s      r,   _init_weightsz OPTPreTrainedModel._init_weights^  s    k"fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r-   N)r9   r:   r;   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2_supports_sdpar    r-   r,   r   r   R  sJ        
 L&*#*+!N	? 	? 	? 	? 	?r-   r   aF  
    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)

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

            If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.
        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**.

        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.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_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.
        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.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`. for padding use -1.

            [What are position IDs?](../glossary#position-ids)
c                       e Zd ZdZdef fdZd Zd Z	 	 	 ddej	        de
eef         d	ed
eej	                 deej	                 dee         fdZ	 	 	 	 	 	 	 	 	 	 ddej        d
eej	                 deej	                 deeej                          deej                 dee         dee         dee         dee         deej                 dee
ef         fdZ xZS )
OPTDecoderz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`]

    Args:
        config: OPTConfig
    rC   c                    t                                                     j        | _        j        | _        j        | _        j        | _        j        | _        t          j
        j        j        | j                  | _        t          j        j                  | _        j        j        k    r't          j        j        j        d          | _        nd | _        j        j        k    r't          j        j        j        d          | _        nd | _        j        r-j        s&t          j        j        j                  | _        nd | _        t          j        fdt3          j                  D                       | _        j        dk    | _        j        dk    | _        d| _        |                                   d S )NFrF   r   c                 .    g | ]}t                    S r   )r   ).0r~   rC   s     r,   
<listcomp>z'OPTDecoder.__init__.<locals>.<listcomp>  s!    $f$f$f_V%<%<$f$f$fr-   r   r   )!r(   r)   rM   	layerdroppad_token_idr   max_position_embeddingsmax_target_positions
vocab_sizer   r   word_embed_proj_dimembed_tokensr!   rH   embed_positionsrS   project_out
project_inr   _remove_final_layer_normr   r   r   
ModuleListrangenum_hidden_layerslayersr   _use_flash_attention_2	_use_sdpagradient_checkpointing	post_initr   s    `r,   r)   zOPTDecoder.__init__  s      ~)!.$*$B! +L):F<VX\Xhii<V=[]c]opp%);;;!y);V=W^cdddD#D%);;; i(BFDV]bcccDOO"DO
 & 	)v/N 	)$&L"v7[% % %D!! %)D!m$f$f$f$feFLdFeFe$f$f$fgg&,&AEX&X#4>&+#r-   c                     | j         S r   r   r*   s    r,   get_input_embeddingszOPTDecoder.get_input_embeddings  s      r-   c                     || _         d S r   r   r*   values     r,   set_input_embeddingszOPTDecoder.set_input_embeddings  s    !r-   Ninputs_embedsinput_shaper/   r.   	head_maskrf   c                    |\  }}||z   }	| j         r.|d|v r|nd}
|t          j        ||	|j                  n|}|
|fS |t          j        ||	|j                  }n2|j        d         |	k    r!t          d|j        d          d|	 d          | j        r|s|t          ||||          }
nt          ||||          }
|
|fS )z:
        Updates the causal mask for the decoder.
        Nr   rj   r   z'The provided attention mask has length z, but its length should be z0 (sum of the lengths of current and past inputs))	r   r4   onesrk   r   rQ   r   r   r   )r*   r   r  r/   r.   r  rf   
batch_size
seq_lengthmask_seq_lengthcausal_attention_masks              r,   _update_causal_maskzOPTDecoder._update_causal_mask  sO    "-
J0:=& 		97E7QVW[iViViNNpt! ") 
:}?STTTT#  ).88!"Z
OML`aaaNN!!$77U.:Nq:Q U U"U U U   > 	"3 		8I$N]<R% %!! %F]<R% %! %n44r-   	input_idspast_key_valuesr   output_hidden_statesreturn_dictr0   r\   c                 *   ||n| j         j        }||n| j         j        }||n| j         j        }|	|	n| j         j        }	||t          d          |1|                                }|                    d|d                   }n.||                                dd         }nt          d          ||                     |          }||d         d         j	        d         nd}| 
                    ||||||          \  }}|
>t          j        |d          }
|
|z  dz
                                  }
|
dd|df         }
|                     |||
	          }| j        |                     |          }||z   }| j        r%| j        r|rt$                              d
           d}|rdnd}|rdnd}|rdnd}t)          |gdg          D ]z\  }}|s|                                d         t+          | j                  k    rCt          d| dt+          | j                   d|                                d          d          {t/          | j                  D ]\  }}|r||fz  }| j        r t          j        g           }|| j        k     r4|||         nd}| j        r3| j        r,|                     |j        |||||         ndd|||
          }n ||||
|||         nd|||          }|d         }|r|||rdnd         fz  }|r||d         fz  }| j        |                     |          }| j        |                     |          }|r||fz  }|r|nd}|	st=          d ||||fD                       S t?          ||||          S )a  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

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

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

                [What are attention masks?](../glossary#attention-mask)
            head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_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**.

            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

                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.
            position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
                config.n_positions - 1]`. for padding use -1.

                [What are position IDs?](../glossary#position-ids)
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timeri   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r&   r   r2   )r0   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r  zThe `z` should be specified for z layers, but it is for r   )r.   r0   re   rd   rf   r   c              3      K   | ]}||V  	d S r   r   )r   vs     r,   	<genexpr>z%OPTDecoder.forward.<locals>.<genexpr>  s(      ttqfgfsfsfsfsfsttr-   last_hidden_stater  rb   
attentions) rC   rf   r  r   use_return_dictrQ   rp   r^   r   r   r	  r4   r5   r6   r   r   r   ro   r   r   ziplenr   	enumeraterandr   _gradient_checkpointing_func__call__r   r   tupler   )r*   r
  r.   r  r  r   r   rf   r  r  r0   r  r/   r  
pos_embedsrb   all_hidden_statesall_self_attnsnext_decoder_cacher   	mask_nameidxdecoder_layerdropout_probabilityrd   layer_outputs
next_caches                              r,   r7   zOPTDecoder.forward  s   B 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]  ]%>sttt"#..**K!r;r?;;II&',,..ss3KKdeee  --i88MCRC^!3A!6!<Q!?!?de040H0H;(>PY[l1
 1
-~
  <A>>>L(>9A=CCEEL'+A+B+B(BCL)).:P_k)ll
?& OOM::M%
2& 	"4= 	" "##p   "	 #7@BBD0:d#,6RR$ %(k]$C$C 	 	 Iy$>>##A&3t{+;+;<<$3	 3 3SEUEU 3 3%NN,,Q/3 3 3  
 #,DK"8"8 (	6 (	6C# 6!m%55!} &+jnn#&775D5P_S11VZN* t}  $ A A!*!)&/&;IcNN% 	! 	! !.!#8!-7@7LYs^^RV#1&7'! ! ! *!,M V"}:K5RQQQR'S&UU"  6=#3"55 , 11-@@M' ,,];;M   	2-!11+4>''$
 	utt]J@QSa$btttttt&+&+%	
 
 
 	
r-   )NNN
NNNNNNNNNN)r9   r:   r;   r<   r   r)   r   r   r4   r   r   r=   r   r   r	  r>   r   r   r   r   r7   r?   r@   s   @r,   r   r     s        %y % % % % % %N! ! !" " " 26,0,0)5 )5|)5 38_)5 !$	)5
 !.)5 EL))5 $D>)5 )5 )5 )5Z '+15,0=A59$(,0/3&*37|
 |
#|
 !.|
 EL)	|

 "$u'8"9:|
   12|
 D>|
 $D>|
 'tn|
 d^|
 u/0|
 
u--	.|
 |
 |
 |
 |
 |
 |
 |
r-   r   c                       e Zd Zdef fdZd Zd Zd Z ee	           e
eeee          	 	 	 	 	 	 	 	 	 	 ddej        d	eej                 d
eej                 deeej                          deej                 dee         dee         dee         dee         deej                 deeef         fd                        Z xZS )OPTModelrC   c                     t                                          |           t          |          | _        |                                  d S r   )r(   r)   r   decoderr   r   s     r,   r)   zOPTModel.__init__  s@       !&))r-   c                     | j         j        S r   r+  r   r   s    r,   r   zOPTModel.get_input_embeddings  s    |((r-   c                     || j         _        d S r   r-  r   s     r,   r   zOPTModel.set_input_embeddings  s    $)!!!r-   c                     | j         S r   )r+  r   s    r,   get_decoderzOPTModel.get_decoder  
    |r-   )
checkpointoutput_typer   expected_outputNr
  r.   r  r  r   r   rf   r  r  r0   r\   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|	|	n| j         j        }	|                     |||
|||||||	
  
        }|	s|S t          |j        |j        |j	        |j
                  S )N
r
  r.   r0   r  r  r   r   rf   r  r  r  )rC   rf   r  r   r  r+  r   r  r  rb   r  )r*   r
  r.   r  r  r   r   rf   r  r  r0   decoder_outputss               r,   r7   zOPTModel.forward  s    ( 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B] ,,)%+'/!5# ' 
 
  	#""&-?+;)7&1	
 
 
 	
r-   r'  )r9   r:   r;   r   r)   r   r   r0  r   OPT_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr4   r>   r   r   r   r   r   r   r   r7   r?   r@   s   @r,   r)  r)    s       
y      ) ) )* * *   +*+?@@&+$.	   '+15,0=A59$(,0/3&*37*
 *
#*
 !.*
 EL)	*

 "$u'8"9:*
   12*
 D>*
 $D>*
 'tn*
 d^*
 u/0*
 
u--	.*
 *
 *
  A@*
 *
 *
 *
 *
r-   r)  c                       e Zd ZdgZ fdZd Zd Zd Zd Zd Z	d Z
 eee	          	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deeej                          deej                 deej                 dee         dee         dee         dee         deej                 deeef         fd            Zed             Z xZS )OPTForCausalLMzlm_head.weightc                     t                                          |           t          |          | _        t	          j        |j        |j        d          | _        | 	                                 d S NFrF   )
r(   r)   r)  r   r   rS   r   r   lm_headr   r   s     r,   r)   zOPTForCausalLM.__init__  sc       f%%
 y!;V=NUZ[[[ 	r-   c                 $    | j         j        j        S r   r   r+  r   r   s    r,   r   z#OPTForCausalLM.get_input_embeddings!      z!..r-   c                 (    || j         j        _        d S r   rB  r   s     r,   r   z#OPTForCausalLM.set_input_embeddings$      */
'''r-   c                     | j         S r   r@  r   s    r,   get_output_embeddingsz$OPTForCausalLM.get_output_embeddings'  r1  r-   c                     || _         d S r   rG  )r*   new_embeddingss     r,   set_output_embeddingsz$OPTForCausalLM.set_output_embeddings*  s    %r-   c                     || j         _        d S r   r   r+  )r*   r+  s     r,   set_decoderzOPTForCausalLM.set_decoder-  s    $
r-   c                     | j         j        S r   rM  r   s    r,   r0  zOPTForCausalLM.get_decoder0  s    z!!r-   r3  r   Nr
  r.   r  r  r   labelsr   rf   r  r  r0   r\   c                    ||n| j         j        }|	|	n| j         j        }	|
|
n| j         j        }
| j                            |||||||||	|

  
        }|                     |d                                                   }d}||                    |j	                  }|dddddf                                         }|dddf                                         }t                      } ||                    d| j         j                  |                    d                    }|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j                  S )a  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

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

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

                [What are attention masks?](../glossary#attention-mask)
            head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_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**.

            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)`. The two additional
                tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

                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.
            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]`.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_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.
            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.
            position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
                config.n_positions - 1]`. for padding use -1.

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

        Returns:

        Example:

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

        >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious. I'm just a little bit of a weirdo."
        ```Nr6  r   .ri   r   losslogitsr  rb   r  )rC   rf   r  r  r   r+  r@  r`   rz   rk   r	   r^   r   r   r  rb   r  )r*   r
  r.   r  r  r   rQ  r   rf   r  r  r0   r   rU  rT  shift_logitsshift_labelsloss_fctoutputs                      r,   r7   zOPTForCausalLM.forward3  s   | 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] *$$)%+'/!5# % 
 
 gaj))4466YYv}--F!#ssAAA+.99;;L!#qrr'?5577L'))H8L--b$+2HII<K\K\]_K`K`aaD 	DY,F'+'7D7V##VC%#3!/)
 
 
 	
r-   c                 T    d}| D ]!}|t          fd|D                       fz  }"|S )Nr   c              3   t   K   | ]2}|                     d                     |j                            V  3dS r8   )index_selectrz   rk   )r   
past_statebeam_idxs     r,   r  z0OPTForCausalLM._reorder_cache.<locals>.<genexpr>  sC      nnU_j--aZ=N1O1OPPnnnnnnr-   )r  )r  r^  reordered_past
layer_pasts    `  r,   _reorder_cachezOPTForCausalLM._reorder_cache  sQ    ) 	 	Jnnnncmnnnnn NN r-   NNNNNNNNNNN)r9   r:   r;   _tied_weights_keysr)   r   r   rH  rK  rN  r0  r   r   r:  r4   r>   r   r   r   r   r   r   r   r7   staticmethodra  r?   r@   s   @r,   r=  r=    s       *+    / / /0 0 0  & & &% % %" " " +AP_``` '+15,0=A59-1$(,0/3&*37H
 H
#H
 !.H
 EL)	H

 "$u'8"9:H
   12H
 )*H
 D>H
 $D>H
 'tnH
 d^H
 u/0H
 
u,,	-H
 H
 H
 a`H
T   \    r-   r=  a  
    The OPT Model transformer with a sequence classification head on top (linear layer).

    [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                       e Zd Zdef fdZ ee           eee	e
ee          	 	 	 	 	 	 	 	 	 	 	 ddeej                 deej                 deej                 deeeej                                   d	eej                 d
eej                 dee         dee         dee         dee         deej                 deee	f         fd                        Zd Zd Z xZS )OPTForSequenceClassificationrC   c                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S r?  )
r(   r)   
num_labelsr)  r   r   rS   r   scorer   r   s     r,   r)   z%OPTForSequenceClassification.__init__  sj        +f%%
Yv94?QVWWW
 	r-   )r2  r3  r   r4  expected_lossNr
  r.   r  r  r   rQ  r   rf   r  r  r0   r\   c                    |
|
n| j         j        }
|                     |||||||||	|

  
        }|d         }|                     |          }||j        dd         \  }}n|j        dd         \  }}| j         j        d}n|rt          j        || j         j                                                  	                    d          dz
  }||j        d         z  }|
                    |j                  }n)d}t                              | j        j         d           |t          j        ||j                  |f         }d}|Z| j         j        f| j        dk    rd	| j         _        nN| j        dk    r7|j        t          j        k    s|j        t          j        k    rd
| j         _        nd| j         _        | j         j        d	k    rWt+                      }| j        dk    r1 ||                                |                                          }n |||          }n| j         j        d
k    rGt/                      } ||                    d| j                  |                    d                    }n*| j         j        dk    rt3                      } |||          }|
s|f|dd         z   }||f|z   n|S t5          |||j        |j        |j                  S )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        N	r  r.   r0   r  r   r   rf   r  r  r   r&   ri   r   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rj   
regressionsingle_label_classificationmulti_label_classificationrS  )rC   r  r   ri  r   r   r4   eqr=   argmaxrz   rk   r   r   r+   r9   arangeproblem_typerh  rl   r6   r
   squeezer	   r^   r   r   r  rb   r  )r*   r
  r.   r  r  r   rQ  r   rf   r  r  r0   transformer_outputsrb   rU  r  sequence_lengthsequence_lengthspooled_logitsrT  rX  rY  s                         r,   r7   z$OPTForSequenceClassification.forward  s)   8 &1%<kk$+B]"jj+)%'/!5# ) 
 
 ,A.M** *3/"1"*='J*7*=bqb*A'J;#+!$#(8It{7O#P#P#T#T#V#V#]#]^`#a#ade#e #3iob6I#I #3#6#6v}#E#E  #% ##~. ^ ^ ^  
 u|Jv}MMMO__`{'/?a''/;DK,,_q((flej.H.HFL\a\eLeLe/LDK,,/KDK,{'<77"99?a''#8M$9$9$;$;V^^=M=MNNDD#8M6::DD)-JJJ+--x 2 22t G GUWYY)-III,..xv66 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r-   c                 $    | j         j        j        S r   rB  r   s    r,   r   z1OPTForSequenceClassification.get_input_embeddingsF  rC  r-   c                 (    || j         j        _        d S r   rB  r   s     r,   r   z1OPTForSequenceClassification.set_input_embeddingsI  rE  r-   rb  )r9   r:   r;   r   r)   r   r8  r   '_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATIONr   r:  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSr   r4   r>   r   r   r   r   r   r7   r   r   r?   r@   s   @r,   rf  rf    s        y       +*+?@@:4$2.   156:15@D59-1$(,0/3&*37[
 [
E,-[
 !!23[
 E-.	[

 "%el(;"<=[
   12[
 )*[
 D>[
 $D>[
 'tn[
 d^[
 u/0[
 
u66	7[
 [
 [
  A@[
z/ / /0 0 0 0 0 0 0r-   rf  z
    The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD
    (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       e Zd Zdef fdZ ee           eee	          	 	 	 	 	 	 	 	 	 	 	 	 dde
ej                 de
ej                 de
ej                 de
eeej                                   d	e
ej                 d
e
ej                 de
ej                 de
e         de
e         de
e         de
e         de
ej                 deeef         fd                        Zd Zd Z xZS )OPTForQuestionAnsweringrC   c                     t                                          |           t          |          | _        t	          j        |j        d          | _        |                                  d S r%   )	r(   r)   r)  r   r   rS   r   
qa_outputsr   r   s     r,   r)   z OPTForQuestionAnswering.__init__U  sX       f%%
)F$>BB 	r-   rP  Nr
  r.   r  r  r   start_positionsend_positionsr   rf   r  r  r0   r\   c                    ||n| j         j        }|                     ||||||||	|
|
  
        }|d         }|                     |          }|                    dd          \  }}|                    d                                          }|                    d                                          }d}||t          |                                          dk    r|                    d          }t          |                                          dk    r|                    d          }|                    d          }|	                    d|          
                    |j                  }|	                    d|          
                    |j                  }t          |          } |||          } |||          }||z   dz  }|s||f|dd         z   }||f|z   n|S t          ||||j        |j        	          S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, OPTForQuestionAnswering
        >>> import torch

        >>> torch.manual_seed(4)  # doctest: +IGNORE_RESULT
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")

        >>> # note: we are loading a OPTForQuestionAnswering from the hub here,
        >>> # so the head will be randomly initialized, hence the predictions will be random
        >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m")

        >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"

        >>> inputs = tokenizer(question, text, return_tensors="pt")
        >>> with torch.no_grad():
        ...     outputs = model(**inputs)

        >>> answer_start_index = outputs.start_logits.argmax()
        >>> answer_end_index = outputs.end_logits.argmax()

        >>> answer_offset = len(tokenizer(question)[0])

        >>> predict_answer_tokens = inputs.input_ids[
        ...     0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1
        ... ]
        >>> predicted = tokenizer.decode(predict_answer_tokens)
        >>> predicted
        ' a nice puppet'
        ```Nrl  r   r   ri   r2   )ignore_indexr&   )rT  start_logits
end_logitsrb   r  )rC   r  r   r  splitrt  r`   r  rp   clamprz   rk   r	   r   rb   r  )r*   r
  r.   r  r  r   r  r  r   rf   r  r  r0   ru  rb   rU  r  r  
total_lossignored_indexrX  
start_lossend_lossrY  s                           r,   r7   zOPTForQuestionAnswering.forward]  s;   x &1%<kk$+B]"jj+)%'/!5# ) 
 
 ,A.//#)<<r<#:#: j#++B//::<<''++6688

&=+D?''))**Q.."1"9"9""="==%%''((1,, - 5 5b 9 9(--a00M-33A}EEHHWWO)//=AADDV]SSM']CCCH!,@@Jx
M::H$x/14J 	R"J/2Eabb2IIF/9/EZMF**6Q+%!-;*5
 
 
 	
r-   c                 $    | j         j        j        S r   rB  r   s    r,   r   z,OPTForQuestionAnswering.get_input_embeddings  rC  r-   c                 (    || j         j        _        d S r   rB  r   s     r,   r   z,OPTForQuestionAnswering.set_input_embeddings  rE  r-   )NNNNNNNNNNNN)r9   r:   r;   r   r)   r   r8  r   r   r:  r   r4   r>   r   r   r   r   r   r7   r   r   r?   r@   s   @r,   r  r  M  s       y       +*+?@@+GVefff 156:15@D596:48$(,0/3&*37j
 j
E,-j
 !!23j
 E-.	j

 "%el(;"<=j
   12j
 "%"23j
   01j
 D>j
 $D>j
 'tnj
 d^j
 u/0j
 
u22	3j
 j
 j
 gf A@j
X/ / /0 0 0 0 0 0 0r-   r  )@r<   typingr   r   r   r   r4   torch.utils.checkpointr   torch.nnr   r	   r
   activationsr   
generationr   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   r   configuration_optr   modeling_flash_attention_utilsr   
get_loggerr9   r   r9  r:  r;  r{  r}  r|  r   r!   ModulerB   r   r   r   r   OPT_START_DOCSTRINGr   r8  r   r)  r=  rf  r  r   r-   r,   <module>r     s     / / / / / / / / / / / /            A A A A A A A A A A ! ! ! ! ! ! ) ) ) ) ) )                   . - - - - -                  ) ( ( ( ( (  KJJJJJJ 
	H	%	%)  &  +F ' ( ; ; ; ; ;BL ; ; ;8[B [B [B [B [B29 [B [B [B|vB vB vB vB vB vB vB vBr_1 _1 _1 _1 _1| _1 _1 _1F +  _ _ _ _ _bi _ _ _D " W ? ? ? ? ? ? ?	 ?(@ F\
 \
 \
 \
 \
# \
 \
 \
~ W A
 A
 A
 A
 A
! A
 A
	 A
Hq q q q q' q q qh   s0 s0 s0 s0 s0#5 s0 s0 s0l   {0 {0 {0 {0 {00 {0 {0 {0 {0 {0r-   