
    qia                        d Z ddl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 dd	lmZ dd
l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m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) ddl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2  e)jf                  e4      Z5de6de6dejn                  fdZ8de6de6dejn                  fdZ9 G d dejt                        Z;	 	 dAdejt                  dejn                  d ejn                  d!ejn                  d"ejn                  dz  d#e<dz  d$e<d%e#e'   fd&Z= G d' d(ejt                        Z> G d) d*ejt                        Z? G d+ d,e      Z@ G d- d.ejt                        ZAe( G d/ d0e!             ZBe( G d1 d2eB             ZC e(d34       G d5 d6eB             ZD e(d74       G d8 d9eB             ZEe( G d: d;eB             ZFe( G d< d=eB             ZGe( G d> d?eB             ZHg d@ZIy)Bz
PyTorch DistilBERT model adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM) and in
part from HuggingFace PyTorch version of Google AI Bert model (https://github.com/google-research/bert)
    )CallableN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )initialization)get_activation)PreTrainedConfig)is_deepspeed_zero3_enabled)create_bidirectional_mask)GradientCheckpointingLayer)BaseModelOutputMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)apply_chunking_to_forward)TransformersKwargsauto_docstringlogging)deprecate_kwarg)can_return_tuplemerge_with_config_defaults)capture_outputs   )DistilBertConfign_posdimoutc                    t               rddd l}|j                  j                  |d      5  t        j
                  j                         dk(  rt        | ||      cd d d        S 	 d d d        y t        | ||      S # 1 sw Y   y xY w)Nr   )modifier_rankr"   r#   r$   )r   	deepspeedzeroGatheredParameterstorchdistributedget_rank_create_sinusoidal_embeddings)r"   r#   r$   r(   s       d/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/distilbert/modeling_distilbert.pycreate_sinusoidal_embeddingsr0   ?   s    !#^^..s!.D 	T  ))+q045csS	T 	T0	T 	T -5csKK		T 	Ts   /A==Bc                    t        j                  t        |       D cg c];  }t        |      D cg c]$  }|t        j                  dd|dz  z  |z        z  & c}= c}}      }d|_        t        j                  t        j                  |d d dd df               |d d dd df<   t        j                  t        j                  |d d dd df               |d d dd df<   |j                          |S c c}w c c}}w )Ni'     Fr   r    )
nparrayrangepowerrequires_gradr+   FloatTensorsincosdetach_)r"   r#   r$   posjposition_encs         r/   r.   r.   J   s    88hmnshtuadQVWZQ[\AcBHHUAaL34F$GG\uvLC$$RVVLADqD,A%BCC14a4L$$RVVLADqD,A%BCC14a4LKKMJ ]us   C<
)C7C<
7C<
c            
            e Zd Zdef fdZ eddd      	 	 ddej                  dej                  dz  d	ej                  dz  d
ej                  fd       Z	 xZ
S )
Embeddingsconfigc                 
   t         |           t        j                  |j                  |j
                  |j                        | _        t        j                  |j                  |j
                        | _	        t        j                  |j
                  d      | _
        t        j                  |j                        | _        | j                  dt        j                  |j                        j!                  d      d       y )N)padding_idx-q=epsposition_idsr    F)
persistent)super__init__r   	Embedding
vocab_sizer#   pad_token_idword_embeddingsmax_position_embeddingsposition_embeddings	LayerNormDropoutdropoutregister_bufferr+   arangeexpandselfrA   	__class__s     r/   rL   zEmbeddings.__init__T   s    !||F,=,=vzzW]WjWjk#%<<0N0NPVPZPZ#[ fjje<zz&..1ELL)G)GHOOPWXej 	 	
    input_embedsz5.6.0inputs_embeds)versionnew_nameN	input_idsrG   returnc                    || j                  |      }|j                  d      }|rt        | d      r| j                  d d d |f   }nPt	        j
                  |t        j                  |j                        }|j                  d      j                  |      }| j                  |      }||z   }| j                  |      }| j                  |      }|S )Nr    rG   )dtypedevicer   )rP   sizehasattrrG   r+   rW   longre   	unsqueeze	expand_asrR   rS   rU   )rZ   ra   r^   rG   
seq_lengthrR   
embeddingss          r/   forwardzEmbeddings.forward_   s       00;M"''*
 t^,#00KZK@$||JejjQZQaQab+55a8BB9M"66|D"%88
