
    h                     
   d Z ddl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 dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZmZmZ ddlmZm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z( ddl)m*Z* ddl+m,Z,  e'       rddl-m.Z. ddl/m0Z0  e(jb                  e2      Z3 G d dejh                        Z5	 d3dejl                  dejn                  dejn                  dejn                  deejn                     de8de8fdZ9 G d  d!ejl                        Z: G d" d#e      Z;e% G d$ d%e              Z< G d& d'e<      Z=e% G d( d)e<             Z> G d* d+e<e      Z? e%d,-       G d. d/e<             Z@e% G d0 d1e<             ZAg d2ZBy)4zPyTorch OPT model.    )CallableOptionalUnionN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPast)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging)deprecate_kwarg   )	OPTConfig)	BlockMask)make_flex_block_causal_maskc                   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      b/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/transformers/models/opt/modeling_opt.pyr,   z&OPTLearnedPositionalEmbedding.__init__9   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-   r1   r2   r3   r.   s       r/   r:   z%OPTLearnedPositionalEmbedding.forward?   s^      <<A>L(>9A=CCEL'+A+B(BCLw|dkk9::r0   )r   N)__name__
__module____qualname____doc__intr,   r7   
LongTensorr   r:   __classcell__r.   s   @r/   r$   r$   4   s]    Fs F3 F '(37	;((; !$; u//0	; ;r0   r$   modulequerykeyvaluer1   scalingdropoutc                    t        j                  ||j                  dd            |z  }|||z   }t        j                  j                  |dt         j                        j                  |j                        }t        j                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )N)r6   dtypeptrainingr   r)   )r7   matmul	transposer   
functionalsoftmaxfloat32torL   rH   rO   
contiguous)
rC   rD   rE   rF   r1   rG   rH   kwargsattn_weightsattn_outputs
             r/   eager_attention_forwardrZ   Q   s     <<s}}R'<=GL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|U3K''1-88:K$$r0   c                   D    e Zd ZdZ	 ddedee   f fdZ eddd      	 	 	 	 	 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                  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,   r]   hidden_size	embed_dimnum_attention_heads	num_headsattention_dropoutrH   enable_biasr^   loggerwarning_oncer.   r;   head_dim	is_causal
