
    Uh                        d Z ddlZddlZddlmZmZmZ ddlZddlZddlm	Z	 ddl
mZmZmZ ddlmZ ddlmZmZmZmZmZmZ dd	lmZmZmZmZ dd
lmZmZ ddlm Z   ejB                  e"      Z# G d de	jH                        Z%d7dZ& G d de	jH                        Z' G d de	jH                        Z( G d de	jH                        Z) G d de	jH                        Z* G d de	jH                        Z+ G d de	jH                        Z, G d de	jH                        Z- G d de	jH                        Z. G d  d!e	jH                        Z/d"e/iZ0 G d# d$e	jH                        Z1 G d% d&e	jH                        Z2 G d' d(e	jH                        Z3e G d) d*e             Z4e G d+ d,e4             Z5e G d- d.e4             Z6 ed/0       G d1 d2e4             Z7 ed30       G d4 d5e4             Z8g d6Z9y)8zPyTorch MarkupLM model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentionsMaskedLMOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModelapply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)auto_docstringlogging   )MarkupLMConfigc                   *     e Zd ZdZ fdZddZ xZS )XPathEmbeddingszConstruct the embeddings from xpath tags and subscripts.

    We drop tree-id in this version, as its info can be covered by xpath.
    c           	         t         t        |           |j                  | _        t	        j
                  |j                  | j                  z  |j                        | _        t	        j                  |j                        | _        t	        j                         | _        t	        j
                  |j                  | j                  z  d|j                  z        | _        t	        j
                  d|j                  z  |j                        | _        t	        j                   t#        | j                        D cg c],  }t	        j$                  |j&                  |j                        . c}      | _        t	        j                   t#        | j                        D cg c],  }t	        j$                  |j*                  |j                        . c}      | _        y c c}w c c}w )N   )superr   __init__	max_depthr   Linearxpath_unit_hidden_sizehidden_sizexpath_unitseq2_embeddingsDropouthidden_dropout_probdropoutReLU
activationxpath_unitseq2_inner	inner2emb
ModuleListrange	Embeddingmax_xpath_tag_unit_embeddingsxpath_tag_sub_embeddingsmax_xpath_subs_unit_embeddingsxpath_subs_sub_embeddingsselfconfig_	__class__s      /var/www/catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/markuplm/modeling_markuplm.pyr   zXPathEmbeddings.__init__6   s\   ot-/)))+63P3PSWSaSa3acicucu)v&zz&"<"<='')$&IIf.K.Kdnn.\^_bhbtbt^t$u!1v'9'9#96;M;MN(* t~~. VAA6C`C`a)
% *, t~~. VBBFDaDab*
&s   51G1Gc           	         g }g }t        | j                        D ]^  }|j                   | j                  |   |d d d d |f                |j                   | j                  |   |d d d d |f                ` t        j                  |d      }t        j                  |d      }||z   }| j                  | j                  | j                  | j                  |                        }|S )Ndim)r-   r    appendr0   r2   torchcatr+   r'   r)   r*   )r4   xpath_tags_seqxpath_subs_seqxpath_tags_embeddingsxpath_subs_embeddingsixpath_embeddingss          r8   forwardzXPathEmbeddings.forwardP   s     " "t~~& 	eA!(()I)F)Fq)I.YZ\]_`Y`Ja)bc!(()J)G)G)J>Z[]^`aZaKb)cd	e !&		*?R H %		*?R H03HH>>$,,ttG`G`aqGr7s*tu    )NN)__name__
__module____qualname____doc__r   rF   __classcell__r7   s   @r8   r   r   0   s    

4 rG   r   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   r;   )neintr>   cumsumtype_aslong)	input_idspadding_idxpast_key_values_lengthmaskincremental_indicess        r8   "create_position_ids_from_input_idsrY   c   sW     <<$((*D <<!4<<TBE[[_cc##%33rG   c                   >     e Zd ZdZ fdZd Z	 	 	 	 	 	 	 ddZ xZS )MarkupLMEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                 l   t         t        |           || _        t	        j
                  |j                  |j                  |j                        | _	        t	        j
                  |j                  |j                        | _        |j                  | _        t        |      | _        t	        j
                  |j                  |j                        | _        t	        j"                  |j                  |j$                        | _        t	        j&                  |j(                        | _        | j-                  dt/        j0                  |j                        j3                  d      d       |j                  | _        t	        j
                  |j                  |j                  | j4                        | _        y )N)rU   epsposition_ids)r   r:   F)
persistent)r   r[   r   r5   r   r.   
vocab_sizer#   pad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsr    r   rE   type_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsr%   r&   r'   register_bufferr>   arangeexpandrU   r4   r5   r7   s     r8   r   zMarkupLMEmbeddings.__init__v   s=    $02!||F,=,=v?Q?Q_e_r_rs#%<<0N0NPVPbPb#c )) / 7%'\\&2H2H&J\J\%]"f&8&8f>S>STzz&"<"<=ELL)G)GHOOPWXej 	 	
 "..#%<<**F,>,>DL\L\$
 rG   c                    |j                         dd }|d   }t        j                  | j                  dz   || j                  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   dtypedevicer   )sizer>   rk   rU   rS   rq   	unsqueezerl   )r4   inputs_embedsinput_shapesequence_lengthr_   s        r8   &create_position_ids_from_inputs_embedsz9MarkupLMEmbeddings.create_position_ids_from_inputs_embeds   s     $((*3B/%a.||q /D4D4D"Dq"HPUPZPZcpcwcw
 %%a(//<<rG   c                    ||j                         }n|j                         d d }||j                  n|j                  }	|+|t        || j                  |      }n| j	                  |      }|&t        j                  |t
        j                  |	      }|| j                  |      }|]| j                  j                  t        j                  t        t        |      | j                  gz         t
        j                  |	      z  }|]| j                  j                  t        j                  t        t        |      | j                  gz         t
        j                  |	      z  }|}
