U
    9%e                     @   s  d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
mZ ddlZddlmZ ddlmZmZmZ ddlmZmZ dd	lmZmZmZ dd
lmZmZ ddlmZmZmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( e%)e*Z+dZ,dZ-dgZ.dd Z/e0 eeedZ1G dd dej2Z3G dd dej2Z4G dd dej2Z5G dd deZ6eG dd de!Z7dZ8dZ9e#d e8G d!d" d"e6Z:e#d#e8G d$d% d%e6Z;e#d&e8G d'd( d(e6Z<e#d)e8G d*d+ d+e6Z=dS ),zPyTorch OpenAI GPT model.    N)	dataclass)AnyDictOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )gelu_newsilu)BaseModelOutputCausalLMOutputSequenceClassifierOutput)PreTrainedModelSequenceSummary)Conv1D find_pruneable_heads_and_indicesprune_conv1d_layer)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )OpenAIGPTConfigz
openai-gptr   c              	      s  ddl }ddl dkr$tjtd  td ddd}t	|}W 5 Q R X td	 ddd}t	|}W 5 Q R X  
 fd
d|D } fddtdD }	  |	d|dd }	dd t|	|D }	dd |	D }	| jjj|	d jkr(td| jjj d|	d j | jjj|	d jkr^td| jjj d|	d j t|	d | jj_t|	d | jj_|d |	d |	d t||	D ]B\}
}|
dd }
|
dd dkrtd|
 d|
dd }
|
d}
| }|
D ]}|d|r$|d|}n|g}|d dkrDt|d}nB|d d kr^t|d!}n(|d d"krxt|d}nt||d }t|d#krt|d }|| }q|j|jkrtd$|j d%|j d&td'|
  t||_q| S )(zGLoad tf pre-trained weights in a pytorch model (from NumPy arrays here)r   Nz.ckptzLoading weights from z/parameters_names.jsonrzutf-8)encodingz/params_shapes.jsonc                    s   g | ]}  |qS  )prod).0shape)npr!   i/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/openai/modeling_openai.py
<listcomp>F   s     z1load_tf_weights_in_openai_gpt.<locals>.<listcomp>c                    s"   g | ]}  d | d qS )z/params_z.npy)load)r#   nr%   openai_checkpoint_folder_pathr!   r&   r'   G   s     
   c                 S   s   g | ]\}}| |qS r!   )Zreshape)r#   paramr$   r!   r!   r&   r'   I   s     c                 S   s   g | ]}|  qS r!   )squeeze)r#   Zarrr!   r!   r&   r'   N   s     r   ztokens_embed.weight.shape: z% does not match init_param[1].shape: zpositions_embed.weight.shape: z% does not match init_param[0].shape:    z:0zLayer z does not end with :0/z[A-Za-z]+\d+z(\d+)gweightbbiasw   zPointer shape z and array shape z mismatchedzInitialize PyTorch weight )renumpyospathdirnameloggerinfoopenjsonr(   ZcumsumrangesplitZconcatenateziptokens_embedr4   r$   
ValueErrorpositions_embedtorchZ
from_numpydatapop	fullmatchgetattrlenint)modelconfigr+   r9   Znames_handlenamesZshapes_handleZshapesoffsetsZinit_paramsnamearrayZpointerZm_nameZscope_namesnumr!   r*   r&   load_tf_weights_in_openai_gpt7   sj    



rV   )Zrelur   ZgeluZswishc                       sL   e Zd Zd fdd	Zdd ZdddZd	d
 ZdddZdddZ  Z	S )	AttentionFc                    s   t    |}||j dkr2td| d|j | jdtt||dd||dd |j| _|| _	|| _
