
    i                      *   d Z 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/m0Z0 ddl1m2Z2 ddl3m4Z4  e-jj                  e6      Z7 G d dejp                        Z9	 	 dNdejp                  dejt                  dejt                  dejt                  dejt                  dz  de;dz  de;de'e+   fd Z< G d! d"ejp                        Z= G d# d$ejp                        Z> G d% d&ejp                        Z? G d' d(ejp                        Z@ G d) d*ejp                        ZA G d+ d,ejp                        ZB G d- d.ejp                        ZC G d/ d0e      ZD G d1 d2ejp                        ZE G d3 d4ejp                        ZFe, G d5 d6e%             ZG e,d78       G d9 d:eG             ZH e,d;8       G d< d=eGe             ZIe, G d> d?eG             ZJ G d@ dAejp                        ZK e,dB8       G dC dDeG             ZLe, G dE dFeG             ZMe, G dG dHeG             ZN G dI dJejp                        ZOe, G dK dLeG             ZPg dMZQy)OzPyTorch X-MOD model.    )CallableN)nn)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   )
XmodConfigc                        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 )XmodEmbeddingszGConstruct 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__r   	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     w/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/transformers/models/xmod/modeling_xmod.pyr4   zXmodEmbeddings.__init__6   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_idsr1   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/   r1   r   r%   )dimindexr2   device)"create_position_ids_from_input_idsr*   &create_position_ids_from_inputs_embedsrG   hasattrr1   rE   shaperB   gatherrF   rH   r-   rX   r9   r;   rI   r<   r@   )rK   rP   r1   r-   rQ   rR   input_shape
batch_size
seq_lengthbuffered_token_type_idsr;   
embeddingsrI   s                rN   forwardzXmodEmbeddings.forwardJ   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   z5XmodEmbeddings.create_position_ids_from_inputs_embedsz   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   z1XmodEmbeddings.create_position_ids_from_input_ids   sW     ||K(,,.$||Da8@@FI__cgg"'')K77rO   )NNNNr   )r   )__name__
__module____qualname____doc__r4   rB   
LongTensorFloatTensorrj   Tensorrc   staticmethodrZ   rY   __classcell__rM   s   @rN   r(   r(   3   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	transposer   
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 )XmodSelfAttentionNc                 @   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   )r3   r4   r7   num_attention_headsr[   
ValueErrorrL   rj   attention_head_sizeall_head_sizer~   r   Linearrz   r{   r|   r>   attention_probs_dropout_probr@   
is_decoder	is_causal	layer_idxrK   rL   r   r   rM   s       rN   r4   zXmodSelfAttention.__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XmodSelfAttention.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   r4   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 )XmodCrossAttentionNc                    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   )r3   r4   r7   r   r[   r   rL   rj   r   r   r~   r   r   rz   r{   r|   r>   r   r@   r   r   r   s       rN   r4   zXmodCrossAttention.__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XmodCrossAttention.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   r4   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 )XmodSelfOutputc                 (   t         |           t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        t        j                  |j                        | _
        y Nr+   )r3   r4   r   r   r7   denser<   r=   r>   r?   r@   rJ   s     rN   r4   zXmodSelfOutput.__init__M  s`    YYv1163E3EF
f&8&8f>S>STzz&"<"<=rO   r   input_tensorrS   c                 T    | j                  |      }| j                  |      }||z   }|S N)r   r@   )rK   r   r   s      rN   rc   zXmodSelfOutput.forwardS  s.    

=1]3%4rO   ro   rp   rq   r4   rB   ru   rc   rw   rx   s   @rN   r   r   K  s1    >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eej                        dz  dee	   d	eej
                     fd
Z
 xZS )XmodAttentionNc                     t         |           || _        |rt        nt        } ||||      | _        t        |      | _        |j                  | _        y )Nr   r   )	r3   r4   is_cross_attentionr   r   rK   r   outputpre_norm)rK   rL   r   r   r   attention_classrM   s         rN   r4   zXmodAttention.__init__[  sH    "40B,HY#Fi9U	$V,rO   r   r}   r   encoder_attention_maskr   r   rS   c                 "   |}| j                   r| j                  j                  |      }| j                  s|n|} | j                  |f|||d|\  }}	| j                  ||      }| j                   s| j                  j                  |      }||	fS )N)r   r}   r   )r   r   r<   r   rK   )
rK   r   r}   r   r   r   r   residualattention_outputr   s
             rN   rc   zXmodAttention.forwardd  s     !== KK11-@M/3/F/FLb)2*
"7)+	*

 *
&,  ;;'7B}}#{{445EF--rO   )FNFNNNN)ro   rp   rq   r4   rB   ru   rt   r   r   r   rc   rw   rx   s   @rN   r   r   Z  s    ( 48:>;?BF.||. ))D0.  %0047	.
 !& 1 1D 8. uU%6%6784?. +,. 
u||	.rO   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )XmodIntermediatec                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y r   )r3   r4   r   r   r7   intermediate_sizer   r   
hidden_actstrr
   intermediate_act_fnrJ   s     rN   r4   zXmodIntermediate.__init__  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XmodIntermediate.forward  s&    

=100?rO   r   rx   s   @rN   r   r     s#    9U\\ ell rO   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )XmodAdapterc                    t         |           |j                  |j                  z  | _        t        j                  |j                  | j                        | _        t        j                  | j                  |j                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y r   )r3   r4   r7   adapter_reduction_factorbottleneck_sizer   r   dense1dense2r   r   r   r
   adapter_act_fnrJ   s     rN   r4   zXmodAdapter.__init__  s    %11V5T5TTii 2 2D4H4HIii 4 4f6H6HIf''-"():):";D"("3"3DrO   r   rS   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r   r   s     rN   rc   zXmodAdapter.forward  s4    M2++M:M2rO   r   rx   s   @rN   r   r     s#    4U\\ ell rO   r   c                        e Zd Z fdZdej
                  dej
                  dej
                  dej
                  fdZdej
                  dej
                  fdZ xZS )
XmodOutputc                    t         |           t        j                  |j                  |j
                        | _        t        j                  |j
                  |j                        | _        |j                  | _	        t        j                  |j                        | _        |j                  r1t        j                  |j
                  |j                        | _        nd | _        |j                  | _        t        j                  i       | _        |j"                  D ]#  }t%        |      | j                   t'        |      <   % y r   )r3   r4   r   r   r   r7   r   r<   r=   ln_before_adapterr>   r?   r@   adapter_layer_normadapter_reuse_layer_norm
ModuleDictadapter_modules	languagesr   r   )rK   rL   languagerM   s      rN   r4   zXmodOutput.__init__  s    YYv779K9KL
f&8&8f>S>ST!'!9!9zz&"<"<=$$&(ll63E3E6K`K`&aD#&*D#(.(G(G%!}}R0(( 	FH2=f2ED  X/	FrO   r   r   lang_idsrS   c                 x    | j                  |      }| j                  |      }||z   }| j                  ||      }|S r   )r   r@   lang_adapter)rK   r   r   r   s       rN   rc   zXmodOutput.forward  s@    

=1]3%4))(MBrO   c                    | j                   s|}| j                  | j                  |      }n| j                  r| j                  |      }| j                   r|}t	        j
                  |      }t        | j                  j                               D ])  \  }}||k(  }||   } | j                  |   |      }	|	||<   + | j                  |      }|z  }|S r   )
r   r   r   r<   rB   
zeros_like	enumerater   r   r@   )
rK   r   r   r   new_hidden_statesadapter_idxlang_key	lang_masklang_hidden_statesadapted_lang_hidden_statess
             rN   r   zXmodOutput.lang_adapter  s    %%$H"". 33MBM** NN=9M!!$H!,,];%.t/C/C/H/H/J%K 	F!K K/I!.y!9)G)=)=h)GHZ)[&+Ei(		F %67!rO   )	ro   rp   rq   r4   rB   ru   rc   r   rw   rx   s   @rN   r   r     s[    FU\\  Y^YeYe jojvjv U\\ %,, rO   r   c                       e Zd Zd fd	Z	 	 	 	 ddej
                  dej
                  dej                  dz  dej                  dz  dej                  dz  deeej                        dz  d	ee	   d
ej
                  fdZ
d Z xZS )	XmodLayerNc                    t         |           |j                  | _        d| _        t	        ||j
                  |      | _        |j
                  | _        |j                  | _        | j                  r.| j
                  st        |  d      t	        |d|d      | _	        t        |      | _        t        |      | _        |j                  | _        y )Nr%   r   z> should be used as a decoder model if cross attention is addedFT)r   r   r   )r3   r4   chunk_size_feed_forwardseq_len_dimr   r   	attentionadd_cross_attentionr   crossattentionr   intermediater   r   r   )rK   rL   r   rM   s      rN   r4   zXmodLayer.__init__  s    '-'E'E$&v9J9JV_` ++#)#=#= ##?? D6)g!hii"/##'	#D -V4 (rO   r   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|\  }}	|}
|
}| j
                  r| j                  j                  |
      }