^^J/
\\*-
r\   )NN)__name__
__module____qualname__r   rL   r   r+   Tensor
LongTensorrm   __classcell__r[   s   @r/   r@   r@   S   sx    	
/ 	
 ^WO .204	<< ||d* &&-	
 
 Pr\   r@   modulequerykeyvalueattention_maskscalingrU   kwargsc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|||z   }t        j
                  j                  |d      }t        j
                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )NrI         r2   r   r#   )ptrainingr    )
rf   r+   matmul	transposer   
functionalsoftmaxrU   r   
contiguous)
ru   rv   rw   rx   ry   rz   rU   r{   attn_weightsattn_outputs
             r/   eager_attention_forwardr   ~   s     **R.D( <<s}}Q':;gEL!#n4==((2(>L==((6??([L,,|U3K''1-88:K$$r\   c            
            e Zd Zdef fdZ	 d	dej                  dej                  dz  dee	   de
ej                     fdZ xZS )
DistilBertSelfAttentionrA   c                 4   t         |           || _        |j                  | _        |j                  | _        | j                  | j                  z  | _        | j
                  dz  | _        | j                  | j                  z  dk7  r&t        d| j                   d| j                   d      t        j                  |j                  |j                        | _
        t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        t        j                  |j                        | _        d| _        y )	Nr}   r   zself.n_heads: z must divide self.dim:  evenlyin_featuresout_featuresr   F)rK   rL   rA   n_headsr#   attention_head_sizerz   
ValueErrorr   Linearq_link_linv_linout_linrT   attention_dropoutrU   	is_causalrY   s     r/   rL   z DistilBertSelfAttention.__init__   s   ~~::#'88t||#; //5 88dll"a'~dll^;RSWS[S[R\\cdeeYY6::FJJO
YY6::FJJO
YY6::FJJO
yyVZZfjjQzzF$<$<=r\   Nhidden_statesry   r{   rb   c                    |j                   d d }g |d| j                  } | j                  |      j                  | j	                  dd      } | j                  |      j                  | j	                  dd      } | j                  |      j                  | j	                  dd      }t        j                  | j                  j                  t              }	 |	| ||||f| j                  sdn| j                  j                  | j                  d|\  }
} |
j                   g |d j#                         }
| j%                  |
      }
|
|fS )NrI   r    r2           )rU   rz   )shaper   r   viewr   r   r   r   get_interfacerA   _attn_implementationr   r   rU   r   rz   reshaper   r   )rZ   r   ry   r{   input_shapehidden_shapequery_layer	key_layervalue_layerattention_interfacer   r   s               r/   rm   zDistilBertSelfAttention.forward   sV    $))#2.CCbC$*B*BC 5djj/44lCMMaQRS2DJJ}-22LAKKAqQ	4djj/44lCMMaQRS(?(M(MKK,,.E)
 %8	%
  $}}C$,,..LL	%
 	%
!\ *k));;;;FFHll;/L((r\   N)rn   ro   rp   r   rL   r+   rq   r8   r   r   tuplerm   rs   rt   s   @r/   r   r      s^    / 2 48)||) ))D0) +,	)
 
u||	)r\   r   c                        e Zd Zdef fdZdej                  dej                  fdZdej                  dej                  fdZ xZ	S )FFNrA   c                    t         |           t        j                  |j                        | _        |j
                  | _        d| _        t        j                  |j                  |j                        | _
        t        j                  |j                  |j                        | _        t        |j                        | _        y )Nr   r    r   )rK   rL   r   rT   rU   chunk_size_feed_forwardseq_len_dimr   r#   
hidden_dimlin1lin2r
   
