U
    ,-ej                     @   s  d Z ddlZddlm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mZmZmZmZ dd
lmZ ddlmZmZmZ ddlmZm Z m!Z!m"Z" ddl#m$Z$ e"%e&Z'dZ(dZ)dgZ*dd Z+dd Z,dd Z-dd Z.G dd dej/j0Z1G dd dej/j0Z2G dd de
j3Z4G dd  d e
j3Z5G d!d" d"e
j3Z6G d#d$ d$e
j3Z7G d%d& d&e
j3Z8G d'd( d(e
j3Z9G d)d* d*e
j3Z:G d+d, d,e
j3Z;G d-d. d.e
j3Z<G d/d0 d0e
j3Z=G d1d2 d2e
j3Z>G d3d4 d4eZ?d5Z@d6ZAe d7e@G d8d9 d9e?ZBe d:e@G d;d< d<e?ZCG d=d> d>e
j3ZDe d?e@G d@dA dAe?ZEe dBe@G dCdD dDe?ZFe dEe@G dFdG dGe?ZGe dHe@G dIdJ dJe?ZHdS )Kz PyTorch YOSO model.    N)Path)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)"BaseModelOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardlogging   )
YosoConfigzuw-madison/yoso-4096r   c                  C   s^   z>ddl m}  dd }|dddg}| d|d	d
 dd laW d	S  tk
rX   d aY dS X d S )Nr   )loadc                    s,   t t jjjd d   fdd| D S )NZkernelsyosoc                    s   g | ]} | qS  r   ).0fileZ
src_folderr   g/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/yoso/modeling_yoso.py
<listcomp><   s     z:load_cuda_kernels.<locals>.append_root.<locals>.<listcomp>)r   __file__resolveparent)filesr   r!   r"   append_root:   s    z&load_cuda_kernels.<locals>.append_rootzfast_lsh_cumulation_torch.cppzfast_lsh_cumulation.cuzfast_lsh_cumulation_cuda.cufast_lsh_cumulationT)verboseF)Ztorch.utils.cpp_extensionr   r)   lsh_cumulation	Exception)r   r(   Z	src_filesr   r   r"   load_cuda_kernels5   s    r-   c                 C   sN   t | tr6g }| D ]}| s&| }|| q|S |  sF|  } | S d S N)
isinstancelistZis_contiguous
contiguousappendZinput_tensorsouttensorr   r   r"   to_contiguousL   s    
r6   c                 C   sL   t | tkr6g }| D ]}|tjj|ddd q|S tjj| dddS d S )N   )pdim)typer0   r2   r   Z
functional	normalizer3   r   r   r"   r<   Z   s    r<   c                 C   s   t |  dkrtdt | dkr0tdtj| d| d|| | jd}dtj|| jd }t| || d| d||}t|||d|d||}|dk	 }|dk	 }	tj
|| dd	}
tj
|	| dd	}
|
	 |
	 fS )
Nr
   zQuery has incorrect size.zKey has incorrect size.r   r7   devicer   r8   r:   )lensize
ValueErrortorchZrandnr>   arangematmulreshapeintsum)querykeynum_hashZhash_lenZrmatZ	raise_powZquery_projectionZkey_projectionZquery_binaryZ
key_binaryZ
query_hashr   r   r"   hashingd   s    $$$rL   c                   @   s$   e Zd Zedd Zedd ZdS )YosoCumulationc           
   
   C   s   |d }dt t ||ddtj  | }||d d d d d f  |d d d d d f  }t ||}	| |||||| || _|	S )Nhash_code_lenr   r8   )rC   acosrE   	transposemathpisave_for_backwardconfig)