t|d || _t||| _t|j| _t|j| _t | _d S )	Nr   zAttention n_state shape: z$ must be divisible by config.n_head r6   r   F
persistentr   )super__init__n_headrF   register_bufferrH   ZtrilZonesview
split_sizescaler   c_attnc_projr   DropoutZ
attn_pdropattn_dropoutresid_pdropresid_dropoutsetpruned_heads)selfnxn_positionsrP   r`   n_state	__class__r!   r&   r[      s"    
zAttention.__init__c                 C   s   t |dkrd S t|| j| j| j | j\}}t||| j |d| j  g}t| j|dd| _t| j	|dd| _	| j| j | jt |  | _| jt | | _| j
|| _d S )Nr   r8   r   dim)rM   r   r\   r_   rh   rH   catr   ra   rb   union)ri   headsindexZ
index_attnr!   r!   r&   prune_heads   s      
  zAttention.prune_headsNc           
      C   s   t ||}| jr&|t|d }| jd d d d d |dd |df }|| dd|   }|d k	rx|| }tjj	|dd}| 
|}|d k	r|| }t ||g}	|r|	| |	S )Nr-   r1   g     r   ro   )rH   matmulr`   mathsqrtsizer6   r   Z
functionalZsoftmaxrd   append)
ri   qkvattention_mask	head_maskoutput_attentionsr7   r5   outputsr!   r!   r&   _attn   s    .

zAttention._attnc                 C   sD   | dddd }| d d |d|d f }|j| S )Nr   r8   r   r   r1   r-   )permute
contiguousry   r^   )ri   xnew_x_shaper!   r!   r&   merge_heads   s    &zAttention.merge_headsc                 C   sX   |  d d | j| d| j f }|j| }|rD|ddddS |ddddS d S )Nr-   r   r8   r   r   )ry   r\   r^   r   )ri   r   r|   r   r!   r!   r&   split_heads   s
    &
zAttention.split_headsc                 C   s   |  |}|j| jdd\}}}| |}| j|dd}| |}| ||||||}|d }	| |	}	| |	}	| |	}	|	g|dd   }
|
S )Nr8   ro   T)r|   r   r   )ra   rC   r_   r   r   r   rb   rf   )ri   r   r~   r   r   querykeyvalueattn_outputsar   r!   r!   r&   forward   s    





zAttention.forward)F)NNF)F)NNF)
__name__
__module____qualname__r[   ru   r   r   r   r   __classcell__r!   r!   rm   r&   rW      s   

rW   c                       s$   e Zd Z fddZdd Z  ZS )MLPc                    sF   t    |j}t||| _t||| _t|j | _t	
|j| _d S N)rZ   r[   n_embdr   c_fcrb   ACT_FNSZafnactr   rc   re   dropout)ri   rl   rP   rj   rm   r!   r&   r[      s    
zMLP.__init__c                 C   s$   |  | |}| |}| |S r   )r   r   rb   r   )ri   r   hZh2r!   r!   r&   r      s    
zMLP.forwardr   r   r   r[   r   r   r!   r!   rm   r&   r      s   r   c                       s(   e Zd Zd fdd	ZdddZ  ZS )	BlockFc                    sX   t    |j}t||||| _tj||jd| _t	d| || _
tj||jd| _d S )N)Zeps   )rZ   r[   r   rW   attnr   	LayerNormZlayer_norm_epsilonln_1r   mlpln_2)ri   rk   rP   r`   rj   rm   r!   r&   r[      s    
zBlock.__init__Nc                 C   sV   | j ||||d}|d }| || }| |}| || }	|	g|dd   }
|
S )N)r~   r   r   r   r   )r   r   r   r   )ri   r   r~   r   r   r   r   r)   mr   r   r!   r!   r&   r      s    
zBlock.forward)F)NNFr   r!   r!   rm   r&   r      s   r   c                   @   s$   e Zd ZdZeZeZdZdd Z	dS )OpenAIGPTPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerc                 C   s   t |tjtfr>|jjjd| jjd |j	dk	r|j	j
  nft |tjr~|jjjd| jjd |jdk	r|jj|j 
  n&t |tjr|j	j
  |jjd dS )zInitialize the weights.g        )ZmeanZstdN      ?)
isinstancer   Linearr   r4   rI   Znormal_rP   Zinitializer_ranger6   Zzero_	EmbeddingZpadding_idxr   Zfill_)ri   moduler!   r!   r&   _init_weights  s    

z&OpenAIGPTPreTrainedModel._init_weightsN)
r   r   r   __doc__r   config_classrV   Zload_tf_weightsZbase_model_prefixr   r!   r!   r!   r&   r     s
   r   c                   @   s~   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
ejed< dZejed< dZeeej  ed< dZeeej  ed< dS )	OpenAIGPTDoubleHeadsModelOutputa  
    Base class for outputs of models predicting if two sentences are consecutive or not.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss.
        mc_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mc_labels` is provided):
            Multiple choice classification loss.
        logits (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        mc_logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
            Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    Nlossmc_losslogits	mc_logitshidden_states
attentions)r   r   r   r   r   r   rH   FloatTensor__annotations__r   r   r   r   r   r   r!   r!   r!   r&   r   )  s   
r   aC  

    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 ([`OpenAIGPTConfig`]): 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.
