o
    h                     @   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   sV   zddl m}  dd }|g d}| d|dd dd laW dS  ty*   d aY d	S w )
Nr   )loadc                    s,   t t jjjd d   fdd| D S )Nkernelsyosoc                    s   g | ]} | qS  r   ).0file
src_folderr   \/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/yoso/modeling_yoso.py
<listcomp><       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_root)zfast_lsh_cumulation_torch.cppzfast_lsh_cumulation.cuzfast_lsh_cumulation_cuda.cufast_lsh_cumulationT)verboseF)torch.utils.cpp_extensionr   r,   lsh_cumulation	Exception)r   r+   	src_filesr   r   r$   load_cuda_kernels5   s   r2   c                 C   sJ   t | trg }| D ]}| s| }|| q	|S |  s#|  } | S N)
isinstancelistis_contiguous
contiguousappendinput_tensorsouttensorr   r   r$   to_contiguousL   s   
r=   c                 C   sF   t | trg }| D ]}|tjj|ddd q	|S tjj| dddS )N   )pdim)r4   r5   r8   r   
functional	normalizer9   r   r   r$   rC   Z   s   
rC   c                 C   s   t |  dkrtdt | dkrt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   r>   devicer   r?   rA   )lensize
ValueErrortorchrandnrE   arangematmulreshapeintsum)querykeynum_hashhash_lenrmat	raise_powquery_projectionkey_projectionquery_binary
key_binary
query_hashr   r   r$   hashingd   s   $$$r\   c                   @   $   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   r?   )rJ   acosrM   	transposemathpisave_for_backwardconfig)
ctx
query_maskkey_maskrQ   rR   valuerf   r_   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 )Nr_   r?   r`   r>   )r=   saved_tensorsrf   rJ   rM   rb   )rg   gradrh   ri   rk   rQ   rR   rj   rf   r_   weighted_exp
grad_querygrad_key
grad_valuer   r   r$   backward   s   zYosoCumulation.backwardN__name__
__module____qualname__staticmethodrm   rt   r   r   r   r$   r^   w   s
    
r^   c                   @   r]   )YosoLSHCumulationc              
   C   sV  | d| dkrtd| d| dkrtd| d| dkr*td| d| dkr8td| d| dkrFtd| d| dkrTtd	t|||||g\}}}}}|j}|d
 }|d }	td|	 }
|d rt||||||	|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 1r>   z,Query and Key differ in sizes in dimension 2rS   r_   use_fast_hash)
rH   rI   r=   is_cudarO   r/   	fast_hashr\   re   rf   )rg   rh   ri   rQ   rR   rj   rf   use_cudarS   r_   hashtable_capacityquery_hash_codekey_hash_coderl   r   r   r$   rm      s8   
zYosoLSHCumulation.forwardc                 C   sj  t |}| j\}}}}}}}| j}	|j}
|	d }td| }|	d rSt|||||||
d}t|||||||d | ||
d
}t|||||||d | ||
d
}nZd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 )Nr_   r>   lsh_backwardr      r?   r`   )r=   rn   rf   r|   rO   r/   lsh_weighted_cumulationrJ   ra   rM   rb   rc   rd   )rg   ro   rh   ri   r   r   rQ   rR   rj   rf   r~   r_   r   rs   rq   rr   rk   rp   r   r   r$   rt      sR   

(0zYosoLSHCumulation.backwardNru   r   r   r   r$   rz      s
    
%rz   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_idxr>   epsposition_ids)r   r?   F)
persistentposition_embedding_typeabsolutetoken_type_idsdtyperE   )super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_bufferrJ   rL   expandgetattrr   zerosr   rH   longrE   selfrf   	__class__r   r$   r      s   

zYosoEmbeddings.__init__Nc                 C   s   |d ur	|  }n|  d d }|d }|d u r$| jd d d |f }|d u rNt| drC| jd d d |f }||d |}|}ntj|tj| jjd}|d u rW| 	|}| 
|}	||	 }
| jdkrn| |}|
|7 }
| |
}
| |
}
|
S )Nr?   r   r   r   r   r   )rH   r   hasattrr   r   rJ   r   r   rE   r   r   r   r   r   r   )r   	input_idsr   r   inputs_embedsinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr   
embeddingsr   r   r   r$   rm   	  s,   







