U
    ,-eG                    @   s  d Z ddlZddlmZmZmZmZmZ ddlZddl	Zddlm
Z
 ddl	mZ ddlmZ ddlmZmZmZmZmZ dd	lmZ dd
lmZ ddlmZmZmZmZmZmZmZ ddl m!Z!m"Z"m#Z# e$e%Z&dZ'dddddddddddddddddgZ(G d d! d!e
j)Z*zdd"l+m,Z, e,Z*e&-d# W n4 e.k
rB   Y n  e/k
r`   e&0d$ Y nX e1e* G d%d& d&e
j)Z2G d'd( d(e
j)Z3G d)d* d*e
j)Z4G d+d, d,e
j)Z5G d-d. d.e
j)Z6G d/d0 d0eZ7d1Z8d2Z9ed3e8G d4d5 d5e7Z:G d6d7 d7e
j)Z;G d8d9 d9e
j)Z<G d:d; d;e
j)Z=G d<d= d=e
j)Z>G d>d? d?e
j)Z?G d@dA dAe
j)Z@dBZAdCZBdDZCedEeAG dFdG dGe7ZDedHeAG dIdJ dJe7ZEdS )Kz Pix2Struct modeling file    N)DictListOptionalTupleUnion)nn)
checkpoint   )ACT2FN)BaseModelOutputBaseModelOutputWithPooling!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)PreTrainedModel)ALL_LAYERNORM_LAYERS)DUMMY_INPUTS
DUMMY_MASKadd_start_docstrings%add_start_docstrings_to_model_forwardis_torch_fx_proxyloggingreplace_return_docstrings   )Pix2StructConfigPix2StructTextConfigPix2StructVisionConfigr   zgoogle/pix2struct-textcaps-basez google/pix2struct-textcaps-largezgoogle/pix2struct-basezgoogle/pix2struct-largezgoogle/pix2struct-ai2d-basezgoogle/pix2struct-ai2d-largez(google/pix2struct-widget-captioning-basez)google/pix2struct-widget-captioning-largez#google/pix2struct-screen2words-basez$google/pix2struct-screen2words-largezgoogle/pix2struct-docvqa-basezgoogle/pix2struct-docvqa-largezgoogle/pix2struct-ocrvqa-basezgoogle/pix2struct-ocrvqa-largezgoogle/pix2struct-chartqa-basez(google/pix2struct-inforgraphics-vqa-basez)google/pix2struct-inforgraphics-vqa-largec                       s&   e Zd Zd fdd	Zdd Z  ZS )Pix2StructLayerNormư>c                    s&   t    tt|| _|| _dS )zc
        Construct a layernorm module in the T5 style. No bias and no subtraction of mean.
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__ s/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/pix2struct/modeling_pix2struct.pyr    M   s    
zPix2StructLayerNorm.__init__c                 C   s\   | tjdjddd}|t|| j  }| jjtj	tj
fkrR| | jj}| j| S )N   T)Zkeepdim)tor"   float32powmeanZrsqrtr%   r$   dtypefloat16Zbfloat16)r&   hidden_statesZvariancer+   r+   r,   forwardU   s
    zPix2StructLayerNorm.forward)r   __name__
__module____qualname__r    r6   __classcell__r+   r+   r)   r,   r   L   s   r   )FusedRMSNormzWDiscovered apex.normalization.FusedRMSNorm - will use it instead of Pix2StructLayerNormzJDiscovered apex but it failed to load, falling back to Pix2StructLayerNormc                       s<   e Zd ZdZedd fddZejejdddZ  Z	S )	Pix2StructVisionEmbeddingsa-  
    Construct the embeddings from patch. In `Pix2Struct` the input is different from classic Vision-transformer models.
    Here the input is a sequence of `seq_len` flattened patches that also combines padding patches (tokens). Each patch
    is represented by a vector of `hidden_size` values.
    Nconfigreturnc                    sR   t    t|j|j| _t|j|j| _	t|j|j| _
t|j| _d S N)r   r    r   LinearZpatch_embed_hidden_sizer'   patch_projection	EmbeddingZseq_lenrow_embeddercolumn_embedderDropoutdropout_ratedropoutr&   r?   r)   r+   r,   r    |   s
    
z#Pix2StructVisionEmbeddings.__init__)flattened_patchesr@   c                 C   s   |d d d d df   }|d d d d df   }|d d d d dd f }| |}| |}| |}|| | }| |}|S )Nr   r   r-   )longrC   rE   rF   rI   )r&   rK   Zrow_indicesZcol_indices
embeddingsZrow_embeddingsZcol_embeddingsr+   r+   r,   r6      s    



z"Pix2StructVisionEmbeddings.forward)
r8   r9   r:   __doc__r   r    r"   Tensorr6   r;   r+   r+   r)   r,   r=   u   s   	r=   c                       s&   e Zd Z fddZdddZ  ZS )Pix2StructVisionAttentionc                    s   t    |j| _|j| _|j| _|j| _| j| j | _	t
j| j| j	dd| _t
j| j| j	dd| _t
j| j| j	dd| _t
j| j	| jdd| _d| _d S NFbias)r   r    r'   d_kvkey_value_proj_dimZnum_attention_headsn_headsZattention_dropoutrI   	inner_dimr   rB   querykeyvalueoutputgradient_checkpointingrJ   r)   r+   r,   r       s    
z"Pix2StructVisionAttention.__init__NFc                    s  |j dd \ } fdd}||}||}	||}
t||	dd}|dkrtjdj||f|j	|j
d}jrjrd|_|dkrtj |f|j	|j
d}| dkr||ddddddf |j	 }n|||j	 }d| }||dkt|j
j}||7 }t|tt|j
j}tjj|d	tjd
|}tjj|jjd}|dk	r|| }t||
}|dd  d	j}|}|f|f }|r||f }|S )z&
        Self-attention block
        Nr-   c                    s    |    djjddS Z
projectionr.   r   r-   
contiguousviewrV   rU   	transposeZstates
batch_sizer&   r+   r,   to_projection_shape   s    z>Pix2StructVisionAttention.forward.<locals>.to_projection_shaper	   r   devicer3   Tr.   )dimr3   ptraining) shaperX   rY   rZ   r"   matmulra   zerosrV   rg   r3   r\   rk   requires_gradr#   rh   r/   Zmasked_fillfinfominmaxtensorr   
functionalsoftmaxr0   type_asrI   r_   r`   rW   r[   )r&   r5   attention_maskposition_biaslayer_head_maskoutput_attentions
seq_lengthre   query_states
key_statesvalue_statesscoresposition_bias_maskedattn_weightsattn_outputoutputsr+   rc   r,   r6      sD    
  &