ctx
query_maskkey_maskrI   rJ   valuerU   rN   expectationcumulation_valuer   r   r"   forwardx   s    (0zYosoCumulation.forwardc                 C   s   t |}| j\}}}}}}| j}|d }	t||dd| }
t|
|	d | }t|
dd|	d | }t|dd|}d d |||d fS )NrN   r8   rO   r7   )r6   saved_tensorsrU   rC   rE   rQ   )rV   gradrW   rX   rZ   rI   rJ   rY   rU   rN   weighted_exp
grad_querygrad_key
grad_valuer   r   r"   backward   s    zYosoCumulation.backwardN__name__
__module____qualname__staticmethodr\   rc   r   r   r   r"   rM   w   s   
rM   c                   @   s$   e Zd Zedd Zedd ZdS )YosoLSHCumulationc              
   C   sX  | d| dkrtd| d| dkr8td| d| dkrTtd| d| dkrptd| d| dkrtd| d| dkrtd	t|||||g\}}}}}|j}|d
 }|d }	td|	 }
|d rt||||||	|d\}}nt||||	\}}t||||||
|d}| ||||||| || _	|S )Nr   z6Query mask and Key mask differ in sizes in dimension 0z3Query mask and Query differ in sizes in dimension 0z1Query mask and Key differ in sizes in dimension 0z8Query mask and Value mask differ in sizes in dimension 0r   z,Key and Value differ in sizes in dimension 1r7   z,Query and Key differ in sizes in dimension 2rK   rN   use_fast_hash)
rA   rB   r6   is_cudarG   r+   Z	fast_hashrL   rT   rU   )rV   rW   rX   rI   rJ   rY   rU   use_cudarK   rN   hashtable_capacityquery_hash_codekey_hash_coder[   r   r   r"   r\      sT    
       
       zYosoLSHCumulation.forwardc                 C   sj  t |}| j\}}}}}}}| j}	|j}
|	d }td| }|	d rt|||||||
d}t|||||||d | ||
d
}t|||||||d | ||
d
}ndtt	||
ddtj  | }||d d d d d f  |d d d d d f  }t	||
dd| }t	||d | }t	|
dd|d | }t	|
dd|}d d |||d fS )NrN   r7   lsh_backwardr      r8   rO   )r6   r]   rU   rk   rG   r+   Zlsh_weighted_cumulationrC   rP   rE   rQ   rR   rS   )rV   r^   rW   rX   rn   ro   rI   rJ   rY   rU   rl   rN   rm   rb   r`   ra   rZ   r_   r   r   r"   rc      s`           

(0zYosoLSHCumulation.backwardNrd   r   r   r   r"   ri      s   
%ri   c                       s*   e Zd ZdZ fddZdddZ  ZS )YosoEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   t    tj|j|j|jd| _t|jd |j| _	t|j
|j| _tj|j|jd| _t|j| _| jdt|jdd dd t|dd	| _| jd
tj| j tj| jjddd d S )N)padding_idxr7   Zepsposition_ids)r   r8   F)
persistentposition_embedding_typeabsolutetoken_type_idsdtyper>   )super__init__r   	Embedding
vocab_sizehidden_sizeZpad_token_idword_embeddingsZmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutZregister_bufferrC   rD   expandgetattrrw   zerosru   rA   longr>   selfrU   	__class__r   r"   r}      s"    
  zYosoEmbeddings.__init__Nc                 C   s   |d k	r|  }n|  d d }|d }|d krH| jd d d |f }|d krt| dr| jd d d |f }||d |}|}ntj|tj| jjd}|d kr| 	|}| 
|}	||	 }
| jdkr| |}|
|7 }
| |
}
| |
}
|
S )Nr8   r   ry   r   rz   rx   )rA   ru   hasattrry   r   rC   r   r   r>   r   r   rw   r   r   r   )r   	input_idsry   ru   inputs_embedsinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr   
embeddingsr   r   r   r"   r\   	  s,    