t        | j                  | j                  | j                  |
      }| j                  |||      }| j
                  s| 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   r   r<   r   feed_forward_chunkr   r   )rK   r   r   r}   r   r   r   r   self_attention_output_r   cross_attention_outputr   intermediate_outputlayer_outputs                  rN   rc   zXmodLayer.forward  s8    $24>>$
 ,$
 	$
 q 1??4@4!12 =dV DD D 
 )<(;(; %&	)
 !0) )%"A  6#==#{{445EF7##((	
 {{#6(K}};;00>LrO   c                 $    | j                  |      S r   )r  )rK   r   s     rN   r  zXmodLayer.feed_forward_chunk  s      !122rO   r   r   )ro   rp   rq   r4   rB   ru   rt   r   r   r   rc   r  rw   rx   s   @rN   r   r     s    (0 48:>;?BF0||0 ,,0 ))D0	0
  %00470 !& 1 1D 80 uU%6%6784?0 +,0 
0d3rO   r   c                       e Zd Z fdZ	 	 	 	 	 ddej
                  dej
                  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
   deej
                     ez  fdZ xZS )XmodEncoderc           	      b   t         |           || _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        |j                  | _
        | j                  r1t        j                  |j                  |j                        | _        y y c c}w )N)r   r+   )r3   r4   rL   r   
