
    g=5                       d Z ddlZddlmZmZmZmZ ddlZddl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mZ dd	lmZ dd
lmZmZ ddlmZmZ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+m,Z,m-Z- ddl.m/Z/  e,j0        e1          Z2dZ3dZ4dZ5 G d dej6                  Z7 G d dej6                  Z8 G d de8          Z9 G d dej6                  Z:e8e9dZ; G d dej6                  Z< G d d ej6                  Z= G d! d"ej6                  Z> G d# d$ej6                  Z? G d% d&ej6                  Z@ G d' d(ej6                  ZA G d) d*e"          ZBd+ZC G d, d-ej6                  ZD G d. d/ej6                  ZE e)d0e5           G d1 d2eB                      ZF e)d3e5           G d4 d5eB                      ZG e)d6e5           G d7 d8eB                      ZH e)d9e5           G d: d;eB                      ZI e)d<e5           G d= d>eB                      ZJ e)d?e5           G d@ dAeB                      ZK e)dBe5           G dC dDeBe                      ZLdFdEZMdS )GzPyTorch CamemBERT model.    N)ListOptionalTupleUnion)version)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FNgelu)GenerationMixin)#_prepare_4d_attention_mask_for_sdpa*_prepare_4d_causal_attention_mask_for_sdpa))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentions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get_torch_versionloggingreplace_return_docstrings   )CamembertConfigzalmanach/camembert-baser%   aC  

    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 ([`CamembertConfig`]): 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.
c                   2     e Zd ZdZ fdZ	 ddZd Z xZS )CamembertEmbeddingszV
    Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
    c                 l   t                                                       t          j        |j        |j        |j                  | _        t          j        |j        |j                  | _	        t          j        |j
        |j                  | _        t          j        |j        |j                  | _        t          j        |j                  | _        t#          |dd          | _        |                     dt)          j        |j                                      d          d           |                     d	t)          j        | j                                        t(          j        
          d           |j        | _        t          j        |j        |j        | j                  | _	        d S )N)padding_idxepsposition_embedding_typeabsoluteposition_ids)r$   F)
persistenttoken_type_idsdtype)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getattrr,   register_buffertorcharangeexpandzerosr.   sizelongr)   selfconfig	__class__s     l/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/camembert/modeling_camembert.pyr5   zCamembertEmbeddings.__init__V   s}   !|F,=v?Q_e_rsss#%<0NPVPb#c#c %'\&2H&J\%]%]" f&8f>STTTz&"<=='.v7PR\']']$EL)GHHOOPWXXej 	 	
 	
 	
 	ek$*;*@*@*B*B%*UUUbg 	 	
 	
 	

 ".#%<*F,>DL\$
 $
 $
       Nr   c                    |.|t          || j        |          }n|                     |          }||                                }n|                                d d         }|d         }|mt	          | d          r2| j        d d d |f         }|                    |d         |          }	|	}n+t          j        |t          j	        | j
        j                  }||                     |          }|                     |          }
||
z   }| j        dk    r|                     |          }||z  }|                     |          }|                     |          }|S )Nr/   r$   r1   r   r3   devicer-   )"create_position_ids_from_input_idsr)   &create_position_ids_from_inputs_embedsrJ   hasattrr1   rH   rF   rI   rK   r.   rT   r:   r>   r,   r<   r?   rC   )rM   	input_idsr1   r.   inputs_embedspast_key_values_lengthinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr>   
embeddingsr<   s                rP   forwardzCamembertEmbeddings.forwardo   s{    $A)TM]_uvv#JJ=YY #..**KK',,..ss3K ^

 !t-.. m*.*=aaa*n*M'3J3Q3QR]^_R`bl3m3m0!A!&[