activationrY   s     r/   rL   zFFN.__init__   s    zzFNN3'-'E'E$II&**6CTCTU	II&*;*;&**U	():):;r\   inputrb   c                 Z    t        | j                  | j                  | j                  |      S r   )r   ff_chunkr   r   )rZ   r   s     r/   rm   zFFN.forward   s%    (8T8TVZVfVfhmnnr\   c                     | j                  |      }| j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r   rU   )rZ   r   xs      r/   r   zFFN.ff_chunk   s=    IIeOOAIIaLLLOr\   )
rn   ro   rp   r   rL   r+   rq   rm   r   rs   rt   s   @r/   r   r      sI    </ <oU\\ oell oell u|| r\   r   c                        e Zd Zdef fdZ	 d
dej                  dej                  dz  dee   de	ej                  df   fd	Z
 xZS )TransformerBlockrA   c                 ~   t         |           |j                  |j                  z  dk7  r&t	        d|j                   d|j                   d      t        |      | _        t        j                  |j                  d      | _	        t        |      | _        t        j                  |j                  d      | _        y )Nr   zconfig.n_heads z must divide config.dim r   rD   )normalized_shaperF   )rK   rL   r#   r   r   r   	attentionr   rS   sa_layer_normr   ffnoutput_layer_normrY   s     r/   rL   zTransformerBlock.__init__   s     ::&!+v~~.>>VW]WaWaVbbijkk08\\6::5Qv;!#vzzu!Ur\   Nr   ry   r{   rb   .c                      | j                   |fd|i|\  }}| j                  ||z         }| j                  |      }| j                  ||z         }|S )Nry   )r   r   r   r   )rZ   r   ry   r{   attention_output_
ffn_outputs          r/   rm   zTransformerBlock.forward   su     -dnn
)
 
!
  --.>.NO XX./
++J9I,IJ
r\   r   )rn   ro   rp   r   rL   r+   rq   r   r   r   rm   rs   rt   s   @r/   r   r      sc    V/ V  /3|| t+ +,	
 
u||S 	!r\   r   c            	       t     e Zd Zdef fdZ	 d	dej                  dej                  dz  dee   de	fdZ
 xZS )
TransformerrA   c                     t         |           |j                  | _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _        y c c}w )NF)	rK   rL   n_layersr   
ModuleListr5   r   layergradient_checkpointing)rZ   rA   r   r[   s      r/   rL   zTransformer.__init__  sQ    ]]eFOOF\#]$4V$<#]^
&+# $^s   A-Nr   ry   r{   rb   c                 P    | j                   D ]  } |||fi |} t        |      S )N)last_hidden_state)r   r   )rZ   r   ry   r{   layer_modules        r/   rm   zTransformer.forward  s>     !JJ 	L( M	 ??r\   r   )rn   ro   rp   r   rL   r+   rq   r   r   r   rm   rs   rt   s   @r/   r   r   
  sX    ,/ , /3@||@ t+@ +,	@
 
@r\   r   c                        e Zd ZU eed<   dZdZdZdZdZ	dZ
eedZ ej                         dej"                  f fd       Z xZS )DistilBertPreTrainedModelrA   
distilbertT)r   
attentionsru   c           
      ,   t         |   |       t        |t              r| j                  j
                  rt        j                  |j                  j                  t        | j                  j                  | j                  j                  t        j                  |j                  j                                     t        j                  |j                  t        j                   |j                  j"                  d         j%                  d             yy)zInitialize the weights.rI   rH   N)rK   _init_weights
isinstancer@   rA   sinusoidal_pos_embdsinitcopy_rR   weightr0   rQ   r#   r+   
empty_likerG   rW   r   rX   )rZ   ru   r[   s     r/   r   z'DistilBertPreTrainedModel._init_weights0  s     	f%fj){{//

..550;;(()C)C)J)JK JJv**ELL9L9L9R9RSU9V,W,^,^_f,gh *r\   )rn   ro   rp   r!   __annotations__base_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr   r   _can_record_outputsr+   no_gradr   Moduler   rs   rt   s   @r/   r   r   "  sd    $&*#N"&)-
 U]]_iBII i ir\   r   c                   j    e Zd Zdef fdZdej                  fdZdefdZ	dej                  fdZ