ModuleListrangenum_hidden_layersr   layerr   is_pre_normr<   r7   r=   )rK   rL   irM   s      rN   r4   zXmodEncoder.__init__  s    ]]ERXRjRjLk#lqIf$B#lm
!??\\&*<*<&BWBWXDN  $ms   B,Nr   r   r}   r   r   r   	use_cacher   rS   c           	          t        | j                        D ]  \  }	}
 |
||||||fi |} | j                  r| j                  |      }t	        ||r|      S d       S )N)last_hidden_stater   )r   r  r  r<   r   )rK   r   r   r}   r   r   r   r  r   r  layer_modules              rN   rc   zXmodEncoder.forward&  s      )4 		OA|(%& M		  NN=9M8+/8O
 	
>B
 	
rO   )NNNNN)ro   rp   rq   r4   rB   ru   rt   r   boolr   r   r   rc   rw   rx   s   @rN   r  r    s    Y 48:>;?BF!%
||
 ,,
 ))D0	

  %0047
 !& 1 1D 8
 uU%6%6784?
 $;
 +,
 
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 )
XmodPoolerc                     t         |           t        j                  |j                  |j                        | _        t        j                         | _        y r   )r3   r4   r   r   r7   r   Tanh
activationrJ   s     rN   r4   zXmodPooler.__init__G  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XmodPooler.forwardL  s6     +1a40

#566rO   r   rx   s   @rN   r  r  F  s#    $
U\\ ell rO   r  c                        e Zd ZeZdZdZg dZdZdZ	dZ
dZeeedZ ej"                          fd       ZdefdZd Z xZS )	XmodPreTrainedModelrobertaT)r(   r   r   )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)r3   _init_weightsr   
XmodLMHeadinitzeros_biasr(   copy_r-   rB   rC   r\   rE   r1   )rK   ry   rM   s     rN   r)  z!XmodPreTrainedModel._init_weightse  s     	f%fj)KK$/JJv**ELL9L9L9R9RSU9V,W,^,^_f,ghKK--. 0rO   r   c           	          || j                   j                  vr0t        |  d| dt        | j                   j                               || j                   _        y)z
        Set the default language code for the model. This is used when the language is not specified in the input.

        Args:
            language (`str`): The language code, such as `"en_XX"` or `"de_DE"`.
        z does not have an adapter for z. Supported languages: N)rL   r   r   listdefault_language)rK   r   s     rN   set_default_languagez(XmodPreTrainedModel.set_default_languageo  s[     4;;000&6xj@WX\]a]h]h]r]rXsWtu  (0$rO   c                    t         j                  d       | j                  j                  j	                         D ]	  }d|_         t         j                  d       | j                  j                  j                  D ]x  }|j                  j                  0|j                  j                  j	                         D ]	  }d|_         |j                  j                  j	                         D ]	  }d|_         z y)z
        Freeze the embeddings and language adapters of the model. Usually, this is applied before the model is
        fine-tuned on a downstream task.
        zFreezing embeddingsFzFreezing adaptersN)loggerinfor%  rb   