z!Pix2StructVisionAttention.forward)NNNFr7   r+   r+   r)   r,   rP      s       rP   c                       s*   e Zd Zed fddZdd Z  ZS )Pix2StructVisionMlpr?   c                    sj   t    tj|j|jdd| _tj|j|jdd| _tj|j|jdd| _t	|j
| _t|j | _d S rQ   r   r    r   rB   r'   d_ffwi_0wi_1worG   rH   rI   r
   Zdense_act_fnactrJ   r)   r+   r,   r       s    
zPix2StructVisionMlp.__init__c                 C   sz   |  | |}| |}|| }| |}t| jjtjrl|j	| jjj	krl| jjj	tj
krl|| jjj	}| |}|S rA   r   r   r   rI   
isinstancer   r$   r"   rO   r3   Zint8r/   r&   r5   Zhidden_geluZhidden_linearr+   r+   r,   r6     s    


zPix2StructVisionMlp.forward)r8   r9   r:   r   r    r6   r;   r+   r+   r)   r,   r      s   r   c                	       sd   e Zd Zedd fddZd	ejeej eej ee	e
ejejf e
ej f dddZ  ZS )
Pix2StructVisionLayerNr>   c                    sT   t    |j| _d| _t|| _t|| _t|j	|j
d| _t|j	|j
d| _d S )Nr   r(   )r   r    Zchunk_size_feed_forwardZseq_len_dimrP   	attentionr   mlpr   r'   layer_norm_epspre_mlp_layer_normpre_attention_layer_normrJ   r)   r+   r,   r      s    


zPix2StructVisionLayer.__init__F)r5   rw   	head_maskrz   r@   c           
      C   sb   |}|  |}| j||||d}|d }|dd  }|| }| |}	| |	| }	|	f| }|S )N)rw   ry   rz   r   r   )r   r   r   r   )
r&   r5   rw   r   rz   Zresidualself_attention_outputsattention_outputr   layer_outputr+   r+   r,   r6     s    


zPix2StructVisionLayer.forward)NNF)r8   r9   r:   r   r    r"   rO   r   boolr   r   r6   r;   r+   r+   r)   r,   r     s      r   c                
       sV   e Zd Zedd fddZd
ejeej eej eeee	e
ef ddd	Z  ZS )Pix2StructVisionEncoderNr>   c                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r+   )r   ).0_r   r+   r,   
<listcomp>D  s     z4Pix2StructVisionEncoder.__init__.<locals>.<listcomp>F)	r   r    r?   r   
ModuleListrangenum_hidden_layerslayerr\   rJ   r)   r   r,   r    A  s    
 z Pix2StructVisionEncoder.__init__FT)r5   rw   r   rz   output_hidden_statesreturn_dictr@   c                    s   |rdnd } rdnd }t | jD ]\}	}
|r8||f }|d k	rH||	 nd }| jr~| jr~ fdd}tjj||
|||}n|
||| }|d } r"||d f }q"|r||f }|stdd |||fD S t|||dS )	Nr+   c                    s    fdd}|S )Nc                     s    | f S rA   r+   inputs)modulerz   r+   r,   custom_forward\  s    zVPix2StructVisionEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr+   r   r   rz   r   r,   create_custom_forward[  s    z>Pix2StructVisionEncoder.forward.<locals>.create_custom_forwardr   r   c                 s   s   | ]}|d k	r|V  qd S rA   r+   r   vr+   r+   r,   	<genexpr>s  s      z2Pix2StructVisionEncoder.forward.<locals>.<genexpr>last_hidden_stater5   
attentions)		enumerater   r\   rk   r"   utilsr   tupler   )r&   r5   rw   r   rz   r   r   all_hidden_statesZall_self_attentionsilayer_modulery   r   layer_outputsr+   r   r,   r6   G  s6    	

