
    i                        d dl mZ d dlZd dlmZ d dlmZmZmZ ddlm	Z
 ddlmZmZ ddlmZmZmZ ddlmZ dd	lmZmZ dd
l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#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.m/Z/ ddl0m1Z1 ddl2m3Z3  e,jh                  e5      Z6 G d dejn                        Z8	 	 dJdejn                  dejr                  dejr                  dejr                  dejr                  dz  de:dz  de:de&e*   fdZ; G d d ejn                        Z< G d! d"ejn                        Z= G d# d$ejn                        Z> G d% d&ejn                        Z? G d' d(ejn                        Z@ G d) d*ejn                        ZA G d+ d,e      ZB G d- d.ejn                        ZCe+ G d/ d0e$             ZD G d1 d2ejn                        ZE G d3 d4ejn                        ZF e+d56       G d7 d8eD             ZGe+ G d9 d:eD             ZH G d; d<ejn                        ZI e+d=6       G d> d?eD             ZJe+ G d@ dAeD             ZKe+ G dB dCeD             ZLe+ G dD dEeD             ZM e+dF6       G dG dHeDe             ZNg dIZOy)K    )CallableN)BCEWithLogitsLossCrossEntropyLossMSELoss   )initialization)ACT2FNgelu)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)create_bidirectional_maskcreate_causal_mask)GradientCheckpointingLayer))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)apply_chunking_to_forward)TransformersKwargsauto_docstringlogging)can_return_tuplemerge_with_config_defaults)capture_outputs   )CamembertConfigc                        e Zd ZdZ fdZ	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  ded	ej                  fd
Z
ed        Zedd       Z xZS )CamembertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                 T   t         |           t        j                  |j                  |j
                  |j                        | _        t        j                  |j                  |j
                        | _	        t        j                  |j
                  |j                        | _
        t        j                  |j                        | _        | j                  dt!        j"                  |j$                        j'                  d      d       | j                  dt!        j(                  | j*                  j-                         t         j.                        d       |j                  | _        t        j                  |j$                  |j
                  | j0                        | _        y )	N)padding_idxepsposition_idsr$   F)
persistenttoken_type_ids)dtype)super__init__nn	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_buffertorcharangemax_position_embeddingsexpandzerosr,   sizelongr)   position_embeddingsselfconfig	__class__s     /var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/transformers/models/camembert/modeling_camembert.pyr3   zCamembertEmbeddings.__init__;   s4   !||F,=,=v?Q?Q_e_r_rs%'\\&2H2H&J\J\%]"f&8&8f>S>STzz&"<"<=ELL)G)GHOOPWXej 	 	
 	ekk$*;*;*@*@*B%**Ubg 	 	
 "..#%<<**F,>,>DL\L\$
     N	input_idsr0   r,   inputs_embedspast_key_values_lengthreturnc                    |<|| j                  || j                  |      }n| j                  || j                        }||j                         }n|j                         d d }|\  }}|t	        | d      rT| j
                  j                  |j                  d   d      }	t        j                  |	d|      }	|	j                  ||      }n:t        j                  |t        j                  | j                  j                        }|| j                  |      }| j                  |      }
||
z   }| j!                  |      }||z   }| j#                  |      }| j%                  |      }|S )Nr.   r0   r   r$   )dimindexr1   device)"create_position_ids_from_input_idsr)   &create_position_ids_from_inputs_embedsrG   hasattrr0   rE   shaperB   gatherrF   rH   r,   rX   r9   r;   rI   r<   r@   )rK   rP   r0   r,   rQ   rR   input_shape
batch_size
seq_lengthbuffered_token_type_idsr;   
embeddingsrI   s                rN   forwardzCamembertEmbeddings.forwardO   sn    $#FFt//1G   $JJ=Z^ZjZjk #..*K',,.s3K!,
J
 !t-.*.*=*=*D*D\EWEWXYEZ\^*_'*/,,7NTU]i*j'!8!?!?