zYosoEmbeddings.forward)NNNNre   rf   rg   __doc__r}   r\   __classcell__r   r   r   r"   rr      s   rr   c                       s0   e Zd Zd	 fdd	Zdd Zd
ddZ  ZS )YosoSelfAttentionNc                    sH  t    |j|j dkr>t|ds>td|j d|j d|j| _t|j|j | _| j| j | _t	
|j| j| _t	
|j| j| _t	
|j| j| _t	|j| _|d k	r|n|j| _|j| _|j| _|jd k	| _|j| _|j| _|j| _| j| j| j| jd| _|jd k	rDt	j|j|j|jdf|jd dfd	|jd
| _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ())rN   rj   rK   rp   r   r7   F)Zin_channelsZout_channelsZkernel_sizepaddingbiasgroups)r|   r}   r   num_attention_headsr   rB   rG   attention_head_sizeall_head_sizer   LinearrI   rJ   rY   r   Zattention_probs_dropout_probr   rw   use_expectationrN   Zconv_windowuse_convrj   rK   rp   
lsh_configZConv2dconvr   rU   rw   r   r   r"   r}   -  sD    
zYosoSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr8   r   r7   r   r
   )rA   r   r   viewpermute)r   layerZnew_layer_shaper   r   r"   transpose_for_scoresZ  s    
z&YosoSelfAttention.transpose_for_scoresFc                 C   sJ  |  |}| | |}| | |}| |}| jr\| ||d d d d d d f  }| \}	}
}}||	|
 ||}||	|
 ||}||	|
 ||}d|d  }| 	d|
d|	|
 |
 }d}| jsR||k rR|	|
 ||| f}tj|tj||jdgdd}tj|tj||jdgdd}tj|tj||jdgdd}| jsb| jrrt||g\}}| jrt|||||| j}nt|||||| j}| js||k r|d d d d d |f }t|}||	|
||}| jr||7 }|dd	dd
 }| d d | jf }|j| }|r@||fn|f}|S )N      ?g     @r       r=   r8   r?   r   r7   r
   rO   )rI   r   rJ   rY   r   r   rA   rF   squeezerepeatrG   r   rC   catr   r>   trainingr<   rM   applyr   ri   r   r1   r   r   )r   hidden_statesattention_maskoutput_attentionsZmixed_query_layerZ	key_layerZvalue_layerZquery_layerZconv_value_layer
batch_sizeZ	num_headsZseq_lenZhead_dimZgpu_warp_sizeZpad_sizeZcontext_layerZnew_context_layer_shapeoutputsr   r   r"   r\   _  s    

"           
zYosoSelfAttention.forward)N)NF)re   rf   rg   r}   r   r\   r   r   r   r   r"   r   ,  s   -r   c                       s4   e Zd Z fddZejejejdddZ  ZS )YosoSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nrt   )r|   r}   r   r   r   denser   r   r   r   r   r   r   r   r"   r}     s    
zYosoSelfOutput.__init__r   input_tensorreturnc                 C   s&   |  |}| |}| || }|S r.   r   r   r   r   r   r   r   r   r"   r\     s    

zYosoSelfOutput.forwardre   rf   rg   r}   rC   Tensorr\   r   r   r   r   r"   r     s   r   c                       s0   e Zd Zd	 fdd	Zdd Zd
ddZ  ZS )YosoAttentionNc                    s.   t    t||d| _t|| _t | _d S )N)rw   )r|   r}   r   r   r   outputsetpruned_headsr   r   r   r"   r}     s    

zYosoAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   r?   )r@   r   r   r   r   r   r   rI   rJ   rY   r   r   r   union)r   headsindexr   r   r"   prune_heads  s       zYosoAttention.prune_headsFc                 C   s4   |  |||}| |d |}|f|dd   }|S )Nr   r   )r   r   )r   r   r   r   Zself_outputsattention_outputr   r   r   r"   r\     s    zYosoAttention.forward)N)NF)re   rf   rg   r}   r   r\   r   r   r   r   r"   r     s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )YosoIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r.   )r|   r}   r   r   r   intermediate_sizer   r/   
hidden_actstrr   intermediate_act_fnr   r   r   r"   r}     s
    