SWSdSk!l!l!l  00;;M $ : :> J J"%::
':55"&":":<"H"H--J^^J//
\\*--
rQ   c                    |                                 dd         }|d         }t          j        | j        dz   || j        z   dz   t          j        |j                  }|                    d                              |          S )z
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.

        Args:
            inputs_embeds: torch.Tensor

        Returns: torch.Tensor
        Nr/   r$   rS   r   )rJ   rF   rG   r)   rK   rT   	unsqueezerH   )rM   rY   r[   sequence_lengthr.   s        rP   rV   z:CamembertEmbeddings.create_position_ids_from_inputs_embeds   s     $((**3B3/%a.|q /D4D"Dq"HPUPZcpcw
 
 
 %%a((//<<<rQ   )NNNNr   )__name__
__module____qualname____doc__r5   r`   rV   __classcell__rO   s   @rP   r'   r'   P   sm         

 
 
 
 
4 rs& & & &P= = = = = = =rQ   r'   c                   ,    e Zd Zd fd	Zdej        dej        fdZ	 	 	 	 	 	 ddej        deej                 d	eej                 d
eej                 deej                 dee	e	ej                                   dee
         de	ej                 fdZ xZS )CamembertSelfAttentionNc                 D   t                                                       |j        |j        z  dk    r0t	          |d          s t          d|j         d|j         d          |j        | _        t          |j        |j        z            | _        | j        | j        z  | _        t          j
        |j        | j                  | _        t          j
        |j        | j                  | _        t          j
        |j        | j                  | _        t          j        |j                  | _        |pt#          |dd          | _        | j        dk    s| j        d	k    r6|j        | _        t          j        d
|j        z  dz
  | j                  | _        |j        | _        d S )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r,   r-   relative_keyrelative_key_query   r$   )r4   r5   r8   num_attention_headsrW   
ValueErrorintattention_head_sizeall_head_sizer   LinearquerykeyvaluerA   attention_probs_dropout_probrC   rD   r,   r;   r6   distance_embedding
is_decoderrM   rN   r,   rO   s      rP   r5   zCamembertSelfAttention.__init__   s    ::a??PVXhHiHi?8F$6 8 8 48 8 8  
 $*#= #&v'9F<V'V#W#W !58PPYv143EFF
9V/1CDDYv143EFF
z&"EFF'> (
'-zC
 C
$ '>99T=Y]q=q=q+1+ID(&(l1v7U3UXY3Y[_[s&t&tD# +rQ   xreturnc                     |                                 d d         | j        | j        fz   }|                    |          }|                    dddd          S )Nr/   r   rq   r$   r   )rJ   rr   ru   viewpermute)rM   r   new_x_shapes      rP   transpose_for_scoresz+CamembertSelfAttention.transpose_for_scores   sP    ffhhssmt'?AY&ZZFF;yyAq!$$$rQ   Fhidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsc                 ^   |                      |          }|d u}	|	r||d         }
|d         }|}n4|	rS|                     |                     |                    }
|                     |                     |                    }|}n||                     |                     |                    }
|                     |                     |                    }t	          j        |d         |
gd          }
t	          j        |d         |gd          }nP|                     |                     |                    }
|                     |                     |                    }|                     |          }|d u}| j        r|
|f}t	          j        ||
                    dd                    }| j	        dk    s| j	        dk    rt|j
        d         |
j
        d         }}|r>t	          j        |dz
  t          j        |j        	                              dd          }n:t	          j        |t          j        |j        	                              dd          }t	          j        |t          j        |j        	                              dd          }||z
  }|                     || j        z   dz
            }|                    |j        
          }| j	        dk    rt	          j        d||          }||z   }n?| j	        dk    r4t	          j        d||          }t	          j        d|
|          }||z   |z   }|t+          j        | j                  z  }|||z   }t0          j                            |d          }|                     |          }|||z  }t	          j        ||          }|                    dddd                                          }|                                d d         | j        fz   }|                    |          }|r||fn|f}| j        r||fz   }|S )Nr   r$   rq   dimr/   ro   rp   rS   r2   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) rx   r   ry   rz   rF   catr}   matmul	transposer,   shapetensorrK   rT   r   rG   r|   r;   tor3   einsummathsqrtru   r   
functionalsoftmaxrC   r   
contiguousrJ   rv   )rM   r   r   r   r   r   r   r   mixed_query_layeris_cross_attention	key_layervalue_layerquery_layer	use_cacheattention_scoresquery_length
key_lengthposition_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probscontext_layernew_context_layer_shapeoutputss                               rP   r`   zCamembertSelfAttention.forward   sZ    !JJ}55
 3$> 	O."<&q)I(+K3NN 	O11$((;P2Q2QRRI33DJJ?T4U4UVVK3NN'11$((=2I2IJJI33DJJ}4M4MNNK	>!#4i"@aHHHI)^A%6$D!LLLKK11$((=2I2IJJI33DJJ}4M4MNNK//0ABB"$.	? 	6 (5N !<Y5H5HR5P5PQQ'>99T=Y]q=q=q'2'8';Y_Q=O*L w!&j1nEJWdWk!l!l!l!q!q" " "'l%*UbUi!j!j!j!o!oprtu!v!v"\*EJ}OcdddiijkmoppN%6H#'#:#:8dFb;bef;f#g#g #7#:#:AR#:#S#S +~==+0<8H+Wk+l+l(#36N#N  -1EEE16>NP[]q1r1r./4|<LiYm/n/n,#36T#TWs#s +di8P.Q.QQ%/.@ -//0@b/II ,,77  -	9O_kBB%--aAq99DDFF"/"4"4"6"6ss";t?Q>S"S%**+BCC6G]=/22mM]? 	2 11GrQ   NNNNNNF)rd   re   rf   r5   rF   Tensorr   r   FloatTensorr   boolr`   rh   ri   s   @rP   rk   rk      s.       , , , , , ,4%el %u| % % % % 7;15=A>BDH,1c c|c !!23c E-.	c
  ((9:c !)): ;c !uU->'?!@Ac $D>c 
u|	c c c c c c c crQ   rk   c                       e Zd Zd fd	Z	 	 	 	 	 	 ddej        deej                 deej                 deej                 deej                 d	eeeej                                   d
ee	         deej                 f fdZ
 xZS )CamembertSdpaSelfAttentionNc                     t                                          ||           |j        | _        t	          j        t                                t	          j        d          k     | _        d S )Nr,   z2.2.0)r4   r5   r{   dropout_probr   parser!   require_contiguous_qkvr~   s      rP   r5   z#CamembertSdpaSelfAttention.__init__2  s[    9PQQQ"?&-m4E4G4G&H&H7=Y`KaKa&a###rQ   Fr   r   r   r   r   r   r   r   c           	         | j         dk    s|s|At                              d           t                                          |||||||          S |                                \  }}	}
|                     |                     |                    }|d u}|r|n|}|r|n|}|r*|r(|d         j        d         |j        d         k    r|\  }}n|                     | 	                    |                    }|                     | 
                    |                    }|>|s<t          j        |d         |gd          }t          j        |d         |gd          }| j        r||f}| j        rN|j        j        dk    r>|<|                                }|                                }|                                }| j        r|s
||	dk    rdnd	}t          j        j                            ||||| j        r| j        nd
|          }|                    dd          }|                    ||	| j                  }|f}| j        r||fz   }|S )Nr-   a  CamembertSdpaSelfAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r   rq   r$   r   cudaTF        )	attn_mask	dropout_p	is_causal)r,   loggerwarning_oncer4   r`   rJ   r   rx   r   ry   rz   rF   r   r}   r   rT   typer   r   r   scaled_dot_product_attentiontrainingr   r   reshaperv   )rM   r   r   r   r   r   r   r   bsztgt_len_r   r   current_statesr   r   r   attn_outputr   rO   s                      rP   r`   z"CamembertSdpaSelfAttention.forward8  s    ':559J5iNcH   77??%&!   (,,..Wa//