J!W!&[

SWSdSdSkSk!l  00;M $ : :> J"%::
"66|D"55
^^J/
\\*-
rO   c                     | j                         dd }|d   }t        j                  |dz   ||z   dz   t        j                  | j                        }|j                  d      j                  |      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$   rW   r   )rG   rB   rC   rH   rX   	unsqueezerE   )rQ   r)   r^   sequence_lengthr,   s        rN   rZ   z:CamembertEmbeddings.create_position_ids_from_inputs_embeds   sp     $((*3B/%a.||!O_{:Q>ejjYfYmYm
 %%a(//<<rO   c                     | j                  |      j                         }t        j                  |d      j	                  |      |z   |z  }|j                         |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$   rU   )neintrB   cumsumtype_asrH   )rP   r)   rR   maskincremental_indicess        rN   rY   z6CamembertEmbeddings.create_position_ids_from_input_ids   sW     ||K(,,.$||Da8@@FI__cgg"'')K77rO   )NNNNr   )r   )__name__
__module____qualname____doc__r3   rB   
LongTensorFloatTensorrj   Tensorrc   staticmethodrZ   rY   __classcell__rM   s   @rN   r'   r'   8   s    Q
, .2260426&'.##d*. ((4/. &&-	.
 ((4/. !$. 
.` = =" 8 8rO   r'   modulequerykeyvalueattention_maskscalingr@   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 )Nr.            r   rh   )ptrainingr$   )
rG   rB   matmul	transposer4   
functionalsoftmaxr@   r   
contiguous)
ry   rz   r{   r|   r}   r~   r@   r   attn_weightsattn_outputs
             rN   eager_attention_forwardr      s     **R.D( <<s}}Q':;gEL!#n4==((2(>L==((6??([L,,|U3K''1-88:K$$rO   c                        e Zd Zd	 fd	Z	 	 d
dej
                  dej                  dz  dedz  dee	   de
ej
                     f
dZ xZS )CamembertSelfAttentionNc                 @   t         |           |j                  |j                  z  dk7  r2t	        |d      s&t        d|j                   d|j                   d      || _        |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _	        | j                  dz  | _
        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                   |j"                        | _        |j&                  | _        || _        || _        y Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r   )r2   r3   r7   num_attention_headsr[   
ValueErrorrL   rj   attention_head_sizeall_head_sizer~   r4   Linearrz   r{   r|   r>   attention_probs_dropout_probr@   
is_decoder	is_causal	layer_idxrK   rL   r   r   rM   s       rN   r3   zCamembertSelfAttention.__init__   sP    : ::a?PVXhHi#F$6$6#7 8 445Q8  #)#=#= #&v'9'9F<V<V'V#W !558P8PP//5YYv1143E3EF
99V//1C1CDYYv1143E3EF
zz&"E"EF ++""rO   hidden_statesr}   past_key_valuesr   rS   c                     |j                   d d }g |d| j                  } | j                  |      j                  | j	                  dd      } | j                  |      j                  | j	                  dd      } | j                  |      j                  | j	                  dd      }	|>|}
t        |t              r|j                  }
|
j                  ||	| j                        \  }}	t        j                  | j                  j                  t               } || |||	|f| j"                  sdn| j$                  j&                  | j(                  d|\  }} |j*                  g |d j-                         }||fS )Nr.   r$   r           r@   r~   )r\   r   rz   viewr   r{   r|   
isinstancer   self_attention_cacheupdater   r   get_interfacerL   _attn_implementationr   r   r@   r   r~   reshaper   )rK   r   r}   r   r   r^   hidden_shapequery_layer	key_layervalue_layercurrent_past_key_valuesattention_interfacer   r   s                 rN   rc   zCamembertSelfAttention.forward   s    $))#2.CCbC$*B*BC 5djj/44lCMMaQRS0DHH]+00,?II!QO	4djj/44lCMMaQRS&&5#/+>?*9*N*N' &=%C%CI{\`\j\j%k"I{(?(M(MKK,,.E)
 %8	%
  $}}C$,,..LL	%
 	%
!\ *k));;;;FFHL((rO   FN)NNro   rp   rq   r3   rB   ru   rt   r   r   r   tuplerc   rw   rx   s   @rN   r   r      sg    #6 48(,	')||') ))D0') 	')
 +,') 
u||	')rO   r   c                        e Zd Zd
 fd	Z	 	 	 ddej
                  dej                  dz  dej                  dz  dedz  dee	   de
ej
                     fd	Z xZS )CamembertCrossAttentionNc                    t         |           |j                  |j                  z  dk7  r2t	        |d      s&t        d|j                   d|j                   d      || _        |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _	        | j                  dz  | _
        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                   |j"                        | _        || _        || _        y r   )r2   r3   r7   r   r[   r   rL   rj   r   r   r~   r4   r   rz   r{   r|   r>   r   r@   r   r   r   s       rN   r3   z CamembertCrossAttention.__init__  sC    : ::a?PVXhHi#F$6$6#7 8 445Q8  #)#=#= #&v'9'9F<V<V'V#W !558P8PP//5YYv1143E3EF
99V//1C1CDYYv1143E3EF
zz&"E"EF""rO   r   encoder_hidden_statesr}   r   r   rS   c                 f   |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }|%|j
                  j                  | j                        nd}	|]|	r[|j                  j                  | j                     j                  }
|j                  j                  | j                     j                  }ng |j                   d d d| j                  }| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|C|j                  j                  |
|| j                        \  }
}d|j
                  | j                  <   t        j                   | j"                  j$                  t&              } || ||
||f| j(                  sdn| j*                  j,                  | j.                  d|\  }} |j0                  g |d j3                         }||fS )Nr.   r$   r   FTr   r   )r\   r   rz   r   r   
is_updatedgetr   cross_attention_cachelayerskeysvaluesr{   r|   r   r   r   rL   r   r   r   r@   r   r~   r   r   )rK   r   r   r}   r   r   r^   r   r   r   r   r   kv_shaper   r   r   s                   rN   rc   zCamembertCrossAttention.forward  s    $))#2.CCbC$*B*BC jj/44\BLLQPQRGVGb_//33DNNChm
&:'==DDT^^TYYI)??FFt~~V]]KX.44Sb9X2Xt?W?WXH!67<<XFPPQRTUVI**%:;@@JTTUVXYZK*)8)N)N)U)U{DNN*&	; >B**4>>:(?(M(MKK,,.E)
 %8	%
  $}}C$,,..LL	%
 	%
!\ *k));;;;FFHL((rO   r   )NNN)ro   rp   rq   r3   rB   ru   rt   r   r   r   r   rc   rw   rx   s   @rN   r   r     s    #4 ;?376:1)||1)  %00471) ))D0	1)
 -t31) +,1) 
u||	1)rO   r   c                   n     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                        | _
        y Nr*   )r2   r3   r4   r   r7   denser<   r=   r>   r?   r@   rJ   s     rN   r3   zCamembertSelfOutput.__init__N  s`    YYv1163E3EF
f&8&8f>S>STzz&"<"<=rO   r   input_tensorrS   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S Nr   r@   r<   rK   r   r   s      rN   rc   zCamembertSelfOutput.forwardT  7    

=1]3}|'CDrO   ro   rp   rq   r3   rB   ru   rc   rw   rx   s   @rN   r   r   M  1    >U\\  RWR^R^ rO   r   c                        e Zd Zd fd	Z	 	 	 	 ddej
                  dej                  dz  dej                  dz  dej                  dz  dedz  dee	   d	e
ej
                     fd
Z xZS )CamembertAttentionNc                     t         |           || _        |rt        nt        } ||||      | _        t        |      | _        y )Nr   r   )r2   r3   is_cross_attentionr   r   rK   r   output)rK   rL   r   r   r   attention_classrM   s         rN   r3   zCamembertAttention.__init__\  s=    "45G1Mc#Fi9U	)&1rO   r   r}   r   encoder_attention_maskr   r   rS   c                     | j                   s|n|} | j                  |f|||d|\  }}| j                  ||      }||fS )N)r   r}   r   )r   rK   r   )	rK   r   r}   r   r   r   r   attention_outputr   s	            rN   rc   zCamembertAttention.forwardc  sd     04/F/FLb)2*
"7)+	*

 *
