
    rhC5                       d dl Z d dlmZ d dlmZmZmZm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 dd	lmZ dd
lmZmZmZmZ ddlmZmZ ddlmZ ddlmZmZmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z.  e%j^                  e0      Z1 G d de	jd                        Z3	 dFde	jd                  dejh                  dejh                  dejh                  deejh                     de5de5fdZ6 G d de	jd                        Z7 G d d e	jd                        Z8 G d! d"e      Z9 G d# d$e	jd                        Z: G d% d&e	jd                        Z; G d' d(e	jd                        Z< G d) d*e	jd                        Z= G d+ d,e	jd                        Z> G d- d.e	jd                        Z? G d/ d0e      Z@ G d1 d2e	jd                        ZA G d3 d4e	jd                        ZBe# G d5 d6e             ZC G d7 d8eC      ZD G d9 d:eC      ZEe e#d;<       G d= d>e!                    ZF e#d?<       G d@ dAeC             ZG e#dB<       G dC dDeCe             ZHg dEZIy)G    N)	dataclass)AnyCallableOptionalUnion)nn   )ACT2FN)GenerationMixin)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsBaseModelOutputWithPooling,BaseModelOutputWithPoolingAndCrossAttentions)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)ModelOutputTransformersKwargsauto_docstringcan_return_tuplelogging	torch_int   )	AutoModelAutoModelForCausalLMAutoModelForSeq2SeqLM   )InstructBlipVideoConfigInstructBlipVideoQFormerConfigInstructBlipVideoVisionConfigc                        e Zd Zdef fdZdej                  dededej                  fdZddej                  d	e
dej                  fd
Z xZS )!InstructBlipVideoVisionEmbeddingsconfigc                 p   t         |           || _        |j                  | _        |j
                  | _        |j                  | _        t        j                  t        j                  dd| j                              | _        t        j                  d| j                  | j                  | j                        | _        | j
                  | j                  z  dz  | _        | j                  dz   | _        t        j                  t        j                  d| j                  | j                              | _        y )Nr"   r	   )in_channelsout_channelskernel_sizestrider   )super__init__r(   hidden_size	embed_dim
image_size
patch_sizer   	Parametertorchrandnclass_embeddingConv2dpatch_embeddingnum_patchesnum_positionsposition_embeddingselfr(   	__class__s     /var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/instructblipvideo/modeling_instructblipvideo.pyr/   z*InstructBlipVideoVisionEmbeddings.__init__7   s    ++ ++ ++!||EKK1dnn,MN!yyDOO\`\k\k 
 !OOt>1D!--1"$,,u{{1d>P>PRVR`R`/a"b    
embeddingsheightwidthreturnc                    |j                   d   dz
  }| j                  j                   d   dz
  }t        j                  j	                         s||k(  r||k(  r| j                  S | j                  ddddf   }| j                  ddddf   }|j                   d   }|| j
                  z  }	|| j
                  z  }
t        |dz        }|j                  d|||      }|j                  dddd      }t        j                  j                  ||	|
fdd	
      }|j                  dddd      j                  dd|      }t        j                  ||fd      S )a   
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
        r"   Ng      ?r   r	   r   bicubicF)sizemodealign_cornersdim)shaper<   r5   jit
is_tracingr3   r   reshapepermuter   
functionalinterpolateviewcat)r>   rB   rC   rD   r:   r;   class_pos_embedpatch_pos_embedrM   
new_height	new_widthsqrt_num_positionss               r@   interpolate_pos_encodingz:InstructBlipVideoVisionEmbeddings.interpolate_pos_encodingI   s`    !&&q)A-//55a81< yy##%+*F6UZ?***11!RaR%811!QR%8r"t.
T__,	&}c'9:)11!5GI[]`a)11!Q1=--33i(	 4 
 *11!Q1=BB1b#Nyy/?;CCrA   pixel_valuesr\   c                    |j                   \  }}}}| j                  j                  j                  }| j                  |j	                  |            }|j                  d      j                  dd      }| j                  j                  |dd      j	                  |      }	t        j                  |	|gd      }
|r| j                  |
||      }n| j                  }|
|d d d |
j                  d      d d f   j	                  |      z   }
|
S )Ndtyper   r"   rG   rL   )rN   r9   weightr`   toflatten	transposer7   expandr5   rV   r\   r<   rI   )r>   r]   r\   
batch_size_rC   rD   target_dtypepatch_embedsclass_embedsrB   r<   s               r@   forwardz)InstructBlipVideoVisionEmbeddings.forwardq   s    '3'9'9$
Avu++2288++LOO,O,OP#++A.88A>++22:q"EHHVYYl;C
#!%!>!>z6SX!Y!%!8!8"4Q8L*//!:L8La5O"P"S"ST`"aa
rA   F)__name__
__module____qualname__r%   r/   r5   Tensorintr\   FloatTensorboolrk   __classcell__r?   s   @r@   r'   r'   6   sm    c< c$&D5<< &D &DUX &D]b]i]i &DPE$5$5 QU bgbnbn rA   r'   modulequerykeyvalueattention_maskscalingdropoutc                 p   t        j                  ||j                  dd            |z  }|||z   }t        j                  j                  |d      }t        j                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )NrG   rL   )ptrainingr"   r   )	r5   matmulrd   r   rS   softmaxr|   r   
contiguous)
rv   rw   rx   ry   rz   r{   r|   kwargsattn_weightsattn_outputs
             r@   eager_attention_forwardr      s     <<s}}R'<=GL!#n4==((2(>L==((6??([L,,|U3K''1-88:K$$rA   c                        e Zd ZdZ fdZdej                  dedefdZ	 	 ddej                  de	ej                     d	e	e
   d
eej                  e	ej                     e	eej                        f   fdZ xZS )InstructBlipVideoAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                    t         |           || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        | j                  | j                  z  | j                  k7  r&t        d| j                   d| j                   d      | j                  dz  | _	        d| _
        |j                  | _        t        j                  | j                  d| j                  z  d      | _        |j                  ret        j                   t#        j$                  | j                              }t        j                   t#        j$                  | j                              }nd }d }|Qt#        j&                  |t#        j(                  |d      |f      }t        j                   |      | j                  _        t        j                  | j                  | j                        | _        y )	Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      Fr	   )bias)requires_grad)r.   r/   r(   r0   r1   num_attention_heads	num_headshead_dim
ValueErrorscale	is_causalattention_dropoutr   Linearqkvqkv_biasr4   r5   zerosrV   
zeros_liker   
projection)r>   r(   q_biasv_biasr   r?   s        r@   r/   z#InstructBlipVideoAttention.__init__   su   ++33$..8==4>>)T^^;MdnnM] ^NN#2'  ]]D(
!'!9!9 99T^^Q-?eL??\\%++dnn"=>F\\%++dnn"=>FFFyy&%*:*:6QV*WY_!`aHLL2DHHM))DNNDNNCrA   tensorseq_lenbszc                     |j                  ||| j                  | j                        j                  dd      j	                         S )Nr"   r   )rU   r   r   rd   r   )r>   r   r   r   s       r@   _shapez!InstructBlipVideoAttention._shape   s7    {{3GQQRSUVWbbddrA   hidden_states	head_maskoutput_attentionsrE   c                    |j                         \  }}}| j                  |      }|j                  ||d| j                  || j                  z        j	                  ddddd      }|d   |d   |d   }}
}	t
        }| j                  j                  dk7  rN| j                  j                  dk(  r|rt        j                  d       nt        | j                  j                     } || |	|