zPix2StructVisionEncoder.forward)NNFFT)r8   r9   r:   r   r    r"   rO   r   r   r   r   r   r6   r;   r+   r+   r)   r,   r   @  s   	     
r   c                   @   s0   e Zd ZdZeZedd Zdd Zdd Z	dS )	Pix2StructPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    c                 C   s$   t t}t t}|||d}|S )N)decoder_input_ids	input_idsdecoder_attention_mask)r"   rs   r   r   )r&   r   Z
input_maskdummy_inputsr+   r+   r,   r     s    

z&Pix2StructPreTrainedModel.dummy_inputsc                 C   s  | j j}t|tr(|jj|d  nt|tr>t| j trJ| j j	j
n| j j
}t| j trh| j j	jn| j j}|jjjjd||d  d t|jdr|jjdk	r|jjj  |jjjjd||d  d t|jdr|jjdk	r|jjj  |jjjjd||d  d t|jdr|jjdk	r|jjj  nt|trJt| j trb| j j	j
n| j j
}t| j tr| j j	jn| j j
}t| j tr| j j	jn| j j}|jjjjd||| d  d |jjjjd||d  d |jjjjd||d  d |jjjjd||| d  d |jr|jjjjd||d  d n|t|tjrt| j trp| j j	j
n| j j
}|jjjd||d  d |jdk	r|jj|j   nt|trt| j tr| j j	j
n| j j
}|j jjjd||d  d nt|tj!tj"fr\tj#j$|jj%t&j'd| j j(d%|jj)|j_|jdk	r|jj  njt|tr|jdk	r|jjd nBt|tjr|jjjd| j j(d |jdk	r|jj|j   dS )zInitialize the weightsg      ?g        g      )r2   ZstdrS   N)*r?   Zinitializer_factorr   r   r$   dataZfill_ Pix2StructTextDenseGatedActDenser   text_configr'   r   r   Znormal_hasattrrS   Zzero_r   r   Pix2StructTextAttentionrT   	num_headsrX   rY   rZ   r[   has_relative_attention_biasrelative_attention_biasr   rD   Zpadding_idxPix2StructTextModellm_headrB   ZConv2dinitZtrunc_normal_r/   r"   r0   Zinitializer_ranger3   )r&   r   factorr'   r   rU   rV   r+   r+   r,   _init_weights  s    



   

  z'Pix2StructPreTrainedModel._init_weightsc                 C   s   | j j}| j j}|d kr tdt|rbt|jd d d |}tj||dd df gdd}n4|	|j}|dd df 
 |ddd f< ||d< |d krtd||d	k| |S )
Nzself.model.config.decoder_start_token_id has to be defined. In Pix2Struct it is usually set to the pad_token_id.See Pix2Struct docs for more information.r.   )r   .rh   r   ).r   z1self.model.config.pad_token_id has to be defined.)r?   decoder_start_token_idpad_token_id
ValueErrorr   r"   fullrl   catZ	new_zeroscloneZmasked_fill_)r&   r   r   r   Zshifted_input_idsr+   r+   r,   _shift_right  s       z&Pix2StructPreTrainedModel._shift_rightN)
r8   r9   r:   rN   r   config_classpropertyr   r   r   r+   r+   r+   r,   r   {  s   

Pr   aL  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`Pix2StructConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        flattened_patches (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_channels x patch_height x patch_width)`):
            Flattened and padded pixel values. These values can be obtained using [`AutoImageProcessor`]. See
            [`Pix2StructVisionImageProcessor.__call__`] for details. Check the [original
            paper](https://arxiv.org/abs/2210.03347) (figure 5) for more details.

        attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:

        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
zjThe bare Pix2StructVision Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd ZeZdZdZdgZed fddZ	de
edd	d
dZdd Zeeee f ddddZeeeeeddeej eej eej ee ee ee eeef dddZ  ZS )Pix2StructVisionModelrK   Tr   r   c                    sD   t  | || _t|| _t|| _t|j|j	d| _
|   d S Nr   )r   r    r?   r=   rM   r   encoderr   r'   r   	layernorm	post_initrJ   r)   r+   r,   r    *  s    