&,  ;;'7G--rO   )FNFNNNNr   rx   s   @rN   r   r   [  s    2 48:>;?(,.||. ))D0.  %0047	.
 !& 1 1D 8. . +,. 
u||	.rO   r   c                   V     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                     | _        y |j                  | _        y r   )r2   r3   r4   r   r7   intermediate_sizer   r   
hidden_actstrr	   intermediate_act_fnrJ   s     rN   r3   zCamembertIntermediate.__init__y  s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$rO   r   rS   c                 J    | j                  |      }| j                  |      }|S r   )r   r   )rK   r   s     rN   rc   zCamembertIntermediate.forward  s&    

=100?rO   r   rx   s   @rN   r   r   x  s#    9U\\ ell rO   r   c                   n     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                        | _        y r   )r2   r3   r4   r   r   r7   r   r<   r=   r>   r?   r@   rJ   s     rN   r3   zCamembertOutput.__init__  s`    YYv779K9KL
f&8&8f>S>STzz&"<"<=rO   r   r   rS   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S r   r   r   s      rN   rc   zCamembertOutput.forward  r   rO   r   rx   s   @rN   r   r     r   rO   r   c                        e Zd Zd fd	Z	 	 	 	 ddej
                  dej                  dz  dej                  dz  dej                  dz  dedz  dee	   d	ej
                  fd