|fd	| j                  sd
n| j                  | j                  d|\  }}|j                  ||d      j                         }| j                  |      }|r||f}|S |d	f}|S )z#Input shape: Batch x Time x Channelr	   r   r   r"      eagersdpaz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.N        )rz   r|   r{   rG   )rI   r   rQ   r   rR   r   r(   _attn_implementationloggerwarning_oncer   r   r   r   r   r   )r>   r   r   r   r   r   tgt_lenr1   	mixed_qkvquery_states
key_statesvalue_statesattention_interfacer   r   outputss                   r@   rk   z"InstructBlipVideoAttention.forward   sr    #0"4"4"6WiHH]+	%%c7At~~yTXTbTbGbckkq!Q
	 2;1y|YWX\,j(?;;++w6{{//69>O##L
 '>dkk>^>^&_#$7		%

  #}}C$2H2HJJ	%
 	%
!\ "))#w;FFHook21B;- JUVZH[rA   NF)rm   rn   ro   __doc__r/   r5   rp   rq   r   r   rs   tuplerk   rt   ru   s   @r@   r   r      s    GD>eU\\ eC ec e -1,1	,||, ELL), $D>	, 
u||Xell3XeELL>Q5RR	S,rA   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )InstructBlipVideoMLPc                    t         |           || _        t        |j                     | _        t        j                  |j                  |j                        | _
        t        j                  |j                  |j                        | _        y N)r.   r/   r(   r
   
hidden_actactivation_fnr   r   r0   intermediate_sizefc1fc2r=   s     r@   r/   zInstructBlipVideoMLP.__init__   sd    #F$5$5699V//1I1IJ99V55v7I7IJrA   r   rE   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r   r>   r   s     r@   rk   zInstructBlipVideoMLP.forward   s4    /**=9/rA   rm   rn   ro   r/   r5   rp   rk   rt   ru   s   @r@   r   r      s$    KU\\ ell rA   r   c            
            e Zd Zdef fdZ	 ddej                  dej                  dee   de	ej                     fdZ xZS )	InstructBlipVideoEncoderLayerr(   c                 D   t         |           |j                  | _        t	        |      | _        t        j                  | j                  |j                        | _	        t        |      | _        t        j                  | j                  |j                        | _        y Neps)r.   r/   r0   r1   r   	self_attnr   	LayerNormlayer_norm_epslayer_norm1r   mlplayer_norm2r=   s     r@   r/   z&InstructBlipVideoEncoderLayer.__init__   sm    ++3F;<<F<Q<QR'/<<F<Q<QRrA   r   rz   r   rE   c                     |}| j                  |      }| j                  |||      \  }}||z   }|}| j                  |      }| j                  |      }||z   }|f}|r||fz  }|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>   r   rz   r   residualr   r   s          r@   rk   z%InstructBlipVideoEncoderLayer.forward  s      !((7&*nn'$/ '5 '
#|
 &0 ((7/%0 "&GrA   rl   )rm   rn   ro   r#   r/   r5   rp   r   rs   r   rr   rk   rt   ru   s   @r@   r   r      sY    S6 S -2	$||$ $ $D>	$
 
u  	!$rA   r   c                        e Zd ZdZdef fdZ	 	 	 	 d
deej                     dee	   dee	   dee	   de
eef   f
d	Z xZS )InstructBlipVideoEncodera"  
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`InstructBlipVideoEncoderLayer`].

    Args:
        config (`InstructBlipVideoConfig`):
            The corresponding vision configuration for the `InstructBlipVideoEncoder`.
    r(   c                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w r   )
r.   r/   r(   r   
ModuleListrangenum_hidden_layersr   layersgradient_checkpointing)r>   r(   rg   r?   s      r@   r/   z!InstructBlipVideoEncoder.__init__5  sQ    mmTYZ`ZrZrTs$tq%B6%J$tu&+# %us   A#rz   r   output_hidden_statesreturn_dictrE   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|rdnd}|rdnd}|}t	        | j
                        D ])  \  }	}
|r||fz   } |
|||      }|d   }|s!||d   fz   }+ |r||fz   }|st        d |||fD              S t        |||      S )a  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Embedded representation of the inputs. Should be float, not int 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)
            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.
        N )rz   r   r   r"   c              3   &   K   | ]	  }||  y wr   r   .0vs     r@   	<genexpr>z3InstructBlipVideoEncoder.forward.<locals>.<genexpr>t  s     eqWXWdes   )last_hidden_stater   
attentions)r(   r   r   use_return_dict	enumerater   r   r   )r>   inputs_embedsrz   r   r   r   encoder_statesall_attentionsr   idxencoder_layerlayer_outputss               r@   rk   z InstructBlipVideoEncoder.forward;  s   8 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]30d%"+DKK"8 	FC#!/=2B!B)-"3M *!,M !/=3C2E!E	F  +}.>>Ne]NN$Seee+>Vd
 	
rA   )NNNN)rm   rn   ro   r   r#   r/   r   r5   rp   rs   r   r   r   rk   rt   ru   s   @r@   r   r   +  sy    ,6 , 26,0/3&*<
 !.<
 $D>	<

 'tn<
 d^<
 
uo%	&<
rA   r   c                   P     e Zd Zd fd	Zd Zd Zd Zd Zd Z	 	 	 	 	 d	dZ	 xZ
S )
*InstructBlipVideoQFormerMultiHeadAttentionc                    t         |           || _        |j                  |j                  z  dk7  r0t        |d      s$t        d|j                  |j                  fz        |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _	        t        j                  |j                  | j                        | _        |r_t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        n^t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                   |j"                        | _        t'        |dd      | _        | j(                  dk(  s| j(                  dk(  rF|j*                  | _        t        j,                  d|j*                  z  d	z
  | j                        | _        d
| _        y )Nr   embedding_sizezLThe hidden size (%d) is not a multiple of the number of attention heads (%d)position_embedding_typeabsoluterelative_keyrelative_key_queryr   r"   F)r.   r/   r(   r0   r   hasattrr   rq   attention_head_sizeall_head_sizer   r   rw   encoder_hidden_sizerx   ry   Dropoutattention_probs_dropout_probr|   getattrr   max_position_embeddings	Embeddingdistance_embeddingsave_attentionr>   r(   is_cross_attentionr?   s      r@   r/   z3InstructBlipVideoQFormerMultiHeadAttention.__init__{  s    : ::a?PVXhHi^%%v'A'ABC 
 $*#=#= #&v'9'9F<V<V'V#W !558P8PPYYv1143E3EF
yy!;!;T=O=OPDH6#=#=t?Q?QRDJyy!3!3T5G5GHDH6#5#5t7I7IJDJzz&"E"EF'.v7PR\']$''>9T=Y=Y]q=q+1+I+ID(&(ll1v7U7U3UXY3Y[_[s[s&tD##rA   c                     || _         y r   attn_gradients)r>   r  s     r@   save_attn_gradientsz>InstructBlipVideoQFormerMultiHeadAttention.save_attn_gradients  s
    ,rA   c                     | j                   S r   r  r>   s    r@   get_attn_gradientsz=InstructBlipVideoQFormerMultiHeadAttention.get_attn_gradients  s    """rA   c                     || _         y r   attention_map)r>   r	  s     r@   save_attention_mapz=InstructBlipVideoQFormerMultiHeadAttention.save_attention_map  s
    *rA   c                     | j                   S r   r  r  s    r@   get_attention_mapz<InstructBlipVideoQFormerMultiHeadAttention.get_attention_map  s    !!!rA   c                     |j                         d d | j                  | j                  fz   } |j                  | }|j	                  dddd      S )NrG   r   r   r"   r	   )rI   r   r   rU   rR   )r>   xnew_x_shapes      r@   transpose_for_scoresz?InstructBlipVideoQFormerMultiHeadAttention.transpose_for_scores  sN    ffhsmt'?'?AYAY&ZZAFFK yyAq!$$rA   c                    |d u}|rC| j                  | j                  |            }| j                  | j                  |            }	|}n@| j                  | j                  |            }| j                  | j                  |            }	| j                  |      }
| j                  |
      }t	        j
                  ||j                  dd            }| j                  dk(  s| j                  dk(  rF|j                         d   }t	        j                  |t        j                  |j                        j                  dd      }t	        j                  |t        j                  |j                        j                  dd      }||z
  }| j                  || j                  z   dz
        }|j                  |j                         }| j                  dk(  rt	        j"                  d||      }||z   }nE| j                  dk(  r6t	        j"                  d||      }t	        j"                  d	||      }||z   |z   }|t%        j&                  | j(                        z  }|j                   }|||z   } t+        j,                  d
      |      j                  |      }|r8| j.                  r,| j1                  |       |j3                  | j4                         | j7                  |      }|||z  }t	        j
                  ||	      }|j9                  dddd      j;                         }|j                         d d | j<                  fz   } |j                  | }|r||f}|S |f}|S )NrG   r~   r   r   r"   r`   devicer_   zbhld,lrd->bhlrzbhrd,lrd->bhlrrL   r   r   r	   )r  rx   ry   rw   r5   r   rd   r   rI   arangelongr  rU   r   r   rb   r`   einsummathsqrtr   r   Softmaxr   r
  register_hookr  r|   rR   r   r   )r>   r   rz   r   encoder_hidden_statesencoder_attention_maskr   r   	key_layervalue_layermixed_query_layerquery_layerattention_scores
seq_lengthposition_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_scores_dtypeattention_probsattention_probs_droppedcontext_layernew_context_layer_shaper   s                              r@   rk   z2InstructBlipVideoQFormerMultiHeadAttention.forward  s8    3$>11$((;P2QRI33DJJ?T4UVK3N11$((=2IJI33DJJ}4MNK JJ}5//0AB !<<Y5H5HR5PQ''>9T=Y=Y]q=q&++-a0J"\\*EJJ}OcOcdiijlnopN"\\*EJJ}OcOcdiijkmopN%6H#'#:#:8dFbFb;bef;f#g #7#:#:ARAR#:#S ++~=+0<<8H+Wk+l(#36N#N --1EE16>NP[]q1r./4||<LiYm/n,#36T#TWs#s +dii8P8P.QQ!1!7!7%/.@ -"**,-=>AABXY$"5"5##O4))$*B*BC #',,"?  &=	&I#%<kJ%--aAq9DDF"/"4"4"6s";t?Q?Q>S"S***,CD6G=/2 O\M]rA   rl   NNNNF)rm   rn   ro   r/   r  r  r
  r  r  rk   rt   ru   s   @r@   r   r   z  s8    $8-#+"% "#KrA   r   c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )"InstructBlipVideoQFormerSelfOutputc                 (   t         |           t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        t        j                  |j                        | _
        y r   )r.   r/   r   r   r0   denser   r   r   hidden_dropout_probr|   r=   s     r@   r/   z+InstructBlipVideoQFormerSelfOutput.__init__  s`    YYv1163E3EF
f&8&8f>S>STzz&"<"<=rA   r   input_tensorrE   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S r   r3  r|   r   r>   r   r5  s      r@   rk   z*InstructBlipVideoQFormerSelfOutput.forward  7    

=1]3}|'CDrA   r   ru   s   @r@   r1  r1    1    >U\\  RWR^R^ rA   r1  c                        e Zd Zd fd	Zd Z	 	 	 	 	 ddej                  deej                     deej                     deej                     deej                     dee	   d	e
ej                     fd
Z xZS )!InstructBlipVideoQFormerAttentionc                     t         |           t        ||      | _        t	        |      | _        t               | _        y r   )r.   r/   r   	attentionr1  outputsetpruned_headsr   s      r@   r/   z*InstructBlipVideoQFormerAttention.__init__  s3    CFL^_8@ErA   c                 >   t        |      dk(  ry t        || j                  j                  | j                  j                  | j
                        \  }}t        | j                  j                  |      | j                  _        t        | j                  j                  |      | j                  _        t        | j                  j                  |      | j                  _	        t        | j                  j                  |d      | j                  _        | j                  j                  t        |      z
  | j                  _        | j                  j                  | j                  j                  z  | j                  _        | j
                  j                  |      | _        y )Nr   r"   rL   )lenr   r>  r   r   rA  r   rw   rx   ry   r?  r3  r   union)r>   headsindexs      r@   prune_headsz-InstructBlipVideoQFormerAttention.prune_heads  s   u:?74>>55t~~7Y7Y[_[l[l