a
  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.FloatTensor` 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)
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        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.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        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.
zdThe bare OpenAI GPT transformer model outputting raw hidden-states without any specific head on top.c                       s   e Zd Z fddZdd Zdd Zdd Zeee	e
eed	deej eej eej eej eej eej ee ee ee eeej ef d
ddZ  ZS )OpenAIGPTModelc                    s   t    t j j| _t j j| _t	 j
| _t fddt jD | _| jdt jdd |   d S )Nc                    s   g | ]}t  j d dqS )T)r`   )r   rk   )r#   _rP   r!   r&   r'     s     z+OpenAIGPTModel.__init__.<locals>.<listcomp>position_idsFrX   )rZ   r[   r   r   
vocab_sizer   rE   rk   rG   rc   Z
embd_pdropdropZ
ModuleListrB   n_layerr   r]   rH   Zarange	post_initri   rP   rm   r   r&   r[     s     zOpenAIGPTModel.__init__c                 C   s   | j S r   rE   ri   r!   r!   r&   get_input_embeddings  s    z#OpenAIGPTModel.get_input_embeddingsc                 C   s
   || _ d S r   r   ri   Znew_embeddingsr!   r!   r&   set_input_embeddings  s    z#OpenAIGPTModel.set_input_embeddingsc                 C   s(   |  D ]\}}| j| j| qdS )zv
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
        N)itemsr   r   ru   )ri   Zheads_to_prunelayerrs   r!   r!   r&   _prune_heads  s    zOpenAIGPTModel._prune_heads
checkpointoutput_typer   N)
	input_idsr~   token_type_idsr   r   inputs_embedsr   output_hidden_statesreturn_dictreturnc
                 C   sB  |d k	r|n| j j}|d k	r |n| j j}|	d k	r4|	n| j j}	|d k	rV|d k	rVtdnP|d k	r| || | }