Z
d Z xZS )CamembertLayerNc                    t         |           |j                  | _        d| _        t	        ||j
                  |      | _        |j
                  | _        |j                  | _        | j                  r.| j
                  st        |  d      t	        |d|d      | _	        t        |      | _        t        |      | _        y )Nr$   r   z> should be used as a decoder model if cross attention is addedFT)r   r   r   )r2   r3   chunk_size_feed_forwardseq_len_dimr   r   	attentionadd_cross_attentionr   crossattentionr   intermediater   r   )rK   rL   r   rM   s      rN   r3   zCamembertLayer.__init__  s    '-'E'E$+Ff>O>O[de ++#)#=#= ##?? D6)g!hii"4##'	#D 2&9%f-rO   r   r}   r   r   r   r   rS   c                      | j                   ||fd|i|\  }}|}	| j                  r:|8t        | d      st        d|  d       | j                  |d ||fd|i|\  }
}|
}	t        | j                  | j                  | j                  |	      }|S )Nr   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[   r   r   r   feed_forward_chunkr   r   )rK   r   r}   r   r   r   r   self_attention_output_r   cross_attention_outputlayer_outputs               rN   rc   zCamembertLayer.forward  s     $24>>$
 ,$
 	$
 q 1??4@4!12 =dV DD D 
 )<(;(;%%&	)
 !0) )%"A  60##T%A%A4CSCSUe
 rO   c                 L    | j                  |      }| j                  ||      }|S r   )r   r   )rK   r   intermediate_outputr   s       rN   r   z!CamembertLayer.feed_forward_chunk  s,    "//0@A{{#68HIrO   r   r   )ro   rp   rq   r3   rB   ru   rt   r   r   r   rc   r   rw   rx   s   @rN   r   r     s    ., 48:>;?(,%||% ))D0%  %0047	%
 !& 1 1D 8% % +,% 
%NrO   r   c                   (     e Zd ZdZ f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                              | _        y r   )r2   r3   r4   r   r7   r   r<   r=   
layer_normr6   decoder	ParameterrB   rF   biasrJ   s     rN   r3   zCamembertLMHead.__init__  s    YYv1163E3EF
,,v'9'9v?T?TUyy!3!3V5F5FGLLV->->!?@	rO   c                     | j                  |      }t        |      }| j                  |      }| j                  |      }|S r   )r   r
   r   r   rK   featuresr   xs       rN   rc   zCamembertLMHead.forward  s;    JJx GOOA LLOrO   ro   rp   rq   rr   r3   rc   rw   rx   s   @rN   r   r     s    6ArO   r   c                   n     e Zd ZeZdZdZdZdZdZ	dZ
eeedZ ej                           fd       Z xZS )CamembertPreTrainedModelrobertaT)r   
attentionscross_attentionsc                    t         |   |       t        |t              r t	        j
                  |j                         yt        |t              ryt	        j                  |j                  t        j                  |j                  j                  d         j                  d             t	        j
                  |j                         yy)zInitialize the weightsr.   r-   N)r2   _init_weightsr   r   initzeros_r   r'   copy_r,   rB   rC   r\   rE   r0   )rK   ry   rM   s     rN   r  z&CamembertPreTrainedModel._init_weights  s     	f%fo.KK$ 34JJv**ELL9L9L9R9RSU9V,W,^,^_f,ghKK--. 5rO   )ro   rp   rq   r%   config_classbase_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr   r   r   _can_record_outputsrB   no_gradr  rw   rx   s   @rN   r   r     sX    "L!&*#N"&',3 U]]_/ /rO   r   c                        e Zd Z fdZ	 	 	 	 	 ddej
                  dej                  dz  dej                  dz  dej                  dz  dedz  dedz  d	e	e
   d
eej
                     ez  fdZ xZS )CamembertEncoderc           	          t         |           || _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        y c c}w )N)r   )	r2   r3   rL   r4   
ModuleListrangenum_hidden_layersr   layer)rK   rL   irM   s      rN   r3   zCamembertEncoder.__init__  sG    ]]QVW]WoWoQp#qAN6Q$G#qr
#qs   ANr   r}   r   r   r   	use_cacher   rS   c                     t        | j                        D ]  \  }}	 |	|||f||d|} t        ||r|      S d       S )N)r   r   )last_hidden_stater   )	enumerater  r   )
rK   r   r}   r   r   r   r  r   r  layer_modules
             rN   rc   zCamembertEncoder.forward  sn      )4 	OA|(% (> / M	 9+/8O
 	
>B
 	
rO   )NNNNN)ro   rp   rq   r3   rB   ru   rt   r   boolr   r   r   r   rc   rw   rx   s   @rN   r  r    s    s 48:>;?(,!%
||
 ))D0
  %0047	

 !& 1 1D 8
 
 $;
 +,
 