parametersrequires_gradencoderr  r   r   r   )rK   	parameterr  s      rN   'freeze_embeddings_and_language_adaptersz;XmodPreTrainedModel.freeze_embeddings_and_language_adapters|  s    
 	)*00;;= 	,I&+I#	,'(\\))// 	0E||..:!&!@!@!K!K!M 4I.3I+4"\\99DDF 0	*/	'0		0rO   )ro   rp   rq   r&   config_classbase_model_prefixsupports_gradient_checkpointingno_split_modules_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr   r   r   _can_record_outputsrB   no_gradr)  r   r2  r:  rw   rx   s   @rN   r$  r$  U  so    L!&*#TN"&"'. U]]_/ /0S 00rO   r$  a0  
    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 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.

    .. _*Attention is all you need*: https://huggingface.co/papers/1706.03762
    )custom_introc                       e Zd 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	j                  dz  dee	j                     dz  dedz  dee   dee	j                     ez  fd                     Zd Z xZS )	XmodModelc                     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)r3   r4   rL   gradient_checkpointingr(   rb   r  r8  r  pooler	post_init)rK   rL   add_pooling_layerrM   s      rN   r4   zXmodModel.__init__  sU    
 	 &+#(0"6*,=j(4 	rO   c                 .    | j                   j                  S r   rb   r9   rK   s    rN   get_input_embeddingszXmodModel.get_input_embeddings  s    ...rO   c                 &    || j                   _        y r   rN  )rK   r|   s     rN   set_input_embeddingszXmodModel.set_input_embeddings  s    */'rO   NrP   r   r}   r1   r-   rQ   r   r   r   r  r   rS   c                 P   |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                  d   n|j                  d   }||j                  n|j                  }|	|	j                         nd}|| j                  j                  t        d      t        | j                  j                  d   j                  j                  j!                               }|j#                  | j                  j                        }|t%        j&                  ||      z  }| j)                  |||||      }| j+                  |||||		      \  }} | j                  |f|||||	|
|d
|}|d   }| j,                  | j-                  |      nd}t/        |||j0                        S )  
        lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of the language adapters that should be activated for each sample, respectively. Default: the index
            that corresponds to `self.config.default_language`.
        Nz:You must specify exactly one of input_ids or inputs_embedsF)rL   r   zPInput language unknown. Please call `XmodPreTrainedModel.set_default_language()`)rX   )rP   r-   r1   rQ   rR   )r}   r   embedding_outputr   r   )r   r}   r   r   r   r  r-   )r  pooler_outputr   )r   rL   r   r  is_encoder_decoderr   r   r\   rX   get_seq_lengthr1  r0  r8  r  r   r   r   rV   rB   onesrb   _create_attention_masksrJ  r   r   )rK   rP   r   r}   r1   r-   rQ   r   r   r   r  r   r_   rX   rR   adapter_languagesdefault_lang_idrU  encoder_outputssequence_outputr"  s                        rN   rc   zXmodModel.forward  s5   , -t";<YZZ;;!!%.%:	@U@UII0 )48V8V $L$DlZ^ZeZeFfg!5  ,5+@Y__Q'mFYFYZ[F\
%.%:!!@T@TETE`!?!?!Afg{{++3 !stt $T\\%7%7%:%A%A%Q%Q%V%V%X Y/55dkk6R6RSO&Jv)NNH??%)'#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   rU  r   r   s         rN   rZ  z!XmodModel._create_attention_masks
  su     ;;!!/{{.- /	N 7{{.-N "-%>{{.5&;	&" 555rO   )T)
NNNNNNNNNN)ro   rp   rq   r4   rP  rR  r#   r$   r    rB   ru   rs   r0  rt   r  r   r   r   r   rc   rZ  rw   rx   s   @rN   rG  rG    sS   $/0   *.,0.2.2,0-1596::>!%O
<<$&O
 ""T)O
 t+	O

 t+O
 llT)O
 ||d*O
  %||d2O
 !&t 3O
 e//047O
 $;O
 +,O
 