zPix2StructVisionModel.__init__FN)r   rZ   r@   c                 C   s   t |tr||_d S rA   )r   r   r\   r&   r   rZ   r+   r+   r,   _set_gradient_checkpointing6  s    
z1Pix2StructVisionModel._set_gradient_checkpointingc                 C   s   | j jS rA   )rM   rC   r&   r+   r+   r,   get_input_embeddings:  s    z*Pix2StructVisionModel.get_input_embeddings)heads_to_pruner@   c                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr   r   r   Zprune_heads)r&   r   r   Zheadsr+   r+   r,   _prune_heads=  s    z"Pix2StructVisionModel._prune_headsoutput_typer   )rK   rw   r   rz   r   r   r@   c                 C   s   |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}|dkrLtd|dkrh|jdddk }| || j j}| 	|}| j
||||||d}|d }	| |	}	|s|	f}
|
|dd  S t|	|j|jdS )	a.  
        Returns:

        Example:

        ```python
        >>> import requests
        >>> from PIL import Image
        >>> from transformers import AutoProcessor, Pix2StructVisionModel

        >>> image_processor = AutoProcessor.from_pretrained("google/pix2struct-textcaps-base")
        >>> model = Pix2StructVisionModel.from_pretrained("google/pix2struct-textcaps-base")

        >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = image_processor(images=image, return_tensors="pt")
        >>> with torch.no_grad():
        ...     outputs = model(**inputs)

        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 2048, 768]
        ```
        Nz%You have to specify flattened_patchesr.   r   r   )rw   r   rz   r   r   r   r   )r?   rz   r   use_return_dictr   sumfloatget_head_maskr   rM   r   r   r   r5   r   )r&   rK   rw   r   rz   r   r   Zembedding_outputencoder_outputsZsequence_outputZhead_outputsr+   r+   r,   r6   E  s8    $

zPix2StructVisionModel.forward)F)NNNNNN)r8   r9   r:   r   r   main_input_namesupports_gradient_checkpointing_no_split_modulesr   r    r   r   r   r   r   intr   r   r   "PIX2STRUCT_VISION_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr   r"   rO   r   r   r6   r;   r+   r+   r)   r,   r      s2   
      
r   c                       s*   e Zd Zed fddZdd Z  ZS )r   r   c                    sj   t    tj|j|jdd| _tj|j|jdd| _tj|j|jdd| _t	|j
| _t|j | _d S rQ   r   rJ   r)   r+   r,   r      s    
z)Pix2StructTextDenseGatedActDense.__init__c                 C   sz   |  | |}| |}|| }| |}t| jjtjrl|j	| jjj	krl| jjj	tj
krl|| jjj	}| |}|S rA   r   r   r+   r+   r,   r6     s    


z(Pix2StructTextDenseGatedActDense.forwardr8   r9   r:   r   r    r6   r;   r+   r+   r)   r,   r     s   r   c                       s*   e Zd Zed fddZdd Z  ZS )Pix2StructTextLayerFFr   c                    s8   t    t|| _t|j|jd| _t	|j
| _d S r   )r   r    r   DenseReluDenser   r'   layer_norm_epsilon
layer_normr   rG   rH   rI   rJ   r)   r+   r,   r      s    

zPix2StructTextLayerFF.__init__c                 C   s&   |  |}| |}|| | }|S rA   )r   r   rI   )r&   r5   Zforwarded_statesr+   r+   r,   r6     s    

zPix2StructTextLayerFF.forwardr   r+   r+   r)   r,   r     s   r   c                       sF   e Zd Zded fddZeddd	ZdddZdddZ  Z	S )r   Fr   c                    s   t    || _|j| _|j| _|j| _|j| _|j| _	|j
| _| j	| j | _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _| jrt| j| j	| _t | _d| _d S rQ   )r   r    r   relative_attention_num_bucketsrelative_attention_max_distancer'   rT   rU   r   rV   rH   rI   rW   r   rB   rX   rY   rZ   r[   rD   r   setpruned_headsr\   r&   r?   r   r)   r+   r,   r      s"    
z Pix2StructTextAttention.__init__T       c                 C   s   d}|r4|d }|| dk tj| 7 }t| } nt| t|  } |d }| |k }|t|  | t||  ||   tj }t|t	||d }|t
|| |7 }|S )a  
        Adapted from Mesh Tensorflow:
        https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593

        Translate relative position to a bucket number for relative attention. The relative position is defined as
        memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
        position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
        small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
        positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
        This should allow for more graceful generalization to longer sequences than the model has been trained on

        Args:
            relative_position: an int32 Tensor
            bidirectional: a boolean - whether the attention is bidirectional
            num_buckets: an integer
            max_distance: an integer

        Returns:
            a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
        r   r-   r   )r/   r"   rL   absrq   Z
zeros_likelogr   mathZ	full_likewhere)relative_positionbidirectionalnum_bucketsmax_distanceZrelative_bucketsZ	max_exactZis_smallZrelative_position_if_larger+   r+   r,   _relative_position_bucket  s.     z1Pix2StructTextAttention._relative_position_bucketNc           	      C   s   |dkr| j jj}tj|tj|ddddf }tj|tj|ddddf }|| }| j|d| j| jd}|  |}|	dddg
d}|S )z%Compute binned relative position biasN)r3   rg   F)r  r  r  r-   r   r   )r   r$   rg   r"   ZarangerL   r  r   r   ZpermuteZ	unsqueeze)	r&   query_length
key_lengthrg   Zcontext_positionZmemory_positionr   Zrelative_position_bucketvaluesr+   r+   r,   compute_bias  s    

