
    <h*Y                     H   S r SSKJr  SSKJrJr  SSKrSSKJrJr  SSK	J
r
  SSKJr  SS	KJrJrJr  S
SKJr  SSKJr  \R*                  " \5      r\\" SS9 " S S\5      5       5       r\\" SS9 " S S\5      5       5       r\\" SS9 " S S\5      5       5       r\ " S S\5      5       r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S  S!\5      r \" S"S9 " S# S$\5      5       r!\" S%S9 " S& S'\5      5       r"\" S(S9 " S) S*\ 5      5       r#/ S+Qr$g),z5PyTorch DPR model for Open Domain Question Answering.    )	dataclass)OptionalUnionN)Tensornn   )BaseModelOutputWithPooling)PreTrainedModel)ModelOutputauto_docstringlogging   )	BertModel   )	DPRConfigz6
    Class for outputs of [`DPRQuestionEncoder`].
    )custom_introc                       \ rS rSr% Sr\R                  \S'   Sr\	\
\R                  S4      \S'   Sr\	\
\R                  S4      \S'   Srg)	DPRContextEncoderOutput*   a  
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.
pooler_outputN.hidden_states
attentions __name__
__module____qualname____firstlineno____doc__torchFloatTensor__annotations__r   r   tupler   __static_attributes__r       \/var/www/html/shao/venv/lib/python3.13/site-packages/transformers/models/dpr/modeling_dpr.pyr   r   *   S     $$$=AM8E%"3"3S"89:A:>Ju00#567>r%   r   c                       \ rS rSr% Sr\R                  \S'   Sr\	\
\R                  S4      \S'   Sr\	\
\R                  S4      \S'   Srg)	DPRQuestionEncoderOutput=   a  
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.
r   N.r   r   r   r   r   r%   r&   r)   r)   =   r'   r%   r)   c                       \ rS rSr% Sr\R                  \S'   Sr\	\R                     \S'   Sr
\	\R                     \S'   Sr\	\\R                  S4      \S'   Sr\	\\R                  S4      \S	'   S
rg)DPRReaderOutputP   a  
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.
start_logitsN
end_logitsrelevance_logits.r   r   r   )r   r   r   r   r   r    r!   r"   r/   r   r0   r   r#   r   r$   r   r%   r&   r,   r,   P   s~     ###.2J**+248hu0018=AM8E%"3"3S"89:A:>Ju00#567>r%   r,   c                       \ rS rSrSrS rSrg)DPRPreTrainedModelh   Tc                    [        U[        R                  5      (       ak  UR                  R                  R                  SU R                  R                  S9  UR                  b%  UR                  R                  R                  5         gg[        U[        R                  5      (       ax  UR                  R                  R                  SU R                  R                  S9  UR                  b2  UR                  R                  UR                     R                  5         gg[        U[        R                  5      (       aJ  UR                  R                  R                  5         UR                  R                  R                  S5        gg)zInitialize the weightsg        )meanstdNg      ?)
isinstancer   Linearweightdatanormal_configinitializer_rangebiaszero_	Embeddingpadding_idx	LayerNormfill_)selfmodules     r&   _init_weights DPRPreTrainedModel._init_weightsl   s   fbii(( MM&&CT[[5R5R&S{{&  &&( '--MM&&CT[[5R5R&S!!-""6#5#56<<> .--KK""$MM$$S) .r%   r   N)r   r   r   r   _supports_sdparF   r$   r   r%   r&   r2   r2   h   s    N*r%   r2   c                      ^  \ rS rSrSrS\4U 4S jjr      SS\S\\   S\\   S\\   S	\	S
\	S\	S\
\\\S4   4   4S jjr\S\4S j5       rSrU =r$ )
DPREncoder}   
bert_modelr<   c                   > [         TU ]  U5        [        USS9U l        U R                  R                  R
                  S::  a  [        S5      eUR                  U l        U R                  S:  aD  [        R                  " U R                  R                  R
                  UR                  5      U l
        U R                  5         g )NF)add_pooling_layerr   z!Encoder hidden_size can't be zero)super__init__r   rL   r<   hidden_size
ValueErrorprojection_dimr   r8   encode_proj	post_initrD   r<   	__class__s     r&   rP   DPREncoder.__init__   s     #FeD??!!--2@AA$33"!yy)?)?)K)KVMbMbcDr%   	input_idsattention_masktoken_type_idsinputs_embedsoutput_attentionsoutput_hidden_statesreturn_dictreturn.c           
          U R                  UUUUUUUS9nUS   n	U	S S 2SS S 24   n
U R                  S:  a  U R                  U
5      n
U(       d	  X4USS  -   $ [        U	U
UR                  UR
                  S9$ )NrY   rZ   r[   r\   r]   r^   r_   r   r   )last_hidden_stater   r   r   )rL   rS   rT   r	   r   r   )rD   rY   rZ   r[   r\   r]   r^   r_   outputssequence_outputpooled_outputs              r&   forwardDPREncoder.forward   s     //))'/!5# " 
 "!*'1a0" ,,];M#3gabkAA)-'!//))	
 	
r%   c                     U R                   S:  a  U R                  R                  $ U R                  R                  R
                  $ )Nr   )rS   rT   out_featuresrL   r<   rQ   )rD   s    r&   embeddings_sizeDPREncoder.embeddings_size   s8    "##000%%111r%   )rL   rT   rS   )NNNFFF)r   r   r   r   base_model_prefixr   rP   r   r   boolr   r	   r#   rg   propertyintrk   r$   __classcell__rW   s   @r&   rJ   rJ   }   s    $	y 	 ,0+/*."'%*!!
