
    %	&h                       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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' ddl(m)Z)  e%       rddl*m+Z+ ddl,m-Z-  e       rddlm.Z.  e&j^                  e0      Z1dZ2dZ3g dZ4dZ5dZ6dZ7 G d dejp                        Z9 G d dejt                        Z; G d de;      Z< G d  d!e;      Z=e;e<e=d"Z> G d# d$ejt                        Z?d%Z@ e#d&e@       G d' d(e              ZAd)ZB G d* d+eA      ZC e#d&e@       G d, d-eA             ZD G d. d/eAe      ZE e#d0e@       G d1 d2eA             ZF e#d3e@       G d4 d5eA             ZGg d6ZHy)7zPyTorch OPT model.    )ListOptionalTupleUnionN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPast)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_torch_flex_attn_availableloggingreplace_return_docstrings   )	OPTConfig)	BlockMask)make_flex_block_causal_mask)_flash_attention_forwardzfacebook/opt-350mr    )r      i   zArthurZ/opt-350m-dummy-scg\(\?z	'LABEL_0'c                   x     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                 N    d| _         t        | 	  || j                   z   |       y N   )offsetsuper__init__)selfr'   r(   	__class__s      z/var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/opt/modeling_opt.pyr.   z&OPTLearnedPositionalEmbedding.__init__N   s$     $++5}E    attention_maskpast_key_values_lengthposition_idsc                     |8t        j                  |d      }||z  dz
  j                         }|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/   r3   r4   r5   r0   s       r1   r<   z%OPTLearnedPositionalEmbedding.forwardT   s^      <<A>L(>9A=CCEL'+A+B(BCLw|dkk9::r2   r   N)__name__
__module____qualname____doc__intr.   r9   
LongTensorr   r<   __classcell__r0   s   @r1   r&   r&   I   s]    Fs F3 F '(37	;((; !$; u//0	; ;r2   r&   c                   H    e Zd ZdZ	 ddedee   f fdZ	 	 	 	 	 	 dd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                     de
ej                  eej                     ee   f   fdZ xZS )OPTAttentionz=Multi-headed attention from 'Attention Is All You Need' paperconfig	layer_idxc                    t         |           || _        |j                  | _        |j
                  | _        |j                  | _        |j                  | _	        || _
        |-t        j                  d| j                  j                   d       | j                  | j                  z  | _        d| _        | j                  | j                  z  | j                  k7  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                        | _        y )	NzInstantiating z without passing a `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.Tz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      ࿩bias)r-   r.   rH   hidden_size	embed_dimnum_attention_heads	num_headsattention_dropoutdropoutenable_biasrI   loggerwarning_oncer0   r>   head_dim	is_causal
ValueErrorscalingr   Lineark_projv_projq_projout_proj)r/   rH   rI   kwargsr0   s       r1   r.   zOPTAttention.__init__h   s    	++33//!--" !8!8 9 :, , $..8MMDNN*t~~=MdnnM]$T^^$4B8  }}d*iiTEUEUViiTEUEUViiTEUEUV		$..$..tGWGWXr2   hidden_statespast_key_valuer3   layer_head_maskoutput_attentionsr5   cache_positionreturnc                 l   |j                         \  }}	}
| j                  |      | j                  z  }|j                  |d| j                  | j
                        j                  dd      }| j                  |      }| j                  |      }|j                  |d| j                  | j
                        j                  dd      }|j                  |d| j                  | j
                        j                  dd      }|#|j                  ||| j                  d|i      \  }}t        j                  ||j                  dd            }|#|ddddddd|j                  d   f   }||z   }t        j                  j!                  |dt        j"                        j%                  |j&                        }|_|j                         | j                  fk7  r*t)        d	| j                  f d
|j                                |j                  dddd      |z  }t        j                  j+                  || j*                  | j,                        }t        j                  ||      }|j                  dd      j/                         }|j1                  ||	| j2                        }| j5                  |      }|||fS )#Input shape: Batch x Time x Channelr   r+   Nrd   r   )r8   dtypez/Head mask for a single layer should be of size z	, but is ptraining)sizer]   rY   viewrP   rV   	transposer[   r\   updaterI   r9   matmulshaper   
functionalsoftmaxfloat32torj   rX   rR   rm   
contiguousreshaperN   r^   )r/   r`   ra   r3   rb   rc   r5   rd   bsztgt_len_query_states
key_statesvalue_statesattn_weightscausal_mask
attn_probsattn_outputs                     r1   r<   zOPTAttention.forward   s}    (,,.Wa {{=1DLL@#((b$..$--PZZ[\^_`[[/
{{=1__S"dnndmmLVVWXZ[\
#((b$..$--PZZ[\^_`%'5'<'<L$..;K^:\($J ||L*2F2Fq!2LM%(Aq2HJ4D4DR4H2H)HIK'+5L }},,\r,WZZ[g[m[mn&##%$..):: Et~~FWEX Y',,./1  +//2q!<|KL]]**<4<<RVR_R_*`
ll:|<!++Aq1<<> "))#wGmmK0J66r2   NNNNFNN)r>   r?   r@   rA   r    r   rB   r.   r9   Tensorr   boolr   r<   rD   rE   s   @r1   rG   rG   e   s    G
 $(!Y!Y C=!YL 9=1526"'/31577||77 !u||!4577 !.	77
 "%,,/77  77 u||,77 !.77 
u||Xell3Xe_D	E77r2   rG   c                   N    e Zd ZdZ fdZ	 	 	 	 	 	 dd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                     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        |   |i | t               | _        y r   )r-   r.   r   _flash_attn_uses_top_left_mask)r/   argsr_   r0   s      r1   r.   zOptFlashAttention2.__init__   s#    $)&)
 /P.Q+r2   r`   ra   r3   rb   rc   r5   rd   re   c                     |j                         \  }}	}
| j                  |      }|j                  |d| j                  | j                        }| j                  |      }| j                  |      }|j                  |d| j                  | j                        j                  dd      }|j                  |d| j                  | j                        j                  dd      }|#|j                  ||| j                  d|i      \  }}| j                  r| j                  nd}|j                  dd      }|j                  dd      }|j                  }|t        j                  k(  rt        j                         rt        j                          }nMt#        | j$                  d      r| j$                  j&                  }n | j                  j(                  j                  }t*        j-                  d| d	       |j/                  |      }|j/                  |      }|j/                  |      }t1        |||||	||| j2                  | j4                  
	      }|j7                  ||	| j                  | j                  z        }| j9                  |      }|sd}|||fS )rg   rh   r   r+   Nrd           _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 .)r5   rR   rW   use_top_left_mask)rn   r]   ro   rP   rV   r[   r\   rp   rq   rI   rm   rR   rj   r9   rv   is_autocast_enabledget_autocast_gpu_dtypehasattrrH   r   weightrT   rU   rw   r#   rW   r   ry   r^   )r/   r`   ra   r3   rb   rc   r5   rd   rz   query_lengthr|   r}   r~   r   attn_dropoutinput_dtypetarget_dtyper   attn_weights_reshapeds                      r1   r<   zOptFlashAttention2.forward   sM     -113\1{{=1#((b$..$--P[[/
{{=1__S"dnndmmLVVWXZ[\
#((b$..$--PZZ[\^_`%'5'<'<L$..;K^:\($J (,}}t||#  ))!Q/
#--a3
 #((%--'((*$;;=&?@#{{BB#{{1177 >$ (??<8L#|4J'??<8L.% nn"AA

 !, 3 3Ct~~X\XeXeGe fmm$9: $(!1>AAr2   r   )r>   r?   r@   rA   r.   r9   r   r   r   r   r<   rD   rE   s   @r1   r   r      s    R 9=1526"'/315LB||LB !u||!45LB !.	LB
 "%,,/LB  LB u||,LB !.LB 
u||Xell3XeELL>Q5RR	SLBr2   r   c                   H    e Zd ZdZ	 	 	 	 	 	 dd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
                     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.
    r`   ra   r3   rb   rc   r5   rd   re   c                    |s|*t         j                  d       t        |   ||||||      S |j	                         \  }}	}
| j                  |      }|j                  |d| j                  | j                        j                  dd      }| j                  |      }| j                  |      }|j                  |d| j                  | j                        j                  dd      }|j                  |d| j                  | j                        j                  dd      }|#|j                  ||| j                  d|i      \  }}|}||d d d d d d d |j                  d   f   }||	dkD  rdnd	}t        j                   j"                  j%                  ||||| j&                  r| j(                  nd
|      }|j                  dd      j+                         }|j                  ||	d      }| j-                  |      }|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".)r`   r3   rb   ra   rc   rd   rh   r   r+   rd   ri   TFr   )	attn_mask	dropout_prW   )rT   rU   r-   r<   rn   r]   ro   rP   rV   rp   r[   r\   rq   rI   rs   r9   r   rt   scaled_dot_product_attentionrm   rR   rx   r^   )r/   r`   ra   r3   rb   rc   r5   rd   rz   q_lenr|   r}   r~   r   r   rW   r   r0   s                    r1   r<   zOPTSdpaAttention.forward*  s     ;e
 7?+- /-"3- #   &**,UA{{=1#((b$..$--PZZ[\^_`[[/
{{=1__S"dnndmmLVVWXZ[\
#((b$..$--PZZ[\^_`%'5'<'<L$..;K^:\($J %%%aA/E1A1A"1E/E&EFK (/EAID5	hh))FF!&*mmdll G 
 "++Aq1<<>!&&sE26mmK0D.00r2   r   )r>   r?   r@   rA   r9   r   r   r   r   r<   rD   rE   s   @r1   r   r   #  s     9=1526"'/315>1||>1 !u||!45>1 !.	>1
 "%,,/>1  >1 u||,>1 !.>1 
u||Xell3XeELL>Q5RR	S>1 >1r2   r   )eagerflash_attention_2sdpac                   j    e Zd Zddede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                     de	ej                  ee	ej                  ej                  f      f   fdZ xZS )OPTDecoderLayerrH   rI   c                    t         |           |j                  | _        t	        |j
                     ||      | _        |j                  | _        |j                  | _        t        |j                     | _        t        j                  | j                  |j                        | _        t        j                   | j                  |j"                  |j$                        | _        t        j                   |j"                  | j                  |j$                        | _        t        j                  | j                  |j                        | _        y )N)rH   rI   elementwise_affinerK   )r-   r.   rM   rN   OPT_ATTENTION_CLASSES_attn_implementation	self_attndo_layer_norm_beforerR   r   activation_functionactivation_fnr   	LayerNormlayer_norm_elementwise_affineself_attn_layer_normrZ   ffn_dimrS   fc1fc2final_layer_norm)r/   rH   rI   r0   s      r1   r.   zOPTDecoderLayer.__init__s  s    ++.v/J/JKSYeno$*$?$?!~~#F$>$>?$&LLNNv/S/S%
! 99T^^V^^&BTBTU99V^^T^^&BTBTU "T^^PVPtPt ur2   r`   r3   rb   ra   rc   	use_cacher5   rd   re   c	           	         |}	| j                   r| j                  |      }| j                  |||||||      \  }}
}t        j                  j                  || j
                  | j                        }|	|z   }| j                   s| j                  |      }|j                  }|j                  d|j                  d            }|}	| j                   r| j                  |      }| j                  |      }| j                  |      }| j                  |      }t        j                  j                  || j
                  | j                        }|	|z   j                  |      }| j                   s| j                  |      }|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
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence..
        )r`   ra   r5   r3   rb   rc   rd   rk   rh   )r   r   r   r   rt   rR   rm   rs   ry   rn   r   r   r   r   ro   )r/   r`   r3   rb   ra   rc   r   r5   rd   residualself_attn_weightspresent_key_valuehidden_states_shapeoutputss                 r1   r<   zOPTDecoderLayer.forward  s   : ! $$ 55mDM ?Cnn')%)+/) ?M ?
