U
    4Afr                    @   s  d Z ddlZddlm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 dd
lmZ ddlmZmZmZmZmZ ddlmZm Z m!Z! e"e#Z$eZ%dEe
j&e
j'ee( dddZ)dFe
j*e
j'e
j+e(dddZ,dGddZ-dZ.dZ/dZ0dZ1eG dd deZ2eG dd deZ3G dd dej4Z5G d d! d!ej4Z6G d"d# d#ej4Z7G d$d% d%ej4Z8G d&d' d'ej4Z9G d(d) d)ej4Z:G d*d+ d+ej4Z;G d,d- d-ej4Z<G d.d/ d/ej4Z=G d0d1 d1ej4Z>G d2d3 d3ej4Z?G d4d5 d5eZ@G d6d7 d7e@ZAG d8d9 d9e@ZBed:e.G d;d< d<e@ZCG d=d> d>ej4ZDed?e.G d@dA dAe@ZEedBe.G dCdD dDe@ZFdS )HzPyTorch KOSMOS-2 model.    N)	dataclass)AnyListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsBaseModelOutputWithPooling!CausalLMOutputWithCrossAttentions)PreTrainedModel)ModelOutputadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )Kosmos2ConfigKosmos2TextConfigKosmos2VisionConfig)maskdtypetgt_lenc                 C   sj   |   \}}|dk	r|n|}| ddddddf |d|||}d| }||tjt|jS )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr         ?)sizeexpandtoZmasked_filltorchboolfinfomin)r   r   r   bszsrc_lenZexpanded_maskZinverted_mask r'   P/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/kosmos2/modeling_kosmos2.py_expand_mask1   s
    *r)   )input_ids_shaper   devicepast_key_values_lengthc                 C   s   | \}}t j||ft |j|d}t j|d|d}|||d |ddk d ||}|dkrt j	t j