u
  2$..2F2FN/0B0BEJ1$..2F2FN.t{{/@/@%QO .2^^-O-ORUV[R\-\*'+~~'I'IDNNLnLn'n$ --33E:rA   r   rz   r   r  r  r   rE   c                 p    | j                  ||||||      }| j                  |d   |      }|f|dd  z   }	|	S )N)r   rz   r   r  r  r   r   r"   )r>  r?  )
r>   r   rz   r   r  r  r   self_outputsattention_outputr   s
             r@   rk   z)InstructBlipVideoQFormerAttention.forward  sY     ~~')"7#9/ & 
  ;;|AF#%QR(88rA   rl   r/  )rm   rn   ro   r/   rG  r5   rp   r   rr   rs   r   rk   rt   ru   s   @r@   r<  r<    s    ";* 7;15=A>B,1|| !!2!23 E--.	
  ((9(9: !)):): ; $D> 
u||	rA   r<  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )$InstructBlipVideoQFormerIntermediatec                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y r   )r.   r/   r   r   r0   r   r3  
isinstancer   strr
   intermediate_act_fnr=   s     r@   r/   z-InstructBlipVideoQFormerIntermediate.__init__4  s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$rA   r   rE   c                 J    | j                  |      }| j                  |      }|S r   )r3  rP  r   s     r@   rk   z,InstructBlipVideoQFormerIntermediate.forward<  s&    

=100?rA   r   ru   s   @r@   rL  rL  3  s#    9U\\ ell rA   rL  c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )InstructBlipVideoQFormerOutputc                 (   t         |           t        j                  |j                  |j
                        | _        t        j                  |j
                  |j                        | _        t        j                  |j                        | _        y r   )r.   r/   r   r   r   r0   r3  r   r   r   r4  r|   r=   s     r@   r/   z'InstructBlipVideoQFormerOutput.__init__C  s`    YYv779K9KL