u||	K	KO
    O
d6rO   rG  zQ
    X-MOD 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	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 )XmodForCausalLM)roberta.embeddings.word_embeddings.weightlm_head.biaszlm_head.decoder.weightzlm_head.decoder.biasc                     t         |   |       |j                  st        j	                  d       t        |d      | _        t        |      | _        | j                          y )NzLIf you want to use `XmodLMHeadModel` as a standalone, add `is_decoder=True.`FrL  
r3   r4   r   r4  warningrG  r%  r*  lm_headrK  rJ   s     rN   r4   zXmodForCausalLM.__init__7  sL       NNij 5A!&) 	rO   c                 .    | j                   j                  S r   ri  decoderrO  s    rN   get_output_embeddingsz%XmodForCausalLM.get_output_embeddingsD      ||###rO   c                 &    || j                   _        y r   rk  rK   new_embeddingss     rN   set_output_embeddingsz%XmodForCausalLM.set_output_embeddingsH      -rO   NrP   r   r}   r1   r-   rQ   r   r   labelsr   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 )aS  
        lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of the language adapters that should be activated for each sample, respectively. Default: the index
            that corresponds to `self.config.default_language`.
        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, XmodForCausalLM, AutoConfig
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-roberta-base")
        >>> config = AutoConfig.from_pretrained("facebook/xmod-base")
        >>> config.is_decoder = True
        >>> model = XmodForCausalLM.from_pretrained("facebook/xmod-base", config=config)
        >>> model.set_default_language("en_XX")

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

        >>> prediction_logits = outputs.logits
        ```NFT)
r   r}   r1   r-   rQ   r   r   r   r  return_dict)logitsrt  r6   )lossrx  r   r   r&  r'   )r%  r  r   rj   sliceri  loss_functionrL   r6   r   r   r   r&  r'  )rK   rP   r   r}   r1   r-   rQ   r   r   rt  r   r  ru  r   outputsr   slice_indicesrx  ry  s                      rN   rc   zXmodForCausalLM.forwardK  s    X 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   )NNNNNNNNNNNr   )ro   rp   rq   _tied_weights_keysr4   rm  rr  r"   r    rB   rs   rt   r   r  rj   ru   r   r   r   rc   rw   rx   s   @rN   ra  ra  +  s    #N .
$.  .2,037260426:>;?*.BF!%-.L
##d*L
 ""T)L
 ))D0	L

 ((4/L
 &&-L
 ((4/L
  %0047L
 !& 1 1D 8L
   4'L
 uU%6%6784?L
 $;L
 ell*L
 +,L
 
u||	@	@L
  L
rO   ra  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	j                  dz  dee   dee	j                     ez  fd              Z xZS )XmodForMaskedLMrb  rc  rd  c                     t         |   |       |j                  rt        j	                  d       t        |d      | _        t        |      | _        | j                          y )NzkIf you want to use `XmodForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Frf  rg  rJ   s     rN   r4   zXmodForMaskedLM.__init__  sR     NN1
 !5A!&) 	rO   c                 .    | j                   j                  S r   rk  rO  s    rN   rm  z%XmodForMaskedLM.get_output_embeddings  rn  rO   c                 &    || j                   _        y r   rk  rp  s     rN   rr  z%XmodForMaskedLM.set_output_embeddings  rs  rO   NrP   r   r}   r1   r-   rQ   r   r   rt  r   rS   c
                 @    | j                   |f|||||||dd|
}|d   }| j                  |      }d}|	Ft               } ||j                  d| j                  j
                        |	j                  d            }t        |||j                  |j                        S )a  
        lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of the language adapters that should be activated for each sample, respectively. Default: the index
            that corresponds to `self.config.default_language`.
        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   r}   r1   r-   rQ   r   r   rw  r   Nr/   ry  rx  r   r&  )	r%  ri  r   r   rL   r6   r   r   r&  )rK   rP   r   r}   r1   r-   rQ   r   r   rt  r   r}  r^  prediction_scoresmasked_lm_lossloss_fcts                   rN   rc   zXmodForMaskedLM.forward  s    0 $,,
))%'"7#9
 
 "!* LL9')H%&7&<&<RAWAW&XZ`ZeZefhZijN$!//))	
 	