dej                  fd	Zeee	 	 	 	 ddej                   d
z  dej                   d
z  dej                   d
z  dej                   d
z  dee   deeej                   df   z  fd                     Z xZS )DistilBertModelrA   c                     t         |   |       t        |      | _        t	        |      | _        | j                          y r   )rK   rL   r@   rl   r   transformer	post_initrY   s     r/   rL   zDistilBertModel.__init__C  s5     $V,&v. 	r\   rb   c                 .    | j                   j                  S z1
        Returns the position embeddings
        )rl   rR   rZ   s    r/   get_position_embeddingsz'DistilBertModel.get_position_embeddingsL  s     222r\   new_num_position_embeddingsc                    || j                   j                  z
  }|dk(  ryt        j                  d| d       || j                   _        | j                  j
                  j                  j                         }t        j                  | j                   j                  | j                   j                        | j                  _        | j                   j                  rKt        | j                   j                  | j                   j                  | j
                  j                         nt        j                         5  |dkD  r8t        j                  |      | j                  j
                  j                  d|  n1t        j                  |d|       | j                  j
                  _        ddd       | j                  j
                  j!                  | j"                         y# 1 sw Y   9xY w)  
        Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.

        Arguments:
            new_num_position_embeddings (`int`):
                The number of new position embedding matrix. If position embeddings are learned, increasing the size
                will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
                end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
                size will add correct vectors at the end following the position encoding algorithm, whereas reducing
                the size will remove vectors from the end.
        r   Nz(Setting `config.max_position_embeddings=z`...r'   )rA   rQ   loggerinforl   rR   r   cloner   rM   r#   r   r0   r+   r   	Parametertore   )rZ   r   num_position_embeds_diffold_position_embeddings_weights       r/   resize_position_embeddingsz*DistilBertModel.resize_position_embeddingsR  su    $?AdAd#d  $q(>?Z>[[_`a.I+)-)L)L)S)S)Y)Y)[&.0ll4;;;^;^`d`k`k`o`o.p+;;++(kk99t{{TXTlTlTsTs  +a/]_]i]i6^DOO77>>?YAY@YZ BD67P8PQBDOO77> 	++..t{{; s   :A/G!!G*c                 .    | j                   j                  S r   rl   rP   r   s    r/   get_input_embeddingsz$DistilBertModel.get_input_embeddings|  s    ...r\   new_embeddingsc                 &    || j                   _        y r   r   rZ   r   s     r/   set_input_embeddingsz$DistilBertModel.set_input_embeddings  s    *8'r\   Nra   ry   r^   rG   r{   .c                     |du |duz  rt        d      | j                  |||      }t        | j                  ||      } | j                  d||d|S )   
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
            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)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, 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.
        Nz:You must specify exactly one of input_ids or inputs_embeds)rA   r^   ry   )r   ry    )r   rl   r   rA   r   )rZ   ra   ry   r^   rG   r{   rl   s          r/   rm   zDistilBertModel.forward  sw    0 -t";<YZZ__Y|L
2;;$)
  t 
$)
 
 	
r\   )NNNN)rn   ro   rp   r   rL   r   rM   r   intr   r   r   r   r   r   r+   rq   r   r   r   r   rm   rs   rt   s   @r/   r   r   A  s    / 3 3(<c (<T/bll /92<< 9   *..2-1,0$
<<$&$
 t+$
 ||d*	$

 llT)$
 +,$
 
5s!23	3$
    $
r\   r   zI
    DistilBert Model with a `masked language modeling` head on top.
    )custom_introc                       e Zd ZddiZdef fdZdej                  fdZde	fdZ
dej                  fd	Zd
ej                  fdZee	 	 	 	 	 ddej"                  dz  dej"                  dz  dej"                  dz  dej$                  dz  dej"                  dz  dee   deeej"                  df   z  fd              Z xZS )DistilBertForMaskedLMzvocab_projector.weightz,distilbert.embeddings.word_embeddings.weightrA   c                    t         |   |       t        |j                        | _        t	        |      | _        t        j                  |j                  |j                        | _	        t        j                  |j                  d      | _        t        j                  |j                  |j                        | _        | j                          t        j                         | _        y )NrD   rE   )rK   rL   r
   r   r   r   r   r   r#   vocab_transformrS   vocab_layer_normrN   vocab_projectorr   r   mlm_loss_fctrY   s     r/   rL   zDistilBertForMaskedLM.__init__  s     ():):;)&1!yyVZZ@ "VZZU C!yyV5F5FG 	//1r\   rb   c                 6    | j                   j                         S r   r   r   r   s    r/   r   z-DistilBertForMaskedLM.get_position_embeddings       6688r\   r   c                 :    | j                   j                  |       yr   Nr   r   rZ   r   s     r/   r   z0DistilBertForMaskedLM.resize_position_embeddings       	223NOr\   c                     | j                   S r   r
  r   s    r/   get_output_embeddingsz+DistilBertForMaskedLM.get_output_embeddings  s    ###r\   r   c                     || _         y r   r  r   s     r/   set_output_embeddingsz+DistilBertForMaskedLM.set_output_embeddings  s
    -r\   Nra   ry   r^   labelsrG   r{   .c           	          | j                   d||||dd|}|d   }| j                  |      }	| j                  |	      }	| j                  |	      }	| j	                  |	      }	d}