f&8&8f>S>STzz&"<"<=rA   r   r5  rE   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S r   r7  r8  s      r@   rk   z&InstructBlipVideoQFormerOutput.forwardI  r9  rA   r   ru   s   @r@   rS  rS  B  r:  rA   rS  c                   >     e Zd Z fdZ	 	 	 	 	 	 ddZd Zd Z xZS )InstructBlipVideoQFormerLayerc                 f   t         |           |j                  | _        d| _        t	        |      | _        || _        ||j                  z  dk(  rt	        |d      | _        d| _	        nd| _	        t        |      | _        t        |      | _        t        |      | _        t        |      | _        y )Nr"   r   T)r   F)r.   r/   chunk_size_feed_forwardseq_len_dimr<  r>  	layer_idxcross_attention_frequencycrossattentionhas_cross_attentionrL  intermediaterS  r?  intermediate_queryoutput_queryr>   r(   r[  r?   s      r@   r/   z&InstructBlipVideoQFormerLayer.__init__Q  s    '-'E'E$:6B"v7771<"CF_c"dD'+D$',D$@H4V<"Fv"N:6BrA   c           
         | j                  ||||      }|d   }	|dd  }
|dkD  r|	d d d |d d f   }| j                  r1|t        d      | j                  ||||||      }|d   }|
|dd  z   }
t	        | j
                  | j                  | j                  |      }|	j                  d   |kD  rt	        | j                  | j                  | j                  |	d d |d d d f         j                  |j                        }t        j                  ||gd      }n,t	        | j                  | j                  | j                  |	      }|f|
z   }
|
S )N)rz   r   r   r   r"   z>encoder_hidden_states must be given for cross-attention layers)rz   r   r  r  r   rL   )r>  r^  r   r]  r   feed_forward_chunk_queryrY  rZ  rN   feed_forward_chunkrb   r  r5   rV   )r>   r   rz   r   r  r  r   query_lengthself_attention_outputsrJ  r   query_attention_outputcross_attention_outputslayer_outputlayer_output_texts                  r@   rk   z%InstructBlipVideoQFormerLayer.forwarde  s    "&)/	 "0 "
 2!4(,!%5a,6I%J"''(0$%eff*.*=*=*#1'*?+A&7 +> +' *A)C&!$;AB$??4--,,  &	L  %%a(<7$=++00$$$Qq%89	%
 "\(() "  %yy,8I)JPQR4'',,   	L  /G+rA   c                 L    | j                  |      }| j                  ||      }|S r   )r_  r?  r>   rJ  intermediate_outputrj  s       r@   re  z0InstructBlipVideoQFormerLayer.feed_forward_chunk  s,    "//0@A{{#68HIrA   c                 L    | j                  |      }| j                  ||      }|S r   )r`  ra  rm  s       r@   rd  z6InstructBlipVideoQFormerLayer.feed_forward_chunk_query  s.    "556FG(()<>NOrA   )NNNNFr   )rm   rn   ro   r/   rk   re  rd  rt   ru   s   @r@   rW  rW  P  s-    C. "#=~
rA   rW  c                   6     e Zd Z fdZ	 	 	 	 	 	 	 	 ddZ xZS )InstructBlipVideoQFormerEncoderc           	          t         |           || _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        d| _	        y c c}w r   )
r.   r/   r(   r   r   r   r   rW  layerr   rb  s      r@   r/   z(InstructBlipVideoQFormerEncoder.__init__  sW    ]]OTU[UmUmOno)*69=o

 ',# ps   A$c
           
         |rdnd }
|rdnd }|rdnd }t        | j                  j                        D ]^  }| j                  |   }|r|
|fz   }
|||   nd } ||||||||	      }|d   }|s:||d   fz   }|	dkD  sI|j                  sV||d   fz   }` |r|
|fz   }
|st        d ||
||fD              S t        ||
||      S )Nr   )r  r   rf  r   r"   r   c              3   $   K   | ]  }|| 
 y wr   r   r   s     r@   r   z:InstructBlipVideoQFormerEncoder.forward.<locals>.<genexpr>  s      	 = 	s   )r   r   r   cross_attentions)r   r(   r   rs  r^  r   r   )r>   r   rz   r   r  r  r   r   r   rf  all_hidden_statesall_self_attentionsall_cross_attentionsilayer_modulelayer_head_maskr   s                    r@   rk   z'InstructBlipVideoQFormerEncoder.forward  s0    #7BD$5b4%6rDt{{445 	VA::a=L#$58H$H!.7.CilO(%'="3)M *!,M &9]1=M<O&O#!#(H(H+?=QRCSBU+U(+	V.   1]4D D 	 "%'(		 	 	 9++*1	
 	
rA   )NNNNFFTr   )rm   rn   ro   r/   rk   rt   ru   s   @r@   rq  rq    s'    , "#":
rA   rq  c                   2     e Zd ZdZ fdZ	 	 	 	 ddZ xZS )"InstructBlipVideoQFormerEmbeddingsz;Construct the embeddings from word and position embeddings.c                 P   t         |           t        j                  |j                  |j
                  |j                        | _        t        j                  |j                  |j
                        | _	        t        j                  |j
                  |j                        | _        t        j                  |j                        | _        | j!                  dt#        j$                  |j                        j'                  d      d       t)        |dd      | _        || _        y )	N)padding_idxr   position_ids)r"   rG   F)
persistentr   r   )r.   r/   r   r   
vocab_sizer0   pad_token_idword_embeddingsr   position_embeddingsr   r   	layernormr   r4  r|   register_bufferr5   r  re   r   r   r(   r=   s     r@   r/   z+InstructBlipVideoQFormerEmbeddings.__init__  s    !||F,=,=v?Q?Q_e_r_rs#%<<0N0NPVPbPb#c f&8&8f>S>STzz&"<"<= 	ELL)G)GHOOPWXej 	 	
 (/v7PR\']$rA   c                    ||j                         d   }nd}|&| j                  d d |||z   f   j                         }|k| j                  |      }| j                  dk(  r/| j                  |j                  |j                              }||z   }|t        j                  ||fd      }n|}|j                  | j                  j                  j                        }| j                  |      }| j                  |      }|S )Nr"   r   r   rL   )rI   r  cloner  r   r  rb   r  r5   rV   r  ra   r`   r|   )r>   	input_idsr  query_embedspast_key_values_lengthr"  rB   r  s           r@   rk   z*InstructBlipVideoQFormerEmbeddings.forward  s      ")!,JJ,,Q0FVlIl0l-lmssuL --i8J++z9&*&>&>|zO`O`?a&b#'*==