zYosoIntermediate.__init__r   r   c                 C   s   |  |}| |}|S r.   )r   r   r   r   r   r   r"   r\     s    

zYosoIntermediate.forwardr   r   r   r   r"   r     s   r   c                       s4   e Zd Z fddZejejejdddZ  ZS )
YosoOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r|   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r"   r}     s    
zYosoOutput.__init__r   c                 C   s&   |  |}| |}| || }|S r.   r   r   r   r   r"   r\     s    

zYosoOutput.forwardr   r   r   r   r"   r     s   r   c                       s.   e Zd Z fddZd	ddZdd Z  ZS )
	YosoLayerc                    sB   t    |j| _d| _t|| _|j| _t|| _t	|| _
d S Nr   )r|   r}   chunk_size_feed_forwardseq_len_dimr   	attentionZadd_cross_attentionr   intermediater   r   r   r   r   r"   r}      s    


zYosoLayer.__init__NFc                 C   sF   | j |||d}|d }|dd  }t| j| j| j|}|f| }|S )Nr   r   r   )r   r   feed_forward_chunkr   r   )r   r   r   r   Zself_attention_outputsr   r   layer_outputr   r   r"   r\   	  s       
zYosoLayer.forwardc                 C   s   |  |}| ||}|S r.   )r   r   )r   r   Zintermediate_outputr   r   r   r"   r     s    
zYosoLayer.feed_forward_chunk)NF)re   rf   rg   r}   r\   r   r   r   r   r   r"   r     s   	
r   c                       s&   e Zd Z fddZdddZ  ZS )	YosoEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r   )r   )r   _rU   r   r"   r#      s     z(YosoEncoder.__init__.<locals>.<listcomp>F)	r|   r}   rU   r   Z
ModuleListrangenum_hidden_layersr   gradient_checkpointingr   r   r   r"   r}     s    
 zYosoEncoder.__init__NFTc                    s   |rdnd } rdnd }t | jD ]l\}	}
|r8||f }| jrh| jrh fdd}tjj||
||}n|
|| }|d } r"||d f }q"|r||f }|stdd |||fD S t|||dS )	Nr   c                    s    fdd}|S )Nc                     s    | f S r.   r   )inputs)moduler   r   r"   custom_forward6  s    zJYosoEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr   )r   r   r   )r   r"   create_custom_forward5  s    z2YosoEncoder.forward.<locals>.create_custom_forwardr   r   c                 s   s   | ]}|d k	r|V  qd S r.   r   )r   vr   r   r"   	<genexpr>K  s      z&YosoEncoder.forward.<locals>.<genexpr>)last_hidden_stater   
attentions)		enumerater   r   r   rC   utils
checkpointtupler   )r   r   r   	head_maskr   output_hidden_statesreturn_dictZall_hidden_statesZall_self_attentionsiZlayer_moduler   Zlayer_outputsr   r   r"   r\   #  s2    	

zYosoEncoder.forward)NNFFTre   rf   rg   r}   r\   r   r   r   r   r"   r     s   	     r   c                       s0   e Zd Z fddZejejdddZ  ZS )YosoPredictionHeadTransformc                    sV   t    t|j|j| _t|jtr6t	|j | _
n|j| _
tj|j|jd| _d S r   )r|   r}   r   r   r   r   r/   r   r   r   transform_act_fnr   r   r   r   r   r"   r}   U  s    
z$YosoPredictionHeadTransform.__init__r   c                 C   s"   |  |}| |}| |}|S r.   )r   r   r   r   r   r   r"   r\   ^  s    


z#YosoPredictionHeadTransform.forwardr   r   r   r   r"   r   T  s   	r   c                       s$   e Zd Z fddZdd Z  ZS )YosoLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)r   )r|   r}   r   	transformr   r   r   r   decoder	ParameterrC   r   r   r   r   r   r"   r}   g  s
    

zYosoLMPredictionHead.__init__c                 C   s   |  |}| |}|S r.   )r   r   r   r   r   r"   r\   t  s    