| j!                  |      }| j#                  |      }| j%                  ||      }|
|z   |z   |z   }| j'                  |      }| j)                  |      }|S )Nr:   ro   )rr   rq   rY   rU   rw   r>   zerosrS   rc   r5   
tag_pad_idonestuplelistr    subs_pad_idre   rg   rE   rh   r'   )r4   rT   r@   rA   token_type_idsr_   rt   rV   ru   rq   words_embeddingsre   rg   rE   
embeddingss                  r8   rF   zMarkupLMEmbeddings.forward   s     #..*K',,.s3K%.%:!!@T@T$A)TM]M]_uv#JJ=Y!"[[EJJvVN  00;M !![[33ejjd;'4>>*::;5::V\7 N !![[44uzzd;'4>>*::;5::V\8 N )"66|D $ : :> J00P%(;;>SSVff
^^J/
\\*-
rG   )NNNNNNr   )rH   rI   rJ   rK   r   rw   rF   rL   rM   s   @r8   r[   r[   s   s,    Q
2=&  2rG   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 )MarkupLMSelfOutputc                 (   t         |           t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        t        j                  |j                        | _
        y Nr]   )r   r   r   r!   r#   denserh   ri   r%   r&   r'   rm   s     r8   r   zMarkupLMSelfOutput.__init__   s`    YYv1163E3EF
f&8&8f>S>STzz&"<"<=rG   hidden_statesinput_tensorreturnc                 r    | j                  |      }| j                  |      }| j                  ||z         }|S Nr   r'   rh   r4   r   r   s      r8   rF   zMarkupLMSelfOutput.forward   7    

=1]3}|'CDrG   rH   rI   rJ   r   r>   TensorrF   rL   rM   s   @r8   r   r      1    >U\\  RWR^R^ rG   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )MarkupLMIntermediatec                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y r   )r   r   r   r!   r#   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnrm   s     r8   r   zMarkupLMIntermediate.__init__   s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$rG   r   r   c                 J    | j                  |      }| j                  |      }|S r   )r   r   r4   r   s     r8   rF   zMarkupLMIntermediate.forward   s&    

=100?rG   r   rM   s   @r8   r   r      s#    9U\\ ell rG   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 )MarkupLMOutputc                 (   t         |           t        j                  |j                  |j
                        | _        t        j                  |j
                  |j                        | _        t        j                  |j                        | _        y r   )r   r   r   r!   r   r#   r   rh   ri   r%   r&   r'   rm   s     r8   r   zMarkupLMOutput.__init__   s`    YYv779K9KL
f&8&8f>S>STzz&"<"<=rG   r   r   r   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S r   r   r   s      r8   rF   zMarkupLMOutput.forward   r   rG   r   rM   s   @r8   r   r      r   rG   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )MarkupLMPoolerc                     t         |           t        j                  |j                  |j                        | _        t        j                         | _        y r   )r   r   r   r!   r#   r   Tanhr)   rm   s     r8   r   zMarkupLMPooler.__init__  s9    YYv1163E3EF
'')rG   r   r   c                 \    |d d df   }| j                  |      }| j                  |      }|S )Nr   )r   r)   )r4   r   first_token_tensorpooled_outputs       r8   rF   zMarkupLMPooler.forward
  s6     +1a40

#566rG   r   rM   s   @r8   r   r     s#    $
U\\ ell rG   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )MarkupLMPredictionHeadTransformc                 h   t         |           t        j                  |j                  |j                        | _        t        |j                  t              rt        |j                     | _
        n|j                  | _
        t        j                  |j                  |j                        | _        y r   )r   r   r   r!   r#   r   r   r   r   r   transform_act_fnrh   ri   rm   s     r8   r   z(MarkupLMPredictionHeadTransform.__init__  s{    YYv1163E3EF
f''-$*6+<+<$=D!$*$5$5D!f&8&8f>S>STrG   r   r   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   rh   r   s     r8   rF   z'MarkupLMPredictionHeadTransform.forward  s4    