ValueErrorrG   r   Lineark_projv_projq_projout_proj)r-   r]   r^   rW   r.   s       r/   r,   zOPTAttention.__init__k   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r0   past_key_valuepast_key_values4.58new_nameversionhidden_statesr1   layer_head_maskoutput_attentionscache_positionreturnc                    |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k7  rN| j                  j                  dk(  r|rt        j                  d       nt         | j                  j                     } || ||||f| j"                  sd	n| j$                  d
d|\  }}|j'                  ||	d      j)                         }| j+                  |      }|sd}||fS )z#Input shape: Batch x Time x ChannelrJ   r   r)   Nr{   eagersdpaz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.              ?)rH   rG   )sizerp   rG   viewre   rj   rQ   rn   ro   updater^   rZ   r]   _attn_implementationrh   ri   r   rO   rH   reshaperV   rq   )r-   rx   rs   r1   ry   rz   r{   rW   bsztgt_len_query_states
key_statesvalue_statesattention_interfacerY   rX   s                    r/   r:   zOPTAttention.forward   s    (,,.Wa {{=1DLL@#((b$..$--PZZ[\^_`[[/
{{=1__S"dnndmmLVVWXZ[\
#((b$..$--PZZ[\^_`&'6'='=L$..;K^:\($J )@;;++w6{{//69>O##L
 '>dkk>^>^&_#$7	%
  $}}C$,,	%
 	%
!\ "))#w;FFHmmK0 LL((r0   N)NNNFN)r;   r<   r=   r>   r    r   r?   r,   r   r7   Tensortupleboolr   r:   rA   rB   s   @r/   r\   r\   h   s    G
 $(!Y!Y C=!YF %0A6R :>1526"'15<)||<) "%"56<) !.	<)
 "%,,/<)  <) !.<) 
u||Xell3Xe_D	E<) S<)r0   r\   c                       e Zd Zddedee   f fdZ eddd      	 	 	 	 	 	 	 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   de
ej                  ee
ej                  ej                  f      f   fd       Z xZS )OPTDecoderLayerr]   r^   c                    t         |           |j                  | _        t	        ||      | _        |j                  | _        |j                  | _        t        |j                     | _
        t        j                  | j                  |j                        | _        t        j                  | j                  |j                   |j"                        | _        t        j                  |j                   | j                  |j"                        | _        t        j                  | j                  |j                        | _        y )N)r]   r^   elementwise_affiner`   )r+   r,   rb   rc   r\   	self_attndo_layer_norm_beforerH   r   activation_functionactivation_fnr   	LayerNormlayer_norm_elementwise_affineself_attn_layer_normrm   ffn_dimrg   fc1fc2final_layer_norm)r-   r]   r^   r.   s      r/   r,   zOPTDecoderLayer.__init__   s    ++%VyI$*$?$?!~~#F$>$>?$&LLNNv/S/S%
! 99T^^V^^&BTBTU99V^^T^^&BTBTU "T^^PVPtPt ur0   rr   rs   rt   ru   rx   r1   ry   rz   	use_cacher3   r{   rW   r|   c	                    |}
| j                   r| j                  |      } | j                  d|||||||d|	\  }}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  }|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_values (`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..
        )rx   rs   r3   r1   ry   rz   r{   rM   rJ    )r   r   r   r   rR   rH   rO   shaper   r   r   r   r   r   r   )r-   rx   r1   ry   rs   rz   r   r3   r{   rW   residualself_attn_weightshidden_states_shapeoutputss                 r/   r:   zOPTDecoderLayer.forward   s   > ! $$ 55mDM ,:4>> 	,
'+%)+/)	,
 	,
(( --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r0   r   )NNNFFNN)r;   r<   r=   r    r   r?   r,   r   r7   r   r   r   r@   r   r   FloatTensorr:   rA   rB   s   @r/   r   r      s3   vy vXc] v" %0A6R 26269=,1$)3715P||P !.P "%,,/	P
 "%"56P $D>P D>P u//0P !.P -.P 
u  (51B1BEDUDU1U+V"WW	XP SPr0   r   c                   @    e Zd ZU eed<   dZdZdgZdZdZ	dZ
dZdZd Zy)OPTPreTrainedModelr]   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 t        |t        j                        rJ|j
                  j                  j                  d       |j                  j                  j                          y y )Nr   )meanstdr   )r]   init_std