||||d|gdd}|ddddddf |d||| S )zB
    Make causal mask used for bi-directional self-attention.
    )r+   r   r   r   r+   ZdimN)r!   fullr#   r$   aranger   Zmasked_fill_viewr    catzerosr   )r*   r   r+   r,   r%   r   r   Z	mask_condr'   r'   r(   _make_causal_mask?   s    "
 r5   c                 C   s6   |  | }tj|dd|| | }| | 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!   ZcumsumZtype_aslong)	input_idspadding_idxr,   r   Zincremental_indicesr'   r'   r(   "create_position_ids_from_input_idsQ   s    r;   a@  
    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 ([`Kosmos2Config`]): 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:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`CLIPImageProcessor.__call__`] for details.
        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:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` 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)
        image_embeds: (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
        image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
            1]`:

            - 1 for places where to put the image features,
            - 0 for places that are not for image features (i.e. for text tokens).

        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

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

        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**.

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

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

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

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        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.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        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:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`CLIPImageProcessor.__call__`] for details.
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

            [What are input IDs?](../glossary#input-ids)
        image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
            1]`:

            - 1 for places where to put the image features,
            - 0 for places that are not for image features (i.e. for text tokens).

        attention_mask (`torch.Tensor` 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)
        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**.
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        image_embeds: (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
        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.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        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.
c                   @   s   e Zd ZU dZdZejed< dZe	e
e
ej   ed< dZe	e
ej  ed< dZe	e
ej  ed< dZe	ej ed< dZe	e
ej  ed< dZeed	< e
e d
ddZdS )Kosmos2ModelOutputa
  
    Base class for text model's outputs that also contains a pooling of the last hidden states.

    Args:
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
        projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
            the weighted average in the self-attention heads.
        vision_model_output(`BaseModelOutputWithPooling`, *optional*):
            The output of the [`Kosmos2VisionModel`].
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
            `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
            encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
            `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
            input) to speed up sequential decoding.
    Nlast_hidden_statepast_key_valueshidden_states
attentionsimage_embedsprojection_attentionsvision_model_outputreturnc                    s   t  fdd  D S )Nc                 3   s,   | ]$}|d kr | nt  | V  qdS )Ztext_model_outputrC   Ngetattrto_tuple.0kselfr'   r(   	<genexpr>;  s   z.Kosmos2ModelOutput.to_tuple.<locals>.<genexpr>tuplekeysrM   r'   rM   r(   rI   :  s    zKosmos2ModelOutput.to_tuple)__name__
__module____qualname____doc__r=   r!   FloatTensor__annotations__r>   r   r   r?   r@   rA   rB   rC   r   r   rI   r'   r'   r'   r(   r<   
  s   
&r<   c                   @   s   e Zd ZU dZdZeej ed< dZ	ejed< dZ
eeeej   ed< dZeeej  ed< dZeeej  ed< dZeej ed< dZeeej  ed	< dZeed
< ee dddZdS )*Kosmos2ForConditionalGenerationModelOutputaR  
    Model output class for `Kosmos2ForConditionalGeneration`.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
        projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
            the weighted average in the self-attention heads.
        vision_model_output(`BaseModelOutputWithPooling`, *optional*):
            The output of the [`Kosmos2VisionModel`].
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
            `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
            encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
            `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
            input) to speed up sequential decoding.
    Nlosslogitsr>   r?   r@   rA   rB   rC   rD   c                    s   t  fdd  D S )Nc                 3   s,   | ]$}|d kr | nt  | V  qdS rF   rG   rJ   rM   r'   r(   rO   u  s   zFKosmos2ForConditionalGenerationModelOutput.to_tuple.<locals>.<genexpr>rP   rM   r'   rM   r(   rI   t  s    z3Kosmos2ForConditionalGenerationModelOutput.to_tuple)rS   rT   rU   rV   rZ   r   r!   rW   rX   r[   r>   r   r?   r@   rA   rB   rC   r   r   rI   r'   r'   r'   r(   rY   A  s   
(rY   c                       s6   e Zd Zed fddZejejdddZ  Z	S )Kosmos2VisionEmbeddingsconfigc                    s   t    || _|j| _|j| _|j| _tt	
| j| _tj|j| j| j| jdd| _| j| j d | _| jd | _t| j| j| _| jdt	| jddd d S )NF)Zin_channelsZout_channelsZkernel_sizeZstridebias   r   position_ids)r   r-   
persistent)super__init__r^   hidden_size	embed_dimZ
image_sizeZ
patch_sizer   	Parameterr!   randnclass_embeddingZConv2dZnum_channelspatch_embeddingZnum_patchesnum_positions	Embeddingposition_embeddingregister_bufferr1   r   rN   r^   	__class__r'   r(   re   }  s"    
z Kosmos2VisionEmbeddings.__init__)pixel_valuesrE   c                 C   sn   |j d }| jjj}| |j|d}|ddd}| j|dd}t	j
||gdd}|| | j }|S )Nr   r   r`   r   r-   r/   )shaperk   weightr   r    flatten	transposerj   r   r!   r3   rn   ra   )rN   rs   
batch_sizeZtarget_dtypeZpatch_embedsZclass_embeds
embeddingsr'   r'   r(   forward  s    

zKosmos2VisionEmbeddings.forward)
rS   rT   rU   r   re   r!   rW   Tensorr{   __classcell__r'   r'   rq   r(   r\   |  s   r\   c                	       sn   e Zd ZdZ fddZejeedddZdeje	ej e	ej e	e
 eeje	ej f d	d
dZ  ZS )Kosmos2VisionAttention=Multi-headed attention from 'Attention Is All You Need' paperc                    s   t    || _|j| _|j| _| j| j | _| j| j | jkrZtd| j d| j d| jd | _	|j
| _t| j| j| _t| j| j| _t| j| j| _t| j| j| _d S )N;embed_dim must be divisible by num_heads (got `embed_dim`:  and `num_heads`: ).      )rd   re   r^   rf   rg   Znum_attention_heads	num_headshead_dim
ValueErrorscaleattention_dropoutdropoutr   Lineark_projv_projq_projout_projrp   rq   r'   r(   re     s    
zKosmos2VisionAttention.__init__)tensorseq_lenr%   c                 C   s    | ||| j| jdd S )Nr   r`   )r2   r   r   rx   
contiguous)rN   r   r   r%   r'   r'   r(   _shape  s    zKosmos2VisionAttention._shapeNFr?   attention_maskcausal_attention_maskoutput_attentionsrE   c                 C   s  |  \}}}| || j }| | |d|}	| | |d|}
|| j d| jf}| |||j| }|	j| }	|
j| }
|	 d}t	
||	dd}|  || j ||fkrtd|| j ||f d|   |dk	rD|  |d||fkrtd|d||f d|   ||| j||| }||| j ||}|dk	r|  |d||fkrtd|d||f d|   ||| j||| }||| j ||}tjj|dd}|r||| j||}||| j ||}nd}tjj|| j| jd	}t	
||
}|  || j || jfkrRtd
|| j|| jf d|   ||| j|| j}|dd}||||}| |}||fS )#Input shape: Batch x Time x Channelr-   r   r`   z$Attention weights should be of size 	, but is N!Attention mask should be of size r/   ptrainingz `attn_output` should be of size )r   r   r   r   r   r   r   r   r2   r!   Zbmmrx   r   r   
functionalsoftmaxr   r   Zreshaper   )rN   r?   r   r   r   r%   r   rg   query_states
key_statesvalue_statesZ
proj_shaper&   attn_weightsZattn_weights_reshapedZ
attn_probsattn_outputr'   r'   r(   r{     sX    	





zKosmos2VisionAttention.forward)NNF)rS   rT   rU   rV   re   r!   r|   r7   r   r   r"   r   r{   r}   r'   r'   rq   r(   r~     s      r~   c                       s0   e Zd Z fddZejejdddZ  ZS )Kosmos2VisionMLPc                    sD   t    || _t|j | _t|j|j	| _
t|j	|j| _d S N)rd   re   r^   r   Z
hidden_actactivation_fnr   r   rf   Zintermediate_sizefc1fc2rp   rq   r'   r(   re   
  s
    
zKosmos2VisionMLP.__init__)r?   rE   c                 C   s"   |  |}| |}| |}|S r   )r   r   r   rN   r?   r'   r'   r(   r{     s    


zKosmos2VisionMLP.forward)rS   rT   rU   re   r!   r|   r{   r}   r'   r'   rq   r(   r   	  s   r   c                       sJ   e Zd Zed fddZdejejejee e	ej
 dddZ  ZS )	Kosmos2VisionEncoderLayerr]   c                    sR   t    |j| _t|| _tj| j|jd| _	t
|| _tj| j|jd| _d S NZeps)rd   re   rf   rg   r~   	self_attnr   	LayerNormlayer_norm_epslayer_norm1r   mlplayer_norm2rp   rq   r'   r(   re     s    