'"YYj'AqI
%J]]4>>#8#8#>#>?
^^J/
\\*-
rA   )NNNr   )rm   rn   ro   r   r/   rk   rt   ru   s   @r@   r~  r~    s    E$  rA   r~  c                   B    e Zd ZU eed<   dZdZdZdZdZ	dZ
dZg dZd Zy) InstructBlipVideoPreTrainedModelr(   blipT)r~  r   r   r1  c                    | j                   j                  }t        |t        j                  t        j
                  f      rY|j                  j                  j                  d|       |j                  %|j                  j                  j                          yyt        |t        j                        r(|j                  j                  j                  d|       yt        |t        j                        rJ|j                  j                  j                          |j                  j                  j                  d       yt        |t              rYt        j                  j!                  |j"                  d|       t        j                  j!                  |j$                  d|       yt        |t&        t(        f      r%|j*                  j                  j                          yy)zInitialize the weightsr   )meanstdN      ?)r(   initializer_rangerN  r   r   r8   ra   datanormal_r   zero_r   r   fill_r'   inittrunc_normal_r<   r7   )InstructBlipVideoForConditionalGenerationInstructBlipVideoModelquery_tokens)r>   rv   factors      r@   _init_weightsz.InstructBlipVideoPreTrainedModel._init_weights;  sI   ..fryy"))45MM&&CV&<{{&  &&( '-MM&&CV&<-KK""$MM$$S) ABGG!!&";";#6!RGG!!&"8"8s!O!JLb cd$$**, erA   N)rm   rn   ro   r#   __annotations__base_model_prefixsupports_gradient_checkpointing_supports_attention_backend_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_no_split_modulesr  r   rA   r@   r  r  (  s>    ##&*#"&N!-rA   r  c                        e Zd ZU dZeed<   def fdZe	 	 	 	 	 ddee	j                     dee   dee   dee   dedeeef   fd	       Zd
 Z xZS )InstructBlipVideoVisionModelr]   r(   c                     t         |   |       || _        |j                  }t	        |      | _        t        |      | _        t        j                  ||j                        | _        | j                          y r   )r.   r/   r(   r0   r'   rB   r   encoderr   r   r   post_layernorm	post_init)r>   r(   r1   r?   s      r@   r/   z%InstructBlipVideoVisionModel.__init__S  s]     &&	;FC/7 ll9&:O:OPrA   r   r   r   r\   rE   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|t	        d      | j                  ||      }| j                  ||||      }|d   }| j                  |      }|d d dd d f   }	| j                  |	      }	|s
||	f|dd  z   S t        ||	|j                  |j                        S )Nz You have to specify pixel_values)r\   )r   r   r   r   r   r"   )r   pooler_outputr   r   )r(   r   r   r   r   rB   r  r  r   r   r   )
r>   r]   r   r   r   r\   r   encoder_outputsr   pooled_outputs
             r@   rk   z$InstructBlipVideoVisionModel.forward^  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]?@@Ogh,,'/!5#	 ' 
 ,A. //0AB)!Q'2++M:%}58KKK)/')77&11	
 	
rA   c                     | j                   S r   )rB   r  s    r@   get_input_embeddingsz1InstructBlipVideoVisionModel.get_input_embeddings  s    rA   r/  )rm   rn   ro   main_input_namer%   r  r/   r   r   r5   rr   rs   r   r   r   rk   r  rt   ru   s   @r@   r  r  O  s    $O))	< 	  59,0/3&*).(
u001(
 $D>(
 'tn	(

 d^(
 #'(
 
u00	1(
 (
TrA   r  c                       e Zd ZdZdZdZdZdZdef fdZ	d Z
d Zd Z	 ddej                  d	ee   d
ej"                  dedej                  f
dZ	 	 	 	 	 	 	 	 	 ddej(                  deej,                     deej(                     deej                     deej,                     deej,                     deej,                     dee   dee   dee   deeej,                     ef   fdZ xZS )InstructBlipVideoQFormerModelz
    Querying Transformer (Q-Former), used in InstructBlipVideo. Slightly modified from BLIP-2 as it also takes the
    instruction as input.
    Fr(   c                     t         |   |       || _        t        |      | _        t        |      | _        | j                          y r   )r.   r/   r(   r~  rB   rq  r  r  r=   s     r@   r/   z&InstructBlipVideoQFormerModel.__init__  s9     <VD6v>rA   c                 .    | j                   j                  S r   rB   r  r  s    r@   r  z2InstructBlipVideoQFormerModel.get_input_embeddings  s    ...rA   c                 &    || j                   _        y r   r  r>   ry   s     r@   set_input_embeddingsz2InstructBlipVideoQFormerModel.set_input_embeddings  s    */'rA   c                     |j                         D ]7  \  }}| j                  j                  |   j                  j	                  |       9 y)z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr  rs  r>  rG  )r>   heads_to_pruners  rE  s       r@   _prune_headsz*InstructBlipVideoQFormerModel._prune_heads  sE    
 +002 	CLE5LLu%//;;EB	CrA   rz   input_shaper  	has_queryrE   c                    |j                         dk(  r|dddddddf   }n=|j                         dk(  r|ddddddf   }nt        d| d|j                   d      |j                  | j                        }d|z
  d	z  }|S )
a>  
        Makes broadcastable attention and causal masks so that future and masked tokens are ignored.

        Arguments:
            attention_mask (`torch.Tensor`):
                Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
            input_shape (`tuple[int]`):
                The shape of the input to the model.
            device: (`torch.device`):
                The device of the input to the model.

        Returns:
            `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.
        r	   Nr   z!Wrong shape for input_ids (shape z) or attention_mask (shape )r_   r  g     )rM   r   rN   rb   r`   )r>   rz   r  r  r  extended_attention_masks         r@   get_extended_attention_maskz9InstructBlipVideoQFormerModel.get_extended_attention_mask  s    . 1$&4Qa]&C#!Q& '5QdA5E&F#3K=@[\j\p\p[qqrs  #:"<"<4::"<"N#&)@#@H"L&&rA   r  r  r  r   r  r  r   r   r   c                 D   ||n| j                   j                  }|	|	n| j                   j                  }	|
|
n| j                   j                  }
||t	        d      ||j
                  d   nd}| j                  |||      }|j                         dd }|\  }}|j                  }|t        j                  ||f|      }| j                  |||      }|t        |t              r|d   j                         \  }}}n|j                         \  }}}||f}t        |t              r|D cg c]  }| j                  |       }}n?|)t        j                  ||      }| j                  |      }n| j                  |      }nd}| j                  || j                   j                         }| j#                  |||||||	|
|	      }|d   }|dddddf   }|
s
||f|dd z   S t%        |||j&                  |j(                  |j*                  |j,                  	      S c c}w )
a  
        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**.
        past_key_values (`Cache` 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)`.
        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`).
        Nz7You have to specify query_embeds when input_ids is Noner"   r   )r  r  r  rG   )r  )rz   r   r  r  r   r   r   rf  )r   r  past_key_valuesr   r   rv  )r(   r   r   r   r   rN   rB   rI   r  r5   onesr  rN  listinvert_attention_maskget_head_maskr   r  r   r  r   r   rv  )r>   r  rz   r  r  r   r  r  r   r   r   rf  embedding_outputr  rf   r"  r  r  encoder_batch_sizeencoder_sequence_lengthrg   encoder_hidden_shapemaskencoder_extended_attention_maskr  sequence_outputr  s                              r@   rk   z%InstructBlipVideoQFormerModel.forward  s   @ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]!5VWW0<0H|))!,a??%% + 
 '++-cr2!,
J!((!"ZZ*j)A6RN #'"B"B>S^`f"g !,/6AVWXAYA^A^A`>"$;QAVA[A[A]>"$;Q$68O#P 0$7`v2wX\43M3Md3S2w/2w'/).4HQW)X&262L2LMc2d/262L2LMc2d/.2+ &&y$++2O2OP	,,2"7#B/!5#% ' 

 *!,'1a0#]3oab6III;-'+;;)77&11,==
 	
C 3xs   -Hrl   )	NNNNNNNNN)rm   rn   ro   r   r  r  r  r  r$   r/   r  r  r  r5   rp   r   rq   r  rs   r  
LongTensorr   rr   r   r   rk   rt   ru   s   @r@   r  r    s   
 #( N= /0C  )')' 3Z)' 	)'
 )' 
)'\ 7;37/315=A>B,0/3&*n
##n
 !!2!23n
 u//0	n

 u||,n
 E--.n
  ((9(9:n
 !)):): ;n
 $D>n
 'tnn
 d^n
 
uU&&')UU	Vn
rA   r  zV
    Class defining the outputs of [`InstructBlipVideoForConditionalGeneration`].
    )custom_introc                      e Zd ZU dZ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ej                        e	d<   dee   fd	Zy)