=0I0IJJ 3$>2DW..-3EY//>  	Q. 	Q^A5F5LQ5OSaSghiSj5j5j%3"I{{11$((>2J2JKKI33DJJ~4N4NOOK)2D)!I~a'8)&D!LLL	#i):K(HaPPP? 	6 (5N
 & 	3;+=+Bf+L+LQ_Qk%0022K!,,..I%0022K Ot,>t>CY^ehi^i^iDDot 	 h)FF$+/=Ad''c G 
 
 "++Aq11!))#w8JKK.? 	2 11GrQ   r   r   )rd   re   rf   r5   rF   r   r   r   r   r   r`   rh   ri   s   @rP   r   r   1  s       b b b b b b 2615=A>BDH,1[ [|[ !.[ E-.	[
  ((9:[ !)): ;[ !uU->'?!@A[ $D>[ 
u|	[ [ [ [ [ [ [ [ [ [rQ   r   c                   P     e Zd Z fdZdej        dej        dej        fdZ xZS )CamembertSelfOutputc                    t                                                       t          j        |j        |j                  | _        t          j        |j        |j                  | _        t          j        |j	                  | _
        d S Nr*   )r4   r5   r   rw   r8   denser?   r@   rA   rB   rC   rL   s     rP   r5   zCamembertSelfOutput.__init__  sf    Yv163EFF
f&8f>STTTz&"<==rQ   r   input_tensorr   c                     |                      |          }|                     |          }|                     ||z             }|S r   r   rC   r?   rM   r   r   s      rP   r`   zCamembertSelfOutput.forward  @    

=11]33}|'CDDrQ   rd   re   rf   r5   rF   r   r`   rh   ri   s   @rP   r   r     i        > > > > >U\  RWR^        rQ   r   )eagersdpac                       e Zd Zd fd	Zd Z	 	 	 	 	 	 ddej        deej                 deej                 deej                 d	eej                 d
ee	e	ej                                   dee
         de	ej                 fdZ xZS )CamembertAttentionNc                     t                                                       t          |j                 ||          | _        t          |          | _        t                      | _        d S )Nr   )	r4   r5    CAMEMBERT_SELF_ATTENTION_CLASSES_attn_implementationrM   r   outputsetpruned_headsr~   s      rP   r5   zCamembertAttention.__init__  s`    4V5PQ,C
 
 
	 *&11EErQ   c                    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          | j
        _        | j        j        t          |          z
  | j        _        | j        j        | j        j        z  | j        _        | j                            |          | _        d S )Nr   r$   r   )lenr   rM   rr   ru   r   r   rx   ry   rz   r   r   rv   union)rM   headsindexs      rP   prune_headszCamembertAttention.prune_heads  s    u::??F7490$)2OQUQb
 
u
 -TY_eDD	*49=%@@	,TY_eDD	.t{/@%QOOO )-	(EE

(R	%"&)"?$)B_"_	 -33E::rQ   Fr   r   r   r   r   r   r   r   c           	          |                      |||||||          }|                     |d         |          }	|	f|dd          z   }
|
S )Nr   r$   )rM   r   )rM   r   r   r   r   r   r   r   self_outputsattention_outputr   s              rP   r`   zCamembertAttention.forward  sa     yy!"
 
  ;;|AFF#%QRR(88rQ   r   r   )rd   re   rf   r5   r   rF   r   r   r   r   r   r`   rh   ri   s   @rP   r   r     s       " " " " " "; ; ;* 7;15=A>BDH,1 | !!23 E-.	
  ((9: !)): ; !uU->'?!@A $D> 
u|	       rQ   r   c                   B     e Zd Z fdZdej        dej        fdZ xZS )CamembertIntermediatec                    t                                                       t          j        |j        |j                  | _        t          |j        t                    rt          |j                 | _        d S |j        | _        d S r   )r4   r5   r   rw   r8   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnrL   s     rP   r5   zCamembertIntermediate.__init__  sn    Yv163KLL
f'-- 	9'-f.?'@D$$$'-'8D$$$rQ   r   r   c                 Z    |                      |          }|                     |          }|S r   )r   r   )rM   r   s     rP   r`   zCamembertIntermediate.forward  s,    

=1100??rQ   r   ri   s   @rP   r   r     s^        9 9 9 9 9U\ el        rQ   r   c                   P     e Zd Z fdZdej        dej        dej        fdZ xZS )CamembertOutputc                    t                                                       t          j        |j        |j                  | _        t          j        |j        |j                  | _        t          j	        |j
                  | _        d S r   )r4   r5   r   rw   r   r8   r   r?   r@   rA   rB   rC   rL   s     rP   r5   zCamembertOutput.__init__  sf    Yv79KLL
f&8f>STTTz&"<==rQ   r   r   r   c                     |                      |          }|                     |          }|                     ||z             }|S r   r   r   s      rP   r`   zCamembertOutput.forward  r   rQ   r   ri   s   @rP   r   r     r   rQ   r   c                       e Zd Z fdZ	 	 	 	 	 	 ddej        deej                 deej                 deej                 deej                 d	eeeej                                   d
ee	         deej                 fdZ
d Z xZS )CamembertLayerc                    t                                                       |j        | _        d| _        t	          |          | _        |j        | _        |j        | _        | j        r/| j        st          |  d          t	          |d          | _	        t          |          | _        t          |          | _        d S )Nr$   z> should be used as a decoder model if cross attention is addedr-   r   )r4   r5   chunk_size_feed_forwardseq_len_dimr   	attentionr}   add_cross_attentionrs   crossattentionr   intermediater   r   rL   s     rP   r5   zCamembertLayer.__init__   s    '-'E$+F33 +#)#= # 	a? j D!h!h!hiii"4VU_"`"`"`D1&99%f--rQ   NFr   r   r   r   r   r   r   r   c           	         |
|d d         nd }|                      |||||          }	|	d         }
| j        r|	dd         }|	d         }n
|	dd          }d }| j        rp|nt          | d          st          d|  d          |
|d	d          nd }|                     |
||||||          }|d         }
||dd         z   }|d         }||z   }t          | j        | j        | j        |
          }|f|z   }| j        r||fz   }|S )
Nrq   )r   r   r   r$   r/   r  z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r   )	r   r}   rW   rs   r  r   feed_forward_chunkr   r   )rM   r   r   r   r   r   r   r   self_attn_past_key_valueself_attention_outputsr   r   present_key_valuecross_attn_present_key_valuecross_attn_past_key_valuecross_attention_outputslayer_outputs                    rP   r`   zCamembertLayer.forward  s    :H9S>"1"#5#5Y] !%/3 "0 "
 "
 2!4 ? 	1,QrT2G 6r :,QRR0G'+$? 	Q4@4!122  Dd D D D   @N?Yrss(;(;_c%&*&9&9 %&)!' '#  7q9 7" ==G ,C2+F( 14P P0#T%A4CSUe
 
  /G+ ? 	5!2 44GrQ   c                 \    |                      |          }|                     ||          }|S r   )r  r   )rM   r   intermediate_outputr  s       rP   r  z!CamembertLayer.feed_forward_chunkO  s2    "//0@AA{{#68HIIrQ   r   )rd   re   rf   r5   rF   r   r   r   r   r   r`   r  rh   ri   s   @rP   r   r     s       . . . . ." 7;15=A>BDH,1? ?|? !!23? E-.	?
  ((9:? !)): ;? !uU->'?!@A? $D>? 