|@| j                  |	j                  d|	j                  d            |j                  d            }
t        |
|	|j                  |j                        S )a  
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
            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)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, 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.
        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]`.
        Tra   ry   r^   rG   return_dictr   NrI   losslogitsr   r   r  )r   r  r   r	  r
  r  r   rf   r   r   r   )rZ   ra   ry   r^   r  rG   r{   dlbrt_outputr   prediction_logitsmlm_losss              r/   rm   zDistilBertForMaskedLM.forward  s    8 't 
)'%
 
 %Q 00? OO,=> 112CD 001BC(():)?)?DUDZDZ[]D^)_agalalmoapqH$&44#..	
 	
r\   NNNNN)rn   ro   rp   _tied_weights_keysr   rL   r   rM   r   r  r   r   r  r  r   r   r+   rq   rr   r   r   r   r   rm   rs   rt   s   @r/   r  r    s    34bc2/ 29 9Pc P$ryy $.BII .  *..2-1*.,01
<<$&1
 t+1
 ||d*	1

   4'1
 llT)1
 +,1
 
%c 12	21
  1
r\   r  z
    DistilBert 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def fdZdej                  fdZdefdZ	e
e	 	 	 	 	 ddej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  dej                  dz  dee   deeej                  df   z  fd              Z xZS )#DistilBertForSequenceClassificationrA   c                    t         |   |       |j                  | _        || _        t	        |      | _        t        j                  |j                  |j                        | _	        t        j                  |j                  |j                        | _
        t        j                  |j                        | _        | j                          y r   )rK   rL   
num_labelsrA   r   r   r   r   r#   pre_classifier
classifierrT   seq_classif_dropoutrU   r   rY   s     r/   rL   z,DistilBertForSequenceClassification.__init__  s      ++)&1 ii

FJJ?))FJJ0A0ABzz&"<"<= 	r\   rb   c                 6    | j                   j                         S r   r  r   s    r/   r   z;DistilBertForSequenceClassification.get_position_embeddings'  r  r\   r   c                 :    | j                   j                  |       yr  r  r  s     r/   r   z>DistilBertForSequenceClassification.resize_position_embeddings-  r  r\   Nra   ry   r^   r  rG   r{   .c           	      F    | j                   d||||dd|}|d   }|dddf   }	| j                  |	      }	 t        j                         |	      }	| j	                  |	      }	| j                  |	      }
d}|| j                  j                  | j                  dk(  rd| j                  _        nl| j                  dkD  rL|j                  t        j                  k(  s|j                  t        j                  k(  rd| j                  _        nd| j                  _        | j                  j                  dk(  rIt               }| j                  dk(  r& ||
j                         |j                               }n ||
|      }n| j                  j                  dk(  r=t               } ||
j!                  d	| j                        |j!                  d	            }n,| j                  j                  dk(  rt#               } ||
|      }t%        ||
|j&                  |j(                  
      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).
        Tr  r   Nr    
regressionsingle_label_classificationmulti_label_classificationrI   r  r  )r   r)  r   ReLUrU   r*  rA   problem_typer(  rd   r+   rh   r  r   squeezer   r   r   r   r   r   )rZ   ra   ry   r^   r  rG   r{   distilbert_outputhidden_statepooled_outputr  r  loss_fcts                r/   rm   z+DistilBertForSequenceClassification.forward;  s   " ,DOO 
)'%
 
 )+$QT*++M:!	-0]3/{{''/??a'/;DKK,__q(fllejj.HFLL\a\e\eLe/LDKK,/KDKK,{{''<7"9??a'#FNN$4fnn6FGD#FF3D))-JJ+-B @&++b/R))-II,./'+99(33	
 	
r\   r#  )rn   ro   rp   r   rL   r   rM   r   r  r   r   r   r+   rq   rr   r   r   r   r   rm   rs   rt   s   @r/   r&  r&    s    / 9 9Pc P  *..2-1*.,0:
<<$&:
 t+:
 ||d*	:

   4':
 llT):
 +,:
 
"E%,,*;$<	<:
  :
r\   r&  c                   `    e Zd Zdef fdZdej                  fdZdefdZ	e
e	 	 	 	 	 	 ddej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  dej                  dz  dej                  dz  dee   deeej                  df   z  fd              Z xZS )DistilBertForQuestionAnsweringrA   c                 X   t         |   |       t        |      | _        t	        j
                  |j                  |j                        | _        |j                  dk7  rt        d|j                         t	        j                  |j                        | _        | j                          y )Nr2   z)config.num_labels should be 2, but it is )rK   rL   r   r   r   r   r#   r(  