4InstructBlipVideoForConditionalGenerationModelOutputa  
    loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
        Language modeling loss from the language model.
    logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
        Prediction scores of the language modeling head of the language model.
    vision_outputs (`BaseModelOutputWithPooling`):
        Outputs of the vision encoder.
    qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`):
        Outputs of the Q-Former (Querying Transformer).
    language_model_outputs (`CausalLMOutputWithPast` or `Seq2SeqLMOutput`):
        Outputs of the language model.
    Nlosslogitsvision_outputsqformer_outputslanguage_model_outputsrE   c                 H     t         fd j                         D              S )Nc              3   d   K   | ]'  }|d vr|   nt        |      j                          ) yw)r  r  r  N)r   to_tuple)r   kr>   s     r@   r   zPInstructBlipVideoForConditionalGenerationModelOutput.to_tuple.<locals>.<genexpr>g  sB      
  WW Gq!**,-
s   -0)r   keysr  s   `r@   r  z=InstructBlipVideoForConditionalGenerationModelOutput.to_tuplef  s%     
 YY[	
 
 	
rA   )rm   rn   ro   r   r  r   r   r5   rr   r  r  r  r  r  r   r  r   rA   r@   r  r  L  s     04D(5**+
,315FHU5,,-.526NHU../6:>OXeE$5$567>AEHU5+<+<%=>E
%* 
rA   r  z`
    InstructBlipVideo base Model consisting of language model, qformer and vision encoder.
    c            #           e Zd ZdZdgZdef fdZd Zd Zd Z	d Z
d	ej                  d
ej                  fdZee	 	 	 	 	 	 	 	 	 	 	 ddej                  dej                  deej                     d	eej                     deej                     deej                     deej                     d
eej$                     dee   dee   dee   dedee   dee   deeef   fd              Z xZS )r  r]   r  r(   c                 (   t         |   |       t        |j                        | _        t        j                  t        j                  d|j                  |j                  j                              | _        t        |j                        | _        t        j                  |j                  j                  |j                   j                        | _        t%        j&                  |j                         | _        | j(                  j*                  /| j*                  j-                  | j(                  j*                         | j(                  j.                  /| j.                  j-                  | j(                  j.                         | j1                          y Nr"   )r.   r/   r  vision_configvision_modelr   r4   r5   r   num_query_tokensqformer_configr0   r  r  qformerr   text_configlanguage_projectionr   from_configlanguage_modelr  extend_keep_in_fp32_modulesr  r=   s     r@   r/   zInstructBlipVideoModel.__init__x  s    89M9MNLLQ8O8OQWQfQfQrQr)st4V5J5JK#%99V-B-B-N-NPVPbPbPnPn#o '33F4F4FG00<""))$*=*=*O*OP44@&&--d.A.A.W.WX 	rA   c                 6    | j                   j                         S r   r  r  r  s    r@   r  z+InstructBlipVideoModel.get_input_embeddings      ""7799rA   c                 :    | j                   j                  |       y r   r  r  r  s     r@   r  z+InstructBlipVideoModel.set_input_embeddings      007rA   c                     | j                   j                  s_| j                  j                  | j                  j                  _        | j                  j                  | j                  j                  _        y y r   r(   use_decoder_only_language_modelr  sharedr  embed_tokensdecoderr  s    r@   _tie_weightsz#InstructBlipVideoModel._tie_weights  T    {{::7;7J7J7Q7QD''47;7J7J7Q7QD''4 ;rA   c                    | j                   }t        |      dkD  r:d|vr6t        j                  j	                         dkD  rt
        j                  d       t        | j                  d      rd| j                  j                  _
        yyz
        Some pre-processing hacks to make the model `accelerate` compatible. Check
        https://github.com/huggingface/transformers/pull/21707 for more details.
        r"   r  a  The `language_model` is not in the `hf_device_map` dictionary and you are running your script in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`. Please pass a `device_map` that contains `language_model` to remove this warning. Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for more details on creating a `device_map` for large models._hf_hookTNhf_device_maprC  r5   cudadevice_countr   warningr   r  r  io_same_devicer>   r  s     r@   _preprocess_acceleratez-InstructBlipVideoModel._preprocess_accelerate  y    
 **}!&6m&KPUPZPZPgPgPilmPmNNM 4&&
3:>D((7 4rA   r  r   c                    |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                  d      j                  |      j                  |j                        }|S zY
        Obtains multimodal placeholdr mask from `input_ids` or `inputs_embeds`.
        r  rG   )r  r5   r   r(   image_token_idr  r  all	unsqueeze	expand_asrb   r>   r  r   special_image_masks       r@   get_placeholder_maskz+InstructBlipVideoModel.get_placeholder_mask       !.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!;!*dkk.H.H!H/99"=GGVYYZgZnZno!!rA   qformer_input_idsqformer_attention_maskrz   decoder_input_idsdecoder_attention_maskr   r   r   r\   	use_cacher   rE   c                    ||n| j                   j                  }|j                  \  }}}}}|j                  ||z  |||      }| j	                  ||	|
||      }|d   }t        j                  |j                         dd t
        j                  |j                        }| j                  j                  |j                  d   dd      }t        j                  |j                         dd t
        j                  |j                        }|t        j                  |      }|j                  |d      }|j                  |d      }t        j                  ||gd      }| j                  ||||||	|
|      }|d   ddd|j                  d      ddf   }| j!                  |      }|j                  || j                   j"                  |z  d      }|Q | j$                  j'                         |      }|| j                   j(                  k(  }|t        j                  |      }nl| | j'                         t        j*                  | j                   j(                  t
        j                  |j                              k(  }|j-                  d      }|j/                  d      j1                  |      j3                  |j                        }|j3                  |j                  |j4                        }|j7                  ||      }| j                   j8                  r | j$                  d|||	|
||d	|}n | j$                  d|||||	|
||d
|}t;        |||      S )a  
        qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided
            to serve as text prompt, which the Q-Former model will encode.

            Indices can be obtained using [`InstructBlipVideoProcessor`]. See [`InstructBlipVideoProcessor.__call__`] for
            details.

            [What are input IDs?](../glossary#input-ids)
        qformer_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)
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be
            provided to serve as text prompt, which the language model can continue.

            Indices can be obtained using [`InstructBlipVideoProcessor`]. See [`InstructBlipVideoProcessor.__call__`] for
            details.

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

            Only relevant in case an encoder-decoder language model (like T5) is used.
        N)r]   r   r   r   r\   r   rG   r  rL   r"   )r  rz   r  r  r  r   r   r   r   rz   r   r   r   r  )r   rz   r  r  r   r   r   r  r  r   )r(   r   rN   rQ   r  r5   r  rI   r  r  r  re   	ones_likerepeat_interleaverV   r  r  r  r  r  video_token_idr   r  r  r  rb   r`   masked_scatterr  r  )r>   r]   r  r  r  rz   r  r  r   r   r   r   r\   r  r   rf   frameschannelrC   rD   r  image_embedsimage_attention_maskr  query_attention_maskquery_outputsquery_outputlanguage_model_inputsr  r   s                                 r@   rk   zInstructBlipVideoModel.forward  s   b &1%<k$++B]B] 6B5G5G2