rO   )	NNNNNNNNN)ro   rp   rq   r  r4   rm  rr  r"   r    rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   r  r    s?    #N . $.  .2,037260426:>;?*./
##d*/
 ""T)/
 ))D0	/

 ((4//
 &&-/
 ((4//
  %0047/
 !& 1 1D 8/
   4'/
 +,/
 
u||	~	-/
  /
rO   r  c                   (     e Zd ZdZ fdZd Z xZS )r*  z*Roberta 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   )r3   r4   r   r   r7   r   r<   r=   
layer_normr6   rl  	ParameterrB   rF   r-  rJ   s     rN   r4   zXmodLMHead.__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  rl  rK   featuresr   xs       rN   rc   zXmodLMHead.forward  s;    JJx GOOA LLOrO   ro   rp   rq   rr   r4   rc   rw   rx   s   @rN   r*  r*    s    4ArO   r*  z
    X-MOD 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                   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 )XmodForSequenceClassificationc                     t         |   |       |j                  | _        || _        t	        |d      | _        t        |      | _        | j                          y NFrf  )	r3   r4   
num_labelsrL   rG  r%  XmodClassificationHead
classifierrK  rJ   s     rN   r4   z&XmodForSequenceClassification.__init__  sJ      ++ 5A08 	rO   NrP   r   r}   r1   r-   rQ   rt  r   rS   c           
          | j                   |f|||||dd|}	|	d   }
| j                  |
      }d}|| j                  j                  | j                  dk(  rd| j                  _        nl| j                  dkD  rL|j
                  t        j                  k(  s|j
                  t        j                  k(  rd| j                  _        nd| j                  _        | j                  j                  dk(  rIt               }| j                  dk(  r& ||j                         |j                               }n |||      }n| j                  j                  dk(  r=t               } ||j                  d	| j                        |j                  d	            }n,| j                  j                  dk(  rt               } |||      }t        |||	j                  |	j                   
      S )a  
        lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of the language adapters that should be activated for each sample, respectively. Default: the index
            that corresponds to `self.config.default_language`.
        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   r}   r1   r-   rQ   rw  r   Nr%   
regressionsingle_label_classificationmulti_label_classificationr/   r  )r%  r  rL   problem_typer  r2   rB   rH   rj   r   squeezer   r   r   r   r   r&  rK   rP   r   r}   r1   r-   rQ   rt  r   r}  r^  rx  ry  r  s                 rN   rc   z%XmodForSequenceClassification.forward  s   , $,,	
))%'	
 	
 "!*1{{''/??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   NNNNNNN)ro   rp   rq   r4   r"   r    rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   r  r    s    	  .2,037260426*.=
##d*=
 ""T)=
 ))D0	=

 ((4/=
 &&-=
 ((4/=
   4'=
 +,=
 
u||	7	7=
  =
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 )XmodForMultipleChoicec                     t         |   |       t        |      | _        t	        j
                  |j                        | _        t	        j                  |j                  d      | _
        | j                          y )Nr%   )r3   r4   rG  r%  r   r>   r?   r@   r   r7   r  rK  rJ   s     rN   r4   zXmodForMultipleChoice.__init__^  sV      (zz&"<"<=))F$6$6: 	rO   NrP   r   r1   r}   rt  r-   rQ   r   rS   c           
      Z   ||j                   d   n|j                   d   }	|!|j                  d|j                  d            nd}
|2|j                  |j                  d      |j                  d      z        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}|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)
        lang_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
            Indices of the language adapters that should be activated for each sample, respectively. Default: the index
            that corresponds to `self.config.default_language`.
        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.

            [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/   r   T)r   r-   r1   r}   rQ   rw  r  )r\   r   rG   repeatr%  r@   r  r   r   r   r&  )rK   rP   r   r1   r}   rt  r-   rQ   r   num_choicesflat_input_idsflat_lang_idsflat_position_idsflat_token_type_idsflat_attention_maskflat_inputs_embedsr}  r"  rx  reshaped_logitsry  r  s                         rN   rc   zXmodForMultipleChoice.forwardh  s   \ -6,Aiooa(}GZGZ[\G]CLCXINN2,>?^bRZRf	q(9INN1<M(MNlp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')HOV4D("!//))	
 	