=1--m<}5rG   r   rM   s   @r8   r   r     s$    UU\\ ell rG   r   c                   *     e Zd Z fdZd Zd Z xZS )MarkupLMLMPredictionHeadc                 H   t         |           t        |      | _        t	        j
                  |j                  |j                  d      | _        t	        j                  t        j                  |j                              | _        | j                  | j                  _        y )NF)bias)r   r   r   	transformr   r!   r#   ra   decoder	Parameterr>   ry   r   rm   s     r8   r   z!MarkupLMLMPredictionHead.__init__'  sm    8@ yy!3!3V5F5FUSLLV->->!?@	 !IIrG   c                 :    | j                   | j                  _         y r   )r   r   r4   s    r8   _tie_weightsz%MarkupLMLMPredictionHead._tie_weights4  s     IIrG   c                 J    | j                  |      }| j                  |      }|S r   )r   r   r   s     r8   rF   z MarkupLMLMPredictionHead.forward7  s$    }5]3rG   )rH   rI   rJ   r   r   rF   rL   rM   s   @r8   r   r   &  s    &&rG   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )MarkupLMOnlyMLMHeadc                 B    t         |           t        |      | _        y r   )r   r   r   predictionsrm   s     r8   r   zMarkupLMOnlyMLMHead.__init__?  s    3F;rG   sequence_outputr   c                 (    | j                  |      }|S r   )r   )r4   r   prediction_scoress      r8   rF   zMarkupLMOnlyMLMHead.forwardC  s     ,,_=  rG   r   rM   s   @r8   r   r   >  s#    <!u|| ! !rG   r   c                   P    e Zd Zd fd	Zdej
                  dej
                  fdZ	 	 	 	 	 	 ddej
                  deej                     deej                     deej                     d	eej                     d
ee	e	ej                           dee
   de	ej
                     fdZ xZS )MarkupLMSelfAttentionc                    t         |           |j                  |j                  z  dk7  r2t	        |d      s&t        d|j                   d|j                   d      |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                        | _        |xs t#        |dd      | _        | j$                  dk(  s| j$                  d	k(  rF|j&                  | _        t        j(                  d
|j&                  z  dz
  | j                        | _        |j,                  | _        y )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()position_embedding_typeabsoluterelative_keyrelative_key_query   r   )r   r   r#   num_attention_headshasattr
ValueErrorrP   attention_head_sizeall_head_sizer   r!   querykeyvaluer%   attention_probs_dropout_probr'   getattrr   rd   r.   distance_embedding
is_decoderr4   r5   r   r7   s      r8   r   zMarkupLMSelfAttention.__init__J  s    : ::a?PVXhHi#F$6$6#7 8 445Q8 
 $*#=#= #&v'9'9F<V<V'V#W !558P8PPYYv1143E3EF
99V//1C1CDYYv1143E3EF
zz&"E"EF'> (
'-zC
$ ''>9T=Y=Y]q=q+1+I+ID(&(ll1v7U7U3UXY3Y[_[s[s&tD# ++rG   xr   c                     |j                         d d | j                  | j                  fz   }|j                  |      }|j	                  dddd      S )Nr:   r   r   r   r
   )rr   r   r   viewpermute)r4   r   new_x_shapes      r8   transpose_for_scoresz*MarkupLMSelfAttention.transpose_for_scoresd  sL    ffhsmt'?'?AYAY&ZZFF;yyAq!$$rG   r   attention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsc                 $   | j                  |      }|d u}	|	r||d   }
|d   }|}n |	rC| j                  | j                  |            }
| j                  | j                  |            }|}n|y| j                  | j                  |            }
| j                  | j                  |            }t	        j
                  |d   |
gd      }
t	        j
                  |d   |gd      }n@| j                  | j                  |            }
| j                  | j                  |            }| j                  |      }|d u}| j                  r|
|f}t	        j                  ||
j                  dd            }| j                  dk(  s| j                  dk(  r|j                  d   |
j                  d   }}|rDt	        j                  |dz
  t        j                  |j                  	      j                  dd      }n@t	        j                  |t        j                  |j                  	      j                  dd      }t	        j                  |t        j                  |j                  	      j                  dd      }||z
  }| j!                  || j"                  z   dz
        }|j%                  |j&                  
      }| j                  dk(  rt	        j(                  d||      }||z   }nE| j                  dk(  r6t	        j(                  d||      }t	        j(                  d|
|      }||z   |z   }|t+        j,                  | j.                        z  }|||z   }t0        j2                  j5                  |d      }| j7                  |      }|||z  }t	        j                  ||      }|j9                  dddd      j;                         }|j=                         d d | j>                  fz   }|j                  |      }|r||fn|f}| j                  r||fz   }|S )Nr   r   r   r;   r:   r   r   ro   rp   zbhld,lrd->bhlrzbhrd,lrd->bhlrr
   ) r   r   r   r   r>   r?   r   matmul	transposer   shapetensorrS   rq   r   rk   r   rd   torp   einsummathsqrtr   r   
