U
    ,-ep                     @   s  d Z ddlmZ ddlmZmZmZ ddlZddlmZm	Z	 ddl
mZ ddlmZ dd	lmZmZmZmZmZ d
dlmZmZ ddlmZ eeZdZdZddgZddgZddgZ eG dd deZ!eG dd deZ"eG dd deZ#G dd deZ$G dd de$Z%G dd  d e$Z&G d!d" d"e$Z'G d#d$ d$e$Z(G d%d& d&e$Z)d'Z*d(Z+d)Z,ed*e*G d+d, d,e'Z-ed-e*G d.d/ d/e(Z.ed0e*G d1d2 d2e)Z/dS )3z6 PyTorch DPR model for Open Domain Question Answering.    )	dataclass)OptionalTupleUnionN)Tensornn   )BaseModelOutputWithPooling)PreTrainedModel)ModelOutputadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )BertEncoder	BertModel   )	DPRConfigr   z'facebook/dpr-ctx_encoder-single-nq-basez&facebook/dpr-ctx_encoder-multiset-basez,facebook/dpr-question_encoder-single-nq-basez+facebook/dpr-question_encoder-multiset-basez"facebook/dpr-reader-single-nq-basez!facebook/dpr-reader-multiset-basec                   @   sH   e Zd ZU dZejed< dZee	ej  ed< dZ
ee	ej  ed< dS )DPRContextEncoderOutputac  
    Class for outputs of [`DPRQuestionEncoder`].

    Args:
        pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
            The DPR encoder outputs the *pooler_output* that corresponds to the context representation. Last layer
            hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
            This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.
        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.
    pooler_outputNhidden_states
attentions__name__
__module____qualname____doc__torchFloatTensor__annotations__r   r   r   r    r!   r!   e/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/dpr/modeling_dpr.pyr   =   s   

r   c                   @   sH   e Zd ZU dZejed< dZee	ej  ed< dZ
ee	ej  ed< dS )DPRQuestionEncoderOutputac  
    Class for outputs of [`DPRQuestionEncoder`].

    Args:
        pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
            The DPR encoder outputs the *pooler_output* that corresponds to the question representation. Last layer
            hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
            This output is to be used to embed questions for nearest neighbors queries with context embeddings.
        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.
    r   Nr   r   r   r!   r!   r!   r"   r#   Y   s   

r#   c                   @   sd   e Zd ZU dZ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 )DPRReaderOutputa  
    Class for outputs of [`DPRQuestionEncoder`].

    Args:
        start_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
            Logits of the start index of the span for each passage.
        end_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
            Logits of the end index of the span for each passage.
        relevance_logits (`torch.FloatTensor` of shape `(n_passages, )`):
            Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the
            question, compared to all the other passages.
        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.
    start_logitsN
end_logitsrelevance_logitsr   r   )r   r   r   r   r   r   r    r&   r'   r   r   r   r   r!   r!   r!   r"   r$   u   s   

r$   c                   @   s   e Zd Zdd ZdddZdS )DPRPreTrainedModelc                 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stdNg      ?)
isinstancer   LinearweightdataZnormal_configZinitializer_rangeZbiasZzero_Z	EmbeddingZpadding_idxZ	LayerNormZfill_)selfmoduler!   r!   r"   _init_weights   s    

z DPRPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S N)r)   r   Zgradient_checkpointing)r.   r/   valuer!   r!   r"   _set_gradient_checkpointing   s    
z.DPRPreTrainedModel._set_gradient_checkpointingN)F)r   r   r   r0   r3   r!   r!   r!   r"   r(      s   r(   c                       sr   e Zd ZdZed fddZdeee ee ee eeee	e
eedf f dd	d
ZeedddZ  ZS )
DPREncoder
bert_modelr-   c                    sd   t  | t|dd| _| jjjdkr0td|j| _| jdkrXt	| jjj|j| _
|   d S )NF)Zadd_pooling_layerr   z!Encoder hidden_size can't be zero)super__init__r   r5   r-   hidden_size
ValueErrorprojection_dimr   r*   encode_proj	post_initr.   r-   	__class__r!   r"   r8      s    
zDPREncoder.__init__NF.	input_idsattention_masktoken_type_idsinputs_embedsoutput_attentionsoutput_hidden_statesreturn_dictreturnc              	   C   sv   | j |||||||d}|d }	|	d d dd d f }
| jdkrJ| |
}
|sb|	|
f|dd   S t|	|
|j|jdS )NrB   rC   rD   rE   rF   rG   rH   r   r   )Zlast_hidden_stater   r   r   )r5   r;   r<   r	   r   r   )r.   rB   rC   rD   rE   rF   rG   rH   outputssequence_outputZpooled_outputr!   r!   r"   forward   s*    
	