;(*; --mt||VZVcVc-d =0 (( 55mDM ,11%--b-2D2DR2HI  $$ 11-@M/**=9/--mt||VZVcVc-d!M1778KL (( 11-@M ")++G)++Gr2   r   )NNNFFNN)r>   r?   r@   r    r   rB   r.   r9   r   r   r   rC   FloatTensorr<   rD   rE   s   @r1   r   r   r  s   vy vXc] v( 26268<,1$)3715Q||Q !.Q "%,,/	Q
 !u||!45Q $D>Q D>Q u//0Q !.Q 
u  (51B1BEDUDU1U+V"WW	XQr2   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                   8    e Zd ZeZdZdZdgZdZdZ	dZ
dZdZd Zy)OPTPreTrainedModelmodelTr   c                    | j                   j                  }t        |t        j                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y y )Nr   )meanstd)rH   init_std
isinstancer   rZ   r   datanormal_rL   zero_	Embeddingpadding_idx)r/   moduler   s      r1   _init_weightsz OPTPreTrainedModel._init_weights  s    kk""fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .r2   N)r>   r?   r@   r    config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cacher    r2   r1   r   r     s@    
 L&*#*+!N  $!	?r2   r   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)

            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)
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                   <    e Zd ZdZdef fdZd Zd Z	 ddej                  dej                  dej                  d	e
d
ef
dZedej                  dededej                  dej                   dej                  defd       Z	 	 	 	 	 	 	 	 	 	 	 dde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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
    rH   c           	      8   t         |   |       |j                  | _        |j                  | _        |j                  | _        |j                  | _        |j                  | _        t        j                  |j                  |j                  | j
                        | _        t        |j                  |j                        | _        |j                  |j                  k7  r2t        j                   |j                  |j                  d      | _        nd | _        |j                  |j                  k7  r2t        j                   |j                  |j                  d      | _        nd | _        |j&                  r=|j(                  s1t        j*                  |j                  |j,                        | _        nd | _        t        j0                  t3        |j4                        D cg c]  }t7        ||       c}      | _        d| _        | j=                          y c c}w )NFrK   r   )rI   )r-   r.   rR   	layerdroppad_token_idr   max_position_embeddingsmax_target_positions
vocab_sizer   r   word_embed_proj_dimembed_tokensr&   rM   embed_positionsrZ   project_out
project_inr   _remove_final_layer_normr   r   r   
ModuleListrangenum_hidden_layersr   layersgradient_checkpointing	post_init)r/   rH   ir0   s      r1   r.   zOPTDecoder.__init__S  s    ~~))!..$*$B$B! ++LL):):F<V<VX\XhXhi<V=[=[]c]o]op%%););;!yy););V=W=W^cdD#D%%););; ii(B(BFDVDV]bcDO"DO
 &&v/N/N$&LL""v7[7[%D! %)D!mmSXY_YqYqSr$sa_Vq%I$st&+#	 %ts   Hc                     | j                   S r   r   r/   s    r1   get_input_embeddingszOPTDecoder.get_input_embeddingsx  s       r2   c                     || _         y r   r   r/   values     r1   set_input_embeddingszOPTDecoder.set_input_embeddings{  s
    !r2   r3   input_tensorrd   past_key_valuesrc   c           
         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r7t        |t        j
                        rt        |      }t        |t              r|S ||j                         nd}t        |t              }| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  |j                  }	}|j                  d   }
|r|j!                         }n1t        |t        j
                        r|j                  d   n||
z   dz   }| j#                  ||
|||	||j                  d   	      }| j                   j                  dk(  rQ|O|j                  j$                  d
v r7|s5t	        j&                  |      j(                  }t        j*                  ||      }|S )Nr   r   flex_attentionr   r   )inputs_embedsr4   is_trainingr   rh   )sequence_lengthtarget_lengthrj   devicerd   
batch_size)cudaxpu)rH   r   anyr   r9   r   r"   r!   get_seq_lengthr   r   _ignore_causal_mask_sdparm   rj   r   rs   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positiontypefinfomin_unmask_unattended)r/   r3   r   rd   r   rc   past_seen_tokensusing_static_cacherj   r   r   r   r   	min_dtypes                 r1   _update_causal_maskzOPTDecoder._update_causal_mask  s    ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L.)4%%
 @O?Z?99;`a'E ;;++v5>PYj%>>*'7 MM	 $**L,?,?v&,,Q/+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**o=%
 E*..I0CCKQZ[Kr2   r   r   rj   r   r   c                    | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||      }|dk7  rt        j
                  |d      }|t        j                  ||      |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }
|ddddddd|
f   | ddddddf   j                  |j                        z   }|dk(  }|ddddddd|
f   j                  ||	      |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to place the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuerj   r   r   )diagonalr   rh   r   )r8   r9   r  r  fulltriuarangery   expandcloners   rw   r   masked_fill)r3   r   r   rj   r   rd   r   r_   r   r  mask_lengthpadding_masks               r1   r  z@OPTDecoder._prepare_4d_causal_attention_mask_with_cache_position  sy   D %.*<*<*>!*C(K* ' E*..I** -0Ye\bK !##jjqA5<<fEH^H^_acdHeeeK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r2   	input_ids	head_maskr   r   output_hidden_statesreturn_dictr5   re   c                 F   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|	|	n| j                   j                  }	|du |duz  rt        d      | j                  r%| j                  r|rt        j                  d       d}||j                  d|j                  d         }|| j                  |      }d}|r>t        |t              s.d}t        j                   |      }|t        j                  d       ||j#                         nd}|2t%        j&                  |||j                  d	   z   |j(                  
      }|A||j                  d	   z   }t%        j*                  |j                  d   ||j(                  
      }| j-                  |||||      }|
8t%        j.                  |d	      }
|
|z  d	z
  j1                         }
|
dd|df   }
| j3                  |||
      }| j4                  | j5                  |      }||j7                  |j(                        z   }|rdnd}|rdnd}d}t9        |gdg      D ]j  \  }}|	|j;                         d   t=        | j>                        k7  s3t        d| dt=        | j>                         d|j;                         d    d       tA        | j>                        D ]  \  }}|r||fz  }| j                  r%t%        jB                  g       }|| jD                  k  r?| j                  r7| j                  r+| jG                  |jH                  |||||   ndd|||
|	      }n ||||
|||   nd||||      }|d   }|r	||rdnd	   }|s||d	   fz  } | jJ                  | jK                  |      }| jL                  | jM                  |      }|r||fz  }|r|nd}|r|jO                         }|	stQ        d ||||fD              S tS        ||||      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)
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
                this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
                the complete sequence length.
        Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Frh   TzPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.53.0. You should pass an instance of `DynamicCache` instead, e.g. `past_key_values=DynamicCache.from_legacy_cache(past_key_values)`.r   r   r  r7   )r5   r   r  zThe `z` should be specified for z layers, but it is for r   )r3   r5   rb   ra   rc   r   rd   r+   c              3   &   K   | ]	  }||  y wr   r   ).0vs     r1   	<genexpr>z%OPTDecoder.forward.<locals>.<genexpr>  s     tqfgfsts   last_hidden_stater   r`   
attentions)*rH   rc   r  r   use_return_dictrX   r   rm   rT   rU   ro   rs   r   r   r   r   from_legacy_cacher  r9   r  r   onesr  r:   r;   r   r   rw   ziprn   lenr   	enumeraterandr   _gradient_checkpointing_func__call__r   r   to_legacy_cachetupler   )r/   r  r3   r  r   r   r   rc   r  r  r5   rd   return_legacy_cacher
  
seq_lengthr   
pos_embedsr`   all_hidden_statesall_self_attnsnext_decoder_cacher   	mask_nameidxdecoder_layerdropout_probabilitylayer_outputs
next_caches                               r1   r<   zOPTDecoder.forward   s   L 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I !r9??2+>?I  --i8M#Z?"&*<<_MO&##Y @O?Z?99;`a!"\\ "2]5H5H5K"KTaThThN !)M,?,?,BBJ"ZZ(;(;A(>
S`SgSghN..M>?L]

  <<A>L(>9A=CCEL'+;+<(<=L)).:JYe)f
??& OOM:M%
m6J6J(KK #7BD0d! %(k]$C 	 Iy$>>#A&3t{{+;<$	{*DSEUDV W%NN,Q/03 	 #,DKK"8 (	6C#!m%55!}}&+jjn#&7**t}} $ A A!**!&/&;IcN% "
! !.!#.!-7@7LYs^RV#2&7'#1	! *!,M%28I1q%Q" =#3"55Q(	6T   , 11-@M' ,,];M  -!11+4'$
#335Jt]J@QSa$bttt&+&+%	
 	
r2   )FNNNNNNNNNNN)r>   r?   r@   rA   r    r.   r   r   r9   r   r   r   r  staticmethodrB   rj   r   r  r   rC   r   r   r   r   r   r<   rD   rE   s   @r1   r   r   K  s   #y #J!" #(DD llD 	D
 D  DL 777 7 {{	7
 7 7 7 7v 1515,0=A59$(,0/3&*3715R
E,,-R
 !.R
 ELL)	R

 "$u'8'8"9:R
   1 12R
 D>R
 $D>R
 'tnR
 d^R
 u//0R
 !.R
 
u--	.R
r2   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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j$                     deeef   fd              Z xZS )OPTModelrH   c                 d    t         |   |       t        |      | _        | j	                          y r   )r-   r.   r   decoderr   r/   rH   r0   s     r1   r.   zOPTModel.__init__  s&     !&)r2   c                 .    | j                   j                  S r   rC  r   r   s    r1   r   zOPTModel.get_input_embeddings  s    ||(((r2   c                 &    || j                   _        y r   rF  r   s     r1   r   zOPTModel.set_input_embeddings  s    $)!r2   c                     | j                   S r   )rC  r   s    r1   get_decoderzOPTModel.get_decoder      ||r2   )
checkpointoutput_typer   expected_outputr  r3   r  r   r   r   rc   r  r  r5   rd   re   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|	|	n| j                   j                  }	| j                  |||
|||||||	|      }|	s|S t        |j                  |j                  |j                  |j                        S )Nr  r3   r5   r  r   r   r   rc   r  r  rd   r$  )rH   rc   r  r   r'  rC  r   r%  r   r`   r&  )r/   r  r3   r  r   r   r   rc   r  r  r5   rd   decoder_outputss                r1   r<   zOPTModel.forward  s    * 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B] ,,)%+'/!5#) ' 
 ""&-??+;;)77&11	
 	
r2   r>  )r>   r?   r@   r    r.   r   r   rI  r   OPT_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr   r9   rC   r   r   r   r   r   r   r<   rD   rE   s   @r1   rA  rA    sR   
y )* ++?@&+$.	 1515,0=A59$(,0/3&*3715,
E,,-,
 !.,
 ELL)	,

 "$u'8'8"9:,
   1 12,
 D>,
 $D>,
 'tn,
 d^,
 u//0,
 !.,
 
u--	.,
 A,
r2   rA  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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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      | _        | j                          y NFrK   )
r-   r.   rA  r   r   rZ   r   r   lm_headr   rD  s     r1   r.   zOPTForCausalLM.__init__"  sK     f%
 yy!;!;V=N=NUZ[ 	r2   c                 B    | j                   j                  j                  S r   r   rC  r   r   s    r1   r   z#OPTForCausalLM.get_input_embeddings,      zz!!...r2   c                 :    || j                   j                  _        y r   r[  r   s     r1   r   z#OPTForCausalLM.set_input_embeddings/      */

'r2   c                     | j                   S r   rY  r   s    r1   get_output_embeddingsz$OPTForCausalLM.get_output_embeddings2  rJ  r2   c                     || _         y r   r`  )r/   new_embeddingss     r1   set_output_embeddingsz$OPTForCausalLM.set_output_embeddings5  s	    %r2   c                 &    || j                   _        y r   r   rC  )r/   rC  s     r1   set_decoderzOPTForCausalLM.set_decoder8  s    $

r2   c                 .    | j                   j                  S r   rf  r   s    r1   rI  zOPTForCausalLM.get_decoder;  s    zz!!!r2   rL  r   r  r3   r  r   r   labelsr   rc   r  r  r5   rd   re   c                 F   ||n| j                   j                  }|	|	n| j                   j                  }	|
|
n| j                   j                  }
| j                  j                  |||||||||	|
|      }| j                  |d         j                         }d}|E|j                  |j                        } | j                  ||fd| j                   j                  i|}|
s|f|dd z   }||f|z   S |S t        |||j                  |j                  |j                        S )a4  
        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)
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
                this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
                the complete sequence length.

        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."
        ```NrO  r   r   r   losslogitsr   r`   r&  )rH   rc   r  r'  r   rC  rY  rx   rw   r   loss_functionr   r   r   r`   r&  )r/   r  r3   r  r   r   rj  r   rc   r  r  r5   rd   r_   r   rn  rm  outputs                     r1   r<   zOPTForCausalLM.forward>  s[   H 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] **$$)%+'/!5#) % 
 gaj)446YYv}}-F%4%%  ;;11 	D Y,F'+'7D7V#CVC%#33!//))
 	