functionalsoftmaxr'   r   
contiguousrr   r   )r4   r   r   r   r   r   r   r   mixed_query_layeris_cross_attention	key_layervalue_layerquery_layer	use_cacheattention_scoresquery_length
key_lengthposition_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probscontext_layernew_context_layer_shapeoutputss                               r8   rF   zMarkupLMSelfAttention.forwardi  s    !JJ}5
 3$>."<&q)I(+K3N11$((;P2QRI33DJJ?T4UVK3N'11$((=2IJI33DJJ}4MNK		>!#4i"@aHI))^A%6$D!LK11$((=2IJI33DJJ}4MNK//0AB"$.	?? (5N !<<Y5H5HR5PQ''>9T=Y=Y]q=q'2'8'8';Y__Q=O*L!&j1nEJJWdWkWk!l!q!q" "'l%**UbUiUi!j!o!oprtu!v"\\*EJJ}OcOcdiijkmopN%6H#'#:#:8dFbFb;bef;f#g #7#:#:ARAR#:#S ++~=+0<<8H+Wk+l(#36N#N --1EE16>NP[]q1r./4||<LiYm/n,#36T#TWs#s +dii8P8P.QQ%/.@ --//0@b/I ,,7  -	9O_kB%--aAq9DDF"/"4"4"6s";t?Q?Q>S"S%**+BC6G=/2mM]?? 11GrG   r   NNNNNF)rH   rI   rJ   r   r>   r   r   r   FloatTensorr   boolrF   rL   rM   s   @r8   r   r   I  s    ,4%ell %u|| % 7;15=A>BDH,1c||c !!2!23c E--.	c
  ((9(9:c !)):): ;c !uU->->'?!@Ac $D>c 
u||	crG   r   eagerc                       e Zd Zd fd	Zd Z	 	 	 	 	 	 ddej                  deej                     deej                     deej                     deej                     dee	e	ej                           d	ee
   d
e	ej                     fdZ xZS )MarkupLMAttentionc                     t         |           t        |j                     ||      | _        t        |      | _        t               | _        y )Nr   )	r   r   MARKUPLM_SELF_ATTENTION_CLASSES_attn_implementationr4   r   outputsetpruned_headsr   s      r8   r   zMarkupLMAttention.__init__  sC    3F4O4OP,C
	 )0ErG   c                 >   t        |      dk(  ry t        || j                  j                  | j                  j                  | j
                        \  }}t        | j                  j                  |      | j                  _        t        | j                  j                  |      | j                  _        t        | j                  j                  |      | j                  _	        t        | j                  j                  |d      | j                  _        | j                  j                  t        |      z
  | j                  _        | j                  j                  | j                  j                  z  | j                  _        | j
                  j                  |      | _        y )Nr   r   r;   )lenr   r4   r   r   r  r   r   r   r   r  r   r   union)r4   headsindexs      r8   prune_headszMarkupLMAttention.prune_heads  s   u:?749900$))2O2OQUQbQb
u
 -TYY__eD		*499==%@		,TYY__eD		.t{{/@/@%QO )-		(E(EE
(R		%"&))"?"?$))B_B_"_		 --33E:rG   r   r   r   r   r   r   r   r   c           	      p    | j                  |||||||      }| j                  |d   |      }	|	f|dd  z   }
|
S )Nr   r   )r4   r  )r4   r   r   r   r   r   r   r   self_outputsattention_outputr  s              r8   rF   zMarkupLMAttention.forward  sW     yy!"
  ;;|AF#%QR(88rG   r   r  )rH   rI   rJ   r   r  r>   r   r   r  r   r  rF   rL   rM   s   @r8   r  r    s    ";* 7;15=A>BDH,1|| !!2!23 E--.	
  ((9(9: !)):): ; !uU->->'?!@A $D> 
u||	rG   r  c                       e Zd Z fdZ	 	 	 	 	 	 ddej
                  deej                     deej                     deej                     deej                     deeeej                           dee	   d	eej
                     fd
Z
d Z xZS )MarkupLMLayerc                 f   t         |           |j                  | _        d| _        t	        |      | _        |j                  | _        |j                  | _        | j                  r,| j                  st        |  d      t	        |d      | _	        t        |      | _        t        |      | _        y )Nr   z> should be used as a decoder model if cross attention is addedr   r
  )r   r   chunk_size_feed_forwardseq_len_dimr  	attentionr   add_cross_attentionr   crossattentionr   intermediater   r  rm   s     r8   r   zMarkupLMLayer.__init__
  s    '-'E'E$*62 ++#)#=#= ##?? D6)g!hii"3FT^"_D08$V,rG   r   r   r   r   r   r   r   r   c           	         ||d d nd }| j                  |||||      }	|	d   }
| j                  r|	dd }|	d   }n|	dd  }d }| j                  rT|Rt        | d      st        d|  d      ||d	d  nd }| j	                  |
||||||      }|d   }
||dd z   }|d   }|z   }t        | j                  | j                  | j                  |
      }|f|z   }| j                  r|fz   }|S )
Nr   )r   r   r   r   r:   r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r   )	r  r   r   r   r   r   feed_forward_chunkr  r  )r4   r   r   r   r   r   r   r   self_attn_past_key_valueself_attention_outputsr  r  present_key_valuecross_attn_present_key_valuecross_attn_past_key_valuecross_attention_outputslayer_outputs                    r8   rF   zMarkupLMLayer.forward  s}    :H9S>"1#5Y] !%/3 "0 "
 2!4 ??,Qr2G 6r :,QR0G'+$??4@4!12 =dV DD D  @N?Yrs(;_c%&*&9&9 %&)!'#  7q9 7" ==G ,C2+F( 14P P0##T%A%A4CSCSUe
  /G+ ??!2 44GrG   c                 L    | j                  |      }| j                  ||      }|S r   )r!  r  )r4   r  intermediate_outputr*  s       r8   r#  z MarkupLMLayer.feed_forward_chunkY  s,    "//0@A{{#68HIrG   r  )rH   rI   rJ   r   r>   r   r   r  r   r  rF   r#  rL   rM   s   @r8   r  r  	  s    -" 7;15=A>BDH,1?||? !!2!23? E--.	?
  ((9(9:? !)):): ;? !uU->->'?!@A? $D>? 