isinstancer   rm   weightdatanormal_ra   zero_	Embeddingpadding_idxr   fill_)r-   rC   r   s      r/   _init_weightsz OPTPreTrainedModel._init_weightsA  s    kk""fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> .-MM$$S)KK""$ .r0   N)r;   r<   r=   r    __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_attention_backend_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraphr   r   r0   r/   r   r   4  s?    &*#*+"&N!%r0   r   c                       e Zd ZdZdef fdZ	 ddeej                  df   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fd       Ze	 	 	 	 	 	 	 	 	 	 	 ddeej$                     deej                     deej                     dee	   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   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
    r]   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 )NFr`   r   )r^   )r+   r,   rH   	layerdroppad_token_idr   max_position_embeddingsmax_target_positions
vocab_sizer   r   word_embed_proj_dimembed_tokensr$   rb   embed_positionsrm   project_out
project_inr   _remove_final_layer_normr   r   r   
ModuleListrangenum_hidden_layersr   layersgradient_checkpointing	post_init)r-   r]   ir.   s      r/   r,   zOPTDecoder.__init__X  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r1   r!   input_tensorr{   rs   rz   c           	         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r't        |t        j
                        rt        |      }|S ||j                         nd}||j                  nd}| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |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 )Nflash_attention_2r   flex_attentionr   Fr   )inputs_embedsr2   is_trainingr   rJ   )sequence_lengthtarget_lengthrL   r{   
batch_size)cudaxpunpu)r]   r   anyr   r7   r   r"   get_seq_lengthis_compileabler   _ignore_causal_mask_sdparO   rL   r   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positiondevicetypefinfomin_unmask_unattended)r-   r1   r   r{   rs   rz   past_seen_tokensusing_compilable_cacherL   r   r   causal_mask	min_dtypes                r/   _update_causal_maskzOPTDecoder._update_causal_mask~  s    ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCKQZ[Kr0   r   r   rL   r   c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||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 )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuerL   r   r   )diagonalr   rJ   r   )r6   r7   r   r   fullr   triuaranger   expandcloner   rU   masked_fill)r1   r   r   rL   r{   r   rW   r   r   mask_lengthpadding_masks              r/   r   z@OPTDecoder._prepare_4d_causal_attention_mask_with_cache_position  s   > %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r0   	input_ids	head_maskr   r   output_hidden_statesreturn_dictr3   rW   r|   c                    ||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                  |      }|r|t        | j                         }||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
  j+                         }
|
dd|df   }
| j-                  |||
      }| j.                  | j/                  |      }||j1                  |j"                        z   }|rdnd}|rdnd}t3        |gdg      D ]j  \  }}|	|j5                         d   t7        | j8                        k7  s3t        d| dt7        | j8                         d|j5                         d    d       t;        | j8                        D ]g  \  }}|r||fz  }| j                  r%t        j<                  g       }|| j>                  k  r? ||f||
|||   nd||||d|}|d   }|s_||d   fz  }i | j@                  | jA                  |      }| jB                  | jC                  |      }|r||fz  }tE        ||||      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 (`Cache`, *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`.FrJ   )r]   r   r   r   r5   )r3   r   r  zThe `z` should be specified for z layers, but it is for .)r1   r3   ry   rs   rz   r   r{   last_hidden_staters   rx   
attentions)#r]   rz   r  r   use_return_dictrl   r   rO   rh   ri   r   r   r   r   r   r7   r   r   onesr   r8   r9   r   r   rU   zipr   lenr   	enumeraterandr   r   r   r   )r-   r  r1   r  rs   r   r   rz   r  r  r3   r{   rW   r   
seq_lengthr   
pos_embedsrx   all_hidden_statesall_self_attns	attn_mask	mask_nameidxdecoder_layerdropout_probabilitylayer_outputss                             r/   r:   zOPTDecoder.forward  s   P 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0*$++>O?N?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)
*)3<3H3d /"3#-
 
M *!,M =#3"553	66   , 11-@M' ,,];M  -!11&+++%	
 	
r0   )FNNNNNNNNNNN)r;   r<   r=   r>   r    r,   r   r7   r   r   r   r   staticmethodr?   rL   r   r   r   r@   r   r   r   r   r   r:   rA   rB   s   @r/   r   r   P  s   #y #X #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4l  1515,0+/59$(,0/3&*3715u
E,,-u
 !.u
 ELL)	u

 "%u
   1 12u
 D>u
 $D>u
 'tnu
 d^u
 u//0u
 !.u
 -.u
 
u--	.u
 u
r0   r   c                       e Zd Zdef fdZd Zd Zee	 	 	 	 	 	 	 	 	 	 	 dde	e
j                     de	e
j                     de	e
j                     de	eee
j                     ef      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   deeef   fd              Z xZS )OPTModelr]   c                 d    t         |   |       t        |      | _        | j	                          y r   )r+   r,   r   decoderr   r-   r]   r.   s     r/   r,   zOPTModel.__init__  s&     !&)r0   c                 .    | j                   j                  S r   r   r   r-   s    r/   get_input_embeddingszOPTModel.get_input_embeddings  s    ||(((r0   c                 &    || j                   _        y r   r#  r-   rF   s     r/   set_input_embeddingszOPTModel.set_input_embeddings  s    $)!r0   r  r1   r  rs   r   r   rz   r  r  r3   r{   rW   r|   c                 |   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|	|	n| j                   j                  }	 | j
                  d|||
||||||d|d|}t        |j                  |j                  |j                  |j                        S )NTr  r1   r3   r  rs   r   r   rz   r  r  r{   r  r   )r]   rz   r  r   r  r   r   r	  rs   rx   r
  )r-   r  r1   r  rs   r   r   rz   r  r  r3   r{   rW   decoder_outputss                 r/   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	
 	
r0   r  )r;   r<   r=   r    r,   r%  r(  r   r   r   r7   r@   r   r   listr   r   r   r   r   r   r   r:   rA   rB   s   @r/   r  r    sO   y )*  1515,0KO59$(,0/3&*3715+
E,,-+
 !.+
 ELL)	+

 "%U->->(?(F"GH+
   1 12+
 D>+
 $D>+
 'tn+
 d^+
 u//0+
 !.+
 -.+
 
