U
    9%ec                     @   s  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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 eeZ dZ!dZ"dddgZ#dZ$dZ%dZ&dddddddgZ'd7ej(ej)ej*e+dddZ,d8ej-ej)ee+ dddZ.G d d! d!ej/Z0G d"d# d#ej1Z2G d$d% d%ej1Z3d&Z4ed'e4G d(d) d)eZ5d*Z6G d+d, d,e5Z7ed'e4G d-d. d.e5Z8G d/d0 d0e5Z9ed1e4G d2d3 d3e5Z:ed4e4G d5d6 d6e5Z;dS )9z PyTorch OPT model.    )ListOptionalTupleUnionN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPast)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )	OPTConfigzfacebook/opt-350mr      i   zArthurZ/opt-350m-dummy-scg\(\?z	'LABEL_0'zfacebook/opt-125mzfacebook/opt-1.3bzfacebook/opt-2.7bzfacebook/opt-6.7bzfacebook/opt-13bzfacebook/opt-30b)input_ids_shapedtypedevicepast_key_values_lengthc                 C   s   | \}}t j||ft |j|d}t j|d|d}|||d |ddk d ||}|dkrt j	t j
||||d|gdd}|ddddddf |d||| S )zB
    Make causal mask used for bi-directional self-attention.
    r   r   r   )r   r   dimN)torchfullfinfominarangesizeZmasked_fill_viewtocatZzerosexpand)r   r   r   r   bsztgt_lenmaskZ	mask_cond r.   c/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/opt/modeling_opt.py_make_causal_maskC   s    "
 r0   )r-   r   r,   c                 C   sj   |   \}}|dk	r|n|}| ddddddf |d|||}d| }||tjt|jS )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr   g      ?)r&   r*   r(   Zmasked_fillr!   boolr#   r$   )r-   r   r,   r+   src_lenZexpanded_maskZinverted_maskr.   r.   r/   _expand_maskT   s
    *r3   c                       s@   e Zd ZdZeed fddZd	ejed fddZ  Z	S )
OPTLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    )num_embeddingsembedding_dimc                    s   d| _ t || j  | d S N   )offsetsuper__init__)selfr5   r6   	__class__r.   r/   r;   g   s    z&OPTLearnedPositionalEmbedding.__init__r   )attention_maskr   c                    sN   |  }tj|dd||   d }|dd|df }t || j S )z3`input_ids_shape` is expected to be [bsz x seqlen].r   r   N)longr!   ZcumsumZtype_asr:   forwardr9   )r<   r?   r   Z	positionsr=   r.   r/   rA   m   s     z%OPTLearnedPositionalEmbedding.forward)r   )
__name__
__module____qualname____doc__intr;   r!   
LongTensorrA   __classcell__r.   r.   r=   r/   r4   b   s   r4   c                       s   e Zd ZdZdeeeeed fddZej	eedd	d
Z
dej	eej	 eeej	  eej	 eej	 eeej	eej	 eeej	  f dddZ  ZS )OPTAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FT	embed_dim	num_headsdropout
is_decoderbiasc                    s   t    || _|| _|| _|| | _| j| | jkrNtd| j d| d| jd | _|| _t	j
|||d| _t	j
|||d| _t	j
|||d| _t	j
|||d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      ࿩rP   )r:   r;   rL   rM   rN   head_dim
ValueErrorscalingrO   r   Lineark_projv_projq_projout_proj)r<   rL   rM   rN   rO   rP   r=   r.   r/   r;   }   s    