u||	?BrG   r  c                   D    e Zd Z fdZ	 	 	 	 	 	 	 	 	 ddej
                  deej                     deej                     deej                     deej                     deeeej                           dee	   d	ee	   d
ee	   dee	   de
eej
                     ef   fdZ xZS )MarkupLMEncoderc                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w )NF)
r   r   r5   r   r,   r-   num_hidden_layersr  layergradient_checkpointingr3   s      r8   r   zMarkupLMEncoder.__init__a  sN    ]]5IaIaCb#caM&$9#cd
&+# $ds   A#r   r   r   r   r   past_key_valuesr   r   output_hidden_statesreturn_dictr   c                    |	rdnd }|rdnd }|r| j                   j                  rdnd }| j                  r%| j                  r|rt        j                  d       d}|rdnd }t        | j                        D ]  \  }}|	r||fz   }|||   nd }|||   nd }| j                  r/| j                  r#| j                  |j                  |||||||      }n ||||||||      }|d   }|r	||d   fz  }|s|||d   fz   }| j                   j                  s||d   fz   } |	r||fz   }|
st        d |||||fD              S t        |||||	      S )
N zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r:   r   r   c              3   $   K   | ]  }|| 
 y wr   r7  ).0vs     r8   	<genexpr>z*MarkupLMEncoder.forward.<locals>.<genexpr>  s      
 = 
s   )last_hidden_stater3  r   
attentionscross_attentions)r5   r  r2  trainingloggerwarning_once	enumerater1  _gradient_checkpointing_func__call__r|   r   )r4   r   r   r   r   r   r3  r   r   r4  r5  all_hidden_statesall_self_attentionsall_cross_attentionsnext_decoder_cacherD   layer_modulelayer_head_maskr   layer_outputss                       r8   rF   zMarkupLMEncoder.forwardg  s    #7BD$5b4%64;;;Z;Zr`d&&4==##p "	#,R$(4 #	VOA|#$58H$H!.7.CilO3B3N_Q/TXN**t}} $ A A ))!"#)*"%	! !-!"#)*"%! *!,M"}R'8&::" &9]1=M<O&O#;;22+?=QRCSBU+U(G#	VJ   1]4D D 
 "&%'(
 
 
 9+.+*1
 	
rG   )	NNNNNNFFT)rH   rI   rJ   r   r>   r   r   r  r   r  r   r   rF   rL   rM   s   @r8   r.  r.  `  s   , 7;15=A>BEI$(,1/4&*S
||S
 !!2!23S
 E--.	S

  ((9(9:S
 !)):): ;S
 "%e.?.?(@"ABS
 D>S
 $D>S
 'tnS
 d^S
 
uU\\"$MM	NS
rG   r.  c                   `     e Zd ZeZdZd Zedee	e
ej                  f      f fd       Z xZS )MarkupLMPreTrainedModelmarkuplmc                 l   t        |t        j                        rm|j                  j                  j                  d| j                  j                         |j                  %|j                  j                  j                          yyt        |t        j                        rz|j                  j                  j                  d| j                  j                         |j                  2|j                  j                  |j                     j                          yyt        |t        j                        rJ|j                  j                  j                          |j                  j                  j                  d       yt        |t              r%|j                  j                  j                          yy)zInitialize the weightsg        )meanstdN      ?)r   r   r!   weightdatanormal_r5   initializer_ranger   zero_r.   rU   rh   fill_r   )r4   modules     r8   _init_weightsz%MarkupLMPreTrainedModel._init_weights  s'   fbii( MM&&CT[[5R5R&S{{&  &&( '-MM&&CT[[5R5R&S!!-""6#5#56<<> .-KK""$MM$$S) 89KK""$ :rG   pretrained_model_name_or_pathc                 2    t        t        | 
  |g|i |S r   )r   rM  from_pretrained)clsr[  
model_argskwargsr7   s       r8   r]  z'MarkupLMPreTrainedModel.from_pretrained  s+    ,cB)
,6
:@
 	
rG   )rH   rI   rJ   r   config_classbase_model_prefixrZ  classmethodr   r   r   osPathLiker]  rL   rM   s   @r8   rM  rM    sD    !L"%$ 
HU3PRP[P[K[E\<] 
 
rG   rM  c                   ~    e Zd Zd fd	Zd Zd Zd Ze	 	 	 	 	 	 	 	 	 	 	 ddee	j                     dee	j                     dee	j                     dee	j                     d	ee	j                     d
ee	j                     dee	j                     dee	j                     dee   dee   dee   deeef   fd       Zd Z xZS )MarkupLMModelc                     t         |   |       || _        t        |      | _        t        |      | _        |rt        |      nd| _        | j                          y)zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        N)
r   r   r5   r[   r   r.  encoderr   pooler	post_init)r4   r5   add_pooling_layerr7   s      r8   r   zMarkupLMModel.__init__  sM    
 	 ,V4&v.0AnV,t 	rG   c                 .    | j                   j                  S r   r   rc   r   s    r8   get_input_embeddingsz"MarkupLMModel.get_input_embeddings  s    ...rG   c                 &    || j                   _        y r   rn  )r4   r   s     r8   set_input_embeddingsz"MarkupLMModel.set_input_embeddings  s    */'rG   c                     |j                         D ]7  \  }}| j                  j                  |   j                  j	                  |       9 y)z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsri  r1  r  r  )r4   heads_to_pruner1  r  s       r8   _prune_headszMarkupLMModel._prune_heads  sE    
 +002 	CLE5LLu%//;;EB	CrG   rT   r@   rA   r   r   r_   r   rt   r   r4  r5  r   c                    |	|	n| j                   j                  }	|