z"Kosmos2VisionEncoderLayer.__init__Fr   c                 C   sd   |}|  |}| j||||d\}}|| }|}| |}| |}|| }|f}|r`||f7 }|S )aI  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
                `(config.encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r?   r   r   r   )r   r   r   r   )rN   r?   r   r   r   residualr   outputsr'   r'   r(   r{   "  s"    




z!Kosmos2VisionEncoderLayer.forward)F)rS   rT   rU   r   re   r!   r|   r   r"   r   rW   r{   r}   r'   r'   rq   r(   r     s    r   c                	       s`   e Zd ZdZed fddZd	eej eej ee	 ee	 ee	 e
eef dddZ  ZS )
Kosmos2VisionEncoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`Kosmos2VisionEncoderLayer`].

    Args:
        config: Kosmos2VisionConfig
    r]   c                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r'   )r   rK   _r]   r'   r(   
<listcomp>X  s     z1Kosmos2VisionEncoder.__init__.<locals>.<listcomp>F)	rd   re   r^   r   
ModuleListrangenum_hidden_layerslayersgradient_checkpointingrp   rq   r]   r(   re   U  s    
 zKosmos2VisionEncoder.__init__N)r   r   r   output_hidden_statesreturn_dictrE   c                 C   s   |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}|rDdnd}|rPdnd}|}	t| jD ]b\}
}|rx||	f }| jr| jr| |j	|	|||}n||	|||d}|d }	|rb||d f }qb|r||	f }|st
dd |	||fD S t|	||dS )	a  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                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.
            attention_mask (`torch.Tensor` 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)
            causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Causal mask for the text model. 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)
            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.
        Nr'   )r   r   r   c                 s   s   | ]}|d k	r|V  qd S r   r'   rK   vr'   r'   r(   rO     s      z/Kosmos2VisionEncoder.forward.<locals>.<genexpr>)r=   r?   r@   )r^   r   r   use_return_dict	enumerater   r   r   _gradient_checkpointing_func__call__rQ   r   )rN   inputs_embedsr   r   r   r   r   Zencoder_statesZall_attentionsr?   idxZencoder_layerlayer_outputsr'   r'   r(   r{   [  sH    &

  zKosmos2VisionEncoder.forward)NNNNN)rS   rT   rU   rV   r   re   r   r!   r|   r"   r   r   r   r{   r}   r'   r'   rq   r(   r   L  s   	     
r   c                       sT   e Zd Zed fddZdeej ee ee ee e	e
ef dddZ  ZS )	Kosmos2VisionTransformerr]   c                    sR   t    || _|j}t|| _tj||jd| _	t
|| _tj||jd| _d S r   )rd   re   r^   rf   r\   rz   r   r   r   pre_layrnormr   encoderpost_layernorm)rN   r^   rg   rq   r'   r(   re     s    


z!Kosmos2VisionTransformer.__init__Nrs   r   r   r   rE   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| |}| |}| j||||d}|d }|d d dd d f }| |}|s||f|dd   S t	|||j
|jdS )Nz You have to specify pixel_values)r   r   r   r   r   r   )r=   Zpooler_outputr?   r@   )r^   r   r   r   r   rz   r   r   r   r   r?   r@   )	rN   rs   r   r   r   r?   Zencoder_outputsr=   Zpooled_outputr'   r'   r(   r{     s2    


z Kosmos2VisionTransformer.forward)NNNN)rS   rT   rU   r   re   r   r!   rW   r"   r   r   r   r{   r}   r'   r'   rq   r(   r     s       
r   c                       s   e Zd ZdZdeeee d fddZdeeee dddZedeeee dd	d
Z	e
 de
je
jee
jdddZdd Z  ZS )(Kosmos2TextSinusoidalPositionalEmbeddingzDThis module produces sinusoidal positional embeddings of any length.Nrl   embedding_dimr:   c                    s4   t    d| _|| _|| _| || j || d S )Nr`   )rd   re   offsetr   r:   make_weights)rN   rl   r   r:   rq   r'   r(   re     s
    
z1Kosmos2TextSinusoidalPositionalEmbedding.__init__)num_embeddingsr   r:   c                 C   sB   |  |||}t| dr.|j| jj| jjd}| jd|dd d S )Nweightsr.   Frb   )get_embeddinghasattrr    r   r   r+   ro   )rN   r   r   r:   Zemb_weightsr'   r'   r(   r     s    
z5Kosmos2TextSinusoidalPositionalEmbedding.make_weightsc                 C   s   |d }t d|d  }ttj|tjd |  }tj| tjd d|d }tjt	|t
|gdd| d}|d dkrtj|t| dgdd}|dk	rd||ddf< |t S )	z
        Build sinusoidal embeddings.

        This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
        "Attention Is All You Need".
        r`   i'  r   rt   r   r/   r-   N)mathlogr!   expr1   Zint64float	unsqueezer3   sincosr2   r4   r    Zget_default_dtype)r   r   r:   Zhalf_dimZembr'   r'   r(   r     s    	 $&z6Kosmos2TextSinusoidalPositionalEmbedding.get_embeddingr   r9   r   r,   ra   c                 C   s   |d k	r4|  \}}|d kr\t|| j||j}n(|  d d \}}|d kr\| ||}| jd | | }|| j dkr| || j | j	| j | j