!
 !(!
 !(	!

  '!
  !
 #!
 !
 
)5+==	>!
F 2 2 2r%   rJ   c                      ^  \ rS rSrSrS\4U 4S jjr    SS\S\S\\   S\	S	\	S
\	S\
\\\S4   4   4S jjrSrU =r$ )DPRSpanPredictor   encoderr<   c                 $  > [         TU ]  U5        [        U5      U l        [        R
                  " U R                  R                  S5      U l        [        R
                  " U R                  R                  S5      U l        U R                  5         g )Nr   r   )
rO   rP   rJ   rv   r   r8   rk   
qa_outputsqa_classifierrU   rV   s     r&   rP   DPRSpanPredictor.__init__   s_     !&)))DLL$@$@!DYYt||'C'CQGr%   rY   rZ   r\   r]   r^   r_   r`   .c           	      F   Ub  UR                  5       OUR                  5       S S u  pxU R                  UUUUUUS9n	U	S   n
U R                  U
5      nUR                  SSS9u  pUR	                  S5      R                  5       nUR	                  S5      R                  5       nU R                  U
S S 2SS S 24   5      nUR                  Xx5      nUR                  Xx5      nUR                  U5      nU(       d
  XU4U	SS  -   $ [        UUUU	R                  U	R                  S9$ )Nr   )rZ   r\   r]   r^   r_   r   r   )dim)r.   r/   r0   r   r   )sizerv   rx   splitsqueeze
contiguousry   viewr,   r   r   )rD   rY   rZ   r\   r]   r^   r_   
n_passagessequence_lengthrd   re   logitsr.   r/   r0   s                  r&   rg   DPRSpanPredictor.forward   sD    ;D:Oinn&6UbUgUgUijlklUm#
,,)'/!5#  
 "!* 1#)<<r<#: #++B/::<''+668
--oaAg.FG $((E__ZA
+00< .>?'!"+MM%!-!//))
 	
r%   )rv   ry   rx   )NFFF)r   r   r   r   rm   r   rP   r   r   rn   r   r,   r#   rg   r$   rq   rr   s   @r&   rt   rt      s    !y  +/"'%*!+
+
 +
  '	+

  +
 #+
 +
 
fck 22	3+
 +
r%   rt   c                   ,    \ rS rSr% Sr\\S'   SrSrSr	g)DPRPretrainedContextEncoder   z
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
r<   Nctx_encoderr   
r   r   r   r   r   r   r"   load_tf_weightsrm   r$   r   r%   r&   r   r      s    
 O%r%   r   c                   ,    \ rS rSr% Sr\\S'   SrSrSr	g)DPRPretrainedQuestionEncoder   r   r<   Nquestion_encoderr   r   r   r%   r&   r   r      s    
 O*r%   r   c                   ,    \ rS rSr% Sr\\S'   SrSrSr	g)DPRPretrainedReaderi	  r   r<   Nspan_predictorr   r   r   r%   r&   r   r   	  s    
 O(r%   r   zf
    The bare DPRContextEncoder transformer outputting pooler outputs as context representations.
    c                      ^  \ rS rSrS\4U 4S jjr\       SS\\   S\\   S\\   S\\   S\\	   S	\\	   S
\\	   S\
\\\S4   4   4S jj5       rSrU =r$ )DPRContextEncoderi  r<   c                 p   > [         TU ]  U5        Xl        [        U5      U l        U R                  5         g N)rO   rP   r<   rJ   r   rU   rV   s     r&   rP   DPRContextEncoder.__init__  s,     %f-r%   rY   rZ   r[   r\   r]   r^   r_   r`   .c           
         Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUb  Ub  [	        S5      eUb  UR                  5       nO"Ub  UR                  5       SS nO[	        S5      eUb  UR                  OUR                  n	Uc/  Uc  [        R                  " XS9OXR                   R                  :g  nUc$  [        R                  " U[        R                  U	S9nU R                  UUUUUUUS9n
U(       d  U
SS $ [        U
R                  U
R                  U
R                   S	9$ )
a  
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)

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 timer|   5You have to specify either input_ids or inputs_embedsdevicedtyper   rb   r   r   r   r   )r<   r]   r^   use_return_dictrR   r~   r   r    onespad_token_idzeroslongr   r   r   r   r   rD   rY   rZ   r[   r\   r]   r^   r_   input_shaper   rd   s              r&   rg   DPRContextEncoder.forward&  sl   b 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] ]%>cdd"#..*K&',,.s3KTUU%.%:!!@T@T! $ 