u--	.+
  +
r0   r  c            !           e Zd ZdgZ fdZd Zd Zd Zd Ze	e
	 	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     d	eej                     d
eeeej"                     ef      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   deeef   fd              Z xZS )OPTForCausalLMzlm_head.weightc                     t         |   |       t        |      | _        t	        j
                  |j                  |j                  d      | _        | j                          y NFr`   )
r+   r,   r  r   r   rm   r   r   lm_headr   r!  s     r/   r,   zOPTForCausalLM.__init__  sK     f%
 yy!;!;V=N=NUZ[ 	r0   c                 B    | j                   j                  j                  S r   r   r   r   r$  s    r/   r%  z#OPTForCausalLM.get_input_embeddings      zz!!...r0   c                 :    || j                   j                  _        y r   r3  r'  s     r/   r(  z#OPTForCausalLM.set_input_embeddings      */

'r0   c                 &    || j                   _        y r   r   r   )r-   r   s     r/   set_decoderzOPTForCausalLM.set_decoder  s    $

r0   c                 .    | j                   j                  S r   r8  r$  s    r/   get_decoderzOPTForCausalLM.get_decoder  s    zz!!!r0   r  r1   r  rs   r   labelsr   rz   r  r  r3   r{   rW   r|   c                     ||n| j                   j                  }|	|	n| j                   j                  }	|
|
n| j                   j                  }
 | j                  j
                  d|||||||||	d|d|}| j                  |d         j                         }d}|E|j                  |j                        } | j                  ||fd| j                   j                  i|}t        |||j                  |j                  |j                        S )an  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, 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."
        ```NTr*  r   r   losslogitsrs   rx   r
  r   )r]   rz   r  r  r   r   r1  rV   rU   r   loss_functionr   r   rs   rx   r
  )r-   r  r1   r  rs   r   r<  r   rz   r  r  r3   r{   rW   r   r@  r?  s                    r/   r:   zOPTForCausalLM.forward
  s;   R 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] %$**$$ 
)%+'/!5)
 
 gaj)446YYv}}-F%4%%  ;;11 	D &#33!//))
 	
r0   NNNNNNNNNNNN)r;   r<   r=   _tied_weights_keysr,   r%  r(  r9  r;  r   r   r   r7   r@   r   r   r,  r   r   r   r   r   r   r   r:   rA   rB   s   @r/   r.  r.    s   *+/0%"  1515,0KO59-1$(,0/3&*3715P
E,,-P
 !.P
 ELL)	P

 "%U->->(?(F"GHP
   1 12P
 ))*P
 D>P
 $D>P
 'tnP
 d^P
 u//0P
 !.P
 +,P
 
u,,	-P
  P
r0   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).
    )custom_introc                   r    e Zd Zdef fdZe	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     dee