d|d||| jjd  S )Nr-   r   r   )r   r;   r:   r    r+   &create_position_ids_from_inputs_embedsr   r   r   r   index_selectr2   ru   detach)rN   r9   r   r,   ra   r%   r   Zmax_posr'   r'   r(   r{     s"      z0Kosmos2TextSinusoidalPositionalEmbedding.forwardc                 C   sV   |  dd }|d }tj| jd || j d tj|jd}|d| | S )z
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.

        Args:
            inputs_embeds: torch.Tensor

        Returns: torch.Tensor
        Nr-   r   r.   r   )	r   r!   r1   r:   r8   r+   r   r   r   )rN   r   r,   input_shapeZsequence_lengthra   r'   r'   r(   r   *  s    	   zOKosmos2TextSinusoidalPositionalEmbedding.create_position_ids_from_inputs_embeds)N)N)N)NNr   N)rS   rT   rU   rV   r7   r   re   r   staticmethodr   r!   Zno_gradr|   r{   r   r}   r'   r'   rq   r(   r     s"       r   c                       s   e Zd ZdZdeeeeeed fddZej	ej	dd	d
Z
dej	eej	 eeej	  eej	 eej	 eeej	eej	 eeej	  f dddZ  ZS )KosmosTextAttentionr           FT)rg   r   r   
is_decoderadd_inner_attn_layernormr_   c                    s   t    || _|| _|| _|| | _| j| | jkrNtd| j d| d| jd | _|| _t	j
|||d| _t	j
|||d| _t	j
|||d| _t	j
|||d| _d | _|rt	j||jd| _d S )Nr   r   r   r   )r_   r   )rd   re   rg   r   r   r   r   scalingr   r   r   r   r   r   r   inner_attn_lnr   r   )rN   r^   rg   r   r   r   r   r_   rq   r'   r(   re   @  s$    


zKosmosTextAttention.__init__)
projectionrE   c                 C   s6   |  d d | j| jf }||dddd}|S )Nr-   r   r`   r   r
   )r   r   r   r2   permute)rN   r   Znew_projection_shapeZnew_projectionr'   r'   r(   r   b  s    zKosmosTextAttention._shapeN)r?   encoder_hidden_statespast_key_valuer   layer_head_maskr   rE   c                 C   s  |dk	}|j dd \}}	|dk	r&|n|}
|r\|r\|d j d |
j d kr\|d }|d }nX| | |
}| | |
}|dk	r|stj|d |gdd}tj|d |gdd}| | || j }t||	dd}| j
r||f}|d}|dk	r>| |d|	|fkr6td|d|	|f d	|  || }tjj|dd}|dk	r`|| }tjj|| j| jd
}t||}|dddd ||	d}| jdk	r| |}| |}|||fS )r   Nr`   r   r   r/   r-   r   r   r   r
   )ru   r   r   r   r!   r3   r   r   matmulrx   r   r   r   r   r   r   r   r   r   r   r2   r   r   )rN   r?   r   r   r   r   r   Zis_cross_attentionry   
seq_lengthZcurrent_statesr   r   r   r   r&   Zcontext_statesr   r'   r'   r(   r{   h  s@     





zKosmosTextAttention.forward)r   FFT)NNNNF)rS   rT   rU   rV   r7   r   r"   re   r!   r|   r   r   r   r{   r}   r'   r'   rq   r(   r   <  s8       "	     r   c                       s*   e Zd Zed fddZdd Z  ZS )Kosmos2TextFFNr]   c                    sb   t    |j| _t|j | _|j| _t|j	|j
| _t|j
|j	| _tj|j
|jd| _d S r   )rd   re   r   r   Zactivation_functionr   activation_dropoutr   r   rg   Zffn_dimr   r   r   r   ffn_layernormrp   rq   r'   r(   re     s    
zKosmos2TextFFN.__init__c                 C   sT   |  | |}tjj|| j| jd}| |}| |}tjj|| j| jd}|S )Nr   )	r   r   r   r   r   r   r   r   r   r   r'   r'   r(   r{     s    

zKosmos2TextFFN.forward)rS   rT   rU   r   re   r{   r}   r'   r'   rq   r(   r     s   r   c                       s   e Zd Zed fddZd
ejeej eej eej eej eej eeej  ee	 ee	 eej
eeej
ej
f  f d
dd	Z  ZS )Kosmos2TextBlockr]   c                    s   t    |j| _t|| j|j|jddd| _|j| _tj	| j|j
d| _|jrt|| j|j|jddd| _tj	| j|j
d| _t|| _tj	| j|j
d| _d S )NT)rg   r   r   r   r   r   F)rd   re   rg   r   attention_headsr   r   r   r   r   r   self_attn_layer_normZadd_cross_attentionencoder_attnencoder_attn_layer_normr   ffnfinal_layer_normrp   rq   r'   r(   re     s0    

zKosmos2TextBlock.__init__NFT)
r?   r   r   encoder_attention_maskr   cross_attn_layer_head_maskr   r   	use_cacherE   c
                 C   s<  |}
|d k	r|d d nd }|  |}| j|||||d\}}}tjj|| j| jd}|
| }d }d }|d k	rt| dstd|  d|}
| |}|d k	r|dd  nd }| j	||||||d\}}}tjj|| j| jd}|
| }|| }|}
| 
|}| |}|
| }|f}|r(|||f7 }|	r8||f7 }|S )	Nr`   )r?   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   )r   r   r   r   r   r   r   r   r   r   r   r   )rN   r?   r   r   r   r   r   r   r   r   r   Zself_attn_past_key_valueZself_attn_weightsZpresent_key_valueZcross_attn_present_key_valueZcross_attn_weightsZcross_attn_past_key_valuer   r'   r'   r(   r{     sV    






zKosmos2TextBlock.forward)NNNNNNFT)rS   rT   rU   r   re   r!   r|   r   r   r"   rW   r{   r}   r'   r'   rq   r(   r     s*            r   c                       s   e Zd ZdZed fddZdd Zdejejeje	ejd	d
dZ
deej eej eej eej eej eej eej eej eeej  eej eej ee ee ee ee eeef dddZ  ZS )Kosmos2TextTransformerz
    Transformer decoder consisting of `config.layers` layers. Each layer is a [`Kosmos2TextBlock`].

    Args:
        config: Kosmos2TextConfig
    r]   c                    s   t     | _ j| _ j| _ jr2t jnd| _	t