u|	? ? ? ?B      rQ   r   c                   L    e Zd Z fdZ	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deej                 d	eej                 d
eeeej                                   dee	         dee	         dee	         dee	         de
eej                 ef         fdZ xZS )CamembertEncoderc                     t                                                       | _        t          j        fdt          j                  D                       | _        d| _        d S )Nc                 .    g | ]}t                    S  )r   ).0r   rN   s     rP   
<listcomp>z-CamembertEncoder.__init__.<locals>.<listcomp>Z  s!    #d#d#dqN6$:$:#d#d#drQ   F)	r4   r5   rN   r   
ModuleListrangenum_hidden_layerslayergradient_checkpointingrL   s    `rP   r5   zCamembertEncoder.__init__W  s`    ]#d#d#d#dE&JbDcDc#d#d#dee
&+###rQ   NFTr   r   r   r   r   past_key_valuesr   r   output_hidden_statesreturn_dictr   c                    |	rdnd }|rdnd }|r| j         j        rdnd }| j        r%| j        r|rt                              d           d}|rdnd }t          | j                  D ]\  }}|	r||fz   }|||         nd }|||         nd }| j        r)| j        r"|                     |j	        |||||||          }n ||||||||          }|d         }|r||d         fz  }|r$||d         fz   }| j         j        r||d         fz   }|	r||fz   }|
st          d |||||fD                       S t          |||||	          S )
Nr  zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r/   r$   rq   c              3      K   | ]}||V  	d S r   r  )r  vs     rP   	<genexpr>z+CamembertEncoder.forward.<locals>.<genexpr>  s4       
 
 =  !===
 
rQ   )last_hidden_stater  r   
attentionscross_attentions)rN   r   r  r   r   r   	enumerater  _gradient_checkpointing_func__call__tupler   )rM   r   r   r   r   r   r  r   r   r  r  all_hidden_statesall_self_attentionsall_cross_attentionsnext_decoder_cacheilayer_modulelayer_head_maskr   layer_outputss                       rP   r`   zCamembertEncoder.forward]  sB    #7@BBD$5?bb4%6d4;;Zdrr`d& 	"4= 	" "##p   "	#,6RR$(44 #	V #	VOA|# I$58H$H!.7.CillO3B3N_Q//TXN* t}  $ A A )!"#)*"%	! 	! !-!"#)*"%! ! *!,M ;"}R'8&::"  V&9]1=M<O&O#;2 V+?=QRCSBU+U( 	E 1]4D D 	 
 
 "&%'(
 
 
 
 
 
 9+.+*1
 
 
 	
rQ   )	NNNNNNFFT)rd   re   rf   r5   rF   r   r   r   r   r   r   r   r`   rh   ri   s   @rP   r  r  V  sD       , , , , , 7;15=A>BEI$(,1/4&*S
 S
|S
 !!23S
 E-.	S

  ((9:S
 !)): ;S
 "%e.?(@"ABS
 D>S
 $D>S
 'tnS
 d^S
 
uU\"$MM	NS
 S
 S
 S
 S
 S
 S
 S
rQ   r  c                   B     e Zd Z fdZdej        dej        fdZ xZS )CamembertPoolerc                     t                                                       t          j        |j        |j                  | _        t          j                    | _        d S r   )r4   r5   r   rw   r8   r   Tanh
activationrL   s     rP   r5   zCamembertPooler.__init__  sC    Yv163EFF
'))rQ   r   r   c                 r    |d d df         }|                      |          }|                     |          }|S Nr   )r   r4  )rM   r   first_token_tensorpooled_outputs       rP   r`   zCamembertPooler.forward  s@     +111a40

#56666rQ   r   ri   s   @rP   r1  r1    s^        $ $ $ $ $
U\ el        rQ   r1  c                   (    e Zd ZdZeZdZdZdZd Z	dS )CamembertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    robertaTc                    t          |t          j                  rT|j        j                            d| j        j                   |j         |j        j        	                                 dS dS t          |t          j
                  r_|j        j                            d| j        j                   |j        +|j        j        |j                 	                                 dS dS t          |t          j                  r?|j        j        	                                 |j        j                            d           dS dS )zInitialize the weightsr   )meanstdNg      ?)r   r   rw   weightdatanormal_rN   initializer_rangebiaszero_r6   r)   r?   fill_)rM   modules     rP   _init_weightsz&CamembertPreTrainedModel._init_weights  s)   fbi(( 	* M&&CT[5R&SSS{& &&((((( '&-- 	*M&&CT[5R&SSS!-"6#56<<>>>>> .--- 	*K""$$$M$$S)))))	* 	*rQ   N)
rd   re   rf   rg   r%   config_classbase_model_prefixsupports_gradient_checkpointing_supports_sdparG  r  rQ   rP   r:  r:    sE         
 #L!&*#N* * * * *rQ   r:  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.
c                   (     e Zd ZdZ fdZd Z xZS )CamembertClassificationHeadz-Head for sentence-level classification tasks.c                 4   t                                                       t          j        |j        |j                  | _        |j        |j        n|j        }t          j        |          | _	        t          j        |j        |j
                  | _        d S r   )r4   r5   r   rw   r8   r   classifier_dropoutrB   rA   rC   
num_labelsout_projrM   rN   rO  rO   s      rP   r5   z$CamembertClassificationHead.__init__  s    Yv163EFF
)/)B)NF%%TZTn 	 z"455	&"4f6GHHrQ   c                     |d d dd d f         }|                      |          }|                     |          }t          j        |          }|                      |          }|                     |          }|S r6  )rC   r   rF   tanhrQ  rM   featureskwargsr   s       rP   r`   z#CamembertClassificationHead.forward  sj    QQQ111WLLOOJJqMMJqMMLLOOMM!rQ   )rd   re   rf   rg   r5   r`   rh   ri   s   @rP   rM  rM    sR        77I I I I I      rQ   rM  c                   .     e Zd ZdZ fdZd Zd Z xZS )CamembertLMHeadz,Camembert Head for masked language modeling.c                    t                                                       t          j        |j        |j                  | _        t          j        |j        |j                  | _        t          j        |j        |j	                  | _
        t          j        t          j        |j	                            | _        | j        | j
        _        d S r   )r4   r5   r   rw   r8   r   r?   r@   