qa_outputsr   rT   
qa_dropoutrU   r   rY   s     r/   rL   z'DistilBertForQuestionAnswering.__init__|  s     )&1))FJJ0A0AB!HIZIZH[\]]zz&"3"34 	r\   rb   c                 6    | j                   j                         S r   r  r   s    r/   r   z6DistilBertForQuestionAnswering.get_position_embeddings  r  r\   r   c                 :    | j                   j                  |       yr  r  r  s     r/   r   z9DistilBertForQuestionAnswering.resize_position_embeddings  r  r\   Nra   ry   r^   start_positionsend_positionsrG   r{   .c           	          | j                   d||||dd|}|d   }	| j                  |	      }	| j                  |	      }
|
j                  dd      \  }}|j	                  d      j                         }|j	                  d      j                         }d}||t        |j                               dkD  r|j	                  d      }t        |j                               dkD  r|j	                  d      }|j                  d      }|j                  d|      }|j                  d|      }t        j                  |      } |||      } |||      }||z   d	z  }t        ||||j                  |j                  
      S )r  Tr  r   r    rI   r~   N)ignore_indexr2   )r  start_logits
end_logitsr   r   r  )r   rU   r<  splitr4  r   lenrf   clampr   r   r   r   r   )rZ   ra   ry   r^   r@  rA  rG   r{   r5  r   r  rD  rE  
total_lossignored_indexr8  
start_lossend_losss                     r/   rm   z&DistilBertForQuestionAnswering.forward  s   2 ,DOO 
)'%
 
 *!,]3/#)<<r<#: j#++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M-33A}EO)//=AM**FH!,@J
M:H$x/14J+%!+99(33
 	
r\   )NNNNNN)rn   ro   rp   r   rL   r   rM   r   r  r   r   r   r+   rq   r   r   r   r   rm   rs   rt   s   @r/   r:  r:  z  s    / 9 9Pc P  *..2-1/3-1,0>
<<$&>
 t+>
 ||d*	>

 ,>
 ||d*>
 llT)>
 +,>
 
&ellC.?(@	@>
  >
r\   r:  c                   @    e Zd Zdef fdZdej                  fdZdefdZ	e
e	 	 	 	 	 ddej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  dej                  dz  dee   deeej                  df   z  fd              Z xZS ) DistilBertForTokenClassificationrA   c                 ,   t         |   |       |j                  | _        t        |      | _        t        j                  |j                        | _        t        j                  |j                  |j                        | _
        | j                          y r   )rK   rL   r(  r   r   r   rT   rU   r   hidden_sizer*  r   rY   s     r/   rL   z)DistilBertForTokenClassification.__init__  sg      ++)&1zz&..1))F$6$68I8IJ 	r\   rb   c                 6    | j                   j                         S r   r  r   s    r/   r   z8DistilBertForTokenClassification.get_position_embeddings  r  r\   r   c                 :    | j                   j                  |       yr  r  r  s     r/   r   z;DistilBertForTokenClassification.resize_position_embeddings  r  r\   Nra   ry   r^   r  rG   r{   .c                 F    | j                   |f|||dd|}|d   }| j                  |      }| j                  |      }	d}
|<t               } ||	j	                  d| j
                        |j	                  d            }