j j j jd| _t j j jd| _t
 fddt jD | _t
 j j| _d| _d S )Nr   )r:   r   c                    s   g | ]}t  qS r'   )r   r   r]   r'   r(   r   P  s     z3Kosmos2TextTransformer.__init__.<locals>.<listcomp>F)rd   re   r^   r   	layerdropZscale_embeddingr   sqrtrg   embed_scaler   rm   
vocab_sizepad_token_idembed_tokensr   Zmax_position_embeddingsembed_positionsr   r   r   r   r   
layer_normr   rp   rq   r]   r(   re   A  s    
 zKosmos2TextTransformer.__init__c                 C   s`   d }|d dkr$t ||j|j|d}|d k	r\t||j|d d|j}|d krT|n|| }|S )Nr-   r   )r+   r,   r   )r5   r   r+   r)   r    )rN   r   r   r   r,   Zcombined_attention_maskZexpanded_attn_maskr'   r'   r(   _prepare_decoder_attention_maskU  s    z6Kosmos2TextTransformer._prepare_decoder_attention_maskNr   )r   rA   img_input_maskr,   ra   c           	      C   s   |d kr|  |}|d k	rB||jd|d||jtjd< || j }| j||||d}||j}|| }t	j
j|| j| jd}|S )Nr-   rt   r   r   )r  r    r+   r2   r   r!   r"   r  r  r   r   r   r   )	rN   r9   r   rA   r
  r,   ra   Z	positionsr?   r'   r'   r(   forward_embeddingl  s$    

 
z(Kosmos2TextTransformer.forward_embeddingr9   r   rA   image_embeds_position_maskr   r   	head_maskcross_attn_head_maskr>   r   ra   r   r   r   r   rE   c                 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nB|d k	r|j}|d|d }n"|
d k	r|
 d d }ntd|	d k	r|	d d jd nd}|dkrd }d }| j	||
||||d}| 
||||}|d k	r(|d k	r(t||
j|d d}tjj|| j| jd}| jrb| jrb|rbtd	 d
}|rldnd }|rzdnd }|r|d k	rdnd }|rdnd }t||gddgD ]V\}}|d k	r| d t| jkrtd| dt| j d| d  dqt| jD ]6\}}|r2||f7 }| jrTtg }|| jk rTq|	d k	rf|	| nd }| jr| jr| |j|||||d k	r|| nd |d k	r|| nd d ||
}n>||||||d k	r|| nd |d k	r|| nd |||d	}|d }|r"|||rdnd f7 }|r||d f7 }|d k	r||d f7 }q| |}|rl||f7 }|stdd |||||fD S t|||||dS )NzDYou cannot specify both input_ids and inputs_embeds at the same timer-   z5You have to specify either input_ids or inputs_embedsr   r`   )r9   r   rA   r
  r,   ra   r  r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr'   r  r  zThe `z` should be specified for z layers, but it is for .)r   r   r   r   r   r   r   r   r
   r   c                 s   s   | ]}|d k	r|V  qd S r   r'   r   r'   r'   r(   rO     s   z1Kosmos2TextTransformer.forward.<locals>.<genexpr>)r=   r>   r?   r@   cross_attentions) r^   r   r   r   r   r   ru   r2   r   r  r	  r)   r   r   r   r   r   r   loggerZwarning_onceziplenr   r   r!   Zrandr   r   r   r  rQ   r   )rN   r9   r   rA   r  r   r   r  r  r>   r   ra   r   r   r   r   r   r,   r?   Zall_hidden_statesZall_self_attnsZall_cross_attentionsZpresent_key_value_statesZ	attn_maskZ	mask_namer   Zdecoder_layerZdropout_probabilityr   r   r'   r'   r(   r{     s    
	   
$