zOPTAttention.__init__)tensorseq_lenr+   c                 C   s    | ||| j| jdd S )Nr   r8   )r'   rM   rR   	transpose
contiguous)r<   rZ   r[   r+   r.   r.   r/   _shape   s    zOPTAttention._shapeN)hidden_stateskey_value_statespast_key_valuer?   layer_head_maskoutput_attentionsreturnc                 C   s  |dk	}|  \}}	}
| || j }|rD|dk	rD|d }|d }n|rr| | |d|}| | |d|}n|dk	r| | |d|}| | |d|}tj|d |gdd}tj|d |gdd}n(| | |d|}| | |d|}| jr||f}|| j	 d| j
f}| ||	|j| }|j| }|j| }| d}t||dd}|  || j	 |	|fkrtd|| j	 |	|f d|   |dk	r*|  |d|	|fkrtd	|d|	|f d|   ||| j	|	|| }t|tjt|jj|jd
}||| j	 |	|}|jtjkrVtjj|dtjdtj}ntjj|dd}|dk	r|  | j	fkrtd| j	f d|   |dddd||| j	|	| }||| j	 |	|}|r||| j	|	|}||| j	 |	|}nd}tjj|| j| jd}t||}|  || j	 |	| j
fkrhtd|| j	|	| j
f d|   ||| j	|	| j
}|dd}|||	| j}| |}|||fS )z#Input shape: Batch x Time x ChannelNr   r   r   r8   r   z$Attention weights should be of size z	, but is z!Attention mask should be of size r   )r    r   z/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size ) r&   rX   rT   r^   rV   rW   r!   r)   rO   rM   rR   r'   Zbmmr\   rS   maxrZ   r#   r   r$   r   Zfloat16r   
functionalZsoftmaxZfloat32r(   rN   rg   reshaperL   rY   )r<   r_   r`   ra   r?   rb   rc   Zis_cross_attentionr+   r,   _Zquery_statesZ
key_statesZvalue_statesZ
proj_shaper2   Zattn_weightsZattn_weights_reshapedZ
attn_probsZattn_outputr.   r.   r/   rA      s    




 
"
zOPTAttention.forward)rJ   FT)NNNNF)rB   rC   rD   rE   rF   floatr1   r;   r!   Tensorr^   r   r   rA   rH   r.   r.   r=   r/   rI   z   s4           rI   c                       sx   e Zd Zed fddZd	ejeej eej eeej  ee	 ee	 eej
eeej
ej
f  f dddZ  ZS )
OPTDecoderLayerconfigc                    s   t    |j| _t| j|j|jd|jd| _|j	| _	|j
| _
t|j | _tj| j|jd| _tj| j|j|jd| _tj|j| j|jd| _tj| j|jd| _d S )NTrK   Zelementwise_affinerQ   )r:   r;   hidden_sizerL   rI   Znum_attention_headsZattention_dropoutZenable_bias	self_attndo_layer_norm_beforerN   r   Zactivation_functionactivation_fnr   	LayerNormlayer_norm_elementwise_affineself_attn_layer_normrU   Zffn_dimfc1fc2final_layer_normr<   rp   r=   r.   r/   r;     s&    
 zOPTDecoderLayer.__init__NF)r_   r?   rb   ra   rc   	use_cacherd   c                 C   s   |}| j r| |}| j|||||d\}}}	tjj|| j| jd}|| }| j s\| |}|j}
|d|	d}|}| j r| 
|}| |}| |}| |}tjj|| j| jd}|| |
}| j s| 
|}|f}|r||f7 }|r||	f7 }|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
        )r_   ra   r?   rb   rc   re   r   )rt   rx   rs   r   ri   rN   rg   shaperj   r&   r{   ry   ru   rz   r'   )r<   r_   r?   rb   ra   rc   r}   ZresidualZself_attn_weightsZpresent_key_valueZhidden_states_shapeoutputsr.   r.   r/   rA   *  s@    








zOPTDecoderLayer.forward)NNNFF)rB   rC   rD   r   r;   r!   rm   r   r   r1   FloatTensorrA   rH   r.   r.   r=   r/   rn     s        rn   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                   @   s0   e Zd ZeZdZdZdgZdd Zd
ddZ	d	S )OPTPreTrainedModelmodelTrn   c                 C   s|   | j j}t|tjr>|jjjd|d |jd k	rx|jj	  n:t|tj
rx|jjjd|d |jd k	rx|jj|j 	  d S )NrJ   )Zmeanstd)rp   Zinit_std
isinstancer   rU   weightdataZnormal_rP   Zzero_	Embeddingpadding_idx)r<   moduler   r.   r.   r/   _init_weights  s    

z OPTPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S N)r   
OPTDecodergradient_checkpointing)r<   r   valuer.   r.   r/   _set_gradient_checkpointing  s    
z.OPTPreTrainedModel._set_gradient_checkpointingN)F)
rB   rC   rD   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesr   r   r.   r.   r.   r/   r     s   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.
c                       s   e Zd ZdZed fddZdd Zdd Zd	d
 Zde	j
ee	j ee	j eee	j  ee	j ee ee ee ee eeef d
ddZ  ZS )r   z
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`]

    Args:
        config: OPTConfig
    ro   c                    s  t     j| _ j| _ j| _ j| _ j| _t	
 j j| j| _t j j| _ j jkr~t	j j jdd| _nd | _ j jkrt	j j jdd| _nd | _ jrЈ jst	j j jd| _nd | _t	 fddt jD | _d| _|   d S )NFrQ   rq   c                    s   g | ]}t  qS r.   )rn   ).0rk   ro   r.   r/   