layer_normr7   decoder	ParameterrF   rI   rC  rL   s     rP   r5   zCamembertLMHead.__init__-  s    Yv163EFF
,v'9v?TUUUy!3V5FGGLV->!?!?@@	 IrQ   c                     |                      |          }t          |          }|                     |          }|                     |          }|S r   )r   r   r[  r\  rU  s       rP   r`   zCamembertLMHead.forward6  sE    JJx  GGOOA LLOOrQ   c                     | j         j        j        j        dk    r| j        | j         _        d S | j         j        | _        d S )Nmeta)r\  rC  rT   r   rM   s    rP   _tie_weightszCamembertLMHead._tie_weights@  s<     <#(F22 $	DL)DIIIrQ   )rd   re   rf   rg   r5   r`   rb  rh   ri   s   @rP   rY  rY  *  s\        66& & & & &  * * * * * * *rQ   rY  zcThe bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.c            !       .    e Zd ZdZg Zd fd	Zd Zd Zd Z e	e
                    d                     eeee          	 	 	 	 	 	 	 	 	 	 	 	 	 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ej                          dee         dee         dee         dee         deeej                 ef         fd                        Z xZS )CamembertModela)  

    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, following the architecture described in *Attention is
    all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
    Kaiser and Illia Polosukhin.

    To behave as a decoder the model needs to be initialized with the `is_decoder` argument of the configuration set to
    `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
    `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.

    .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762

    Tc                 0   t                                          |           || _        t          |          | _        t          |          | _        |rt          |          nd | _        |j	        | _
        |j        | _        |                                  d S r   )r4   r5   rN   r'   r_   r  encoderr1  poolerr   attn_implementationr,   	post_init)rM   rN   add_pooling_layerrO   s      rP   r5   zCamembertModel.__init__`  s       -f55'//1BLof---#)#> '-'E$ 	rQ   c                     | j         j        S r   r_   r:   ra  s    rP   get_input_embeddingsz#CamembertModel.get_input_embeddingso  s    ..rQ   c                     || j         _        d S r   rl  )rM   rz   s     rP   set_input_embeddingsz#CamembertModel.set_input_embeddingsr  s    */'''rQ   c                     |                                 D ]/\  }}| j        j        |         j                            |           0d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   )rM   heads_to_pruner  r   s       rP   _prune_headszCamembertModel._prune_headsu  sU    
 +0022 	C 	CLE5Lu%/;;EBBBB	C 	CrQ   batch_size, sequence_length
checkpointoutput_typerH  NrX   r   r1   r.   r   rY   r   r   r  r   r   r  r  r   c                 ~   ||n| j         j        }||n| j         j        }||n| j         j        }| j         j        r|
|
n| j         j        }
nd}
||t          d          |+|                     ||           |                                }n.||                                dd         }nt          d          |\  }}||j	        n|j	        }|	|	d         d         j
        d         nd}|gt          | j        d          r1| j        j        ddd|f         }|                    ||          }|}n!t          j        |t          j        |	          }|                     |||||
          }|t          j        |||z   f|          }| j        dk    o| j        dk    o|du o| }|rO|                                dk    r7| j         j        rt-          ||||          }n.t/          ||j        |          }n|                     ||          }| j         j        r~|||                                \  }}}||f}|t          j        ||          }|r0|                                dk    rt/          ||j        |          }n|                     |          }nd}|                     || j         j                  }|                     ||||||	|
|||
  
        }|d         }| j        |                     |          nd}|s||f|dd         z   S t?          |||j         |j!        |j"        |j#                  S )a?  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, target_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timer/   z5You have to specify either input_ids or inputs_embedsr   rq   r1   rS   )rX   r.   r1   rY   rZ   )rT   r   r-   )r   )	r   r   r   r   r  r   r   r  r  r$   )r!  pooler_outputr  r   r"  r#  )$rN   r   r  use_return_dictr}   r   rs   %warn_if_padding_and_no_attention_maskrJ   rT   r   rW   r_   r1   rH   rF   rI   rK   onesrh  r,   r   r   r   r3   get_extended_attention_maskinvert_attention_maskget_head_maskr  rf  rg  r   r  r   r"  r#  ) rM   rX   r   r1   r.   r   rY   r   r   r  r   r   r  r  r[   