zKosmos2TextTransformer.forward)NNNr   N)NNNNNNNNNNNNNNN)rS   rT   rU   rV   r   re   r	  r!   r|   r7   r  r   r   rW   r"   r   r   r   r{   r}   r'   r'   rq   r(   r   9  s`        %               
r   c                   @   s(   e Zd ZdZeZdZddgZdd ZdS )Kosmos2PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    Tr   r   c                 C   s  t | tr| jj}nt | ttfr,| jjj}t | ttfrD| jj	}nt | ttfr\| jj
j	}t |trtjj|jd|jd | d tjj|jj|jj| d tjj|jj|jj| d n6t |tr|jd d|jj d  | }|jd | }tjj|jj|d tjj|jj|d tjj|jj|d tjj|jj|d |jjdk	rd|jjj  |jjdk	r|jjj  |jjdk	r|jjj  |jjdk	r|jjj  n:t |tr`|jjd d|jj d  | }d|jj d | }tjj|j j|d tjj|j!j|d |j jdk	r@|j jj  |j!jdk	r|j!jj  nt |t"r|j#jj  |j#jj$d |j%jj  |j%jj$d nJt |t&r|j'jj  |j'jj$d |j(jj  |j(jj$d nt |t)rtjj|jj|d tjj|jj|d tjj|jj|d tjj|jj|d |jjdk	rp|jjj  |jjdk	r|jjj  |jjdk	r|jjj  |jjdk	r|jjj  n.t |t*r6tjj|j j|d tjj|j!j|d |j jdk	r|j jj  |j!jdk	r|j!jj  nt |trttjj|j+j|d |j+jdk	r|j+jj  nt |t,rtjj|j-j|d |j-jdk	r|j-jj  nDt |t.r|j/jjjd|d |j/j0dk	r|j/jj|j/j0   dS )zInitialize the weightsr   r   )Zmeanstd)r  r`   Nr   )1
isinstanceKosmos2VisionModelr^   Zinitializer_factorKosmos2ModelKosmos2ForConditionalGenerationvision_configKosmos2TextModelKosmos2TextForCausalLMZinit_stdtext_configr\   r   initZnormal_rj   rg   rk   rv   Zinitializer_rangern   r~   r   r   r   r   r   r_   dataZzero_r   rf   r   r   r   r   Zfill_r   r   r   r   r   r   lm_headKosmos2ImageToTextProjectiondenser   r  r:   )rN   moduleZfactorr  Zin_proj_stdZout_proj_stdZfc_stdr'   r'   r(   _init_weights;  s    





  z$Kosmos2PreTrainedModel._init_weightsN)	rS   rT   rU   rV   r   config_classZsupports_gradient_checkpointingZ_no_split_modulesr%  r'   r'   r'   r(   r  1  s
   r  c                
       s   e Zd ZeZdZed fddZejdddZ	e
eeeeddeej ee ee ee eeef d
ddZ  ZS )r  rs   r]   c                    s"   t  | t|| _|   d S r   )rd   re   r   model	post_initrp   rq   r'   r(   re     s    
zKosmos2VisionModel.__init__rD   c                 C   s
   | j jjS r   )r'  rz   rk   rM   r'   r'   r(   get_input_embeddings  s    z'Kosmos2VisionModel.get_input_embeddingsoutput_typer&  Nr   c                 C   s   | j ||||dS )
        Returns:

        rs   r   r   r   r'  )rN   rs   r   r   r   r'   r'   r(   r{     s    zKosmos2VisionModel.forward)NNNN)rS   rT   rU   r   r&  main_input_namere   r   Moduler)  r   KOSMOS2_VISION_INPUTS_DOCSTRINGr   r   r   r!   rW   r"   r   r   r{   r}   r'   r'   rq   r(   r    s"   
    
r  c                       s   e Zd ZeZed fddZejd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j eeej  eej eej ee ee ee ee eeef dddZ  ZS )r  r]   c                    s"   t  | t|| _|   d S r   )rd   re   r   r'  r(  rp   rq   r'   r(   re     s    
zKosmos2TextModel.__init__rD   c                 C   s   | j jS r   r'  r  rM   r'   r'   r(   r)    s    z%Kosmos2TextModel.get_input_embeddingsc                 C   s   || j _d S r   r2  rN   valuer'   r'   r(   set_input_embeddings  s    z%Kosmos2TextModel.set_input_embeddingsr*  Nr  c                 C   s(   | j |||||||||	|
|||||dS )r,  r9   r   rA   r  r   r   r  r  r>   r   ra   r   r   r   r   r.  )rN   r9   r   rA   r  r   r   r  r  r>   r   ra   r   r   r   r   r'   r'   r(   r{     s"    zKosmos2TextModel.forward)NNNNNNNNNNNNNNN)rS   rT   rU   r   r&  re   r   r0  r)  r5  r   KOSMOS2_TEXT_INPUTS_DOCSTRINGr   r   r   r!   r|   r   rW   r"   r   r   r{   r}   r'   r'   rq   r(   r    sN   
               
r  z
    The text model from KOSMOS-2 with a language modeling head on top (linear layer with weights tied to the input
    embeddings).
    c                       s  e Zd ZeZdgZed fddZejdddZ	dd	 Z
ejd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j eeej  eej eej eej ee ee ee ee eeef dddZdddZedd Z  ZS )r  zlm_head.weightr]   c                    s8   t  | t|| _tj|j|jdd| _| 	  d S )NF)Zin_featuresZout_featuresr_   )
rd   re   r   r'  r   r   rg   r  r!  r(  rp   rq   r'   r(   re     s    
zKosmos2TextForCausalLM.__init__rD   c                 C   s   | j jS r   r2  rM   r'   r'   r(   r)    s    z+Kosmos2TextForCausalLM.get_input_embeddingsc                 C   s   || j _d S r   r2  r3  r'   r'   r(   r5    s    z+Kosmos2TextForCausalLM.set_input_embeddingsc                 C   s   | j S r   r!  rM   r'   r'   r(   get_output_embeddings  s    z,Kosmos2TextForCausalLM.get_output_embeddingsc                 C   s
   || _ d S r   r8  rN   Znew_embeddingsr'   r'   r(   set_output_embeddings
  s    z,Kosmos2TextForCausalLM.set_output_embeddingsr*  N)r9   r   rA   r  r   r   r  r  r>   r   ra   labelsr   r   r   r   rE   c                 C   s(  |dk	r|n| j j}|dk	r.|r*td d}| j|||||||||	|
|||||d}| |d }d}|dk	r||j}|dddddf  }|dddf  }|j	\}}}t
 }|||| |||| }|s|f|dd  }|dk	r|f| S |S t|||j|j|j|jd	S )