zYosoLMPredictionHead.forwardr   r   r   r   r"   r   f  s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )YosoOnlyMLMHeadc                    s   t    t|| _d S r.   )r|   r}   r   predictionsr   r   r   r"   r}   |  s    
zYosoOnlyMLMHead.__init__)sequence_outputr   c                 C   s   |  |}|S r.   )r   )r   r   prediction_scoresr   r   r"   r\     s    
zYosoOnlyMLMHead.forwardr   r   r   r   r"   r   {  s   r   c                   @   s.   e Zd ZdZeZdZdZdd Zd
ddZ	d	S )YosoPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    r   Tc                 C   s   t |tjr:|jjjd| jjd |jdk	r|jj	  nft |tj
rz|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 weightsg        )ZmeanZstdNr   )r/   r   r   weightdataZnormal_rU   Zinitializer_ranger   Zzero_r~   rs   r   Zfill_)r   r   r   r   r"   _init_weights  s    

z!YosoPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S r.   )r/   r   r   )r   r   rY   r   r   r"   _set_gradient_checkpointing  s    
z/YosoPreTrainedModel._set_gradient_checkpointingN)F)
re   rf   rg   r   r   config_classZbase_model_prefixZsupports_gradient_checkpointingr  r  r   r   r   r"   r     s   r   aG  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`YosoConfig`]): 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.
a5
  
    Args:
        input_ids (`torch.LongTensor` of shape `({0})`):
            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 `({0})`, *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 `({0})`, *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 `({0})`, *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 `({0}, 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.
z^The bare YOSO Model transformer 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	d	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f d
ddZ  ZS )	YosoModelc                    s2   t  | || _t|| _t|| _|   d S r.   )r|   r}   rU   rr   r   r   encoder	post_initr   r   r   r"   r}     s
    

zYosoModel.__init__c                 C   s   | j jS r.   r   r   r   r   r   r"   get_input_embeddings  s    zYosoModel.get_input_embeddingsc                 C   s   || j _d S r.   r  )r   rY   r   r   r"   set_input_embeddings  s    zYosoModel.set_input_embeddingsc                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr  r   r   r   )r   Zheads_to_pruner   r   r   r   r"   _prune_heads  s    zYosoModel._prune_headsbatch_size, sequence_lengthr   output_typer  N)
r   r   ry   ru   r   r   r   r   r   r   c
                 C   s  |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n@|d k	rt| || | }
n"|d k	r| d d }
ntd|
\}}|d k	r|jn|j}|d krtj	||f|d}|d kr t
| jdr| jjd d d |f }|||}|}ntj|
tj|d}| ||
}| || j j}| j||||d}| j||||||	d}|d	 }|	s|f|d
d   S t||j|j|jdS )NzDYou cannot specify both input_ids and inputs_embeds at the same timer8   z5You have to specify either input_ids or inputs_embedsr=   ry   rz   )r   ru   ry   r   )r   r   r   r   r   r   r   )r   r   r   cross_attentions)rU   r   r   use_return_dictrB   Z%warn_if_padding_and_no_attention_maskrA   r>   rC   Zonesr   r   ry   r   r   r   Zget_extended_attention_maskZget_head_maskr   r  r   r   r   r  )r   r   r   ry   ru   r   r   r   r   r   r   r   r   r>   r   r   Zextended_attention_maskZembedding_outputZencoder_outputsr   r   r   r"   r\     s^    


zYosoModel.forward)	NNNNNNNNN)re   rf   rg   r}   r
  r  r  r   YOSO_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   rC   r   boolr   r   r\   r   r   r   r   r"   r    s>   
         
r  z2YOSO Model with a `language modeling` head on top.c                       s   e Zd ZddgZ fddZdd Zdd Zee	d	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f dddZ  ZS )YosoForMaskedLMzcls.predictions.decoder.weightzcls.predictions.decoder.biasc                    s,   t  | t|| _t|| _|   d S r.   )r|   r}   r  r   r   clsr  r   r   r   r"   r}   X  s    

zYosoForMaskedLM.__init__c                 C   s
   | j jjS r.   r  r   r   r	  r   r   r"   get_output_embeddingsa  s    z%YosoForMaskedLM.get_output_embeddingsc                 C   s   || j j_d S r.   r  )r   Znew_embeddingsr   r   r"   set_output_embeddingsd  s    z%YosoForMaskedLM.set_output_embeddingsr  r  Nr   r   ry   ru   r   r   labelsr   r   r   r   c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dk	rpt }||d| j j|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 computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (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]`.
        Nr   ry   ru   r   r   r   r   r   r   r8   r   losslogitsr   r   )