t        |
|	|j                  |j                        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]`.
        Try   r^   rG   r  r   NrI   r  )	r   rU   r*  r   r   r(  r   r   r   )rZ   ra   ry   r^   r  rG   r{   outputssequence_outputr  r  r8  s               r/   rm   z(DistilBertForTokenClassification.forward  s     "$//
)'%
 
 "!*,,71')HFKKDOO<fkk"oND$!//))	
 	
r\   r#  )rn   ro   rp   r   rL   r   rM   r   r  r   r   r   r+   rq   rr   r   r   r   r   rm   rs   rt   s   @r/   rN  rN    s    	/ 	9 9Pc P  *..2-1*.,0%
<<$&%
 t+%
 ||d*	%

   4'%
 llT)%
 +,%
 
u||S'8!9	9%
  %
r\   rN  c                   @    e Zd Zdef fdZdej                  fdZdefdZ	e
e	 	 	 	 	 ddej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  dej                  dz  dee   deeej                  df   z  fd              Z xZS )DistilBertForMultipleChoicerA   c                 T   t         |   |       t        |      | _        t	        j
                  |j                  |j                        | _        t	        j
                  |j                  d      | _        t	        j                  |j                        | _        | j                          y )Nr    )rK   rL   r   r   r   r   r#   r)  r*  rT   r+  rU   r   rY   s     r/   rL   z$DistilBertForMultipleChoice.__init__-  so     )&1 ii

FJJ?))FJJ2zz&"<"<= 	r\   rb   c                 6    | j                   j                         S r   r  r   s    r/   r   z3DistilBertForMultipleChoice.get_position_embeddings8  r  r\   r   c                 :    | j                   j                  |       y)a  
        Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.

        Arguments:
            new_num_position_embeddings (`int`)
                The number of new position embeddings. If position embeddings are learned, increasing the size will add
                newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
                position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
                add correct vectors at the end following the position encoding algorithm, whereas reducing the size
                will remove vectors from the end.
        Nr  r  s     r/   r   z6DistilBertForMultipleChoice.resize_position_embeddings>  r  r\   Nra   ry   r^   r  rG   r{   .c                    ||j                   d   n|j                   d   }|!|j                  d|j                  d            nd}|!|j                  d|j                  d            nd}|1|j                  d|j                  d      |j                  d            nd} | j                  |f|||dd|}|d   }	|	dddf   }
| j	                  |
      }
 t        j                         |
      }
| j                  |
      }
| j                  |
      }|j                  d|      }d}|t               } |||      }t        |||j                  |j                        S )	a^  
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, 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.
        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)

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
        >>> model = DistilBertForMultipleChoice.from_pretrained("distilbert-base-cased")

        >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
        >>> choice0 = "It is eaten with a fork and a knife."
        >>> choice1 = "It is eaten while held in the hand."
        >>> labels = torch.tensor(0).unsqueeze(0)  # choice0 is correct (according to Wikipedia ;)), batch size 1

        >>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors="pt", padding=True)
        >>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels)  # batch size is 1

        >>> # the linear classifier still needs to be trained
        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```Nr    rI   TrT  r   r  )r   r   rf   r   r)  r   r2  rU   r*  r   r   r   r   )rZ   ra   ry   r^   r  rG   r{   num_choicesrU  r6  r7  r  reshaped_logitsr  r8  s                  r/   rm   z#DistilBertForMultipleChoice.forwardL  s   b -6,Aiooa(}GZGZ[\G]>G>SINN2y~~b'9:Y]	M[Mg,,R1D1DR1HImq ( r=#5#5b#9=;M;Mb;QR 	 "$//
)'%
 
 qz$QT*++M:!	-0]3/ ++b+6')HOV4D("!//))	
 	
r\   r#  )rn   ro   rp   r   rL   r   rM   r   r  r   r   r   r+   rq   rr   r   r   r   r   rm   rs   rt   s   @r/   rX  rX  +  s    	/ 	9 9Pc P  *..2-1*.,0U
<<$&U
 t+U
 ||d*	U

   4'U
 llT)U
 +,U
 
#U5<<+<%=	=U
  U
r\   rX  )r  rX  r:  r&  rN  r   r   )Nr   )J__doc__collections.abcr   numpyr3   r+   r   torch.nnr   r   r    r	   r   activationsr
   configuration_utilsr   integrations.deepspeedr   masking_utilsr   modeling_layersr   modeling_outputsr   r   r   r   r   r   modeling_utilsr   r   processing_utilsr   pytorch_utilsr   utilsr   r   r   utils.deprecationr   utils.genericr   r   utils.output_capturingr   configuration_distilbertr!   
get_loggerrn   r   r  rq   r0   r.   r   r@   floatr   r   r   r   r   r   r   r  r&  r:  rN  rX  __all__r  r\   r/   <module>rv     s{  
 %    A A & ) 3 @ 6 9  G & 
 1 I 5 6 
		H	%L L# LELL L 3 U\\ ' 'b !%II%<<% 
% <<	%
 LL4'% T\% % '(%85)bii 5)p")) * 1  F@")) @0 i i i< g
/ g
 g
T 
_
5 _

_
D ^
*C ^
^
B b
%> b
 b
J G
'@ G
 G
T w
"; w
 w
tr\   