zYosoEmbeddings.forward)NNNNrv   rw   rx   __doc__r   rm   __classcell__r   r   r   r$   r      s    r   c                       0   e Zd Zd	 fdd	Zdd Zd
ddZ  ZS )YosoSelfAttentionNc                    sJ  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 ur[|n|j| _|j| _|j| _|jd u| _|j| _|j| _|j| _| j| j| j| jd| _|jd urt	j|j|j|jdf|jd dfd	|jd
| _d S d S )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ())r_   r{   rS   r   r   r>   F)in_channelsout_channelskernel_sizepaddingbiasgroups)r   r   r   num_attention_headsr   rI   rO   attention_head_sizeall_head_sizer   LinearrQ   rR   rj   r   attention_probs_dropout_probr   r   use_expectationr_   conv_windowuse_convr{   rS   r   
lsh_configConv2dconvr   rf   r   r   r   r$   r   -  sJ   


zYosoSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr?   r   r>   r   r
   )rH   r   r   viewpermute)r   layernew_layer_shaper   r   r$   transpose_for_scoresZ  s   
z&YosoSelfAttention.transpose_for_scoresFc                 C   s>  |  |}| | |}| | |}| |}| jr.| ||d d d d d d f  }| \}	}
}}||	|
 ||}||	|
 ||}||	|
 ||}d|d  }| 	d|