<listcomp>  s     z'OPTDecoder.__init__.<locals>.<listcomp>)r:   r;   rN   	layerdroppad_token_idr   Zmax_position_embeddingsZmax_target_positions
vocab_sizer   r   word_embed_proj_dimembed_tokensr4   rr   embed_positionsrU   project_out
project_inrt   Z_remove_final_layer_normrv   rw   r{   Z
ModuleListrangeZnum_hidden_layerslayersr   	post_initr|   r=   ro   r/   r;     s.     
 zOPTDecoder.__init__c                 C   s   | j S r   r   r<   r.   r.   r/   get_input_embeddings  s    zOPTDecoder.get_input_embeddingsc                 C   s
   || _ d S r   r   r<   r   r.   r.   r/   set_input_embeddings  s    zOPTDecoder.set_input_embeddingsc                 C   s`   d }|d dkr$t ||j|j|d}|d k	r\t||j|d d|j}|d krT|n|| }|S )Nr   r   )r   r   )r,   )r0   r   r   r3   r(   )r<   r?   input_shapeinputs_embedsr   Zcombined_attention_maskZexpanded_attn_maskr.   r.   r/   _prepare_decoder_attention_mask  s    z*OPTDecoder._prepare_decoder_attention_maskN
	input_idsr?   	head_maskpast_key_valuesr   r}   rc   output_hidden_statesreturn_dictrd   c
              	      s   dk	r n| j j |dk	r |n| j j}|dk	r4|n| j j}|	dk	rH|	n| j j}	|dk	rj|dk	rjtdnD|dk	r| }
|d|
d }n"|dk	r| dd }
ntd|dkr| |}|
\}}|dk	r|d d j	d nd}|| }|dkrt
j|||jd}n,|j	d |kr8td	|j	d  d
| d| ||
||}| ||}| jdk	rj| |}|| }| jr| jr|rtd d}|rdnd} rdnd}|rdnd}t|gdgD ]V\}}|dk	r| d t| jkrtd| dt| j d| d  dqt| jD ]\}}|rH||f7 }| jrjt
g }|| jk rjq0|dk	r||| nd}| jr| jrʇ fdd}t
jj|||||dk	r|| ndd}n&||||dk	r|| nd| |d}|d }|r|| rdnd f7 } r0||d f7 }q0| jdk	rD| |}| jdk	rZ| |}|rj||f7 }|rt|nd}|	stdd ||||fD S t||||d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.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r8   r   r   z'The provided attention mask has length z, but its length should be z0 (sum of the lengths of current and past inputs)zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr.   r   zThe `z` should be specified for z layers, but it is for .c                    s    fdd}|S )Nc                     s    | d f S r   r.   )inputs)r   rc   r.   r/   custom_forward  s    zIOPTDecoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr.   )r   r   rc   )r   r/   create_custom_forward  s    z1OPTDecoder.forward.<locals>.create_custom_forward)r?   rb   ra   rc   r}   c                 s   s   | ]}|d k	r|V  qd S r   r.   )r   vr.   r.   r/   	<genexpr>  s      z%OPTDecoder.forward.<locals>.<genexpr>last_hidden_stater   r_   
attentions) rp   rc   r   r}   use_return_dictrS   r&   r'   r   r~   r!   Zonesr   r   r   r   r   rg   loggerZwarning_onceziplenr   	enumerateZrandr   utils
checkpointr{   r   tupler   )r<   r   r?   r   r   r   r}   rc   r   r   r   
batch_sizeZ
seq_lengthr   Zmask_seq_lengthZcausal_attention_maskZ
pos_embedsr_   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheZ	attn_maskZ	mask_nameidxZdecoder_layerZdropout_probabilityra   r   Zlayer_outputsZ
next_cacher.   r   r/   rA   ,  s    ;


   

$

	


zOPTDecoder.forward)	NNNNNNNNN)rB   rC   rD   rE   r   r;   r   r   r   r!   rG   r   rm   r   r   r1   r   r   r   rA   rH   r.   r.   r=   r/   r     s4   %         
r   c                       s   e Zd Zed fddZdd Zdd Zdd	 Zee	e
eeeed
dejeej eej eeej  eej ee ee ee ee eeef d
ddZ  ZS )OPTModelro   c                    s"   t  | t|| _|   d S r   )r:   r;   r   decoderr   r|   r=   r.   r/   r;     s    
zOPTModel.__init__c                 C   s   | j jS r   r   r   r   r.   r.   r/   r     s    zOPTModel.get_input_embeddingsc                 C   s   || j _d S r   r   r   r.   r.   r/   r     s    zOPTModel.set_input_embeddingsc                 C   s   | j S r   )r   r   r.   r.   r/   get_decoder  s    zOPTModel.get_decoder)r   output_typer   expected_outputNr   c
                 C   s   |d k	r|n| j j}|d k	r |n| j j}|d k	r4|n| j j}|	d k	rH|	n| j j}	| j|||||||||	d	}
|	st|
S t|
j|
j|
j	|
j
dS )N	r   r?   r   r   r   r}   rc   r   r   r   )rp   rc   r   r}   r   r   r   r   r   r_   r   )r<   r   r?   r   r   r   r}   rc   r   r   Zdecoder_outputsr.   r.   r/   rA      s0    zOPTModel.forward)	NNNNNNNNN)rB   rC   rD   r   r;   r   r   r   r   OPT_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr!   rG   r   rm   r   r   r1   r   r   rA   rH   r.   r.   r=   r/   r     s@            
r   c                       s   e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
eeeddejeej eej eeej  eej eej ee ee ee ee eeef dddZdddZedd Z  ZS )OPTForCausalLMzlm_head.weightc                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFrQ   )
r:   r;   r   r   r   rU   r   r   lm_headr   r|   r=   r.   r/   r;   5  s    
zOPTForCausalLM.__init__c                 C   s
   | j jjS r   r   r   r   r   r.   r.   r/   r   ?  s    z#OPTForCausalLM.get_input_embeddingsc                 C   s   || j j_d S r   r   r   r.   r.   r/   r   B  s    z#OPTForCausalLM.set_input_embeddingsc                 C   s   | j S r   r   r   r.   r.   r/   get_output_embeddingsE  s    z$OPTForCausalLM.get_output_embeddingsc                 C   s
   || _ d S r   r   )r<   Znew_embeddingsr.   r.   r/   set_output_embeddingsH  s    z$OPTForCausalLM.set_output_embeddingsc                 C   s   || j _d S r   r   r   )r<   r   r.   r.   r/   set_decoderK  s    zOPTForCausalLM.set_decoderc                 C   s   | j jS r   r   r   r.   r.   r/   r   N  s    zOPTForCausalLM.get_decoderr   r   Nr   r?   r   r   r   labelsr}   rc   r   r   rd   c                 C   s  |dk	r|n| j j}|	dk	r |	n| j j}	|
dk	r4|
n| j j}
| jj||||||||	|
d	}| |d  }d}|dk	r||j	}|dddddf  }|dddf  }t
 }||d| j j|d}|
s|f|dd  }|dk	r|f| S |S t|||j|j|jdS )aU  
        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.

        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."
        ```Nr   r   .r   r   losslogitsr   r_   r   )rp   rc   r   r   r   r   r   r]   r(   r   r   r'   r   r   r   r_   r   )r<   r   r?   r   r   r   r   r}   rc   r   r   r   r   r   Zshift_logitsZshift_labelsloss_fctoutputr.   r.   r/   rA   Q  sB    XzOPTForCausalLM.forwardc                 K   sV   |r|d d dd f }|d k	r2|d kr2d|i}nd|i}| ||d|d |S )Nr   r   r   r}   )r   r}   r?   )updateget)r<   r   r   r?   r   kwargsZmodel_inputsr.   r.   r/   prepare_inputs_for_generation  s    
z,OPTForCausalLM.prepare_inputs_for_generationc                    s.   d}| D ] }|t  fdd|D f7 }q|S )Nr.   c                 3   s"   | ]}| d  |jV  qdS )r   N)Zindex_selectr(   r   )r   Z
past_statebeam_idxr.   r/   r     s     z0OPTForCausalLM._reorder_cache.<locals>.<genexpr>)r   )r   r   Zreordered_pastZ
layer_pastr.   r   r/   _reorder_cache  s    zOPTForCausalLM._reorder_cache)
NNNNNNNNNN)NNN)rB   rC   rD   Z_tied_weights_keysr;   r   r   r   r   r   r   r   r   r   r!   rG   r   rm   r   r   r1   r   r   rA   r   staticmethodr   rH   r.   r.   r=   r/   r   2  sN   

          
      