z$Pix2StructTextAttention.compute_biasc
                    s  |j dd \ }
|
}|dk	r\t|dkr>tdt| d||dkrV|d j d n|7 }|dkrh|n|j d } fddfd	d
}|}||j||dk	r|d nd}||j||dk	r|d nd}t||dd}|dkrj	s6tj
dj||f|j|jd}jrHjrHd|_nj|||jd}|dk	rz|dddd|d dddf }|dk	r|| }jrt|j d }d|tj< |dd| f }n|}||7 }tjj| dd|}tjj|jjd}|dk	r|| }t||}|dd  dj} |}|rV||fnd}|f|f |f }|	r|||f }|S )z
        Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
        Nr-   z?past_key_value should have 2 past states: keys and values. Got z past statesr   r   c                    s    |    djjddS r]   r^   rb   rc   r+   r,   re   <  s    z<Pix2StructTextAttention.forward.<locals>.to_projection_shapec                    sx   |dkr || } n|dkr* ||} |dk	rt|dkrNt j|| gdd} n&|jd |jd krp ||} n|} | S )z4projects hidden states correctly to key/query statesNr-   r   r   )r"   r   rl   )r5   Z
proj_layerkey_value_statespast_key_value)re   r+   r,   project@  s    z0Pix2StructTextAttention.forward.<locals>.projectr	   rf   Trg   r.   r   ri   )!rl   lenr   rX   rY   rZ   r"   rm   ra   r   rn   rV   rg   r3   r\   rk   ro   r  sizer   r#   listr   r   rt   ru   r   rv   rI   r_   r`   rW   r[   )r&   r5   maskr	  rx   r
  ry   r  	use_cacherz   r{   Zreal_seq_lengthr  r  r|   r}   r~   r   r   r   r   present_key_value_stater   r+   )rd   r&   re   r,   r6     sx           

  
(



zPix2StructTextAttention.forward)F)Tr   r   )N)NNNNNNFF)
r8   r9   r:   r   r    staticmethodr  r  r6   r;   r+   r+   r)   r,   r     s   0
        r   c                       s(   e Zd Zd fdd	ZdddZ  ZS )	 Pix2StructTextLayerSelfAttentionFc                    s<   t    t||d| _t|j|jd| _t	|j
| _d S )Nr   r   r   r    r   r   r   r'   r   r   r   rG   rH   rI   r   r)   r+   r,   r      s    
z)Pix2StructTextLayerSelfAttention.__init__Nc              	   C   sJ   |  |}| j|||||||d}	|| |	d  }|f|	dd   }
|
S )N)r  rx   ry   r
  r  rz   r   r   r   r   rI   )r&   r5   rw   rx   ry   r
  r  rz   normed_hidden_statesr   r   r+   r+   r,   r6     s    

	z(Pix2StructTextLayerSelfAttention.forward)F)NNNNFFr7   r+   r+   r)   r,   r    s   	      r  c                       s&   e Zd Z fddZdddZ  ZS )!Pix2StructTextLayerCrossAttentionc                    s<   t    t|dd| _t|j|jd| _t	|j
| _d S )NFr  r   r  rJ   r)   r+   r,   r      s    
z*Pix2StructTextLayerCrossAttention.__init__NFc
                 C   sN   |  |}
| j|
||||||||	d	}|| |d  }|f|dd   }|S )N)r  r	  rx   ry   r
  r  r  rz   r   r   r  )r&   r5   r	  rw   rx   ry   r
  r  r  rz   r  r   r   r   r+   r+   r,   r6     s    
z)Pix2StructTextLayerCrossAttention.forward)NNNNFNFr7   r+   r+   r)   r,   r    s   
       r  c                       s(   e Zd Zd fdd	Zd	ddZ  ZS )
Pix2StructTextBlockFc                    s0   t    t||d| _t|| _t|| _d S )Nr  )r   r    r  self_attentionr  encoder_decoder_attentionr   r   r   r)   r+   r,   r      s    
 
zPix2StructTextBlock.__init__NTc                 C   s  |	d k	rj|d krdnd}t |	|krPtd| d|dkr:dnd dt |	 d|	d d }|	dd  }nd	\}}| j||||||
|d
}|d d \}}|dd  }|jtjkrt| rt|jj	d }tj
|| |d}|d k	}|r|d k	r|d jd }nd }| j||||||||
|d	}|d }|jtjkrvt| rvt|jj	d }tj
|| |d}|d k	r||d  }||dd   }| |}|jtjkrt| rt|jj	d }tj
|| |d}|f}|
r||f | }n|| }|S )Nr-      zThere should be z past states. z$2 (past / key) for cross attention.  zGot z past key / value states)NN)rw   rx   ry   r
  r  rz   i  )rq   rr   r   )r	  rw   rx   ry   r
  r  r  rz   r   )r  r   r  r3   r"   r4   isinfanyrp   rr   clamprl   r  r   )r&   r5   rw   rx   encoder_hidden_statesencoder_attention_maskencoder_decoder_position_biasry   cross_attn_layer_head_maskr
  r  rz   r   Zexpected_num_past_key_valuesZself_attn_past_key_valueZcross_attn_past_key_valuer   r  Zattention_outputsZclamp_valueZdo_cross_attentionr  Zcross_attention_outputsr   r+   r+   r,   r6     sn    &	