u||	H	H
rO   r  c                   V     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                         | _        y r   )r2   r3   r4   r   r7   r   Tanh
activationrJ   s     rN   r3   zCamembertPooler.__init__'  s9    YYv1163E3EF
'')rO   r   rS   c                 \    |d d df   }| j                  |      }| j                  |      }|S Nr   )r   r$  )rK   r   first_token_tensorpooled_outputs       rN   rc   zCamembertPooler.forward,  s6     +1a40

#566rO   r   rx   s   @rN   r!  r!  &  s#    $
U\\ ell rO   r!  a
  
    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](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
    Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.

    To behave as an 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.
    )custom_introc                       e Zd ZddgZd fd	Zd Z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
j                  dz  de
j                  dz  de
j                  dz  dedz  dedz  dee   dee
j                     ez  fd                     Zd Z xZS )CamembertModelr'   r   c                     t         |   |       || _        d| _        t	        |      | _        t        |      | _        |rt        |      nd| _	        | j                          y)zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        FN)r2   r3   rL   gradient_checkpointingr'   rb   r  encoderr!  pooler	post_init)rK   rL   add_pooling_layerrM   s      rN   r3   zCamembertModel.__init__D  sU    
 	 &+#-f5'/1Bof- 	rO   c                 .    | j                   j                  S r   rb   r9   rK   s    rN   get_input_embeddingsz#CamembertModel.get_input_embeddingsU  s    ...rO   c                 &    || j                   _        y r   r3  )rK   r|   s     rN   set_input_embeddingsz#CamembertModel.set_input_embeddingsX  s    */'rO   NrP   r}   r0   r,   rQ   r   r   r   r  r   rS   c
           
         |d u |d uz  rt        d      | j                  j                  r|	|	n| j                  j                  }	nd}	|	rd|b|| j                  j                  r4t        t        | j                        t        | j                              nt        | j                        }||j                         nd}| j                  |||||      }| j                  |||||      \  }} | j                  |f|||||	|d|
}|j                  }| j                  | j                  |      nd }t        |||j                        S )	Nz:You must specify exactly one of input_ids or inputs_embedsF)rL   r   )rP   r,   r0   rQ   rR   )r}   r   embedding_outputr   r   )r}   r   r   r   r  r,   )r  pooler_outputr   )r   rL   r   r  is_encoder_decoderr   r   get_seq_lengthrb   _create_attention_masksr.  r  r/  r   r   )rK   rP   r}   r0   r,   rQ   r   r   r   r  r   rR   r9  encoder_outputssequence_outputr(  s                   rN   rc   zCamembertModel.forward[  s|     -t";<YZZ;;!!%.%:	@U@UII0 )48V8V $L$DlZ^ZeZeFfg!5  FUE`!?!?!Afg??%)'#9 + 
 261M1M)#9-"7+ 2N 2
.. '$,,	
)"7#9+%	
 	
 *;;8<8OO4UY;-'+;;
 	