r2   c                 J    d}| D ]  }|t        fd|D              fz  } |S )Nr   c              3   t   K   | ]/  }|j                  d j                  |j                               1 ywr=   )index_selectrw   r   )r!  
past_statebeam_idxs     r1   r#  z0OPTForCausalLM._reorder_cache.<locals>.<genexpr>  s.     nU_j--aZ=N=N1OPns   58)r1  )r   ru  reordered_past
layer_pasts    `  r1   _reorder_cachezOPTForCausalLM._reorder_cache  s=    ) 	Jncmnn N	 r2   NNNNNNNNNNNN)r>   r?   r@   _tied_weights_keysr.   r   r   ra  rd  rg  rI  r   r   rS  r   r9   rC   r   r   r   r   r   r   r<   r?  rx  rD   rE   s   @r1   rV  rV    s   *+/0&%" +AP_` 1515,0=A59-1$(,0/3&*3715O
E,,-O
 !.O
 ELL)	O

 "$u'8'8"9:O
   1 12O
 ))*O
 D>O
 $D>O
 'tnO
 d^O
 u//0O
 !.O
 
u,,	-O
 aO
b  r2   rV  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 )OPTForSequenceClassificationrH   c                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  | j                  d      | _        | j                          y rX  )
r-   r.   
num_labelsrA  r   r   rZ   r   scorer   rD  s     r1   r.   z%OPTForSequenceClassification.__init__  sT      ++f%
YYv994??QVW
 	r2   )rK  rL  r   rM  expected_lossr  r3   r  r   r   rj  r   rc   r  r  r5   re   c                    |