zPix2StructTextBlock.forward)F)NNNNNNNNFFTr7   r+   r+   r)   r,   r    s              r  a  

    The Pix2Struct model was proposed in [Pix2Struct: Screenshot Parsing as Pretraining for Visual Language
    Understanding](https://arxiv.org/abs/2210.03347) by Kenton Lee, Mandar Joshi, Iulia Turc, Hexiang Hu, Fangyu Liu,
    Julian Eisenschlos, Urvashi Khandelwal, Peter Shaw, Ming-Wei Chang, Kristina Toutanova. It's an encoder decoder
    transformer pre-trained in a image-to-text setting.

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config (Union[`Pix2StructConfig`, `Pix2StructTextConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Pix2StructText is a model with relative position
            embeddings so you should be able to pad the inputs on both the right and the left.

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

            [What are input IDs?](../glossary#input-ids)

            To know more on how to prepare `input_ids` for pretraining take a look a [Pix2StructText
            Training](./t5#training).
        attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

            [What are attention masks?](../glossary#attention-mask)
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            Pix2StructText uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
            `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            To know more on how to prepare `decoder_input_ids` for pretraining take a look at [Pix2StructText
            Training](./t5#training).
        decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules in the encoder. Mask values selected in `[0,
            1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        decoder_head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
            1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        cross_attn_head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
                Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in
                `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
            Tuple consists of (`last_hidden_state`, `optional`: *hidden_states*, `optional`: *attentions*)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden states at
            the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention layers. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, 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.
        decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
            representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
            input (see `past_key_values`). This is useful if you want more control over how to convert
            `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

            If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
            of `inputs_embeds`.

        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
a  
    Args:
        flattened_patches (`torch.FloatTensor` of shape `(batch_size, seq_length, hidden_size)`):
            Flattened pixel patches. the `hidden_size` is obtained by the following formula: `hidden_size` =
            `num_channels` * `patch_size` * `patch_size`

            The process of flattening the pixel patches is done by `Pix2StructProcessor`.

        attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

            [What are attention masks?](../glossary#attention-mask)
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            Pix2StructText uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
            `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            To know more on how to prepare `decoder_input_ids` for pretraining take a look at [Pix2StructText
            Training](./t5#training).
        decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules in the encoder. Mask values selected in `[0,
            1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        decoder_head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
            1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        cross_attn_head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
                Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in
                `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
            Tuple consists of (`last_hidden_state`, `optional`: *hidden_states*, `optional`: *attentions*)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden states at
            the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention layers. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
            representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
            input (see `past_key_values`). This is useful if you want more control over how to convert
            `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

            If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
            of `inputs_embeds`.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss for the decoder.

        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
z)The standalone text decoder of Pix2Structc                       s   e Zd ZeZdgZdgZdZdddZ fddZ	d	d
 Z
dd Zdd Zdd Zdd Zeeeeeddeej eej eej eej eej eej eej eeeej   ee ee ee eej ee eeejdf ef dddZ  ZS )r   r  zlm_head.weightTFc                 C   s   t |ttfr||_d S rA   )r   r   r   r\   r   r+   r+   r,   r   +  s    z/Pix2StructTextModel._set_gradient_checkpointingc                    s   t    t j j| _t fddt j	D | _
t j jd| _t j| _tj j jdd| _|   d| _d S )Nc                    s    g | ]}t  t|d kdqS )r   r  )r  r   )r   r   r   r+   r,   r   4  s     z0Pix2StructTextModel.__init__.<locals>.<listcomp>r   FrR   )r   r    r   rD   
vocab_sizer'   embed_tokensr   r   
num_layersr   r   r   final_layer_normrG   rH   rI   rB   r   r   r\   rJ   r)   r   r,   r    /  s    zPix2StructTextModel.__init__c              	   C   s   |d krt d |S d}|D ]}d}|D ]}||d||jf }q*|d j|d jkrtd|d j d|d j dt|t|krtdt| dt| d||f }q|S )	NzHYou might want to consider setting `use_cache=True` to speed up decodingr+   r   z%reordered_layer_past_states[0] shape z  and layer_past_states[0] shape z mismatchedz&length of reordered_layer_past_states z! and length of layer_past_states )loggerwarningZindex_selectr/   rg   rl   r   r  )r&   past_key_valuesZbeam_idxZreordered_decoder_pastZlayer_past_statesZreordered_layer_past_statesZlayer_past_stater+   r+   r,   _reorder_cache@  s(    
z"Pix2StructTextModel._reorder_cachec                 C   s   | j S rA   r'  r   r+   r+   r,   r   ^  s    z(Pix2StructTextModel.get_input_embeddingsc                 C   s
   || _ d S rA   r.  r&   Znew_embeddingsr+   r+   r,   set_input_embeddingsa  s    z(Pix2StructTextModel.set_input_embeddingsc                 C   s   | j S rA   r   r   r+   r+   r,   get_output_embeddingsd  s    z)Pix2StructTextModel.get_output_embeddingsc                 C   s
   || _ d S rA   r1  r/  r+   r+   r,   set_output_embeddingsg  s    z)Pix2StructTextModel.set_output_embeddingsr   N.)r   rw   r"  r#  inputs_embedsr   cross_attn_head_maskr,  r  rz   r   labelsr   r@   c           ,         s"  dk	rn| j j dk	r  n| j j |dk	r4|n| j j}|dk	rH|n| j j}|dk	rj|dk	rjtdnD|dk	r| }|d|d }n"|dk	r| dd }ntd|dkr| jdk	st	d| |}|\}}|dk	r|d d j
d | n|}|dkrtj|||jd}|dkrL|dk	rL|j
d	 }tj|||jtjd
}|dkrfdgt| j }| ||}|dk	r| \}}}||f}|dkrtj||jd}| |}nd}| || j j}| || j j}rdnd}|rdnd} rdnd} rdnd}d}d}| |} tt| j|D ]4\}!\}"}#||! }$||! }%|rd|| f }| jr| jrrtd d fdd}&t|&|"| ||||||$|%d
}'n|"| ||||||$|%|# d}'dkr|'dd	 d |'d	d  }'|'dd \} }(|'d }|dk	r.|' r(dnd }r>||(f } r6||'d f }|dk	r6||'d f }q6| | } | | } | | })|r|| f }d}*|dk	r||)j}t j!ddd}+|+|)" d|)d|" d}*|st#dd |*|)||||fD S t$|*|)||||dS )a  
        Returns:

        Example:

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

        >>> processor = AutoProcessor.from_pretrained("google/pix2struct-textcaps-base")
        >>> model = Pix2StructTextModel.from_pretrained("google/pix2struct-textcaps-base")

        >>> inputs = processor(text="Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)
        >>> loss = outputs.loss
        ```
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer.   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsz<You have to initialize the model with valid token embeddingsr   r-   r  r   rf   r+   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fc                    s    fdd}|S )Nc                     s   t  | f S rA   )r   r   )r   rz   r  r+   r,   r     s    zRPix2StructTextModel.forward.<locals>.create_custom_forward.<locals>.custom_forwardr+   r   rz   r  r   r,   r     s    z:Pix2StructTextModel.forward.<locals>.create_custom_forward)
rw   rx   r"  r#  r$  ry   r%  r
  r  rz   rA   r  r	      r   r2   )Zignore_indexZ	reductionc                 s   s   | ]}|d k	r|V  qd S rA   r+   r   r+   r+   r,   r   $  s   z.Pix2StructTextModel.forward.<locals>.<genexpr>)losslogitsr,  r5   r   cross_attentions)%r?   r  rz   r   r   r   r  r`   r'  AssertionErrorrl   r"   r#   rg   rL   r  r   Zget_extended_attention_maskZinvert_attention_maskr   r(  rI   r   zipr\   rk   r*  r+  r   r)  r   r/   r   ZCrossEntropyLossr_   r   r   ),r&   r   rw   r"  r#  r4  r   r5  r,  r  rz   r   r6  r   kwargsZinput_shaperd   r{   Zmask_seq_lengthZencoder_seq_lengthZextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZencoder_extended_attention_maskZpresent_key_value_statesr   Zall_attentionsZall_cross_attentionsrx   r$  r5   r   r   r
  ry   r%  r   r   r  r:  r9  Zloss_fctr+   r7  r,   r6   j  s    #

"

   













&zPix2StructTextModel.forward)F)NNNNNNNNNNNNN)r8   r9   r:   r   r   r   _tied_weights_keysr   r   r    r-  r   r0  r2  r3  r    PIX2STRUCT_TEXT_INPUTS_DOCSTRINGr   r   r   r   r"   
LongTensorFloatTensorrO   r   r   r   r6   r;   r+   r+   r)   r,   r   !  sT   

             r   zhA conditional generation model with a language modeling head. Can be used for sequence generation tasks.c                       sX  e Zd ZeZdZdgZed fddZdd Zdd	 Z	e
jd
ddZdd Zdee e
jdddZdd Zdd Zeeeeeddeej eej eej eej eej eej eej eeeej   eeeej   eej eej ee ee ee ee e eej ef dddZ!d eej eej eej dddZ"  Z#S )!"Pix2StructForConditionalGenerationrK   zdecoder.lm_head.weightr   c                    s8   t  | t|j| _t|j| _|j| _| 	  d S rA   )
r   r    r   Zvision_configr   r   r   decoderZis_vqar   rJ   r)   r+   r,   r    C  s
    z+Pix2StructForConditionalGeneration.__init__c                 C   s
   | j  S rA   )rD  r   r   r+   r+   r,   r   N  s    z7Pix2StructForConditionalGeneration.get_input_embeddingsc                 C   s   | j | d S rA   )rD  r0  r/  r+   r+   r,   r0  Q  s    z7Pix2StructForConditionalGeneration.set_input_embeddings)r@   c                 C   s
   | j  S rA   )rD  r2  r   r+   r+   r,   r2  T  s    z8Pix2StructForConditionalGeneration.get_output_embeddingsc                 C   s   | j | d S rA   )rD  r3  r/  r+   r+   r,   r3  W  s    z8Pix2StructForConditionalGeneration.set_output_embeddingsN)new_num_tokensr@   c                 C   s   | j |}|| jj_|S rA   )rD  resize_token_embeddingsr?   r   r&  )r&   rE  Zmodel_embedsr+   r+   r,   rF  Z  s    
z:Pix2StructForConditionalGeneration.resize_token_embeddingsc                 C   s   | j S rA   )rD  r   r+   r+   r,   get_decoderb  s    z.Pix2StructForConditionalGeneration.get_decoderc                 C   s   | j S rA   )r   r   r+   r+   r,   get_encodere  s    z.Pix2StructForConditionalGeneration.get_encoderr   )rK   rw   r   r   r   decoder_head_maskr5  r   r,  r6  decoder_inputs_embedsr  rz   r   r   r@   c                 C   sH  |dk	r|n| j jj}|dk	r"|n| j j}|dkrJ| j||||||d}nH|rt|tst|d t|dkrt|d ndt|dkr|d ndd}|d }|
dk	r|dkr|dkr| |
}|dk	r|n|	| j j
 }d|dddf< | j||||	||||||||
|d}|s|| S t|j|j|j|j|j|j|j|j|jd	S )	a  
        Returns:

        Example:

        Inference:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, Pix2StructForConditionalGeneration

        >>> processor = AutoProcessor.from_pretrained("google/pix2struct-textcaps-base")
        >>> model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-base")

        >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(images=image, return_tensors="pt")

        >>> # autoregressive generation
        >>> generated_ids = model.generate(**inputs, max_new_tokens=50)
        >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
        >>> print(generated_text)
        A stop sign is on a street corner.

        >>> # conditional generation
        >>> text = "A picture of"
        >>> inputs = processor(text=text, images=image, return_tensors="pt", add_special_tokens=False)

        >>> generated_ids = model.generate(**inputs, max_new_tokens=50)
        >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
        >>> print(generated_text)
        A picture of a stop sign with a red stop sign
        ```

        Training:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, Pix2StructForConditionalGeneration

        >>> processor = AutoProcessor.from_pretrained("google/pix2struct-base")
        >>> model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-base")

        >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> text = "A stop sign is on the street corner."

        >>> inputs = processor(images=image, return_tensors="pt")
        >>> labels = processor(text=text, return_tensors="pt").input_ids

        >>> # forward pass
        >>> outputs = model(**inputs, labels=labels)
        >>> loss = outputs.loss
        >>> print(f"{loss.item():.5f}")
        5.94282
        ```N)rK   rw   r   rz   r   r   r   r   r-   r   )r   rw   r4  r,  r"  r#  r   r5  r  rz   r   r6  r   )	r9  r:  r,  Zdecoder_hidden_statesZdecoder_attentionsr;  Zencoder_last_hidden_stater"  Zencoder_attentions)r?   r   r  r   r   r   r   r  r   ner   r   rD  r   r9  r:  r,  r5   r   r;  r   )r&   rK   rw   r   r   r   rI  r5  r   r,  r6  rJ  r  rz   r   r   r5   Zdecoder_outputsr+   r+   r,   r6   h  sj    O
z*Pix2StructForConditionalGeneration.forward)rK   rw   r   c                 K   sP   |d krt ||j}|d k	r6|d d dd f }||||
||||||	d
S )Nr.   )
rK   r   r,  r   rw   r   r   rI  r5  r  )r"   Z	ones_liker/   rg   )r&   r   rK   rw   r   r,  r   rI  r5  r  r   r>  r+   r+   r,   prepare_inputs_for_generation  s    z@Pix2StructForConditionalGeneration.prepare_inputs_for_generation)N)NNNNNNNNNNNNNNN)	NNNNNNNNN)$r8   r9   r:   r   r   r   r?  r    r   r0  r   Moduler2  r3  r   r   rD   rF  rG  rH  r   PIX2STRUCT_INPUTS_DOCSTRINGr   r   r   r"   rB  rA  Z
BoolTensorrO   r   r   r   r6   rL  r;   r+   r+   r)   r,   rC  :  sz   
                         rC  )FrN   r   typingr   r   r   r   r   r"   Ztorch.utils.checkpointr   r   Zactivationsr
   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   r   r   r   r   r   r   Zconfiguration_pix2structr   r   r   Z
get_loggerr8   r*  r   Z(PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LISTrM  r   Zapex.normalizationr<   infoImportError	Exceptionr+  appendr=   rP   r   r   r   r   Z!PIX2STRUCT_VISION_START_DOCSTRINGr   r   r   r   r   r  r  r  ZPIX2STRUCT_START_DOCSTRINGr@  rN  r   rC  r+   r+   r+   r,   <module>   s   $	


$_+;r ]!$o_Y  