|d|
d }n"|d k	r| d d }
ntd|d kr| jd d |
d f }|d k	r
|	d	d}|j
t|  jd}d| t| jj }| || j j}|d kr.| |}| |}|d k	r`|d|d}| |}nd}|| | }| |}|
|df }|rd	nd }|rd	nd }t| jD ]J\}}|r||f }||||| |d
}|d }|r||d f }q|j| }|r||f }|	s4tdd |||fD S t|||dS )NzDYou cannot specify both input_ids and inputs_embeds at the same timer-   z5You have to specify either input_ids or inputs_embedsr   r8   )dtyper   r   r!   )r   c                 s   s   | ]}|d k	r|V  qd S r   r!   )r#   r}   r!   r!   r&   	<genexpr>  s      z)OpenAIGPTModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   r   )rP   r   r   use_return_dictrF   Z%warn_if_padding_and_no_attention_maskry   r^   r   Z	unsqueezetonext
parametersr   rH   ZfinfominZget_head_maskr   rE   rG   r   	enumerater   tupler   )ri   r   r~   r   r   r   r   r   r   r   Zinput_shapeZposition_embedsZtoken_type_embedsr   Zoutput_shapeZall_attentionsZall_hidden_statesiblockr   r!   r!   r&   r     sb    









zOpenAIGPTModel.forward)	NNNNNNNNN)r   r   r   r[   r   r   r   r   OPENAI_GPT_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   rH   
LongTensorr   boolr   r   Tensorr   r   r!   r!   rm   r&   r     s>            r   z
    OpenAI GPT Model transformer with a language modeling head on top (linear layer with weights tied to the input
    embeddings).
    c                       s   e Zd ZdgZ fddZdd Zdd Zeee	e
eeddeej eej eej eej eej eej eej ee ee ee eeej ef d
ddZejeeef dddZ  ZS )OpenAIGPTLMHeadModellm_head.weightc                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFr6   )
rZ   r[   r   r   r   r   r   r   lm_headr   r   rm   r!   r&   r[     s    
zOpenAIGPTLMHeadModel.__init__c                 C   s   | j S r   r   r   r!   r!   r&   get_output_embeddings   s    z*OpenAIGPTLMHeadModel.get_output_embeddingsc                 C   s
   || _ d S r   r   r   r!   r!   r&   set_output_embeddings#  s    z*OpenAIGPTLMHeadModel.set_output_embeddingsr   Nr   r~   r   r   r   r   labelsr   r   r   r   c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dk	r|dddddf  }|dddf  }t }||d|d|d}|
s|f|dd  }|dk	r|f| S |S t|||j	|j
dS )a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
            are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
        Nr~   r   r   r   r   r   r   r   r   .r-   r   r   r   r   r   )rP   r   r   r   r   r
   r^   ry   r   r   r   )ri   r   r~   r   r   r   r   r   r   r   r   transformer_outputsr   	lm_logitsr   shift_logitsshift_labelsloss_fctoutputr!   r!   r&   r   &  s:    
zOpenAIGPTLMHeadModel.forward)r   r   c                 K   s   d|iS )Nr   r!   )ri   r   kwargsr!   r!   r&   prepare_inputs_for_generationc  s    z2OpenAIGPTLMHeadModel.prepare_inputs_for_generation)
NNNNNNNNNN)r   r   r   _tied_weights_keysr[   r   r   r   r   r   r   r   r   r   rH   r   r   r   r   r   r   r   r   strr   r   r   r!   r!   rm   r&   r     sD             7r   ai  
OpenAI GPT Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
input embeddings, the classification head takes as input the input of a specified classification token index in the
input sequence).
c                       s   e Zd ZdgZ fddZdd Zdd Zeee	e
eddeej eej eej eej eej eej eej eej eej ee ee ee eeej e
f d
ddZ  ZS )OpenAIGPTDoubleHeadsModelr   c                    sH   t  | d|_t|| _tj|j|jdd| _	t
|| _|   d S )Nr   Fr   )rZ   r[   
num_labelsr   r   r   r   r   r   r   r   multiple_choice_headr   r   rm   r!   r&   r[   s  s    

z"OpenAIGPTDoubleHeadsModel.__init__c                 C   s   | j S r   r   r   r!   r!   r&   r   ~  s    z/OpenAIGPTDoubleHeadsModel.get_output_embeddingsc                 C   s
   || _ d S r   r   r   r!   r!   r&   r     s    z/OpenAIGPTDoubleHeadsModel.set_output_embeddings)r   r   N)r   r~   r   r   r   r   mc_token_idsr   	mc_labelsr   r   r   r   c                 C   s@  |dk	r|n| j j}| j|||||||
||d	}|d }| |}| ||d}d\}}|	dk	rt }||d|d|	d}|dk	r|dddddf 	 }|dddf 	 }t }||d|d|d}|s(||f|dd  }|dk	r|f| }|dk	r$|f| S |S t
|||||j|jdS )	a  
        mc_token_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input):
            Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
            1]`.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-1, 0, ..., config.vocab_size]` All labels set to `-100` are
            ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
        mc_labels (`torch.LongTensor` of shape `(batch_size)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
            where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)

        Return:

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("openai-gpt")
        >>> model = OpenAIGPTDoubleHeadsModel.from_pretrained("openai-gpt")
        >>> tokenizer.add_special_tokens(
        ...     {"cls_token": "[CLS]"}
        ... )  # Add a [CLS] to the vocabulary (we should train it also!)
        >>> model.resize_token_embeddings(len(tokenizer))

        >>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
        >>> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0)  # Batch size 1, 2 choices
        >>> mc_token_ids = torch.tensor([input_ids.size(-1) - 1, input_ids.size(-1) - 1]).unsqueeze(0)  # Batch size 1

        >>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
        >>> lm_logits = outputs.logits
        >>> mc_logits = outputs.mc_logits
        ```Nr   r   r-   )NN.r   )r   r   r   r   r   r   )rP   r   r   r   r   r/   r
   r^   ry   r   r   r   r   )ri   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Zlm_lossr   r   r   r   r   r!   r!   r&   r     sJ    4


z!OpenAIGPTDoubleHeadsModel.forward)NNNNNNNNNNNN)r   r   r   r   r[   r   r   r   r   r   r   r   r   rH   r   r   r   r   r   r   r   r   r!   r!   rm   r&   r   g  sB   

            r   a  
    The Original OpenAI GPT Model transformer with a sequence classification head on top (linear layer).
    [`OpenAIGPTForSequenceClassification`] 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 fddZeeeeee	dde
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeej ef dddZ  ZS )	"OpenAIGPTForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r   )
rZ   r[   r   r   r   r   r   r   scorer   r   rm   r!   r&   r[     s
    
z+OpenAIGPTForSequenceClassification.__init__r   Nr   c                 C   s4  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}|dk	r^|jdd \}}n|jdd \}}| j jdkr|dkrtd| j jdkrd}nH|dk	rt|| j j	 
dd |j}nd}t| jj d |t||f }d}|dk	r| j jdkrb| jdkr(d	| j _n:| jdkrZ|jtj	ksP|jtjkrZd
| 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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).
        Nr   r   r8   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r-   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`Z