r   a  
    The OPT Model transformer with a sequence classification head on top (linear layer).

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

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                       s   e Zd Zed fddZeeeee	e
eeddeej eej eej eeeej   eej eej ee ee ee ee eee	f dddZd	d
 Zdd Z  ZS )OPTForSequenceClassificationro   c                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r   )
r:   r;   
num_labelsr   r   r   rU   r   scorer   r|   r=   r.   r/   r;     s
    
z%OPTForSequenceClassification.__init__)r   r   r   r   Zexpected_lossNr   c                 C   s$  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}|dk	r^|jdd \}}n|jdd \}}| j jdkrd}nH|dk	rt|| j j 	dd 
|j}nd}t| jj d |tj||jd|f }d}|dk	r| j jdkrN| jdkrd	| j _n:| jdkrF|jtjks<|jtjkrFd
| j _nd| j _| j jd	krt }| jdkr|| | }n
|||}nN| j jd
krt }||d| j|d}n| j jdkrt }|||}|
s|f|dd  }|dk	r|f| S |S t|||j|j|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nr   r?   r   r   r}   rc   r   r   r   r8   r   r   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r   Z
regressionZsingle_label_classificationZmulti_label_classificationr   )rp   r   r   r   r~   r   r!   eqr@   Zargmaxr(   r   r   warningr>   rB   r%   Zproblem_typer   r   rF   r	   squeezer   r'   r   r   r   r_   r   )r<   r   r?   r   r   r   r   r}   rc   r   r   transformer_outputsr_   r   r   Zsequence_lengthZsequence_lengthsZpooled_logitsr   r   r   r.   r.   r/   rA     sr    


(

z$OPTForSequenceClassification.forwardc                 C   s
   | j jjS r   r   r   r.   r.   r/   r   o  s    z1OPTForSequenceClassification.get_input_embeddingsc                 C   s   || j j_d S r   r   r   r.   r.   r/   r   r  s    z1OPTForSequenceClassification.set_input_embeddings)
NNNNNNNNNN)rB   rC   rD   r   r;   r   r   r   '_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATIONr   r   _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSr   r!   rG   r   r   rm   r1   r   rA   r   r   rH   r.   r.   r=   r/   r     sD   		          
Z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                       s   e Zd Zed fddZeeeee	dde
ej e
ej e
ej e
eeej   e
ej e
ej e
ej e
e e
e e
e e
e eeef dddZd	d
 Zdd Z  ZS )OPTForQuestionAnsweringro   c                    s2   t  | t|| _t|jd| _|   d S r7   )	r:   r;   r   r   r   rU   r   