FGVU#++J,?&RWX**%/!5#%= + 
 &a(  %zz,*;*;*=cr*B%**]i]p]pq ((//0B0B10Er2N$zz,*;*;*=cr*B%**]i]p]pq!)%*__5F%G"-??A?N!7!I!I&VW!I!X!&,@BX+Y_`!a'1%".#7/!5# % 	
 %Q'+A\->->q-A+A1(DE !% 8 8 F !6 = =j$++JfJfioJoqs t FD//DDFyQM!*dkk.H.H!H%!&!;!.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!;/99"=GGVYYZgZnZno 5 8 89M9M}ObOb c%445GI^_;;66)d)) +-"3%9'# G *d)) 
+-"3'="3%9'#
 
G D))#*
 	
rA   )NNNNNNNNNFN)rm   rn   ro   r  r  r#   r/   r  r  r  r  r5   r  rr   r  r   r   r   rp   rs   r   r   r   r   r  rk   rt   ru   s   @r@   r  r  o  s    %O+,6 &:8R
?("e.>.> "uO`O` " 
 >B15598<=A04,0/3&*).$(G
''G
 !,,G
 !))9)9 :	G

 E--.G
 !!1!12G
 $E$4$45G
 !))9)9 :G
  -G
 $D>G
 'tnG
 d^G
 #'G
 D>G
 -.G
  
uJJ	K!G
  G
rA   r  a  
    InstructBlipVideo Model for generating text given an image and an optional text prompt. The model consists of a vision
    encoder, Querying Transformer (Q-Former) and a language model.

    One can optionally pass `input_ids` to the model, which serve as a text prompt, to make the language model continue
    the prompt. Otherwise, the language model starts generating text from the [BOS] (beginning-of-sequence) token.
    c            %       (    e Zd ZU eed<   dZdZdgZdef fdZd Z	d Z
d Zd	ej                  fd
Zd Zd Zd Zd Z	 	 	 d"dej(                  dej*                  deej*                     dee   dee   f
dZdej*                  dej(                  fdZee	 	 	 	 	 	 	 	 	 	 	 	 d#dej(                  dej(                  deej*                     deej(                     deej*                     deej*                     deej*                     deej(                     dee   dee   deej*                     dee   dedee   dee   d	eee f   f d              Z! ejD                         	 	 	 	 	 	 d$dej(                  deej*                     deej*                     deej*                     deej*                     deej(                     ded	ej*                  fd        Z#	 	 	 d"dej(                  dej*                  deej*                     dee   dee   f
d!Z$ xZ%S )%r  r(   r]   Tr  c                 \   t         |   |       t        j                  |j                        | _        t        j                  t        j                  d|j                  |j                  j                              | _        t        j                  |j                        | _        t        j                   |j                  j                  |j"                  j                        | _        |j&                  r t)        j*                  |j"                        }nt-        j*                  |j"                        }|j.                  %| j.                  j1                  |j.                         |j2                  %| j2                  j1                  |j2                         || _        | j7                          y r  )r.   r/   r  _from_configr  r  r   r4   r5   r   r  r  r0   r  r  r  r   r  r  r  r    r  r!   r  r  r  r  r  )r>   r(   r  r?   s      r@   r/   z2InstructBlipVideoForConditionalGeneration.__init__U  s3    8EEfFZFZ[LLQ8O8OQWQfQfQrQr)st4AA&BWBWX#%99V-B-B-N-NPVPbPbPnPn#o 111==f>P>PQN2>>v?Q?QRN++7"")).*J*JK//;&&--n.R.RS, 	rA   c                 6    | j                   j                         S r   r  r  s    r@   r  z>InstructBlipVideoForConditionalGeneration.get_input_embeddingso  r  rA   c                 :    | j                   j                  |       y r   r  r  s     r@   r  z>InstructBlipVideoForConditionalGeneration.set_input_embeddingsr  r  rA   c                 :    | j                   j                  |       y r   )r  set_output_embeddings)r>   new_embeddingss     r@   r0  z?InstructBlipVideoForConditionalGeneration.set_output_embeddingsu  s    11.ArA   rE   c                 6    | j                   j                         S r   )r  get_output_embeddingsr  s    r@   r3  z?InstructBlipVideoForConditionalGeneration.get_output_embeddingsx  s    ""88::rA   c                 6    | j                   j                         S r   )r  get_encoderr  s    r@   r5  z5InstructBlipVideoForConditionalGeneration.get_encoder{      ""..00rA   c                 6    | j                   j                         S r   )r  get_decoderr  s    r@   r8  z5InstructBlipVideoForConditionalGeneration.get_decoder~  r6  rA   c                     | j                   j                  s_| j                  j                  | j                  j                  _        | j                  j                  | j                  j                  _        y y r   r  r  s    r@   r  z6InstructBlipVideoForConditionalGeneration._tie_weights  r   rA   c                    | j                   }t        |      dkD  r:d|vr6t        j                  j	                         dkD  rt
        j                  d       t        | j                  d      rd| j                  j                  _
        yyr  r  r
  s     r@   r  z@InstructBlipVideoForConditionalGeneration._preprocess_accelerate  r  rA   r  r  r\   r   c                      y)$  
        Encodes images into continuous embeddings that can be forwarded to the language model.

        Args:
            pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
                The tensors corresponding to the input images.
        Nr   )r>   r]   r  r  r\   r   s         r@   get_image_featuresz<InstructBlipVideoForConditionalGeneration.get_image_features  s     	rA   r  r   c                    |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                  d      j                  |      j                  |j                        }|S r  )r  r5   r   r(   r   r  r  r  r  r  rb   r  s       r@   r  z>InstructBlipVideoForConditionalGeneration.get_placeholder_mask  r  rA   rz   r  r  r   r   labelsr  r   c                 H   ||n| j                   j                  }| j                  ||||d      \  }}}|s|j                         n|}|s|j                         n|}| | j	                         |      }|t        j                  |      }|j                  |j                  |j                        }| j                  ||      }|j                  ||      }| j                   j                  re | j                  d|||	|