|
n| j                   j                  }
||n| j                   j                  }||t	        d      |#| j                  ||       |j                         }n!||j                         dd }nt	        d      ||j                  n|j                  }|t        j                  ||      }|&t        j                  |t        j                  |      }|j                  d      j                  d      }|j                  | j                  	      }d
|z
  dz  }||j                         dk(  rh|j                  d      j                  d      j                  d      j                  d      }|j!                  | j                   j"                  dddd      }nB|j                         dk(  r/|j                  d      j                  d      j                  d      }|j                  t%        | j'                               j                  	      }ndg| j                   j"                  z  }| j)                  ||||||      }| j+                  ||||	|
|      }|d   }| j,                  | j-                  |      nd}|s
||f|dd z   S t/        |||j0                  |j2                  |j4                        S )a  
        xpath_tags_seq (`torch.LongTensor` of shape `(batch_size, sequence_length, config.max_depth)`, *optional*):
            Tag IDs for each token in the input sequence, padded up to config.max_depth.
        xpath_subs_seq (`torch.LongTensor` of shape `(batch_size, sequence_length, config.max_depth)`, *optional*):
            Subscript IDs for each token in the input sequence, padded up to config.max_depth.

        Examples:

        ```python
        >>> from transformers import AutoProcessor, MarkupLMModel

        >>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base")
        >>> model = MarkupLMModel.from_pretrained("microsoft/markuplm-base")

        >>> html_string = "<html> <head> <title>Page Title</title> </head> </html>"

        >>> encoding = processor(html_string, return_tensors="pt")

        >>> outputs = model(**encoding)
        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 4, 768]
        ```NzDYou cannot specify both input_ids and inputs_embeds at the same timer:   z5You have to specify either input_ids or inputs_embeds)rq   ro   r   r   r   rR  g     r   )rT   r@   rA   r_   r   rt   )r   r   r4  r5  )r<  pooler_outputr   r=  r>  )r5   r   r4  use_return_dictr   %warn_if_padding_and_no_attention_maskrr   rq   r>   r{   ry   rS   rs   r   rp   r<   rl   r0  next
parametersr   ri  rj  r   r   r=  r>  )r4   rT   r@   rA   r   r   r_   r   rt   r   r4  r5  ru   rq   extended_attention_maskembedding_outputencoder_outputsr   r   s                      r8   rF   zMarkupLMModel.forward  s   L 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] ]%>cdd"66y.Q#..*K&',,.s3KTUU%.%:!!@T@T!"ZZFCN!"[[EJJvVN"0":":1"="G"G"J"9"<"<4::"<"N#&)@#@H"L }}!#%//2<<Q?II"MWWXZ[	%,,T[[-J-JBPRTVXZ[	A%%//2<<R@JJ2N	!40A+B+H+HII!>!>>I??))%)' + 
 ,,#/!5# ' 
 *!,8<8OO4UY#]3oab6III;-')77&11,==
 	