zDPREncoder.forward)rI   c                 C   s   | j dkr| jjS | jjjS )Nr   )r;   r<   Zout_featuresr5   r-   r9   )r.   r!   r!   r"   embeddings_size   s    
zDPREncoder.embeddings_size)NNNFFF)r   r   r   base_model_prefixr   r8   r   r   boolr   r	   r   rM   propertyintrN   __classcell__r!   r!   r?   r"   r4      s(         #r4   c                       sV   e Zd ZdZed fddZdeeee eeee	e
eedf f dd	d
Z  ZS )DPRSpanPredictorencoderr6   c                    sF   t  | t|| _t| jjd| _t| jjd| _| 	  d S )Nr   r   )
r7   r8   r4   rU   r   r*   rN   
qa_outputsqa_classifierr=   r>   r?   r!   r"   r8      s
    
zDPRSpanPredictor.__init__NF.rB   rC   rE   rF   rG   rH   rI   c                 C   s   |d k	r|  n|  d d \}}| j||||||d}	|	d }
| |
}|jddd\}}|d }|d }| |
d d dd d f }|||}|||}||}|s|||f|	dd   S t||||	j	|	j
dS )Nr   )rC   rE   rF   rG   rH   r   r   )dim)r%   r&   r'   r   r   )sizerU   rV   splitZsqueeze
contiguousrW   viewr$   r   r   )r.   rB   rC   rE   rF   rG   rH   Z
n_passagesZsequence_lengthrK   rL   Zlogitsr%   r&   r'   r!   r!   r"   rM      s6    
$

zDPRSpanPredictor.forward)NFFF)r   r   r   rO   r   r8   r   r   rP   r   r$   r   rM   rS   r!   r!   r?   r"   rT      s       rT   c                   @   s   e Zd ZdZeZdZdZdS )DPRPretrainedContextEncoder
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    Nctx_encoderr   r   r   r   r   config_classZload_tf_weightsrO   r!   r!   r!   r"   r_   "  s   r_   c                   @   s   e Zd ZdZeZdZdZdS )DPRPretrainedQuestionEncoderr`   Nquestion_encoderrb   r!   r!   r!   r"   rd   -  s   rd   c                   @   s   e Zd ZdZeZdZdZdS )DPRPretrainedReaderr`   Nspan_predictorrb   r!   r!   r!   r"   rf   8  s   rf   a=  

    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 ([`DPRConfig`]): 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. To match pretraining, DPR input sequence should be
            formatted with [CLS] and [SEP] tokens as follows:

            (a) For sequence pairs (for a pair title+text for example):

            ```
            tokens:         [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
            token_type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
            ```

            (b) For single sequences (for a question for example):

            ```
            tokens:         [CLS] the dog is hairy . [SEP]
            token_type_ids:   0   0   0   0  0     0   0
            ```

            DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
            rather than the left.

            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)
        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.
a?  
    Args:
        input_ids (`Tuple[torch.LongTensor]` of shapes `(n_passages, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question
            and 2) the passages titles and 3) the passages texts To match pretraining, DPR `input_ids` sequence should
            be formatted with [CLS] and [SEP] with the format:

                `[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>`

            DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
            rather than the left.

            Indices can be obtained using [`DPRReaderTokenizer`]. See this class documentation for more details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.FloatTensor` of shape `(n_passages, 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)
        inputs_embeds (`torch.FloatTensor` of shape `(n_passages, 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.
z\The bare DPRContextEncoder transformer outputting pooler outputs as context representations.c                       s   e Zd Zed fddZeeeee	dd
e
e e
e e
e e
e e
e e
e e
e eeeedf f ddd	Z  ZS )DPRContextEncoderr6   c                    s(   t  | || _t|| _|   d S r1   )r7   r8   r-   r4   ra   r=   r>   r?   r!   r"   r8     s    
zDPRContextEncoder.__init__output_typerc   N.rA   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n4|dk	rh| }n"|dk	r| dd }ntd|dk	r|jn|j}	|dkr|dkrtj||	dn
|| j j	k}|dkrtj
|tj|	d}| j|||||||d}
|s|
dd S t|
j|
j|
jd	S )
a  
        Return:

        Examples:

        ```python
        >>> from transformers import DPRContextEncoder, DPRContextEncoderTokenizer

        >>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
        >>> model = DPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
        >>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
        >>> embeddings = model(input_ids).pooler_output
        ```NDYou cannot specify both input_ids and inputs_embeds at the same timerY   5You have to specify either input_ids or inputs_embedsdeviceZdtypern   rJ   r   r   r   r   )r-   rF   rG   use_return_dictr:   r[   rn   r   onespad_token_idzeroslongra   r   r   r   r   r.   rB   rC   rD   rE   rF   rG   rH   input_shapern   rK   r!   r!   r"   rM     sF    



  zDPRContextEncoder.forward)NNNNNNN)r   r   r   r   r8   r   DPR_ENCODERS_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr   r   rP   r   r   rM   rS   r!   r!   r?   r"   rh     s(   
       rh   z^The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.c                       s   e Zd Zed fddZeeeee	dd