a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
            `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
            ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

        Returns:

        NzJThe `use_cache` argument is changed to `False` since `labels` is provided.Fr6  r   .r-   r   )rZ   r[   r>   r?   r@   r  )r^   r   r  warningr'  r!  r    r+   r   ru   r	   r2   r   r>   r?   r@   r  )rN   r9   r   rA   r  r   r   r  r  r>   r   ra   r<  r   r   r   r   r   Z	lm_logitsrZ   Zshift_logitsZshift_labelsry   r   r  Zloss_fctoutputr'   r'   r(   r{     sZ    
 zKosmos2TextForCausalLM.forwardc                 K   s   |j }|d kr||}d }	|d k	rdt|| jjddd d dd f }	|d d dd f }d }d }nJ|d k	r| \}
}| d }tj|tj|
|| ftj	|j
dfdd}||||||	|dS )Nr   )r:   r,   r-   )r   r   r+   r   r/   )r9   rA   r  r>   r   ra   r   )ru   Znew_onesr;   r^   r  r   r!   r3   r4   r"   r+   )rN   r9   rA   r  r>   r   r   Zmodel_kwargsr   ra   ry   r   Zmask_lenr'   r'   r(   prepare_inputs_for_generation`  s@    



	z4Kosmos2TextForCausalLM.prepare_inputs_for_generationc                    s.   d}| D ] }|t  fdd|D f7 }q|S )Nr'   c                 3   s"   | ]}| d  |jV  qdS )r   N)r   r    r+   )rK   Z
past_statebeam_idxr'   r(   rO     s     z8Kosmos2TextForCausalLM._reorder_cache.<locals>.<genexpr>)rQ   )r>   rA  Zreordered_pastZ
layer_pastr'   r@  r(   _reorder_cache  s    z%Kosmos2TextForCausalLM._reorder_cache)NNNNNNNNNNNNNNNN)NNNNN)rS   rT   rU   r   r&  _tied_weights_keysre   r   r0  r)  r5  r9  r;  r   r7  r   r   r   r!   r|   r   rW   
LongTensorr"   r   r   r{   r?  r   rB  r}   r'   r'   rq   r(   r    sh   	
                
T     
3r  c                       s.   e Zd ZdZed fddZdd Z  ZS )r"  zmThe layer that transforms the image model's output to part of the text model's input (namely, image features)r]   c                    sb   t    t|jj|jj| _t	t
|j|jj| _t|j|jj|jj|jjddd| _d S )NF)r   r   r   )rd   re   r   r   r  rf   r  rg   r#  rh   r!   ri   Zlatent_query_numlatent_queryr   r   r   x_attnrp   rq   r'   r(   re     s    
z%Kosmos2ImageToTextProjection.__init__c                 C   sZ   |  |}| jd|ddd}tj||gdd}| j||d d d d\}}}||fS )Nr   r-   r   r/   )r?   r   r   r   r   )r#  rE  r   r   r   r!   r3   rF  )rN   featuresr?   rE  Zkey_value_statesr   r   r'   r'   r(   r{     s    
z$Kosmos2ImageToTextProjection.forward)rS   rT   rU   rV   r   re   r{   r}   r'   r'   rq   r(   r"    s   r"  z}
    KOSMOS-2 Model for generating text and image features. The model consists of a vision encoder and a language model.
    c                       s   e Zd ZeZdZed fddZejd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ej  eej eej eej ee ee ee ee eeef dddZ  ZS )r  rs   r]   c                    s:   t  | t|j| _t|j| _t|| _	| 
  d S r   )rd   re   r  r  
text_modelr  r  vision_modelr"  image_to_text_projectionr(  rp   rq   r'   r(   re     s
    
zKosmos2Model.__init__rD   c                 C   s
   | j jjS r   rH  r'  r  rM   r'   r'   r(   r)    s    z!Kosmos2Model.get_input_embeddingsc                 C   s   || j j_d S r   rK  r3  r'   r'   r(   r5    s    z!Kosmos2Model.set_input_embeddingsr*  N)rs   r9   r  r   r  r>   rA   r   ra   r   r   r   r   rE   c                 C   s  |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}d}d}|dkr|dkr\td| j||||d}| jj|d }tj	j