rG   c                 J    d}|D ]  }|t        fd|D              fz  } |S )Nr7  c              3   t   K   | ]/  }|j                  d j                  |j                               1 yw)r   N)index_selectr   rq   )r9  
past_statebeam_idxs     r8   r;  z/MarkupLMModel._reorder_cache.<locals>.<genexpr>m  s.     nU_j--aZ=N=N1OPns   58)r|   )r4   r3  r  reordered_past
layer_pasts     `  r8   _reorder_cachezMarkupLMModel._reorder_cachei  s=    ) 	Jncmnn N	 rG   )T)NNNNNNNNNNN)rH   rI   rJ   r   ro  rq  ru  r   r   r>   
LongTensorr  r  r   r   r   rF   r  rL   rM   s   @r8   rg  rg    sH    /0C  1559596:59371559,0/3&*h
E,,-h
 !!1!12h
 !!1!12	h

 !!2!23h
 !!1!12h
 u//0h
 E--.h
   1 12h
 $D>h
 'tnh
 d^h
 
uBB	Ch
 h
VrG   rg  c                        e Zd Z fdZe	 	 	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     deej                     deej                     d	eej                     d
eej                     deej                     dee   dee   dee   de	e
ej                     ef   fd       Z xZS )MarkupLMForQuestionAnsweringc                     t         |   |       |j                  | _        t        |d      | _        t        j                  |j                  |j                        | _        | j                          y NF)rl  )
r   r   
num_labelsrg  rN  r   r!   r#   
qa_outputsrk  rm   s     r8   r   z%MarkupLMForQuestionAnswering.__init__u  sU      ++%fF))F$6$68I8IJ 	rG   rT   r@   rA   r   r   r_   r   rt   start_positionsend_positionsr   r4  r5  r   c                 ,   ||n| j                   j                  }| j                  |||||||||||      }|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  }|s||f|dd z   }||f|z   S |S t        ||||j                  |j                  	      S )
ae  
        xpath_tags_seq (`torch.LongTensor` of shape `(batch_size, sequence_length, config.max_depth)`, *optional*):
            Tag IDs for each token in the input sequence, padded up to config.max_depth.
        xpath_subs_seq (`torch.LongTensor` of shape `(batch_size, sequence_length, config.max_depth)`, *optional*):
            Subscript IDs for each token in the input sequence, padded up to config.max_depth.

        Examples:

        ```python
        >>> from transformers import AutoProcessor, MarkupLMForQuestionAnswering
        >>> import torch

        >>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base-finetuned-websrc")
        >>> model = MarkupLMForQuestionAnswering.from_pretrained("microsoft/markuplm-base-finetuned-websrc")

        >>> html_string = "<html> <head> <title>My name is Niels</title> </head> </html>"
        >>> question = "What's his name?"

        >>> encoding = processor(html_string, questions=question, return_tensors="pt")

        >>> with torch.no_grad():
        ...     outputs = model(**encoding)

        >>> answer_start_index = outputs.start_logits.argmax()
        >>> answer_end_index = outputs.end_logits.argmax()

        >>> predict_answer_tokens = encoding.input_ids[0, answer_start_index : answer_end_index + 1]
        >>> processor.decode(predict_answer_tokens).strip()
        'Niels'
        ```N
r@   rA   r   r   r_   r   rt   r   r4  r5  r   r   r:   r;   )ignore_indexr   )lossstart_logits
end_logitsr   r=  )r5   rx  rN  r  splitsqueezer   r  rr   clamp_r   r   r   r=  )r4   rT   r@   rA   r   r   r_   r   rt   r  r  r   r4  r5  r  r   logitsr  r  
total_lossignored_indexloss_fct
start_lossend_lossr  s                            r8   rF   z$MarkupLMForQuestionAnswering.forward  s   ^ &1%<k$++B]B]--))))%'/!5#   
 "!*1#)<<r<#: j#++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M""1m4  M2']CH!,@J
M:H$x/14J"J/'!"+=F/9/EZMF*Q6Q+%!!//))
 	
rG   )NNNNNNNNNNNNN)rH   rI   rJ   r   r   r   r>   r   r  r   r   r   rF   rL   rM   s   @r8   r  r  r  sY     -115151515/3,0042604,0/3&*`
ELL)`
 !.`
 !.	`

 !.`
 !.`
 u||,`
 ELL)`
  -`
 "%,,/`
  -`
 $D>`
 'tn`
 d^`
 
uU\\"$@@	A`
 `
rG   r  zC
    MarkupLM Model with a `token_classification` head on top.
    )custom_introc                       e Zd Z fdZe	 	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     deej                     deej                     d	eej                     d
eej                     dee   dee   dee   de	e
ej                     ef   fd       Z xZS )MarkupLMForTokenClassificationc                 d   t         |   |       |j                  | _        t        |d      | _        |j
                  |j
                  n|j                  }t        j                  |      | _	        t        j                  |j                  |j                        | _        | j                          y r  )r   r   r  rg  rN  classifier_dropoutr&   r   r%   r'   r!   r#   
classifierrk  r4   r5   r  r7   s      r8   r   z'MarkupLMForTokenClassification.__init__  s      ++%fF)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ 	rG   rT   r@   rA   r   r   r_   r   rt   labelsr   r4  r5  r   c                    ||n| j                   j                  }| j                  |||||||||
||      }|d   }| j                  |      }d}|	Ft	               } ||j                  d| j                   j                        |	j                  d            }|s|f|dd z   }||f|z   S |S t        |||j                  |j                        S )a  
        xpath_tags_seq (`torch.LongTensor` of shape `(batch_size, sequence_length, config.max_depth)`, *optional*):
            Tag IDs for each token in the input sequence, padded up to config.max_depth.
        xpath_subs_seq (`torch.LongTensor` of shape `(batch_size, sequence_length, config.max_depth)`, *optional*):
            Subscript IDs for each token in the input sequence, padded up to config.max_depth.
        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]`.

        Examples:

        ```python
        >>> from transformers import AutoProcessor, AutoModelForTokenClassification
        >>> import torch

        >>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base")
        >>> processor.parse_html = False
        >>> model = AutoModelForTokenClassification.from_pretrained("microsoft/markuplm-base", num_labels=7)

        >>> nodes = ["hello", "world"]
        >>> xpaths = ["/html/body/div/li[1]/div/span", "/html/body/div/li[1]/div/span"]
        >>> node_labels = [1, 2]
        >>> encoding = processor(nodes=nodes, xpaths=xpaths, node_labels=node_labels, return_tensors="pt")

        >>> with torch.no_grad():
        ...     outputs = model(**encoding)

        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```Nr  r   r:   r   r  r  r   r=  )