batch_sizer\   rT   rZ   r]   r^   embedding_outputuse_sdpa_attention_masksextended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskencoder_outputssequence_outputr8  s                                    rP   r`   zCamembertModel.forward}  sK   V 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B];! 	%.%:		@UIII ]%>cddd"66y.QQQ#..**KK&',,..ss3KKTUUU!,
J%.%:!!@T DSC^!3A!6!<Q!?!?de!t(899 [*./*HKZK*X'3J3Q3QR\^h3i3i0!A!&[
SY!Z!Z!Z??%)'#9 + 
 
 !"ZZBX5X(YbhiiiN $. &,
:&T!& &%	 	! $ 	d(:(:(<(<(A(A {% 
*T"$*	+ +'' +N"$4$:J+ + +'' '+&F&F~Wb&c&c# ;! 	3&;&G=R=W=W=Y=Y: 7$68O#P %-).4HQW)X)X)X&' e,B,F,F,H,HA,M,M 3V*,<,BJ3 3 3// 372L2LMc2d2d//.2+ &&y$+2OPP	,,2"7#B+/!5# ' 
 
 *!,8<8OO444UY 	J#]3oabb6III;-'+;)7&1,=
 
 
 	
rQ   )T)NNNNNNNNNNNNN)rd   re   rf   rg   _no_split_modulesr5   rm  ro  rs  r    CAMEMBERT_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   rF   r   r   r   r   r   r   r`   rh   ri   s   @rP   rd  rd  I  s       
       / / /0 0 0C C C +*+E+L+LMj+k+kll&@$   -11515/3,0048<9==A$(,0/3&*`
 `
EL)`
 !.`
 !.	`

 u|,`
 EL)`
  -`
  (5`
 !) 6`
 "$u'8"9:`
 D>`
 $D>`
 'tn`
 d^`
 
uU\"$PP	Q`
 `
 `
  ml`
 `
 `
 `
 `
rQ   rd  z7CamemBERT Model with a `language modeling` head on top.c                       e Zd ZddgZ fdZd Zd Z ee	                    d                     e
eeedd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j                 dee         dee         dee         deeej                 ef         fd                        Z xZS )CamembertForMaskedLMlm_head.decoder.weightlm_head.decoder.biasc                    t                                          |           |j        rt                              d           t          |d          | _        t          |          | _        | 	                                 d S )NzpIf you want to use `CamembertForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Frj  
r4   r5   r}   r   warningrd  r;  rY  lm_headri  rL   s     rP   r5   zCamembertForMaskedLM.__init__/  s~        	NN1  
 &fFFF&v.. 	rQ   c                     | j         j        S r   r  r\  ra  s    rP   get_output_embeddingsz*CamembertForMaskedLM.get_output_embeddings>      |##rQ   c                     || j         _        d S r   r  rM   new_embeddingss     rP   set_output_embeddingsz*CamembertForMaskedLM.set_output_embeddingsA      -rQ   rt  z<mask>z' Paris'g?)rv  rw  rH  maskexpected_outputexpected_lossNrX   r   r1   r.   r   rY   r   r   labelsr   r  r  r   c                    ||n| j         j        }|                     |||||||||
||          }|d         }|                     |          }d}|	e|	                    |j                  }	t                      } ||                    d| j         j                  |	                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j
        |j                  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]`
        kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
            Used to hide legacy arguments that have been deprecated.
        N)
r   r1   r.   r   rY   r   r   r   r  r  r   r/   rq   losslogitsr   r"  )rN   rz  r;  r  r   rT   r
   r   r7   r   r   r"  )rM   rX   r   r1   r.   r   rY   r   r   r  r   r  r  r   r  prediction_scoresmasked_lm_lossloss_fctr   s                      rP   r`   zCamembertForMaskedLM.forwardD  s0   @ &1%<kk$+B],,))%'"7#9/!5#  
 
 "!* LL99YY0788F'))H%X&7&<&<RAW&X&XZ`ZeZefhZiZijjN 	Z')GABBK7F3A3M^%..SYY$!/)	
 
 
 	
rQ   )NNNNNNNNNNNN)rd   re   rf   _tied_weights_keysr5   r  r  r    r  r  r   r  r   r  r   rF   
LongTensorr   r   r   r   r   r`   rh   ri   s   @rP   r  r  '  s        34JK    $ $ $. . . +*+E+L+LMj+k+kll&"$"   156:59371559=A>B-1,0/3&*9
 9
E,-9
 !!239
 !!12	9

 u/09
 E-.9
   129
  ((9:9
 !)): ;9
 )*9
 $D>9
 'tn9
 d^9
 
uU\"N2	39
 9
 9
  ml9
 9
 9
 9
 9
rQ   r  z
    CamemBERT 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Z ee                    d                     edee	d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j                 ef         fd                        Z xZS )"CamembertForSequenceClassificationc                     t                                          |           |j        | _        || _        t	          |d          | _        t          |          | _        |                                  d S NFr  )	r4   r5   rP  rN   rd  r;  rM  
classifierri  rL   s     rP   r5   z+CamembertForSequenceClassification.__init__  sg        +%fFFF5f== 	rQ   rt  z'cardiffnlp/twitter-roberta-base-emotionz
'optimism'g{Gz?rv  rw  rH  r  r  NrX   r   r1   r.   r   rY   r  r   r  r  r   c                    |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }d}|t|                    |j                  }| j         j        f| j        dk    rd| j         _        nN| j        dk    r7|j        t          j
        k    s|j        t          j        k    rd| j         _        nd| j         _        | j         j        dk    rWt                      }| j        dk    r1 ||                                |                                          }n |||          }n| j         j        dk    rGt                      } ||                    d| j                  |                    d                    }n*| j         j        dk    rt!                      } |||          }|
s|f|d	d         z   }||f|z   n|S 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).
        Nr   r1   r.   r   rY   r   r  r  r   r$   
regressionsingle_label_classificationmulti_label_classificationr/   rq   r  )rN   rz  r;  r  r   rT   problem_typerP  r3   rF   rK   rt   r   squeezer
   r   r	   r   r   r"  rM   rX   r   r1   r.   r   rY   r  r   r  r  r   r  r  r  r  r   s                    rP   r`   z*CamembertForSequenceClassification.forward  s   6 &1%<kk$+B],,))%'/!5#  

 

 "!*11YYv}--F{'/?a''/;DK,,_q((flej.H.HFL\a\eLeLe/LDK,,/KDK,{'<77"99?a''#8FNN$4$4fnn6F6FGGDD#8FF33DD)-JJJ+--xB @ @&++b//RR)-III,..x// 	FY,F)-)9TGf$$vE'!/)	
 
 
 	