rU   r  r   r  r   r   r   r   r   r   )r   r   r   ry   ru   r   r   r  r   r   r   r   r   r   Zmasked_lm_lossloss_fctr   r   r   r"   r\   g  s6    
zYosoForMaskedLM.forward)
NNNNNNNNNN)re   rf   rg   Z_tied_weights_keysr}   r  r  r   r  r  r   r  r   r  r   rC   r   r  r   r   r\   r   r   r   r   r"   r  T  sB   	          
r  c                       s(   e Zd ZdZ fddZdd Z  ZS )YosoClassificationHeadz-Head for sentence-level classification tasks.c                    sF   t    t|j|j| _t|j| _t|j|j	| _
|| _d S r.   )r|   r}   r   r   r   r   r   r   r   
num_labelsout_projrU   r   r   r   r"   r}     s
    
zYosoClassificationHead.__init__c                 K   sR   |d d dd d f }|  |}| |}t| jj |}|  |}| |}|S )Nr   )r   r   r   rU   r   r&  )r   featureskwargsxr   r   r"   r\     s    



zYosoClassificationHead.forwardr   r   r   r   r"   r$    s   r$  zYOSO Model transformer with a sequence classification/regression head on top (a linear layer on top of
    the pooled output) e.g. for GLUE tasks.c                       s   e Zd Z fddZeed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	f dddZ  ZS )
YosoForSequenceClassificationc                    s4   t  | |j| _t|| _t|| _|   d S r.   )r|   r}   r%  r  r   r$  
classifierr  r   r   r   r"   r}     s
    

z&YosoForSequenceClassification.__init__r  r  Nr  c                 C   sr  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dk	r.| j jdkr| jdkrpd| j _n4| jdkr|jtjks|jtj	krd| j _nd| j _| j jdkrt
 }| jdkr|| | }n
|||}nN| j jdkrt }||d| j|d}n| j jdkr.t }|||}|
s^|f|dd  }|dk	rZ|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   r   Z
regressionZsingle_label_classificationZmulti_label_classificationr8   r   )rU   r  r   r+  Zproblem_typer%  r{   rC   r   rG   r	   r   r   r   r   r   r   r   )r   r   r   ry   ru   r   r   r  r   r   r   r   r   r"  r!  r#  r   r   r   r"   r\     sT    



"


z%YosoForSequenceClassification.forward)
NNNNNNNNNN)re   rf   rg   r}   r   r  r  r   r  r   r  r   rC   r   r  r   r   r\   r   r   r   r   r"   r*    s<   	          
r*  zYOSO Model with a multiple choice classification head on top (a linear layer on top of
    the pooled output and a softmax) e.g. for RocStories/SWAG tasks.c                       s   e Zd Z fddZeed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	f dddZ  ZS )
YosoForMultipleChoicec                    sD   t  | t|| _t|j|j| _t|jd| _| 	  d S r   )
r|   r}   r  r   r   r   r   pre_classifierr+  r  r   r   r   r"   r}     s
    
zYosoForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr  Nr  c                 C   s  |
dk	r|
n| j j}
|dk	r&|jd n|jd }|dk	rJ|d|dnd}|dk	rh|d|dnd}|dk	r|d|dnd}|dk	r|d|dnd}|dk	r|d|d|dnd}| j||||||||	|
d	}|d }|dddf }| |}t |}| 	|}|d|}d}|dk	rLt
 }|||}|