d|	|
 |
 }d}| js||k r|	|
 ||| 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s| jrt||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}|S |f}|S )N      ?g     @r       rD   r?   rF   r   r>   r
   r`   )rQ   r   rR   rj   r   r   rH   rN   squeezerepeatrO   r   rJ   catr   rE   trainingrC   r^   applyr   rz   r   r7   r   r   )r   hidden_statesattention_maskoutput_attentionsmixed_query_layer	key_layervalue_layerquery_layerconv_value_layer
batch_size	num_headsseq_lenhead_dimgpu_warp_sizepad_sizecontext_layernew_context_layer_shapeoutputsr   r   r$   rm   _  sp   

" 
zYosoSelfAttention.forwardr3   NF)rv   rw   rx   r   r   rm   r   r   r   r   r$   r   ,  s    -r   c                       8   e Zd Z fddZdejdejdejfddZ  ZS )YosoSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr   )r   r   r   r   r   denser   r   r   r   r   r   r   r   r$   r        
zYosoSelfOutput.__init__r   input_tensorreturnc                 C   &   |  |}| |}| || }|S r3   r   r   r   r   r   r   r   r   r$   rm        

zYosoSelfOutput.forwardrv   rw   rx   r   rJ   Tensorrm   r   r   r   r   r$   r         $r   c                       r   )YosoAttentionNc                    s.   t    t||d| _t|| _t | _d S )N)r   )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   rF   )rG   r   r   r   r   r   r   rQ   rR   rj   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   self_outputsattention_outputr   r   r   r$   rm     s   zYosoAttention.forwardr3   r   )rv   rw   rx   r   r   rm   r   r   r   r   r$   r     s    r   c                       2   e Zd Z fddZdejdejfddZ  ZS )YosoIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r3   )r   r   r   r   r   intermediate_sizer   r4   
hidden_actstrr   intermediate_act_fnr   r   r   r$   r     s
   
zYosoIntermediate.__init__r   r   c                 C      |  |}| |}|S r3   )r   r  r   r   r   r   r$   rm        

zYosoIntermediate.forwardr   r   r   r   r$   r    s    r  c                       r   )
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     r   zYosoOutput.__init__r   r   r   c                 C   r   r3   r   r   r   r   r$   rm     r   zYosoOutput.forwardr   r   r   r   r$   r	    r   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   	attention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   self_attention_outputsr   r   layer_outputr   r   r$   rm   	  s   
zYosoLayer.forwardc                 C   s   |  |}| ||}|S r3   )r  r   )r   r   intermediate_outputr  r   r   r$   r    s   
zYosoLayer.feed_forward_chunkr   )rv   rw   rx   r   rm   r  r   r   r   r   r$   r
    s    
	r
  c                       s0   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    _rf   r   r$   r%      r&   z(YosoEncoder.__init__.<locals>.<listcomp>F)	r   r   rf   r   
ModuleListrangenum_hidden_layersr   gradient_checkpointingr   r   r  r$   r     s   
 
zYosoEncoder.__init__NFTc                 C   s   |rdnd }|r
dnd }t | jD ].\}	}
|r||f }| jr,| jr,| |
j|||}n|
|||}|d }|r?||d f }q|rG||f }|sUtdd |||fD S t|||dS )Nr   r   r   c                 s   s    | ]	}|d ur|V  qd S r3   r   )r    vr   r   r$   	<genexpr>E  s    z&YosoEncoder.forward.<locals>.<genexpr>)last_hidden_stater   
attentions)	enumerater   r  r   _gradient_checkpointing_func__call__tupler   )r   r   r   	head_maskr   output_hidden_statesreturn_dictall_hidden_statesall_self_attentionsilayer_modulelayer_outputsr   r   r$   rm   #  s4   	

zYosoEncoder.forward)NNFFTrv   rw   rx   r   rm   r   r   r   r   r$   r    s    	r  c                       r   )YosoPredictionHeadTransformc                    sV   t    t|j|j| _t|jtrt	|j | _
n|j| _
tj|j|jd| _d S r   )r   r   r   r   r   r   r4   r  r  r   transform_act_fnr   r   r   r   r   r$   r   O  s   
z$YosoPredictionHeadTransform.__init__r   r   c                 C   s"   |  |}| |}| |}|S r3   )r   r.  r   r  r   r   r$   rm   X  s   


z#YosoPredictionHeadTransform.forwardr   r   r   r   r$   r-  N  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	ParameterrJ   r   r   r   r   r   r$   r   a  s
   

zYosoLMPredictionHead.__init__c                 C   r  r3   )r0  r1  r  r   r   r$   rm   n  r  zYosoLMPredictionHead.forwardr,  r   r   r   r$   r/  `  s    r/  c                       r   )YosoOnlyMLMHeadc                    s   t    t|| _d S r3   )r   r   r/  predictionsr   r   r   r$   r   v  s   
zYosoOnlyMLMHead.__init__sequence_outputr   c                 C   s   |  |}|S r3   )r4  )r   r5  prediction_scoresr   r   r$   rm   z  s   
zYosoOnlyMLMHead.forwardr   r   r   r   r$   r3  u  s    r3  c                   @   s$   e Zd ZdZeZdZdZ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ur|jj	  dS dS t |tj
rC|jjjd| jjd |jdurA|jj|j 	  dS dS t |tjrX|jj	  |jjd dS dS )zInitialize the weightsg        )meanstdNr   )r4   r   r   weightdatanormal_rf   initializer_ranger   zero_r   r   r   fill_)r   moduler   r   r$   _init_weights  s   

z!YosoPreTrainedModel._init_weightsN)	rv   rw   rx   r   r   config_classbase_model_prefixsupports_gradient_checkpointingrA  r   r   r   r$   r7    s    r7  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deej deej deej deej deej deej dee dee dee deeef fddZ  ZS )	YosoModelc                    s2   t  | || _t|| _t|| _|   d S r3   )r   r   rf   r   r   r  encoder	post_initr   r   r   r$   r     s
   

zYosoModel.__init__c                 C   s   | j jS r3   r   r   r   r   r   r$   get_input_embeddings  s   zYosoModel.get_input_embeddingsc                 C   s   || j _d S r3   rH  )r   rj   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)itemsrF  r   r  r   )r   heads_to_pruner   r   r   r   r$   _prune_heads  s   zYosoModel._prune_headsbatch_size, sequence_length
checkpointoutput_typerB  Nr   r   r   r   r$  r   r   r%  r&  r   c
                 C   s  |d ur|n| j j}|d ur|n| j j}|	d ur|	n| j j}	|d ur*|d ur*td|d ur9| || | }