regressionZsingle_label_classificationZmulti_label_classificationr   )rP   r   r   r   r$   Zpad_token_idrF   rH   eqlongZargmaxr   Zdevicer>   warningrn   r   rB   Zproblem_typer   r   rN   r   r/   r
   r^   r	   r   r   r   )ri   r   r~   r   r   r   r   r   r   r   r   r   r   r   Z
batch_sizeZsequence_lengthZsequence_lengthsZpooled_logitsr   r   r   r!   r!   r&   r     st    


(

z*OpenAIGPTForSequenceClassification.forward)
NNNNNNNNNN)r   r   r   r[   r   r   r   r   r   r   r   rH   r   r   r   r   r   r   r   r   r!   r!   rm   r&   r     s<   	          r   )>r   rA   rw   r;   dataclassesr   typingr   r   r   r   r   rH   r   Ztorch.nnr	   r
   r   Zactivationsr   r   Zmodeling_outputsr   r   r   Zmodeling_utilsr   r   Zpytorch_utilsr   r   r   utilsr   r   r   r   r   r   Zconfiguration_openair   Z
get_loggerr   r>   r   r   Z(OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LISTrV   ZReLUr   ModulerW   r   r   r   r   ZOPENAI_GPT_START_DOCSTRINGr   r   r   r   r   r!   r!   r!   r&   <module>   sb    
N]"2|R	t	