|dd}| |\}}| j||||||||	|
|||d}|s||||f }tdd	 |D S t|j|j|j|j|||d
S )a  
        Returns:

        Examples:

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

        >>> model = Kosmos2Model.from_pretrained("microsoft/kosmos-2-patch14-224")
        >>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")

        >>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> text = (
        ...     "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863>"
        ...     "</object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911>"
        ...     "</object>"
        ... )

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

        >>> last_hidden_state = model(
        ...     pixel_values=inputs["pixel_values"],
        ...     input_ids=inputs["input_ids"],
        ...     attention_mask=inputs["attention_mask"],
        ...     image_embeds_position_mask=inputs["image_embeds_position_mask"],
        ... ).last_hidden_state
        >>> list(last_hidden_state.shape)
        [1, 91, 2048]
        ```N<You have to specify either `pixel_values` or `image_embeds`.r-  r   r-   r/   )r9   r   rA   r  r  r>   r   ra   r   r   r   r   c                 s   s   | ]}|d k	r|V  qd S r   r'   rK   r>  r'   r'   r(   rO   7  s      z'Kosmos2Model.forward.<locals>.<genexpr>)r=   r>   r?   r@   rA   rB   rC   )r^   r   r   r   r   rI  r'  r   r   r   	normalizerJ  rH  rQ   r<   r=   r>   r?   r@   )rN   rs   r9   r  r   r  r>   rA   r   ra   r   r   r   r   rC   rB   r   r'   r'   r(   r{     sX    3zKosmos2Model.forward)NNNNNNNNNNNNN)rS   rT   rU   r   r&  r/  re   r   r0  r)  r5  r   KOSMOS2_INPUTS_DOCSTRINGr   r<   _CONFIG_FOR_DOCr   r!   r|   r   rW   r"   r   r   r{   r}   r'   r'   rq   r(   r    sH   

             
r  z
    KOSMOS-2 Model for generating text and bounding boxes given an image. The model consists of a vision encoder and a
    language model.
    c                       s.  e Zd ZeZdZdgZed fddZej	dddZ
d	d
 Zej	d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ej  eej eej eej eej ee ee ee ee eeef dddZdeej eej eej eej eej dddZ  ZS )r  rs   ztext_model.lm_head.weightr]   c                    s:   t  | t|j| _t|j| _t|| _	| 
  d S r   )rd   re   r  r  rH  r  r  rI  r"  rJ  r(  rp   rq   r'   r(   re   P  s
    
z(Kosmos2ForConditionalGeneration.__init__rD   c                 C   s
   | j jjS r   rK  rM   r'   r'   r(   r)  [  s    z4Kosmos2ForConditionalGeneration.get_input_embeddingsc                 C   s   || j j_d S r   rK  r3  r'   r'   r(   r5  ^  s    z4Kosmos2ForConditionalGeneration.set_input_embeddingsc                 C   s
   | j  S r   )rH  r9  rM   r'   r'   r(   r9  a  s    z5Kosmos2ForConditionalGeneration.get_output_embeddingsc                 C   s   | j | d S r   )rH  r;  r:  r'   r'   r(   r;  d  s    z5Kosmos2ForConditionalGeneration.set_output_embeddingsr*  N)rs   r9   r  r   r  r>   rA   r   ra   r<  r   r   r   r   rE   c                 C   s  |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}d}d}|dkr|dkr\td| j||||d}| jj|d }tj	j
|dd}| |\}}| j||||||||	|
||||d}|s||||f }tdd	 |D S t|j|j|j|j|j|||d
S )a	  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
            `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
            ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

        Returns:

        Examples:

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

        >>> model = Kosmos2ForConditionalGeneration.from_pretrained("microsoft/kosmos-2-patch14-224")
        >>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")

        >>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> prompt = "<grounding> An image of"

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

        >>> generated_ids = model.generate(
        ...     pixel_values=inputs["pixel_values"],
        ...     input_ids=inputs["input_ids"],
        ...     attention_mask=inputs["attention_mask"],
        ...     image_embeds=None,
        ...     image_embeds_position_mask=inputs["image_embeds_position_mask"],
        ...     use_cache=True,
        ...     max_new_tokens=64,
        ... )
        >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
        >>> processed_text = processor.post_process_generation(generated_text, cleanup_and_extract=False)
        >>> processed_text
        '<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>.'

        >>> caption, entities = processor.post_process_generation(generated_text)
        >>> caption
        'An image of a snowman warming himself by a fire.'

        >>> entities
        [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
        ```NrL  r-  r   r-   r/   )r9   r   rA   r  r  r>   r   ra   r<  r   r   r   r   c                 s   s   | ]}|d k	r|V  qd S r   r'   rM  r'   r'   r(   rO     s      z:Kosmos2ForConditionalGeneration.forward.<locals>.<genexpr>)rZ   r[   r>   r?   r@   rA   rB   rC   )r^   r   r   r   r   rI  r'  r   r   r   rN  rJ  rH  rQ   rY   rZ   r[   r>   r?   r@   )rN   rs   r9   r  r   r  r>   rA   r   ra   r<  r   r   r   r   rC   rB   Z
lm_outputsr   r'   r'   r(   r{   g  s\    Az'Kosmos2ForConditionalGeneration.forward)rs   r  r9   r   rA   c                 K   s   | dd }|d k	r,|d k	r,td| d|d kr@|d k	r@|}|d kr| |}| jj|d }tjj|dd}| |\}}	| j	j
f ||||d|}
|
S )Ninputsz
`inputs`: zp were passed alongside `pixel_values` which is not allowed.Make sure to either pass `inputs` or pixel_values=...r   r-   r/   )r9   r   rA   r  )popr   rI  r'  r   r   r   rN  rJ  rH  generate)rN   rs   r  r9   r   rA   kwargsrQ  rC   rB   r>  r'   r'   r(   rS    s*    


z(Kosmos2ForConditionalGeneration.generate)NNNNNNNNNNNNNN)NNNNN)rS   rT   rU   r   r&  r/  rC  re   r   r0  r)  r5  r9  r;  r   rO  r   rY   rP  r   r!   r|   r   rW   rD  r"   r   r   r{   rS  r}   r'   r'   rq   r(   r  D  sj   
              
x     r  )N)r   )r   )GrV   r   Zdataclassesr   typingr   r   r   r   r   r!   Ztorch.utils.checkpointr   Ztorch.nnr	   Zactivationsr   Zmodeling_outputsr   r   r   r   Zmodeling_utilsr   utilsr   r   r   r   r   Zconfiguration_kosmos2r   r   r   Z
get_loggerrS   r  rP  r|   r   r7   r)   Sizer+   r5   r;   ZKOSMOS2_START_DOCSTRINGr1  r7  rO  r<   rY   r0  r\   r~   r   r   r   r   r   r   r   r   r   r  r  r  r  r"  r  r  r'   r'   r'   r(   <module>   s~   
    
L?6:$i3b6Xwo y^$: +#}