s||f|dd  }|dk	rx|f| S |S t|||j|jdS )aJ  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
            num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
            `input_ids` above)
        Nr   r8   rO   r  r   r   )rU   r  shaper   rA   r   r-  r   ZReLUr+  r   r   r   r   )r   r   r   ry   ru   r   r   r  r   r   r   Znum_choicesr   Zhidden_stateZpooled_outputr"  Zreshaped_logitsr!  r#  r   r   r   r"   r\   "  sP    



zYosoForMultipleChoice.forward)
NNNNNNNNNN)re   rf   rg   r}   r   r  r  r   r  r   r  r   rC   r   r  r   r   r\   r   r   r   r   r"   r,    s<   
          
r,  zYOSO Model with a token classification head on top (a linear layer on top of
    the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.c                       s   e Zd Z fddZeed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	f dddZ  ZS )
YosoForTokenClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r.   )r|   r}   r%  r  r   r   r   r   r   r   r   r+  r  r   r   r   r"   r}   s  s    
z#YosoForTokenClassification.__init__r  r  Nr  c                 C   s
  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	rt }|dk	r|ddk}|d| j}t	||dt
|j|}|||}n||d| j|d}|
s|f|dd  }|dk	r|f| S |S t|||j|jdS )z
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Nr  r   r8   r   r   )rU   r  r   r   r+  r   r   r%  rC   wherer5   ignore_indexZtype_asr   r   r   )r   r   r   ry   ru   r   r   r  r   r   r   r   r   r"  r!  r#  Zactive_lossZactive_logitsZactive_labelsr   r   r   r"   r\   ~  sJ    

  z"YosoForTokenClassification.forward)
NNNNNNNNNN)re   rf   rg   r}   r   r  r  r   r  r   r  r   rC   r   r  r   r   r\   r   r   r   r   r"   r/  m  s<             
r/  zYOSO Model 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 fddZeed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 ee ee eee	f dddZ  ZS )
YosoForQuestionAnsweringc                    sB   t  | d|_|j| _t|| _t|j|j| _| 	  d S )Nr7   )
r|   r}   r%  r  r   r   r   r   
qa_outputsr  r   r   r   r"   r}     s    
z!YosoForQuestionAnswering.__init__r  r  N)r   r   ry   ru   r   r   start_positionsend_positionsr   r   r   r   c                 C   sD  |dk	r|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d}|d}d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|d|}|d|}t	|d}|||}|||}|| d }|s.||f|dd  }|dk	r*|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.
        Nr  r   r   r8   r?   )r1  r7   )r!  start_logits
end_logitsr   r   )rU   r  r   r3  splitr   r@   rA   clampr   r   r   r   )r   r   r   ry   ru   r   r   r4  r5  r   r   r   r   r   r"  r6  r7  Z
total_lossZignored_indexr#  Z
start_lossZend_lossr   r   r   r"   r\     sP    








z YosoForQuestionAnswering.forward)NNNNNNNNNNN)re   rf   rg   r}   r   r  r  r   r  r   r  r   rC   r   r  r   r   r\   r   r   r   r   r"   r2    s@              
r2  )Ir   rR   pathlibr   typingr   r   r   rC   Ztorch.utils.checkpointr   Ztorch.nnr   r   r	   Zactivationsr   Zmodeling_outputsr   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   r   r   r   r   r   Zconfiguration_yosor   Z
get_loggerre   loggerr  r  Z"YOSO_PRETRAINED_MODEL_ARCHIVE_LISTr-   r6   r<   rL   ZautogradFunctionrM   ri   Modulerr   r   r   r   r   r   r   r   r   r   r   r   ZYOSO_START_DOCSTRINGr  r  r  r$  r*  r,  r/  r2  r   r   r   r"   <module>   s    

Z< !8
2oMVVP