rO   r  )ro   rp   rq   r4   r"   r    rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   r  r  [  s      .2,02637*.0426S
##d*S
 ""T)S
 ((4/	S

 ))D0S
   4'S
 &&-S
 ((4/S
 +,S
 
u||	8	8S
  S
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 )XmodForTokenClassificationc                 d   t         |   |       |j                  | _        t        |d      | _        |j
                  |j
                  n|j                  }t        j                  |      | _	        t        j                  |j                  |j                        | _        | j                          y r  )r3   r4   r  rG  r%  classifier_dropoutr?   r   r>   r@   r   r7   r  rK  rK   rL   r  rM   s      rN   r4   z#XmodForTokenClassification.__init__  s      ++ 5A)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ 	rO   NrP   r   r}   r1   r-   rQ   rt  r   rS   c           
      J    | j                   |f|||||dd|}	|	d   }
| j                  |
      }
| j                  |
      }d}|<t               } ||j	                  d| j
                        |j	                  d            }t        |||	j                  |	j                        S )a  
        lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of the language adapters that should be activated for each sample, respectively. Default: the index
            that corresponds to `self.config.default_language`.
        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]`.
        Tr  r   Nr/   r  )	r%  r@   r  r   r   r  r   r   r&  r  s                 rN   rc   z"XmodForTokenClassification.forward  s    ( $,,	
))%'	
 	
 "!*,,71')HFKKDOO<fkk"oND$!//))	
 	
rO   r  )ro   rp   rq   r4   r"   r    rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   r  r    s      .2,037260426*.,
##d*,
 ""T),
 ))D0	,

 ((4/,
 &&-,
 ((4/,
   4',
 +,,
 
u||	4	4,
  ,
rO   r  c                   (     e Zd ZdZ fdZd Z xZS )r  z-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   )r3   r4   r   r   r7   r   r  r?   r>   r@   r  out_projr  s      rN   r4   zXmodClassificationHead.__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   tanhr  r  s       rN   rc   zXmodClassificationHead.forward  sY    Q1WLLOJJqMJJqMLLOMM!rO   r  rx   s   @rN   r  r    s    7I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j                  dz  de	e
   deej                     ez  fd              Z xZS )XmodForQuestionAnsweringc                     t         |   |       |j                  | _        t        |d      | _        t        j                  |j                  |j                        | _        | j                          y r  )
r3   r4   r  rG  r%  r   r   r7   
qa_outputsrK  rJ   s     rN   r4   z!XmodForQuestionAnswering.__init__  sU      ++ 5A))F$6$68I8IJ 	rO   NrP   r   r}   r1   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 )rT  Tr  r   r%   r/   rh   N)ignore_indexr   )ry  start_logits
end_logitsr   r&  )r%  r  splitr  r   lenrG   clampr   r   r   r&  )rK   rP   r   r}   r1   r-   rQ   r  r  r   r}  r^  rx  r  r  
total_lossignored_indexr  
start_lossend_losss                       rN   rc   z XmodForQuestionAnswering.forward&  s   & $,,	
))%'	
 	
 "!*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   )NNNNNNNN)ro   rp   rq   r4   r"   r    rB   rs   rt   r   r   r   ru   r   rc   rw   rx   s   @rN   r  r    s     .2,0372604263715:
##d*:
 ""T):
 ))D0	:

 ((4/:
 &&-:
 ((4/:
 ))D0:
 ''$.:
 +,:
 
u||	;	;:
  :
rO   r  )ra  r  r  r  r  r  rG  r$  )Nr   )Rrr   collections.abcr   rB   r   torch.nnr   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_xmodr&   
get_loggerro   r4  Moduler(   ru   floatr   r   r   r   r   r   r   r   r   r  r  r$  rG  ra  r  r*  r  r  r  r  r  __all__rz  rO   rN   <module>r     s    $   A A & ' C C ) J 9	 	 	 G & 6 @ @ I 5 * 
		H	%g8RYY g8b !%II%<<% 
% <<	%
 LL4'% T\% % '(%:@)		 @)HI) I)XRYY $.BII $.Pryy ")) $, ,^H3* H3V%
")) %
R  40/ 40 40n M6# M6M6` 
i
)? i

i
X O
) O
 O
f , L
$7 L
L
^ a
/ a
 a
H >
!4 >
 >
DRYY , H
2 H
 H
V	rO   