;6;;#;#;; 
 !"[[EJJvVN""))'/!5# # 
 12;&!//w?T?Tahasas
 	
r%   )r<   r   NNNNNNN)r   r   r   r   r   rP   r   r   r   rn   r   r   r#   rg   r$   rq   rr   s   @r&   r   r     s    y   '++/+/*.,0/3&*X
F#X
 !(X
 !(	X

  'X
 $D>X
 'tnX
 d^X
 
&fck(::	;X
 X
r%   r   zh
    The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.
    c                      ^  \ rS rSrS\4U 4S jjr\       SS\\   S\\   S\\   S\\   S\\	   S	\\	   S
\\	   S\
\\\S4   4   4S jj5       rSrU =r$ )DPRQuestionEncoderi  r<   c                 p   > [         TU ]  U5        Xl        [        U5      U l        U R                  5         g r   )rO   rP   r<   rJ   r   rU   rV   s     r&   rP   DPRQuestionEncoder.__init__  s,      *6 2r%   rY   rZ   r[   r\   r]   r^   r_   r`   .c           
         Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUb  Ub  [	        S5      eUb"  U R                  X5        UR                  5       nO"Ub  UR                  5       SS nO[	        S5      eUb  UR                  OUR                  n	Uc/  Uc  [        R                  " XS9OXR                   R                  :g  nUc$  [        R                  " U[        R                  U	S9nU R                  UUUUUUUS9n
U(       d  U
SS $ [        U
R                  U
R                   U
R"                  S	9$ )
a  
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)

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
```
Nr   r|   r   r   r   rb   r   r   )r<   r]   r^   r   rR   %warn_if_padding_and_no_attention_maskr~   r   r    r   r   r   r   r   r)   r   r   r   r   s              r&   rg   DPRQuestionEncoder.forward  sz   b 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] ]%>cdd"66yQ#..*K&',,.s3KTUU%.%:!!@T@T! $ 

;6;;#;#;; 
 !"[[EJJvVN''))'/!5# ( 
 12;'!//w?T?Tahasas
 	
r%   )r<   r   r   )r   r   r   r   r   rP   r   r   r   rn   r   r)   r#   rg   r$   rq   rr   s   @r&   r   r     s    y   '++/+/*.,0/3&*Y
F#Y
 !(Y
 !(	Y

  'Y
 $D>Y
 'tnY
 d^Y
 
'vs{);;	<Y
 Y
r%   r   zE
    The bare DPRReader transformer outputting span predictions.
    c                      ^  \ rS rSrS\4U 4S jjr\      SS\\   S\\   S\\   S\\	   S\\	   S	\\	   S
\
\\\S4   4   4S jj5       rSrU =r$ )	DPRReaderi  r<   c                 p   > [         TU ]  U5        Xl        [        U5      U l        U R                  5         g r   )rO   rP   r<   rt   r   rU   rV   s     r&   rP   DPRReader.__init__  s,     .v6r%   rY   rZ   r\   r]   r^   r_   r`   .c           	         Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUb  Ub  [	        S5      eUb"  U R                  X5        UR                  5       nO"Ub  UR                  5       SS nO[	        S5      eUb  UR                  OUR                  nUc  [        R                  " XxS9nU R                  UUUUUUS9$ )a  
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)
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.

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
```
Nr   r|   r   r   )r\   r]   r^   r_   )r<   r]   r^   r   rR   r   r~   r   r    r   r   )	rD   rY   rZ   r\   r]   r^   r_   r   r   s	            r&   rg   DPRReader.forward  s   ` 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] ]%>cdd"66yQ#..*K&',,.s3KTUU%.%:!!@T@T!"ZZCN""'/!5# # 
 	
r%   )r<   r   )NNNNNN)r   r   r   r   r   rP   r   r   r   rn   r   r,   r#   rg   r$   rq   rr   s   @r&   r   r     s    y   '++/*.,0/3&*K
F#K
 !(K
  '	K

 $D>K
 'tnK
 d^K
 
fck 22	3K
 K
r%   r   )r   r   r2   r   r   r   r   )%r   dataclassesr   typingr   r   r    r   r   modeling_outputsr	   modeling_utilsr
   utilsr   r   r   bert.modeling_bertr   configuration_dprr   
get_loggerr   loggerr   r)   r,   r2   rJ   rt   r   r   r   r   r   r   __all__r   r%   r&   <module>r      s   < ! "   : - 
 + ( 
		H	% 

?k 
? 
? 

?{ 
? 
? 
?k ? ?$ * * *(52# 52p6
) 6
|&"4 &+#5 +), )  
a
3 a

a
H 
b
5 b

b
J 
T
# T

T
nr%   