rO   c                     | j                   j                  rt        | j                   |||      }nt        | j                   ||      }|t        | j                   |||      }||fS )N)rL   rQ   r}   r   )rL   rQ   r}   )rL   rQ   r}   r   )rL   r   r   r   )rK   r}   r   r9  r   r   s         rN   r=  z&CamembertModel._create_attention_masks  su     ;;!!/{{.- /	N 7{{.-N "-%>{{.5&;	&" 555rO   )T)	NNNNNNNNN)ro   rp   rq   _no_split_modulesr3   r5  r7  r"   r#   r   rB   ru   r   r  r   r   r   r   rc   r=  rw   rx   s   @rN   r+  r+  5  s/    /0@A"/0   *..2.2,0-1596:(,!%?
<<$&?
 t+?
 t+	?

 llT)?
 ||d*?
  %||d2?
 !&t 3?
 ?
 $;?
 +,?
 
u||	K	K?
    ?
B6rO   r+  c                       e Zd ZdddZ fdZd Z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	j                  dz  de	j                  dz  dee   dee	j                     ez  fd              Z xZS )CamembertForMaskedLM)roberta.embeddings.word_embeddings.weightlm_head.biaszlm_head.decoder.weightzlm_head.decoder.biasc                     t         |   |       |j                  rt        j	                  d       t        |      | _        t        |d      | _        | j                          y )NzpIf you want to use `CamembertForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Fr1  
r2   r3   r   loggerwarningr   lm_headr+  r  r0  rJ   s     rN   r3   zCamembertForMaskedLM.__init__  sR     NN1 'v.%fF 	rO   c                 .    | j                   j                  S r   rL  r   r4  s    rN   get_output_embeddingsz*CamembertForMaskedLM.get_output_embeddings      ||###rO   c                 &    || j                   _        y r   rN  rK   new_embeddingss     rN   set_output_embeddingsz*CamembertForMaskedLM.set_output_embeddings      -rO   NrP   r}   r0   r,   rQ   r   r   labelsr   rS   c	                 t    | j                   |f||||||dd|	}
|
d   }| j                  |      }d}|a|j                  |j                        }t	               } ||j                  d| j                  j                        |j                  d            }t        |||
j                  |
j                        S )a  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.
            This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
            >= 2. All the value in this tensor should be always < type_vocab_size.

            [What are token type IDs?](../glossary#token-type-ids)
        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)r}   r0   r,   rQ   r   r   return_dictr   Nr.   losslogitsr   r  )r  rL  torX   r   r   rL   r6   r   r   r  )rK   rP   r}   r0   r,   rQ   r   r   rV  r   outputsr?  prediction_scoresmasked_lm_lossloss_fcts                  rN   rc   zCamembertForMaskedLM.forward  s    : $,,

))%'"7#9

 

 "!* LL9YY0778F')H%&7&<&<RAWAW&XZ`ZeZefhZijN$!//))	
 	
rO   )NNNNNNNN)ro   rp   rq   _tied_weights_keysr3   rO  rT  r!   r   rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   rC  rC    s'    #N .
$.  .237260426:>;?*.5
##d*5
 ))D05
 ((4/	5

 &&-5
 ((4/5
  %00475
 !& 1 1D 85
   4'5
 +,5
 
u||	~	-5
  5
rO   rC  c                   (     e Zd ZdZ fdZd Z xZS )CamembertClassificationHeadz-Head for sentence-level classification tasks.c                 Z   t         |           t        j                  |j                  |j                        | _        |j                  |j                  n|j                  }t        j                  |      | _	        t        j                  |j                  |j                        | _        y r   )r2   r3   r4   r   r7   r   classifier_dropoutr?   r>   r@   
num_labelsout_projrK   rL   re  rM   s      rN   r3   z$CamembertClassificationHead.__init__  s    YYv1163E3EF
)/)B)B)NF%%TZTnTn 	 zz"45		&"4"4f6G6GHrO   c                     |d d dd d f   }| j                  |      }| j                  |      }t        j                  |      }| j                  |      }| j	                  |      }|S r&  )r@   r   rB   tanhrg  r   s       rN   rc   z#CamembertClassificationHead.forward"  sY    Q1WLLOJJqMJJqMLLOMM!rO   r   rx   s   @rN   rc  rc    s    7IrO   rc  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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j                     ez  fd              Z xZS )"CamembertForSequenceClassificationc                     t         |   |       |j                  | _        || _        t	        |      | _        t        |d      | _        | j                          y NFrH  )	r2   r3   rf  rL   rc  
classifierr+  r  r0  rJ   s     rN   r3   z+CamembertForSequenceClassification.__init__3  sJ      ++5f=%fF 	rO   NrP   r}   r0   r,   rQ   rV  r   rS   c           	          | j                   |f||||dd|}|d   }	| j                  |	      }
d}||j                  |
j                        }| 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  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.
            This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
            >= 2. All the value in this tensor should be always < type_vocab_size.

            [What are token type IDs?](../glossary#token-type-ids)
        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).
        Tr}   r0   r,   rQ   rX  r   Nr$   