rQ   
NNNNNNNNNN)rd   re   rf   r5   r    r  r  r   r   r  r   rF   r  r   r   r   r   r   r`   rh   ri   s   @rP   r  r    s       	 	 	 	 	 +*+E+L+LMj+k+kll<,$$   156:59371559-1,0/3&*E
 E
E,-E
 !!23E
 !!12	E

 u/0E
 E-.E
   12E
 )*E
 $D>E
 'tnE
 d^E
 
uU\"$<<	=E
 E
 E
  mlE
 E
 E
 E
 E
rQ   r  z
    CamemBERT 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                       e Zd Z fdZ ee                    d                     eee	e
          	 	 	 	 	 	 	 	 	 	 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j                 e	f         fd                        Z xZS )CamembertForMultipleChoicec                    t                                          |           t          |          | _        t	          j        |j                  | _        t	          j        |j	        d          | _
        |                                  d S )Nr$   )r4   r5   rd  r;  r   rA   rB   rC   rw   r8   r  ri  rL   s     rP   r5   z#CamembertForMultipleChoice.__init__  sl       %f--z&"<==)F$6:: 	rQ   z(batch_size, num_choices, sequence_lengthru  NrX   r1   r   r  r.   r   rY   r   r  r  r   c                    |
|
n| j         j        }
||j        d         n|j        d         }|)|                    d|                    d                    nd}|)|                    d|                    d                    nd}|)|                    d|                    d                    nd}|)|                    d|                    d                    nd}|=|                    d|                    d          |                    d                    nd}|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }|                    d|          }d}|4|                    |j	                  }t                      } |||          }|
s|f|dd         z   }||f|z   n|S t          |||j        |j                  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   )r.   r1   r   r   rY   r   r  r  rq   r  )rN   rz  r   r   rJ   r;  rC   r  r   rT   r
   r   r   r"  )rM   rX   r1   r   r  r.   r   rY   r   r  r  num_choicesflat_input_idsflat_position_idsflat_token_type_idsflat_attention_maskflat_inputs_embedsr   r8  r  reshaped_logitsr  r  r   s                           rP   r`   z"CamembertForMultipleChoice.forward   sA   6 &1%<kk$+B],5,Aioa((}GZ[\G]CLCXINN2,>,>???^bLXLdL--b,2C2CB2G2GHHHjnR`Rln11"n6I6I"6M6MNNNrvR`Rln11"n6I6I"6M6MNNNrv ( r=#5#5b#9#9=;M;Mb;Q;QRRR 	 ,,*..,/!5#  

 

  
]33// ++b+66YY566F'))H8OV44D 	F%''!""+5F)-)9TGf$$vE("!/)	
 
 
 	
rQ   r  )rd   re   rf   r5   r    r  r  r   r  r   r  r   rF   r  r   r   r   r   r   r`   rh   ri   s   @rP   r  r    s            +*"))*TUU   &-$   15596:-1371559,0/3&*A
 A
E,-A
 !!12A
 !!23	A

 )*A
 u/0A
 E-.A
   12A
 $D>A
 'tnA
 d^A
 
uU\"$==	>A
 A
 A
  A
 A
 A
 A
 A
rQ   r  z
    CamemBERT 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                       e Zd Z fdZ ee                    d                     edee	d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j                 ef         fd                        Z xZS )CamembertForTokenClassificationc                 Z   t                                          |           |j        | _        t          |d          | _        |j        |j        n|j        }t          j        |          | _	        t          j
        |j        |j                  | _        |                                  d S r  )r4   r5   rP  rd  r;  rO  rB   r   rA   rC   rw   r8   r  ri  rR  s      rP   r5   z(CamembertForTokenClassification.__init__U  s        +%fFFF)/)B)NF%%TZTn 	 z"455)F$68IJJ 	rQ   rt  z'Jean-Baptiste/roberta-large-ner-englishzF['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']g{Gz?r  NrX   r   r1   r.   r   rY   r  r   r  r  r   c                    |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }d}|`|                    |j                  }t                      } ||                    d| j	                  |                    d                    }|
s|f|dd         z   }||f|z   n|S 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]`.
        Nr  r   r/   rq   r  )rN   rz  r;  rC   r  r   rT   r
   r   rP  r   r   r"  r  s                    rP   r`   z'CamembertForTokenClassification.forwardc  s(   2 &1%<kk$+B],,))%'/!5#  

 

 "!*,,7711YYv}--F'))H8FKKDO<<fkk"ooNND 	FY,F)-)9TGf$$vE$!/)	
 
 
 	
rQ   r  )rd   re   rf   r5   r    r  r  r   r   r  r   rF   r  r   r   r   r   r   r`   rh   ri   s   @rP   r  r  L  s            +*+E+L+LMj+k+kll<)$`   156:59371559-1,0/3&*4
 4
E,-4
 !!234
 !!12	4

 u/04
 E-.4
   124
 )*4
 $D>4
 'tn4
 d^4
 
uU\"$99	:4
 4
 4
  ml4
 4
 4
 4
 4
rQ   r  z
    CamemBERT 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                       e Zd Z fdZ ee                    d                     edee	d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j                 ef         fd                        Z xZS )CamembertForQuestionAnsweringc                     t                                          |           |j        | _        t          |d          | _        t          j        |j        |j                  | _        | 	                                 d S r  )
r4   r5   rP  rd  r;  r   rw   r8   
qa_outputsri  rL   s     rP   r5   z&CamembertForQuestionAnswering.__init__  sj        +%fFFF)F$68IJJ 	rQ   rt  zdeepset/roberta-base-squad2z	' puppet'gQ?r  NrX   r   r1   r.   r   rY   start_positionsend_positionsr   r  r  r   c                    ||n| j         j        }|                     |||||||	|
|	  	        }|d         }|                     |          }|                    dd          \  }}|                    d                                          }|                    d                                          }d}||t          |                                          dk    r|                    d          }t          |                                          dk    r|                    d          }|                    d          }|	                    d|          }|	                    d|          }t          |          } |||          } |||          }||z   dz  }|s||f|dd         z   }||f|z   n|S t          ||||j        |j        	          S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        Nr  r   r$   r/   r   )ignore_indexrq   )r  start_logits
end_logitsr   r"  )rN   rz  r;  r  splitr  r   r   rJ   clampr
   r   r   r"  )rM   rX   r   r1   r.   r   rY   r  r  r   r  r  r   r  r  r  r  
total_lossignored_indexr  
start_lossend_lossr   s                          rP   r`   z%CamembertForQuestionAnswering.forward  s   @ &1%<kk$+B],,))%'/!5#  

 

 "!*11#)<<r<#:#: j#++B//::<<''++6688

&=+D?''))**Q.."1"9"9""="==%%''((1,, - 5 5b 9 9(--a00M-33A}EEO)//=AAM']CCCH!,@@Jx
M::H$x/14J 	R"J/'!""+=F/9/EZMF**6Q+%!!/)
 
 
 	
rQ   )NNNNNNNNNNN)rd   re   rf   r5   r    r  r  r   r   r  r   rF   r  r   r   r   r   r   r`   rh   ri   s   @rP   r  r    s            +*+E+L+LMj+k+kll00$#   156:593715596:48,0/3&*H
 H
E,-H
 !!23H
 !!12	H

 u/0H
 E-.H
   12H
 "%"23H
   01H
 $D>H
 'tnH
 d^H
 