e
e e
e e
e e
e e
e e
e e
e eeeedf f ddd	Z  ZS )DPRQuestionEncoderr6   c                    s(   t  | || _t|| _|   d S r1   )r7   r8   r-   r4   re   r=   r>   r?   r!   r"   r8     s    
zDPRQuestionEncoder.__init__ri   N.rA   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r|dkrtj	||	dn
|| j j
k}|dkrtj|tj|	d}| j|||||||d}
|s|
dd S t|
j|
j|
jd	S )
a  
        Return:

        Examples:

        ```python
        >>> from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer

        >>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
        >>> model = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
        >>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
        >>> embeddings = model(input_ids).pooler_output
        ```
        Nrk   rY   rl   rm   ro   rJ   r   rp   )r-   rF   rG   rq   r:   %warn_if_padding_and_no_attention_maskr[   rn   r   rr   rs   rt   ru   re   r#   r   r   r   rv   r!   r!   r"   rM     sH    



  zDPRQuestionEncoder.forward)NNNNNNN)r   r   r   r   r8   r   rx   r   r#   ry   r   r   rP   r   r   rM   rS   r!   r!   r?   r"   rz     s(   
       rz   z;The bare DPRReader transformer outputting span predictions.c                       sz   e Zd Zed fddZeeeee	dd
e
e e
e e
e e
e e
e e
e eeeedf f ddd	Z  ZS )	DPRReaderr6   c                    s(   t  | || _t|| _|   d S r1   )r7   r8   r-   rT   rg   r=   r>   r?   r!   r"   r8   ]  s    
zDPRReader.__init__ri   N.rX   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	||d}| j
||||||dS )a  
        Return:

        Examples:

        ```python
        >>> from transformers import DPRReader, DPRReaderTokenizer

        >>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
        >>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
        >>> encoded_inputs = tokenizer(
        ...     questions=["What is love ?"],
        ...     titles=["Haddaway"],
        ...     texts=["'What Is Love' is a song recorded by the artist Haddaway"],
        ...     return_tensors="pt",
        ... )
        >>> outputs = model(**encoded_inputs)
        >>> start_logits = outputs.start_logits
        >>> end_logits = outputs.end_logits
        >>> relevance_logits = outputs.relevance_logits
        ```
        Nrk   rY   rl   rm   )rE   rF   rG   rH   )r-   rF   rG   rq   r:   r{   r[   rn   r   rr   rg   )	r.   rB   rC   rE   rF   rG   rH   rw   rn   r!   r!   r"   rM   d  s.    !

zDPRReader.forward)NNNNNN)r   r   r   r   r8   r   DPR_READER_INPUTS_DOCSTRINGr   r$   ry   r   r   rP   r   r   rM   rS   r!   r!   r?   r"   r|   X  s$   
      r|   )0r   dataclassesr   typingr   r   r   r   r   r   Zmodeling_outputsr	   Zmodeling_utilsr
   utilsr   r   r   r   r   Zbert.modeling_bertr   r   Zconfiguration_dprr   Z
get_loggerr   loggerry   Z_CHECKPOINT_FOR_DOCZ1DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LISTZ2DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LISTZ(DPR_READER_PRETRAINED_MODEL_ARCHIVE_LISTr   r#   r$   r(   r4   rT   r_   rd   rf   ZDPR_START_DOCSTRINGrx   r}   rh   rz   r|   r!   r!   r!   r"   <module>   sf   
 8>8%MN