n|d urF| d d }
ntd|
\}}|d urU|jn|j}|d u retj	||f|d}|d u rt
| 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 timer?   z5You have to specify either input_ids or inputs_embedsrD   r   r   )r   r   r   r   )r   r$  r   r%  r&  r   r   )r  r   r  cross_attentions)rf   r   r%  use_return_dictrI   %warn_if_padding_and_no_attention_maskrH   rE   rJ   onesr   r   r   r   r   r   get_extended_attention_maskget_head_maskr  rF  r   r   r  rS  )r   r   r   r   r   r$  r   r   r%  r&  r   r   r   rE   r   r   extended_attention_maskembedding_outputencoder_outputsr5  r   r   r$   rm     s^   
zYosoModel.forward)	NNNNNNNNN)rv   rw   rx   r   rJ  rK  rN  r   YOSO_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   rJ   r   boolr   r   rm   r   r   r   r   r$   rE    sR    
	

rE  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deej deej deej deej deej deej deej dee dee dee deeef fddZ  ZS )YosoForMaskedLMzcls.predictions.decoder.weightzcls.predictions.decoder.biasc                    s,   t  | t|| _t|| _|   d S r3   )r   r   rE  r   r3  clsrG  r   r   r   r$   r   N  s   

zYosoForMaskedLM.__init__c                 C   s
   | j jjS r3   rb  r4  r1  rI  r   r   r$   get_output_embeddingsW  s   
z%YosoForMaskedLM.get_output_embeddingsc                 C   s   || j j_d S r3   rc  )r   new_embeddingsr   r   r$   set_output_embeddingsZ  s   z%YosoForMaskedLM.set_output_embeddingsrO  rP  Nr   r   r   r   r$  r   labelsr   r%  r&  r   c                 C   s   |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dur8t }||d| j j|d}|
sN|f|dd  }|durL|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   r   r   r$  r   r   r%  r&  r   r?   r   losslogitsr   r  )
rf   rT  r   rb  r   r   r   r   r   r  )r   r   r   r   r   r$  r   rg  r   r%  r&  r   r5  r6  masked_lm_lossloss_fctr   r   r   r$   rm   ]  s6   
zYosoForMaskedLM.forward
NNNNNNNNNN)rv   rw   rx   _tied_weights_keysr   rd  rf  r   r\  r]  r   r^  r   r_  r   rJ   r   r`  r   r   rm   r   r   r   r   r$   ra  J  sX    		

ra  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 r3   )r   r   r   r   r   r   r   r   r   
num_labelsout_projrf   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   rf   r  rr  )r   featureskwargsxr   r   r$   rm     s   



zYosoClassificationHead.forwardr   r   r   r   r$   rp    s    rp  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                          e Zd Z fddZeedeee	e
d										ddeej deej deej d	eej d
eej deej deej dee dee dee deee	f fddZ  ZS )YosoForSequenceClassificationc                    s4   t  | |j| _t|| _t|| _|   d S r3   )r   r   rq  rE  r   rp  
classifierrG  r   r   r   r$   r     s
   

z&YosoForSequenceClassification.__init__rO  rP  Nr   r   r   r   r$  r   rg  r   r%  r&  r   c                 C   sh  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dur| j jdu rQ| jdkr7d| j _n| jdkrM|jtjksH|jtj	krMd| j _nd| j _| j jdkrot
 }| jdkri|| | }n+|||}n%| j jdkrt }||d| j|d}n| j jdkrt }|||}|
s|f|dd  }|du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).
        Nrh  r   r   
regressionsingle_label_classificationmulti_label_classificationr?   ri  )rf   rT  r   rx  problem_typerq  r   rJ   r   rO   r	   r   r   r   r   r   r   r  )r   r   r   r   r   r$  r   rg  r   r%  r&  r   r5  rk  rj  rm  r   r   r   r$   rm     sT   


"


z%YosoForSequenceClassification.forwardrn  )rv   rw   rx   r   r   r\  r]  r   r^  r   r_  r   rJ   r   r`  r   r   rm   r   r   r   r   r$   rw    sR    		

rw  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                       rv  )YosoForMultipleChoicec                    sD   t  | t|| _t|j|j| _t|jd| _| 	  d S r  )
r   r   rE  r   r   r   r   pre_classifierrx  rG  r   r   r   r$   r     s
   
zYosoForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthrP  Nr   r   r   r   r$  r   rg  r   r%  r&  r   c                 C   s  |
dur|
n| j j}
|dur|jd n|jd }|dur%|d|dnd}|dur4|d|dnd}|durC|d|dnd}|durR|d|dnd}|dure|d|d|dnd}| j||||||||	|
d	}|d }|dddf }| |}t |}| 	|}|d|}d}|durt
 }|||}|
s|f|dd  }|dur|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   r?   r`   rh  r   ri  )rf   rT  shaper   rH   r   r~  r   ReLUrx  r   r   r   r  )r   r   r   r   r   r$  r   rg  r   r%  r&  num_choicesr   hidden_statepooled_outputrk  reshaped_logitsrj  rm  r   r   r   r$   rm     sP   


zYosoForMultipleChoice.forwardrn  )rv   rw   rx   r   r   r\  r]  r   r^  r   r_  r   rJ   r   r`  r   r   rm   r   r   r   r   r$   r}    sR    
	

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                       rv  )YosoForTokenClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r3   )r   r   rq  rE  r   r   r   r   r   r   r   rx  rG  r   r   r   r$   r   i  s   
z#YosoForTokenClassification.__init__rO  rP  Nr   r   r   r   r$  r   rg  r   r%  r&  r   c                 C   s
  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|duret }|durX|ddk}|d| j}t	||dt
|j|}|||}n||d| j|d}|
s{|f|dd  }|dury|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]`.
        Nrh  r   r?   r   ri  )rf   rT  r   r   rx  r   r   rq  rJ   wherer<   ignore_indextype_asr   r   r  )r   r   r   r   r   r$  r   rg  r   r%  r&  r   r5  rk  rj  rm  active_lossactive_logitsactive_labelsr   r   r   r$   rm   t  sF   

z"YosoForTokenClassification.forwardrn  )rv   rw   rx   r   r   r\  r]  r   r^  r   r_  r   rJ   r   r`  r   r   rm   r   r   r   r   r$   r  c  sR    	

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deej deej deej d	eej d
eej deej deej deej dee dee dee deee	f fddZ  ZS )YosoForQuestionAnsweringc                    sB   t  | d|_|j| _t|| _t|j|j| _| 	  d S )Nr>   )
r   r   rq  rE  r   r   r   r   
qa_outputsrG  r   r   r   r$   r     s   
z!YosoForQuestionAnswering.__init__rO  rP  Nr   r   r   r   r$  r   start_positionsend_positionsr   r%  r&  r   c                 C   s@  |dur|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d}|d}d}|dur~|dur~t| dkrK|d}t| dkrX|d}|d}|d|}|d|}t	|d}|||}|||}|| d }|s||f|dd  }|du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.
        Nrh  r   r   r?   rF   )r  r>   )rj  start_logits
end_logitsr   r  )rf   rT  r   r  splitr   rG   rH   clampr   r   r   r  )r   r   r   r   r   r$  r   r  r  r   r%  r&  r   r5  rk  r  r  
total_lossignored_indexrm  
start_lossend_lossr   r   r   r$   rm     sP   








z YosoForQuestionAnswering.forward)NNNNNNNNNNN)rv   rw   rx   r   r   r\  r]  r   r^  r   r_  r   rJ   r   r`  r   r   rm   r   r   r   r   r$   r    sX    	

r  )Ir   rc   pathlibr   typingr   r   r   rJ   torch.utils.checkpointr   torch.nnr   r   r	   activationsr   modeling_outputsr   r   r   r   r   r   modeling_utilsr   pytorch_utilsr   r   r   utilsr   r   r   r   configuration_yosor   
get_loggerrv   loggerr^  r_  "YOSO_PRETRAINED_MODEL_ARCHIVE_LISTr2   r=   rC   r\   autogradFunctionr^   rz   Moduler   r   r   r   r  r	  r
  r  r-  r/  r3  r7  YOSO_START_DOCSTRINGr\  rE  ra  rp  rw  r}  r  r  r   r   r   r$   <module>   s    

Z< !2
2oMVVP