uU\"$@@	AH
 H
 H
  mlH
 H
 H
 H
 H
rQ   r  zKCamemBERT Model with a `language modeling` head on top for CLM fine-tuning.c            #       F    e Zd ZddgZ fdZd Zd Z ee	                    d                     e
ee          	 	 	 	 	 	 	 	 	 	 	 	 	 	 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j                 deeej                          dee         dee         dee         dee         deeej                 ef         fd                        Zd Z xZS )CamembertForCausalLMr  r  c                    t                                          |           |j        st                              d           t          |d          | _        t          |          | _        | 	                                 d S )NzQIf you want to use `CamembertLMHeadModel` as a standalone, add `is_decoder=True.`Fr  r  rL   s     rP   r5   zCamembertForCausalLM.__init__  su         	pNNnooo%fFFF&v.. 	rQ   c                     | j         j        S r   r  ra  s    rP   r  z*CamembertForCausalLM.get_output_embeddings  r  rQ   c                     || j         _        d S r   r  r  s     rP   r  z*CamembertForCausalLM.set_output_embeddings  r  rQ   rt  )rw  rH  NrX   r   r1   r.   r   rY   r   r   r  r  r   r   r  r  r   c                    ||n| j         j        }|	d}|                     |||||||||
||||          }|d         }|                     |          }d}|	|	                    |j                  }	|ddddddf                                         }|	ddddf                                         }	t                      } ||                    d| j         j	                  |	                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        |j                  S )	a6
  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the left-to-right language modeling loss (next word prediction). 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]`
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, CamembertForCausalLM, AutoConfig
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("almanach/camembert-base")
        >>> config = AutoConfig.from_pretrained("almanach/camembert-base")
        >>> config.is_decoder = True
        >>> model = CamembertForCausalLM.from_pretrained("almanach/camembert-base", config=config)

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)

        >>> prediction_logits = outputs.logits
        ```NF)r   r1   r.   r   rY   r   r   r  r   r   r  r  r   r/   r$   rq   )r  r  r  r   r"  r#  )rN   rz  r;  r  r   rT   r   r
   r   r7   r   r  r   r"  r#  )rM   rX   r   r1   r.   r   rY   r   r   r  r  r   r   r  r  r   r  r  lm_lossshifted_prediction_scoresr  r   s                         rP   r`   zCamembertForCausalLM.forward!  s   | &1%<kk$+B]I,,))%'"7#9+/!5#  
 
  "!* LL99YY0788F(9!!!SbS!!!)(D(O(O(Q(Q%AAAqrrE]--//F'))Hh8==b$+BXYY[a[f[fgi[j[jkkG 	L')GABBK7F,3,?WJ''VK0$#3!/)$5
 
 
 	
rQ   c                 T    d}|D ]!}|t          fd|D                       fz  }"|S )Nr  c              3   t   K   | ]2}|                     d                     |j                            V  3dS )r   N)index_selectr   rT   )r  
past_statebeam_idxs     rP   r   z6CamembertForCausalLM._reorder_cache.<locals>.<genexpr>  sC      nnU_j--aZ=N1O1OPPnnnnnnrQ   )r'  )rM   r  r  reordered_past
layer_pasts     `  rP   _reorder_cachez#CamembertForCausalLM._reorder_cache  sQ    ) 	 	Jnnnncmnnnnn NN rQ   )NNNNNNNNNNNNNN)rd   re   rf   r  r5   r  r  r    r  r  r#   r   r  r   rF   r  r   r   r   r   r   r`   r  rh   ri   s   @rP   r  r    s       
 34JK
 
 
 
 
$ $ $. . . +*+E+L+LMj+k+kll+L[jkkk 156:59371559=A>B-1;?$(,0/3&*h
 h
E,-h
 !!23h
 !!12	h

 u/0h
 E-.h
   12h
  ((9:h
 !)): ;h
 )*h
 uU%678h
 D>h
 $D>h
 'tnh
 d^h
  
uU\"$EE	F!h
 h
 h
 lk mlh
T      rQ   r  c                     |                      |                                          }t          j        |d                              |          |z   |z  }|                                |z   S )a  
    Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
    are ignored. This is modified from fairseq's `utils.make_positions`.

    Args:
        x: torch.Tensor x:

    Returns: torch.Tensor
    r$   r   )nert   rF   cumsumtype_asrK   )rX   r)   rZ   r  incremental_indicess        rP   rU   rU     sg     <<$$((**D <!444<<TBBE[[_cc##%%33rQ   )r   )Nrg   r   typingr   r   r   r   rF   torch.utils.checkpoint	packagingr   r   torch.nnr	   r
   r   activationsr   r   
generationr   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   r   r   r   r   r   modeling_utilsr   pytorch_utilsr   r   r   utilsr   r   r    r!   r"   r#   configuration_camembertr%   
get_loggerrd   r   r  r  CAMEMBERT_START_DOCSTRINGModuler'   rk   r   r   r   r   r   r   r   r  r1  r:  r  rM  rY  rd  r  r  r  r  r  r  rU   r  rQ   rP   <module>r      s       / / / / / / / / / / / /                  A A A A A A A A A A ' ' ' ' ' ' ' ' ) ) ) ) ) )       	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 . - - - - - l l l l l l l l l l                5 4 4 4 4 4 
	H	%	%/ # $V= V= V= V= V=") V= V= V=tC C C C CRY C C CNb b b b b!7 b b bL    ")    $&$ $  0 0 0 0 0 0 0 0h    BI        bi   S S S S SRY S S SnZ
 Z
 Z
 Z
 Z
ry Z
 Z
 Z
|    bi   * * * * * * * *:/ f    ")   .* * * * *bi * * *> i W
 W
 W
 W
 W
- W
 W
	 W
t A 
Z
 Z
 Z
 Z
 Z
3 Z
 Z
 
Z
z   Y
 Y
 Y
 Y
 Y
)A Y
 Y
 Y
x   T
 T
 T
 T
 T
!9 T
 T
 T
n   K
 K
 K
 K
 K
&> K
 K
 K
\   [
 [
 [
 [
 [
$< [
 [
 [
| UWp G G G G G3_ G G	 GV4 4 4 4 4 4rQ   