eej                     ef      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 )OPTForSequenceClassificationr]   c                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  | j                  d      | _        | j                          y r0  )
r+   r,   
num_labelsr  r   r   rm   r   scorer   r!  s     r/   r,   z%OPTForSequenceClassification.__init__n  sT      ++f%
YYv994??QVW
 	r0   r  r1   r  rs   r   r<  r   rz   r  r  r3   r|   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	rs   r1   r3   r  r   r   rz   r  r  r   r)   r   z=Cannot handle batch sizes > 1 if no padding token is defined.rJ   )r   rL   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_classificationr>  )r]   r  r   rI  r   r   rl   rU   r   r7   int32r   argmaxrh   ri   r.   r;   problem_typerH  rL   r9   r?   r	   squeezer   r   r   r   rs   rx   r
  )r-   r  r1   r  rs   r   r<  r   rz   r  r  r3   transformer_outputsrx   r@  r   r   last_non_pad_tokennon_pad_masktoken_indicespooled_logitsr?  loss_fctoutputs                           r/   r:   z$OPTForSequenceClassification.forwardw  s   * &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
 	
r0   c                 B    | j                   j                  j                  S r   r3  r$  s    r/   r%  z1OPTForSequenceClassification.get_input_embeddings  r4  r0   c                 :    || j                   j                  _        y r   r3  r'  s     r/   r(  z1OPTForSequenceClassification.set_input_embeddings  r6  r0   r  )r;   r<   r=   r    r,   r   r   r7   r@   r   r   r,  r   r   r   r   r:   r%  r(  rA   rB   s   @r/   rF  rF  _  sL   y   156:15KO59-1$(,0/3&*37\
E,,-\
 !!2!23\
 E--.	\

 "%U->->(?(F"GH\
   1 12\
 ))*\
 D>\
 $D>\
 'tn\
 d^\
 u//0\
 
u66	7\
 \
|/0r0   rF  c                       e Zd Zdef fdZe	 	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     dee
eej                     ef      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 )OPTForQuestionAnsweringr]   c                     t         |   |       t        |      | _        t	        j
                  |j                  d      | _        | j                          y r(   )	r+   r,   r  r   r   rm   r   
qa_outputsr   r!  s     r/   r,   z OPTForQuestionAnswering.__init__  s@     f%
))F$>$>B 	r0   r  r1   r  rs   r   start_positionsend_positionsr   rz   r  r  r3   r|   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  
        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'
        ```NrK  r   r   rJ   r5   )ignore_indexr)   )r?  start_logits
end_logitsrx   r
  )r]   r  r   r_  splitrR  rV   r  r   clamprU   r   r   r   rx   r
  )r-   r  r1   r  rs   r   r`  ra  r   rz   r  r  r3   rS  rx   r@  rd  re  
total_lossignored_indexrX  
start_lossend_lossrY  s                           r/   r:   zOPTForQuestionAnswering.forward  s   ` &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
 	
r0   c                 B    | j                   j                  j                  S r   r3  r$  s    r/   r%  z,OPTForQuestionAnswering.get_input_embeddingsI  r4  r0   c                 :    || j                   j                  _        y r   r3  r'  s     r/   r(  z,OPTForQuestionAnswering.set_input_embeddingsL  r6  r0   rB  )r;   r<   r=   r    r,   r   r   r7   r@   r   r   r,  r   r   r   r   r:   r%  r(  rA   rB   s   @r/   r]  r]    se   y   156:15KO596:48$(,0/3&*37_
E,,-_
 !!2!23_
 E--.	_

 "%U->->(?(F"GH_
   1 12_
 "%"2"23_
   0 01_
 D>_
 $D>_
 'tn_
 d^_
 u//0_
 
u22	3_
 _
B/0r0   r]  )r.  r  r   rF  r]  )r   )Cr>   typingr   r   r   r7   torch.utils.checkpointr   torch.nnr   r   r	   activationsr   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.deprecationr   configuration_optr    !torch.nn.attention.flex_attentionr!   integrations.flex_attentionr"   
get_loggerr;   rh   r   r$   Moduler   floatrZ   r\   r   r   r   r  r.  rF  r]  __all__r   r0   r/   <module>r     s    , ,    A A ! . ) > B 9  G & p p 0 (  !;J 
		H	%;BLL ;H %II%<<% 
% <<	%
 U\\*% % %.c)299 c)Lc0 cL % % %6`
# `
F :
! :
 :
zk
' k
\ m0#5 m0m0` o00 o0 o0dr0   