qa_outputsr   r|   r=   r.   r/   r;   ~  s    
z OPTForQuestionAnswering.__init__r   N)r   r?   r   r   r   start_positionsend_positionsr}   rc   r   r   rd   c                 C   sP  |dk	r|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d }|d }d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|s:||f|dd  }|dk	r6|f| S |S t||||j|jd	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   r   r   )Zignore_indexr8   )r   start_logits
end_logitsr_   r   )rp   r   r   r   splitr   r]   r   r&   clampr   r   r_   r   )r<   r   r?   r   r   r   r   r   r}   rc   r   r   r   r_   r   r   r   Z
total_lossZignored_indexr   Z
start_lossZend_lossr   r.   r.   r/   rA     sP    ;






zOPTForQuestionAnswering.forwardc                 C   s
   | j jjS r   r   r   r.   r.   r/   r     s    z,OPTForQuestionAnswering.get_input_embeddingsc                 C   s   || j j_d S r   r   r   r.   r.   r/   r     s    z,OPTForQuestionAnswering.set_input_embeddings)NNNNNNNNNNN)rB   rC   rD   r   r;   r   r   r   r   r   r   r!   rG   r   r   rm   r1   r   rA   r   r   rH   r.   r.   r=   r/   r   v  s<   
           
jr   )r   )N)<rE   typingr   r   r   r   r!   Ztorch.utils.checkpointr   Ztorch.nnr   r   r	   Zactivationsr   Zmodeling_outputsr   r   r   r   Zmodeling_utilsr   r   r   r   r   r   r   Zconfiguration_optr   Z
get_loggerrB   r   r   r   r   r   r   r   Z!OPT_PRETRAINED_MODEL_ARCHIVE_LISTSizer   r   rF   r0   rm   r3   r   r4   ModulerI   rn   ZOPT_START_DOCSTRINGr   r   r   r   r   r   r   r.   r.   r.   r/   <module>   s   

     d>  B Cs