regressionsingle_label_classificationmulti_label_classificationr.   rY  )r  ro  r\  rX   rL   problem_typerf  r1   rB   rH   rj   r   squeezer   r   r   r   r   r  rK   rP   r}   r0   r,   rQ   rV  r   r]  r?  r[  rZ  r`  s                rN   rc   z*CamembertForSequenceClassification.forward>  s   6 $,,
))%'
 
 "!*1YYv}}-F{{''/??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,./'!//))	
 	
rO   NNNNNN)ro   rp   rq   r3   r!   r   rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   rl  rl  ,  s    	  .237260426*.C
##d*C
 ))D0C
 ((4/	C

 &&-C
 ((4/C
   4'C
 +,C
 
u||	7	7C
  C
rO   rl  c                   *    e Zd Z 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j                     ez  fd              Z xZS )CamembertForMultipleChoicec                     t         |   |       t        j                  |j                        | _        t        j                  |j                  d      | _        t        |d      | _
        | j                          y )Nr$   FrH  )r2   r3   r4   r>   r?   r@   r   r7   ro  r+  r  r0  rJ   s     rN   r3   z#CamembertForMultipleChoice.__init__  sX     zz&"<"<=))F$6$6:%fF 	rO   NrP   r0   r}   rV  r,   rQ   r   rS   c           	      "   ||j                   d   n|j                   d   }|!|j                  d|j                  d            nd}	|!|j                  d|j                  d            n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   }| j	                  |      }| j                  |      }|j                  d|      }d}|.|j                  |j                        }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)
        token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.
            This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
            >= 2. All the value in this tensor should be always < type_vocab_size.

            [What are token type IDs?](../glossary#token-type-ids)
        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)
        position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *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)
        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.
        Nr$   r.   T)r,   r0   r}   rQ   rX  rY  )r\   r   rG   r  r@   ro  r\  rX   r   r   r   r  )rK   rP   r0   r}   rV  r,   rQ   r   num_choicesflat_input_idsflat_position_idsflat_token_type_idsflat_attention_maskflat_inputs_embedsr]  r(  r[  reshaped_logitsrZ  r`  s                       rN   rc   z"CamembertForMultipleChoice.forward  s   V -6,Aiooa(}GZGZ[\G]CLCXINN2,>?^bLXLdL--b,2C2CB2GHjnR`Rln11"n6I6I"6MNrvR`Rln11"n6I6I"6MNrv ( r=#5#5b#9=;M;Mb;QR 	 $,,
*..,
 
  
]3/ ++b+6YY556F')HOV4D("!//))	
 	
rO   rx  )ro   rp   rq   r3   r!   r   rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   rz  rz    s      .22637*.0426P
##d*P
 ((4/P
 ))D0	P

   4'P
 &&-P
 ((4/P
 +,P
 
u||	8	8P
  P
rO   rz  c                   *    e Zd Z 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j                     ez  fd              Z xZS )CamembertForTokenClassificationc                 d   t         |   |       |j                  | _        |j                  |j                  n|j                  }t        j                  |      | _        t        j                  |j                  |j                        | _
        t        |d      | _        | j                          y rn  )r2   r3   rf  re  r?   r4   r>   r@   r   r7   ro  r+  r  r0  rh  s      rN   r3   z(CamembertForTokenClassification.__init__  s      ++)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ%fF 	rO   NrP   r}   r0   r,   rQ   rV  r   rS   c           	      ~    | j                   |f||||dd|}|d   }	| j                  |	      }	| j                  |	      }
d}|W|j                  |
j                        }t               } ||
j                  d| j                        |j                  d            }t        ||
|j                  |j                        S )a-  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.
            This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
            >= 2. All the value in this tensor should be always < type_vocab_size.

            [What are token type IDs?](../glossary#token-type-ids)
        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]`.
        Trq  r   Nr.   rY  )r  r@   ro  r\  rX   r   r   rf  r   r   r  rw  s                rN   rc   z'CamembertForTokenClassification.forward  s    2 $,,
))%'
 
 "!*,,71YYv}}-F')HFKKDOO<fkk"oND$!//))	
 	
rO   rx  )ro   rp   rq   r3   r!   r   rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   r  r    s      .237260426*.2
##d*2
 ))D02
 ((4/	2

 &&-2
 ((4/2
   4'2
 +,2
 
u||	4	42
  2
rO   r  c                   J    e Zd Z 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j                  dz  d
e	e
   deej                     ez  fd              Z xZS )CamembertForQuestionAnsweringc                     t         |   |       |j                  | _        t        j                  |j
                  |j                        | _        t        |d      | _        | j                          y rn  )
r2   r3   rf  r4   r   r7   
qa_outputsr+  r  r0  rJ   s     rN   r3   z&CamembertForQuestionAnswering.__init__0  sU      ++))F$6$68I8IJ%fF 	rO   NrP   r}   r0   r,   rQ   start_positionsend_positionsr   rS   c           	          | j                   |f||||dd|}	|	d   }
| 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        |      } |||      } |||      }||z   d	z  }t        ||||	j                  |	j                  
      S )a[  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.
            This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
            >= 2. All the value in this tensor should be always < type_vocab_size.

            [What are token type IDs?](../glossary#token-type-ids)
        Trq  r   r$   r.   rh   N)ignore_indexr   )rZ  start_logits
end_logitsr   r  )r  r  splitrv  r   lenrG   clampr   r   r   r  )rK   rP   r}   r0   r,   rQ   r  r  r   r]  r?  r[  r  r  
total_lossignored_indexr`  
start_lossend_losss                      rN   rc   z%CamembertForQuestionAnswering.forward:  s   0 $,,
))%'
 
 "!*1#)<<r<#: j#++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M-33A}EO)//=AM']CH!,@J