|
n| j                   j                  }
| j                  |||||||||	|

      }|d   }| j                  |      }||j                  dd \  }}n|j                  dd \  }}| j                   j
                  |dk7  rt        d      | j                   j
                  d}n||| j                   j
                  k7  j                  |j                  t        j                        }t        j                  |j                  d   |j                  t        j                        }||z  j                  d      }n.d}t        j                  | j                  j                    d	       |t        j                  ||j                  
      |f   }d}|| j                   j"                  | j$                  dk(  rd| j                   _        nl| j$                  dkD  rL|j&                  t        j(                  k(  s|j&                  t        j*                  k(  rd| j                   _        nd| j                   _        | j                   j"                  dk(  rIt-               }| j$                  dk(  r& ||j/                         |j/                               }n |||      }n| j                   j"                  dk(  r=t1               } ||j3                  d| j$                        |j3                  d            }n,| j                   j"                  dk(  rt5               } |||      }|
s|f|dd z   }||f|z   S |S t7        |||j8                  |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   r3   r5   r  r   r   rc   r  r  r   r+   r   z=Cannot handle batch sizes > 1 if no padding token is defined.rh   )r   rj   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r  
regressionsingle_label_classificationmulti_label_classificationrl  )rH   r'  r   r  rs   r   rX   rw   r   r9   int32r  argmaxrT   rU   r0   r>   problem_typer~  rj   r;   rB   r
   squeezer	   ro   r   r   r   r`   r&  )r/   r  r3   r  r   r   rj  r   rc   r  r  r5   transformer_outputsr`   rn  r   r   last_non_pad_tokennon_pad_masktoken_indicespooled_logitsrm  loss_fctrp  s                           r1   r<   z$OPTForSequenceClassification.forward  s   8 &1%<k$++B]B]"jj+)%'/!5# ) 
 ,A.M* *3//"1*='J*7*=*=bq*A'J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||Jv}}MOaab{{''/??a'/;DKK,__q(fllejj.HFLL\a\e\eLe/LDKK,/KDKK,{{''<7"9??a'#M$9$9$;V^^=MND#M6:D))-JJ+- 2 22t GUWY))-II,.v6#%(;AB(??F)-)9TGf$EvE/ /??-;;*55
 	