r5   rx  rN  r  r   r   r  r   r   r=  )r4   rT   r@   rA   r   r   r_   r   rt   r  r   r4  r5  r  r   r   r  r  r  s                      r8   rF   z&MarkupLMForTokenClassification.forward  s    Z &1%<k$++B]B]--))))%'/!5#   
 "!* OOO<')H!&&r4;;+A+ABBD
 ')GABK7F)-)9TGf$EvE$$!//))	
 	
rG   NNNNNNNNNNNN)rH   rI   rJ   r   r   r   r>   r   r  r   r   r   rF   rL   rM   s   @r8   r  r    sA     -115151515/3,004)-,0/3&*P
ELL)P
 !.P
 !.	P

 !.P
 !.P
 u||,P
 ELL)P
  -P
 &P
 $D>P
 'tnP
 d^P
 
uU\\"N2	3P
 P
rG   r  z
    MarkupLM 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	 	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     deej                     deej                     d	eej                     d
eej                     dee   dee   dee   de	e
ej                     ef   fd       Z xZS )!MarkupLMForSequenceClassificationc                 n   t         |   |       |j                  | _        || _        t	        |      | _        |j                  |j                  n|j                  }t        j                  |      | _
        t        j                  |j                  |j                        | _        | j                          y r   )r   r   r  r5   rg  rN  r  r&   r   r%   r'   r!   r#   r  rk  r  s      r8   r   z*MarkupLMForSequenceClassification.__init__T  s      ++%f-)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ 	rG   rT   r@   rA   r   r   r_   r   rt   r  r   r4  r5  r   c                 D   ||n| j                   j                  }| j                  |||||||||
||      }|d   }| j                  |      }| j	                  |      }d}|	| j                   j
                  | j                  dk(  rd| j                   _        nl| j                  dkD  rL|	j                  t        j                  k(  s|	j                  t        j                  k(  rd| j                   _        nd| j                   _        | j                   j
                  dk(  rIt               }| j                  dk(  r& ||j                         |	j                               }n |||	      }n| j                   j
                  dk(  r=t               } ||j                  d| j                        |	j                  d            }n,| j                   j
                  dk(  rt               } |||	      }|s|f|dd z   }||f|z   S |S t!        |||j"                  |j$                  	      S )
a  
        xpath_tags_seq (`torch.LongTensor` of shape `(batch_size, sequence_length, config.max_depth)`, *optional*):
            Tag IDs for each token in the input sequence, padded up to config.max_depth.
        xpath_subs_seq (`torch.LongTensor` of shape `(batch_size, sequence_length, config.max_depth)`, *optional*):
            Subscript IDs for each token in the input sequence, padded up to config.max_depth.
        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).

        Examples:

        ```python
        >>> from transformers import AutoProcessor, AutoModelForSequenceClassification
        >>> import torch

        >>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base")
        >>> model = AutoModelForSequenceClassification.from_pretrained("microsoft/markuplm-base", num_labels=7)

        >>> html_string = "<html> <head> <title>Page Title</title> </head> </html>"
        >>> encoding = processor(html_string, return_tensors="pt")

        >>> with torch.no_grad():
        ...     outputs = model(**encoding)

        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```Nr  r   
regressionsingle_label_classificationmulti_label_classificationr:   r   r  )r5   rx  rN  r'   r  problem_typer  rp   r>   rS   rP   r	   r  r   r   r   r   r   r=  )r4   rT   r@   rA   r   r   r_   r   rt   r  r   r4  r5  r  r   r  r  r  r  s                      r8   rF   z)MarkupLMForSequenceClassification.forwardc  s   X &1%<k$++B]B]--))))%'/!5#   
  
]3/{{''/??a'/;DKK,__q(fllejj.HFLL\a\e\eLe/LDKK,/KDKK,{{''<7"9??a'#FNN$4fnn6FGD#FF3D))-JJ+-B @&++b/R))-II,./Y,F)-)9TGf$EvE'!//))	
 	
rG   r  )rH   rI   rJ   r   r   r   r>   r   r  r   r   r   rF   rL   rM   s   @r8   r  r  L  sB     -115151515/3,004)-,0/3&*_
ELL)_
 !._
 !.	_

 !._
 !._
 u||,_
 ELL)_
  -_
 &_
 $D>_
 'tn_
 d^_
 
uU\\"$<<	=_
 _
rG   r  )r  r  r  rg  rM  )r   ):rK   r   rd  typingr   r   r   r>   torch.utils.checkpointr   torch.nnr   r   r	   activationsr   modeling_outputsr   r   r   r   r   r   modeling_utilsr   r   r   r   utilsr   r   configuration_markuplmr   
get_loggerrH   r@  Moduler   rY   r[   r   r   r   r   r   r   r   r   r  r  r  r.  rM  rg  r  r  r  __all__r7  rG   r8   <module>r     s     	 ) )    A A !   - 2 
		H	%/ bii / f4 _ _F 299  RYY RYY  bii $ryy 0!")) !CBII CN "# 0		 0hSBII SnZ
bii Z
z 
o 
 
< R+ R Rj m
#: m
 m
` 
a
%< a

a
H q
(? q
q
hrG   