M:H$x/14J+%!!//))
 	
rO   )NNNNNNN)ro   rp   rq   r3   r!   r   rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   r  r  .  s      .2372604263715>
##d*>
 ))D0>
 ((4/	>

 &&->
 ((4/>
 ))D0>
 ''$.>
 +,>
 
u||	;	;>
  >
rO   r  zU
    Camembert Model with a `language modeling` head on top for CLM fine-tuning.
    c                       e Zd ZdddZ fdZd Z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	j                  dz  de	j                  dz  deee	j                        dz  dedz  dee	j                  z  dee   dee	j                     ez  fd              Z xZS )CamembertForCausalLMrD  rE  rF  c                     t         |   |       |j                  st        j	                  d       t        |      | _        t        |d      | _        | j                          y )NzQIf you want to use `CamembertLMHeadModel` as a standalone, add `is_decoder=True.`FrH  rI  rJ   s     rN   r3   zCamembertForCausalLM.__init__  sL       NNno&v.%fF 	rO   c                 .    | j                   j                  S r   rN  r4  s    rN   rO  z*CamembertForCausalLM.get_output_embeddings  rP  rO   c                 &    || j                   _        y r   rN  rR  s     rN   rT  z*CamembertForCausalLM.set_output_embeddings  rU  rO   NrP   r}   r0   r,   rQ   r   r   rV  r   r  logits_to_keepr   rS   c                    |d}
 | j                   |f|||||||	|
dd	|}|j                  }t        |t              rt	        | d      n|}| j                  |dd|ddf         }d}|* | j                  d||| j                  j                  d|}t        |||j                  |j                  |j                  |j                        S )aq  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.
            This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
            >= 2. All the value in this tensor should be always < type_vocab_size.

            [What are token type IDs?](../glossary#token-type-ids)
        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]`

        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
        ```NFT)	r}   r0   r,   rQ   r   r   r   r  rX  )r[  rV  r6   )rZ  r[  r   r   r  r   )r  r  r   rj   slicerL  loss_functionrL   r6   r   r   r   r  r  )rK   rP   r}   r0   r,   rQ   r   r   rV  r   r  r  r   r]  r   slice_indicesr[  rZ  s                     rN   rc   zCamembertForCausalLM.forward  s    ` I@LA
))%'"7#9+A
 A
  118B>SV8W~ot4]kmA}a,?@A%4%%pVFt{{OeOepiopD0#33!//))$55
 	
rO   )NNNNNNNNNNr   )ro   rp   rq   ra  r3   rO  rT  r!   r   rB   rs   rt   r   r  rj   ru   r   r   r   rc   rw   rx   s   @rN   r  r  }  s    #N .

$.  .237260426:>;?*.BF!%-.O
##d*O
 ))D0O
 ((4/	O

 &&-O
 ((4/O
  %0047O
 !& 1 1D 8O
   4'O
 uU%6%6784?O
 $;O
 ell*O
 +,O
 
u||	@	@O
  O
rO   r  )r  rC  rz  r  rl  r  r+  r   )Nr   )Pcollections.abcr   rB   torch.nnr4   r   r   r    r   r  activationsr	   r
   cache_utilsr   r   r   
generationr   masking_utilsr   r   modeling_layersr   modeling_outputsr   r   r   r   r   r   r   r   modeling_utilsr   r   processing_utilsr   pytorch_utilsr   utilsr   r   r    utils.genericr!   r"   utils.output_capturingr#   configuration_camembertr%   
get_loggerro   rJ  Moduler'   ru   floatr   r   r   r   r   r   r   r   r   r   r  r!  r+  rC  rc  rl  rz  r  r  r  __all__r  rO   rN   <module>r     s  , %   A A & ' C C ) J 9	 	 	 G & 6 @ @ I 5 4 
		H	%g8")) g8` !%II%<<% 
% <<	%
 LL4'% T\% % '(%8@)RYY @)FI)bii I)X")) . .:BII bii >/ >Bbii , / / /2
ryy 
@bii  	|6- |6|6~ R
3 R
 R
j")) , Q
)A Q
Q
h ]
!9 ]
 ]
@ C
&> C
 C
L K
$< K
 K
\ 
i
3_ i

i
X	rO   