r2   c                 B    | j                   j                  j                  S r   r[  r   s    r1   r   z1OPTForSequenceClassification.get_input_embeddingsY  r\  r2   c                 :    || j                   j                  _        y r   r[  r   s     r1   r   z1OPTForSequenceClassification.set_input_embeddings\  r^  r2   r>  )r>   r?   r@   r    r.   r   rQ  r   '_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATIONr   rS  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSr   r9   rC   r   r   r   r   r   r<   r   r   rD   rE   s   @r1   r|  r|    sh    y  ++?@:4$2. 156:15@D59-1$(,0/3&*37\
E,,-\
 !!2!23\
 E--.	\

 "%ell(;"<=\
   1 12\
 ))*\
 D>\
 $D>\
 'tn\
 d^\
 u//0\
 
u66	7\
 A\
|/0r2   r|  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 )OPTForQuestionAnsweringrH   c                     t         |   |       t        |      | _        t	        j
                  |j                  d      | _        | j                          y r*   )	r-   r.   rA  r   r   rZ   r   
qa_outputsr   rD  s     r1   r.   z OPTForQuestionAnswering.__init__h  s@     f%
))F$>$>B 	r2   ri  r  r3   r  r   r   start_positionsend_positionsr   rc   r  r  r5   re   c                    ||n| j                   j                  }| j                  ||||||||	|
|
      }|d   }| j                  |      }|j	                  dd      \  }}|j                  d      j                         }|j                  d      j                         }d}||t        |j                               dkD  r|j                  d      }t        |j                               dkD  r|j                  d      }|j                  d      }|j                  d|      j                  |j                        }|j                  d|      j                  |j                        }t        |      } |||      } |||      }||z   dz  }|s||f|dd z   }||f|z   S |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'
        ```Nr  r   r   rh   r7   )ignore_indexr+   )rm  start_logits
end_logitsr`   r&  )rH   r'  r   r  splitr  rx   r+  rn   clamprw   r   r	   r   r`   r&  )r/   r  r3   r  r   r   r  r  r   rc   r  r  r5   r  r`   rn  r  r  
total_lossignored_indexr  
start_lossend_lossrp  s                           r1   r<   zOPTForQuestionAnswering.forwardp  s   x &1%<k$++B]B]"jj+)%'/!5# ) 
 ,A./#)<<r<#: j#++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M-33A}EHHWO)//=ADDV]]SM']CH!,@J