||d|}|r|j                  n|d   }d}|w | j                  d||| j                   j                   j"                  d|}nB | j                  d|||||	|
|||d	|}|r|j$                  n|d   }|r|j                  n|d	   }t'        |||||
      S )a  
        qformer_input_ids (`torch.LongTensor` of shape (batch_size, sequence_length)):
            The sequence used as a prompt to be fed to the Q-Former module.
        qformer_attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
            Mask to avoid performing attention on padding token indices.

        Examples:

        ```python
        >>> from transformers import InstructBlipVideoProcessor, InstructBlipVideoForConditionalGeneration
        >>> import torch
        >>> from huggingface_hub import hf_hub_download
        >>> import av
        >>> import numpy as np

        >>> def read_video_pyav(container, indices):
        ...     '''
        ...     Decode the video with PyAV decoder.
        ...     Args:
        ...         container (`av.container.input.InputContainer`): PyAV container.
        ...         indices (`list[int]`): List of frame indices to decode.
        ...     Returns:
        ...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
        ...     '''
        ...     frames = []
        ...     container.seek(0)
        ...     start_index = indices[0]
        ...     end_index = indices[-1]
        ...     for i, frame in enumerate(container.decode(video=0)):
        ...         if i > end_index:
        ...             break
        ...         if i >= start_index and i in indices:
        ...             frames.append(frame)
        ...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])

        >>> model = InstructBlipVideoForConditionalGeneration.from_pretrained("Salesforce/instructblip-vicuna-7b", device_map="auto")
        >>> processor = InstructBlipVideoProcessor.from_pretrained("Salesforce/instructblip-vicuna-7b")

        >>> file_path = hf_hub_download(
        ...       repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
        ... )
        >>> container = av.open(file_path)

        >>> # sample uniformly 4 frames from the videWhy is this video funny?o
        >>> total_frames = container.streams.video[0].frames
        >>> indices = np.arange(0, total_frames, total_frames / 4).astype(int)
        >>> clip = read_video_pyav(container, indices)

        >>> prompt = "What is happening in the video?"
        >>> inputs = processor(text=prompt, images=clip, return_tensors="pt").to(model.device)

        >>> outputs = model.generate(
        ...     **inputs,
        ...     do_sample=False,
        ...     num_beams=5,
        ...     max_length=256,
        ...     repetition_penalty=1.5,
        ...     length_penalty=1.0,
        ... )
        >>> generated_text = processor.batch_decode(outputs, skip_special_tokens=True)[0].strip()
        >>> print(generated_text)
        "A person is eating a bowl of pasta, and they are using a fork to eat it. The person is sitting at a table, and the plate of pasta is on the table in front"
        ```NTr  r  r\   r   r   r  r   )r  r?  r  )	r   rz   r  r  r   r   r   r?  r  r"   )r  r  r  r  r  r   )r(   r   get_video_featuresr  r  r5   r  rb   r  r`   r  r!  r  r  r  loss_functionr  r  r  r  )r>   r]   r  r  r  rz   r  r  r   r   r   r?  r   r\   r  r   r)  r  r'  r  r   r  r  s                          r@   rk   z1InstructBlipVideoForConditionalGeneration.forward  s   f &1%<k$++B]B]?C?V?V/#9%= @W @
<~} ;F002>8C..0 7D557	BM!"__Y7N 5 8 89M9M}ObOb c!66yP]6^%445GI^_;;66)d)) +-"3%9'# G (3W^^
FD!)t)) !&T[[=T=T=_=_ci
 *d)) +-"3'="3%9'# G $/7<<GAJD'2W^^
FC))#*
 	
rA   c                 H   t        | d      r| j                          |j                  d   }	| j                  ||||d      \  }
}}||| j                  j
                  g| j                  j                  z  dz  }|| j                  j                  j                  gz   }t        j                  |gt        j                  |j                        }|j                  |	d      } | j                         |      }|t        j                  |      }|
j!                  |j                  |j"                        }
| j%                  ||      }|j'                  ||
      }||d	}| j(                  j                  j*                  s||d
<    | j(                  j,                  di ||}|S )a  
        Overrides `generate` function to be able to use the model as a conditional generator.

        Args:
            pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width) or
                (batch_size, num_frames, num_channels, height, width)): Input images or videos to be processed.
            qformer_input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
                The sequence used as a prompt to be fed to the Q-Former module.
            qformer_attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
                Mask to avoid performing attention on padding token indices.
            input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
                The sequence used as a prompt for the generation.
            attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
                Mask to avoid performing attention on padding token indices.
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Embedded representation of the inputs. Should be float, not int tokens.
            interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
                Whether to interpolate the positional encoding of the image embeddings.

        Returns:
            captions (list): A list of strings of length batch_size * num_captions.
        r  r   TrA  r   r  r"   rB  )r   rz   r  r   )r   r  rN   rC  r(   video_token_indexr  r  bos_token_idr5   r   r  r  repeatr  r  rb   r`   r  r!  r  is_encoder_decodergenerate)r>   r]   r  r  r  rz   r   r\   generate_kwargsrf   r)  r  r'  video_tokensstart_tokensr  inputsr   s                     r@   rJ  z2InstructBlipVideoForConditionalGeneration.generateL  s   D 4)'')!''*
?C?V?V/#9%= @W @
<~}    $ = =>A]A]]`aa+t{{/F/F/S/S.TT!LL,uzzR^ReRef	%,,Z;	7D557	BM!"__Y7N 5 8 89M9M}ObOb c!66yP]6^%445GI^_#0NS""))<<"+F;.$%%..KK?KrA   c                    |j                   \  }}}}	}
|j                  ||z  ||	|
      }| j                  ||d      }|d   }t        j                  |j                         dd t        j                  |j                        }| j                  j                  |j                   d   dd      }t        j                  |j                         dd t        j                  |j                        }|t        j                  |      }|j                  |d      }|j                  |d      }t        j                  ||gd      }| j                  |||||d	      }|d   ddd|j                  d      ddf   }| j                  |      }|j                  || j                  j                   |z  d      }|r|||fS |S )
r<  T)r]   r\   r   r   NrG   r  rL   r"   )r  rz   r  r  r  r   )rN   rQ   r  r5   r  rI   r  r  r  re   r  r  rV   r  r  r(   r  )r>   r]   r  r  r\   r   rf   r"  r#  rC   rD   r  r$  r%  r  r&  r'  r(  r)  s                      r@   rC  z<InstructBlipVideoForConditionalGeneration.get_video_features  s   " 6B5G5G2
FGVU#++J,?&RWX**%%= + 

 &a(  %zz,*;*;*=cr*B%**]i]p]pq ((//0B0B10Er2N$zz,*;*;*=cr*B%**]i]p]pq!)%*__5F%G"-??A?N!7!I!I&VW!I!X!&,@BX+Y_`!a'1%".#7 % 
 %Q'+A\->->q-A+A1(DE !% 8 8 F !6 = =j$++JfJfioJoqs t(.-GG$$rA   )NFF)NNNNNNNNNNFN)NNNNNF)&rm   rn   ro   r#   r  r  r  r  r/   r  r  r0  r   Moduler3  r5  r8  r  r  r5   rr   r  r   rs   r=  r  r   r   r   r   r   r   r  rk   no_gradrJ  rC  rt   ru   s   @r@   r  r  E  sz    $#$O!+,6 4:8B;ryy ;11R
?0 >B38&+'' !++ !))9)9 :	
 #+4. d^""e.>.> "uO`O` " 
 >B15598<=A59,0/3-1&*).$(N
''N
 !,,N
 !))9)9 :	N

 E--.N
 !!1!12N
 $E$4$45N
 !))9)9 :N
   1 12N
 $D>N
 'tnN
 ))*N
 d^N
 #'N
 D>N
  +,!N
" 
uJJ	K#N
  N
` U]]_ 9==A045959).C''C $E$4$45C !))9)9 :	C
 E,,-C !!1!12C   1 12C #'C 
		C CR >B38&+9%''9% !++9% !))9)9 :	9%
 #+4.9% d^9%rA   r  )r  r  r  r  r  )r   )Jr  dataclassesr   typingr   r   r   r   r5   r   activationsr
   
generationr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   modeling_utilsr   r   processing_utilsr   pytorch_utilsr   r   r   utilsr   r   r   r   r   r   autor   r    r!   configuration_instructblipvideor#   r$   r%   
get_loggerrm   r   rP  r'   rp   floatr   r   r   r   r   r   r1  r<  rL  rS  rW  rq  r~  r  r  r  r  r  r  __all__r   rA   r@   <module>rb     sq  ,  ! 1 1   ! ) B 9  G & l l j j I I  
		H	%G		 Gd %II%<<% 
% <<	%
 U\\*% % %.Q Qh299 -$> -`L
ryy L
^y yx ,		 ,^299 RYY \$> \~C
bii C
L0 0f #- #- #-L;#C ;||
$D |
~ 

; 
 
: 
N
= N

N
b }%0PRa }%}%@rA   