M:H$x/14J"J/2Eab2IIF/9/EZMF*Q6Q+%!-;;*55
 	
r2   c                 B    | j                   j                  j                  S r   r[  r   s    r1   r   z,OPTForQuestionAnswering.get_input_embeddings  r\  r2   c                 :    || j                   j                  _        y r   r[  r   s     r1   r   z,OPTForQuestionAnswering.set_input_embeddings  r^  r2   ry  )r>   r?   r@   r    r.   r   rQ  r   r   rS  r   r9   rC   r   r   r   r   r   r<   r   r   rD   rE   s   @r1   r  r  `  sw   y  ++?@+GVef 156:15@D596:48$(,0/3&*37j
E,,-j
 !!2!23j
 E--.	j

 "%ell(;"<=j
   1 12j
 "%"2"23j
   0 01j
 D>j
 $D>j
 'tnj
 d^j
 u//0j
 
u22	3j
 g Aj
X/0r2   r  )rV  rA  r   r|  r  )IrA   typingr   r   r   r   r9   torch.utils.checkpointr   torch.nnr   r	   r
   activationsr   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   r   modeling_outputsr   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   configuration_optr    !torch.nn.attention.flex_attentionr!   integrations.flex_attentionr"   r#   
get_loggerr>   rT   rR  rS  rT  r  r  r  r   r&   ModulerG   r   r   r   r   OPT_START_DOCSTRINGr   rQ  r   rA  rV  r|  r  __all__r   r2   r1   <module>r     s    / /    A A ! ; ; ) i  .  )  !;J J 
		H	%)  &  +F ' ( ;BLL ;8]7299 ]7@[B [B|E1| E1R + cbii cL " W? ?	?.D NG
# G
T WC
! C
	C
Lx' xv  t0#5 t0t0n  {00 {0{0|r2   