
    ^jg                     R   d Z ddlZddlZddlmZ ddl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 ddl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'm(Z(m)Z)m*Z*m+Z+m,Z,  ed      e	 G d de                    Z- ed      e	 G d de                     Z. ed      e	 G d de                    Z/ G d de'      Z0ee G d de                    Z1ee G d de                    Z2 G d  d!e+      Z3 G d" d#e)      Z4 G d$ d%e#      Z5 G d& d'e"      Z6 G d( d)e%      Z7 G d* d+e%      Z8e G d, d-e(             Z9 G d. d/e$      Z: G d0 d1e9      Z; G d2 d3e*      Z< G d4 d5e,      Z= G d6 d7e&      Z> ed89       G d: d;e9             Z?g d<Z@y)=zPyTorch CLIPSeg model.    N)	dataclass)Any)strict)nn   )initialization)BaseModelOutputWithPooling)PreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstring)can_return_tuplemerge_with_config_defaults)capture_outputs   )
CLIPConfigCLIPTextConfigCLIPVisionConfig)CLIPMLPCLIPAttentionCLIPEncoderCLIPEncoderLayer	CLIPModel
CLIPOutputCLIPPreTrainedModelCLIPTextEmbeddingsCLIPTextModelCLIPVisionEmbeddingsCLIPVisionModelzCIDAS/clipseg-rd64)
checkpointc                       e Zd ZdZ e       Zy)CLIPSegTextConfiga  
    Example:

    ```python
    >>> from transformers import CLIPSegTextConfig, CLIPSegTextModel

    >>> # Initializing a CLIPSegTextConfig with CIDAS/clipseg-rd64 style configuration
    >>> configuration = CLIPSegTextConfig()

    >>> # Initializing a CLIPSegTextModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
    >>> model = CLIPSegTextModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```N__name__
__module____qualname____doc__AttributeErrorprojection_dim     v/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/clipseg/modular_clipseg.pyr#   r#   0         $%Nr,   r#   c                       e Zd ZdZ e       Zy)CLIPSegVisionConfiga  
    Example:

    ```python
    >>> from transformers import CLIPSegVisionConfig, CLIPSegVisionModel

    >>> # Initializing a CLIPSegVisionConfig with CIDAS/clipseg-rd64 style configuration
    >>> configuration = CLIPSegVisionConfig()

    >>> # Initializing a CLIPSegVisionModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
    >>> model = CLIPSegVisionModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```Nr$   r+   r,   r-   r0   r0   F   r.   r,   r0   c                       e Zd ZU dZdZee   eedf   z  ed<   dZ	eed<   dZ
eed<   d	Zeez  ed
<   dZeed<   dZeed<   dZeed<   dZeed<   y)CLIPSegConfiga  
    extract_layers (`list[int]`, *optional*, defaults to `[3, 6, 9]`):
        Layers to extract when forwarding the query image through the frozen visual backbone of CLIP.
    reduce_dim (`int`, *optional*, defaults to 64):
        Dimensionality to reduce the CLIP vision embedding.
    conditional_layer (`int`, *optional*, defaults to 0):
        The layer to use of the Transformer encoder whose activations will be combined with the condition
        embeddings using FiLM (Feature-wise Linear Modulation). If 0, the last layer is used.
    use_complex_transposed_convolution (`bool`, *optional*, defaults to `False`):
        Whether to use a more complex transposed convolution in the decoder, enabling more fine-grained
        segmentation..

    Example:

    ```python
    >>> from transformers import CLIPSegConfig, CLIPSegModel

    >>> # Initializing a CLIPSegConfig with CIDAS/clipseg-rd64 style configuration
    >>> configuration = CLIPSegConfig()

    >>> # Initializing a CLIPSegModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
    >>> model = CLIPSegModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config

    >>> # We can also initialize a CLIPSegConfig from a CLIPSegTextConfig and a CLIPSegVisionConfig

    >>> # Initializing a CLIPSegText and CLIPSegVision configuration
    >>> config_text = CLIPSegTextConfig()
    >>> config_vision = CLIPSegVisionConfig()

    >>> config = CLIPSegConfig(text_config=config_text, vision_config=config_vision)
    ```)r      	   .extract_layers@   
reduce_dim   decoder_num_attention_heads        decoder_attention_dropout
quick_geludecoder_hidden_acti   decoder_intermediate_sizer   conditional_layerF"use_complex_transposed_convolutionN)r%   r&   r'   r(   r5   listinttuple__annotations__r7   r9   r;   floatr=   strr>   r?   r@   boolr+   r,   r-   r2   r2   \   su    !F 3<NDIc3h/;J'((-0us{0**%)s)s/4&4r,   r2   c                       e Zd Zy)CLIPSegOutputNr%   r&   r'   r+   r,   r-   rI   rI          r,   rI   c                       e Zd ZU dZdZej                  dz  ed<   dZe	ej                  df   dz  ed<   dZ
e	ej                  df   dz  ed<   y)CLIPSegDecoderOutputa  
    logits (`torch.FloatTensor` of shape `(batch_size, height, width)`):
        Classification scores for each pixel.
    hidden_states (`tuple(torch.FloatTensor)`, *optional*,):
        Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        Rreturned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`
    attentions (`tuple(torch.FloatTensor)`, *optional*):
        Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
        heads. Returned when `output_attentions=True` is passed or when `config.output_attentions=True`
    Nlogits.hidden_states
attentions)r%   r&   r'   r(   rN   torchFloatTensorrD   rO   rC   rP   r+   r,   r-   rM   rM      s\    	 (,FE$+:>M5**C/047>7;Je'',-4;r,   rM   c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	ej                  dz  ed<   dZ
ej                  dz  ed<   dZeed<   dZeed<   d	ee   fd
Zy)CLIPSegImageSegmentationOutputa  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Binary cross entropy loss for segmentation.
    logits (`torch.FloatTensor` of shape `(batch_size, height, width)`):
        Classification scores for each pixel.
    conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, projection_dim)`):
        Conditional embeddings used for segmentation.
    pooled_output (`torch.FloatTensor` of shape `(batch_size, embed_dim)`):
        Pooled output of the [`CLIPSegVisionModel`].
    vision_model_output (`BaseModelOutputWithPooling`):
        The output of the [`CLIPSegVisionModel`].
    decoder_output (`CLIPSegDecoderOutput`):
        The output of the [`CLIPSegDecoder`].
    NlossrN   conditional_embeddingspooled_outputvision_model_outputdecoder_outputreturnc                 B    t        d | j                         D              S )Nc              3   `   K   | ]&  }t        |t              r|j                         n| ( y wN)
isinstancer   to_tuple).0vs     r-   	<genexpr>z:CLIPSegImageSegmentationOutput.to_tuple.<locals>.<genexpr>   s$     ^1Z;%?QZZ\QF^s   ,.)rC   values)selfs    r-   r_   z'CLIPSegImageSegmentationOutput.to_tuple   s    ^PTP[P[P]^^^r,   )r%   r&   r'   r(   rU   rQ   rR   rD   rN   rV   rW   rX   r	   rY   rM   rC   r   r_   r+   r,   r-   rT   rT      s     &*D%

d
")'+FE$+7;E--4;.2M5$$t+26:3:+/N(/_%* _r,   rT   c                   R     e Zd Zddej                  dej
                  f fdZ xZS )CLIPSegVisionEmbeddingspixel_valuesrZ   c                 &    t         |   ||       y r]   superforward)rd   rg   interpolate_pos_encoding	__class__s      r-   rk   zCLIPSegVisionEmbeddings.forward   s    &>?r,   T)r%   r&   r'   rQ   rR   Tensorrk   __classcell__rm   s   @r-   rf   rf      s,    @E$5$5 @Y^YeYe @ @r,   rf   c                       e Zd Zy)CLIPSegTextEmbeddingsNrJ   r+   r,   r-   rs   rs      rK   r,   rs   c                       e Zd Zy)CLIPSegAttentionNrJ   r+   r,   r-   ru   ru      rK   r,   ru   c                       e Zd Zy)
CLIPSegMLPNrJ   r+   r,   r-   rw   rw      rK   r,   rw   c                       e Zd Zy)CLIPSegEncoderLayerNrJ   r+   r,   r-   ry   ry      rK   r,   ry   c                   f    e Zd ZdZdej
                  dej
                  deej                     fdZy)CLIPSegDecoderLayerz
    CLIPSeg decoder layer, which is identical to `CLIPSegEncoderLayer`, except that normalization is applied after
    self-attention/MLP, rather than before.
    rO   attention_maskrZ   c                     |} | j                   d||d|\  }}||z   }| j                  |      }|}| j                  |      }||z   }| j                  |      }|S )N)rO   r|   r+   )	self_attnlayer_norm1mlplayer_norm2)rd   rO   r|   kwargsresidual_s         r-   rk   zCLIPSegDecoderLayer.forward   s     !)4>> 
')
 
q !=0((7 / =0((7r,   N)	r%   r&   r'   r(   rQ   ro   rC   rR   rk   r+   r,   r-   r{   r{      s;    
|| 
 
u  	!r,   r{   c                   H    e Zd ZeegedZ ej                         d        Z	y)CLIPSegPreTrainedModel)rO   rP   c                    t        j                  | |       | j                  j                  }t	        |t
              rt        j                  |j                  j                  d|dz         t        j                  |j                  j                  d|dz         t        j                  |j                  t        j                  |j                  j                  d         j!                  d             y	t	        |t"              rt        j                  |j$                  d|j&                  dz  |z         t        j                  |j(                  j                  |j                  j*                  |z         t        j                  |j                  j                  |j                  j*                  |z         t        j                  |j                  t        j                  |j,                        j!                  d             y	t	        |t.              r|j&                  dz  d|j                  j0                  z  dz  z  |z  }|j&                  dz  |z  }t        j                  |j2                  j                  |       t        j                  |j4                  j                  |       t        j                  |j6                  j                  |       t        j                  |j8                  j                  |       y	t	        |t:              r|j                  j<                  dz  d|j                  j0                  z  dz  z  |z  }d|j                  j<                  z  dz  |z  }t        j                  |j>                  j                  |       t        j                  |j@                  j                  |       y	t	        |tB              rwt        j                  |jD                  j                  |jF                  dz  |z         t        j                  |jH                  j                  |jJ                  dz  |z         y	y	)
zInitialize the weightsr:   g{Gz?)meanstd)   r   g      )r   r   N)&r
   _init_weightsconfiginitializer_factorr^   rs   initnormal_token_embeddingweightposition_embeddingcopy_position_idsrQ   arangeshapeexpandrf   class_embedding	embed_dimpatch_embeddinginitializer_rangenum_positionsru   num_hidden_layersq_projk_projv_projout_projrw   hidden_sizefc1fc2CLIPSegModeltext_projectiontext_embed_dimvisual_projectionvision_embed_dim)rd   modulefactorin_proj_stdout_proj_stdfc_stds         r-   r   z$CLIPSegPreTrainedModel._init_weights   s	    	%%dF3//f34LL//66SftmTLL2299RVWJJv**ELL9L9L9R9RSU9V,W,^,^_f,gh 78LL//cv?O?OQU?UX^?^_LL//66FMM<[<[^d<deLL2299v}}?^?^ag?ghJJv**ELL9M9M,N,U,UV],^_ 01!++T1q6==;Z;Z7Z_c6cdgmmK",,d2f<LLL--;?LL--;?LL--;?LL//\B
+!==44d:FMMDcDc@chl?lmpvvK&--333<vEFLL**7LL**<-LL&&--))4/&8 LL((//++T1F: .r,   N)
r%   r&   r'   ry   r{   ru   _can_record_outputsrQ   no_gradr   r+   r,   r-   r   r      s4     ./BC&
 U]]_! !r,   r   c                       e Zd Zy)CLIPSegEncoderNrJ   r+   r,   r-   r   r   !  rK   r,   r   c                        e Zd Zdef fdZeeedee	j                     de	j                  dee   defd                     Z xZS )CLIPSegDecoderr   c                 &   t         |   |       |j                  | _        t        j                  |j
                  |j                        | _        t        j                  |j
                  |j                        | _        |j                  r|j                  j                  dz  |j                  j                  dz  f}t        j                  t        j                  |j                  |j                  dd      t        j                         t        j                  |j                  |j                  dz  |d   |d         t        j                         t        j                  |j                  dz  d|d   |d               | _        nPt        j                  |j                  d|j                  j                  |j                  j                        | _        t#        |j$                        }t        j&                  t)        |      D cg c]6  }t        j                  |j                  j*                  |j                        8 c}      | _        t/        j0                  |j                        }|j                  |_        |j2                  |_        |j6                  |_        d	|_        t        j&                  t)        t#        |j$                              D cg c]  }t=        |       c}      | _        | jA                          y c c}w c c}w )
Nr8   r   r   )kernel_sizepaddingr   r   )r   stride)r   relu)!rj   __init__r?   r   Linearr*   r7   film_mulfilm_addr@   vision_config
patch_size
SequentialConv2dReLUConvTranspose2dtransposed_convolutionlenr5   
ModuleListranger   reducescopydeepcopyr9   num_attention_headsr>   intermediate_size
hidden_actr{   layers	post_init)rd   r   transposed_kernelsdepthr   decoder_configrm   s         r-   r   zCLIPSegDecoder.__init__&  s[    !'!9!9		&"7"79J9JK		&"7"79J9JK44"("6"6"A"AQ"FH\H\HgHgklHl!m*,--		&++V->->AWXY	""%%%%* 21 5-a0	 	""%%*A;Ma;PYklmYn+D' +-*<*<!!1f&:&:&E&EfNbNbNmNm+D' F))*}}UZ[`UabPQRYYv++779J9JKb
 v';';<%+%6%6"-3-O-O*+1+K+K($*!mmRWX[\b\q\qXrRs$tQ%8%H$tu c %us   ;L	LrO   rV   r   rZ   c                    |ddd   }d}t        t        || j                  | j                              D ]  \  }\  }}}	| |	|      |z   }n |	|      }|| j                  k(  rJ| j                  |      |j                  ddd      z  | j                  |      z   }|j                  ddd      } ||fddi|} |ddddddf   j                  dd      }t        t        j                  |j                  d               }
|j                  d   }|j                  ||j                  d   |
|
      }| j                  |      j                  d      }t!        |      S )a/  
        conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*):
            The conditional embeddings for the query images. If provided, the model will use this instead of computing
            the embeddings from the conditional_pixel_values.
        Nr   r   r   r   r|   )rN   )	enumeratezipr   r   r?   r   permuter   	transposerB   mathsqrtr   viewr   squeezerM   )rd   rO   rV   r   activationsoutputi
activationlayerreducesize
batch_sizerN   s                r-   rk   zCLIPSegDecoder.forwardR  sk    $DbD).7KVZVbVb8c.d 	B*A*
E6!
+f4
+D***'=>PQSTVWAXX[_[h[h*\   1a06A$A&AF	B 12q!++Aq1499V\\!_-.+11!4
Za$E,,V4<<Q?#622r,   )r%   r&   r'   r2   r   r   r   r   rC   rQ   ro   r   r   rM   rk   rp   rq   s   @r-   r   r   %  sm    *} *X  %3U\\*%3 !&%3 +,	%3
 
%3    %3r,   r   c                   *     e Zd Zdeez  f fdZ xZS )CLIPSegTextModelrZ   c                 "    t        |   di |S )a;  
        Examples:

        ```python
        >>> from transformers import AutoTokenizer, CLIPSegTextModel

        >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
        >>> model = CLIPSegTextModel.from_pretrained("CIDAS/clipseg-rd64-refined")

        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled (EOS token) states
        ```r+   ri   rd   super_kwargsrm   s     r-   rk   zCLIPSegTextModel.forward~  s      w...r,   )r%   r&   r'   rC   r	   rk   rp   rq   s   @r-   r   r   }  s    /1K)K / /r,   r   c            
       `     e Zd Z	 ddej                  dz  dedz  dee   dee	z  f fdZ
 xZS )CLIPSegVisionModelrg   Nrl   r   rZ   c                 &    t        |   ||fi |S )a+  
        Examples:

        ```python
        >>> import httpx
        >>> from io import BytesIO
        >>> from PIL import Image
        >>> from transformers import AutoProcessor, CLIPSegVisionModel

        >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
        >>> model = CLIPSegVisionModel.from_pretrained("CIDAS/clipseg-rd64-refined")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

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

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled CLS states
        ```ri   rd   rg   rl   r   rm   s       r-   rk   zCLIPSegVisionModel.forward  s    8 w|-EPPPr,   rn   )r%   r&   r'   rQ   rR   rG   r   r   rC   r	   rk   rp   rq   s   @r-   r   r     sY     15Q''$.Q #'+Q +,	Q
 
+	+Q Qr,   r   c            
       p     e Zd Z fdZ	 ddej
                  dedee   de	e
z  f fdZddef fdZ xZS )	r   c                 "    t        |   di |S )a  
        Examples:

        ```python
        >>> import torch
        >>> from transformers import AutoTokenizer, CLIPSegModel

        >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
        >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")

        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     text_features = model.get_text_features(**inputs)
        ```r+   )rj   get_text_featuresr   s     r-   r   zCLIPSegModel.get_text_features  s     w(8<88r,   rg   rl   r   rZ   c                 &    t        |   ||fi |S )a  
        Examples:

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, CLIPSegModel
        >>> from transformers.image_utils import load_image

        >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
        >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = load_image(url)

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

        >>> with torch.inference_mode():
        ...     image_features = model.get_image_features(**inputs)
        ```)rj   get_image_featuresr   s       r-   r   zCLIPSegModel.get_image_features  s    2 w),8P[TZ[[r,   c                 (    t        |   dd|i| y)a  
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.

        Examples:

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, CLIPSegModel
        >>> from transformers.image_utils import load_image

        >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
        >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = load_image(url)

        >>> inputs = processor(
        ...     text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
        ... )

        >>> with torch.inference_mode():
        ...     outputs = model(**inputs)
        >>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
        >>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities
        ```rl   Nr+   ri   )rd   rl   r   rm   s      r-   rk   zCLIPSegModel.forward  s    6 	Z1IZ\Zr,   rn   )r%   r&   r'   r   rQ   rR   rG   r   r   rC   r	   r   rk   rp   rq   s   @r-   r   r     sc    9( *.\''\ #'\ +,	\
 
+	+\6[ [ [r,   r   zn
    CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.
    )custom_introc                       e Zd ZU eed<   def fdZ	 	 	 	 	 ddedz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  fd
Z
ee	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dedee   d	eez  fd              Z xZS )CLIPSegForImageSegmentationr   c                     t         |   |       t        |      | _        |j                  | _        t        |      | _        | j                          y r]   )rj   r   r   clipr5   r   decoderr   )rd   r   rm   s     r-   r   z$CLIPSegForImageSegmentation.__init__  s@      (	$33%f-r,   Nr   	input_idsr|   r   conditional_pixel_valuesrZ   c                    |`t        |      |k7  rt        d      t        j                         5  | j                  j                  |||      j                  }d d d        |S |]t        |      |k7  rt        d      t        j                         5  | j                  j                  |      j                  }d d d        |S t        d      # 1 sw Y   S xY w# 1 sw Y   S xY w)Nz@Make sure to pass as many prompt texts as there are query images)r|   r   zAMake sure to pass as many prompt images as there are query imagesz[Invalid conditional, should be either provided as `input_ids` or `conditional_pixel_values`)r   
ValueErrorrQ   r   r   r   pooler_outputr   )rd   r   r   r|   r   r   rV   s          r-   get_conditional_embeddingsz6CLIPSegForImageSegmentation.get_conditional_embeddings  s      9~+ !cdd  )-)D)Dn< *E *- '  &% &1+,
: !dee n)-)E)EF^)_)m)m&n &%	 m   &%n &%s   )C&CCC$rg   rV   labelsrl   r   c	                 ^   t        j                         5  d|	d<    | j                  j                  d||d|	}
|
j                  }|
j
                  }| j                  D cg c]
  }||dz       }}t        |
j                  |
j                  |
j
                  |
j                        }
ddd       |$| j                  |j                  d   ||||      }n[|j                  d   |j                  d   k7  rt        d	      |j                  d   | j                  j                  k7  rt        d
       | j                  |fi |	}|j                   }d}|8|j#                  |j$                        }t'        j(                         } |||      }t+        |||
|      S c c}w # 1 sw Y   xY w)a~  
        conditional_pixel_values (`torch.FloatTensor`, *optional*):
            The pixel values of the conditional images.
        conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*):
            The conditional embeddings for the query images. If provided, the model will use this instead of computing
            the embeddings from the conditional_pixel_values.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Examples:

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, CLIPSegForImageSegmentation
        >>> from transformers.image_utils import load_image

        >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
        >>> model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = load_image(url)

        >>> texts = ["a cat", "a remote", "a blanket"]
        >>> inputs = processor(text=texts, images=[image] * len(texts), padding=True, return_tensors="pt")

        >>> with torch.inference_mode():
        ...     outputs = model(**inputs)

        >>> logits = outputs.logits
        >>> print(logits.shape)
        torch.Size([3, 352, 352])
        ```Toutput_hidden_states)rg   rl   r   )last_hidden_stater   rO   rP   Nr   )r   r   r|   r   r   zWMake sure to pass as many conditional embeddings as there are query images in the batchzcMake sure that the feature dimension of the conditional embeddings matches `config.projection_dim`.)rU   rN   rV   rW   rX   rY   r+   )rQ   r   r   r   r   rO   r5   r	   r  rP   r   r   r   r   r*   r   rN   todevicer   BCEWithLogitsLossrT   )rd   r   rg   r   rV   r|   r   r   rl   r   vision_outputsrW   rO   r   r   decoder_outputsrN   rU   loss_fns                      r-   rk   z#CLIPSegForImageSegmentation.forward)  s   b ]]_ 	-1F)*9TYY99 ))A N
 +88M*88M9=9L9LMA=Q/MKM 8"0"B"B,::,::)44	N	, ")%)%D%D'--a0#-))A &E &" &++A.,2D2DQ2GG m  &++A.$++2L2LL 0  '$,,"
 

 !''YYv}}-F**,G66*D-#9' .*
 	
[ N	 	s   AF# F/9F#F##F,)NNNNN)NNNNNNNT)r%   r&   r'   r2   rD   r   rB   rQ   ro   rR   r   r   r   
LongTensorrG   r   r   rC   rI   rk   rp   rq   s   @r-   r   r     s    }  "&)-.2,08<&$J& <<$&& t+	&
 llT)& #(,,"5& 
		&:  /315=A;?.204*.)-n
$$t+n
 ''$.n
 #("3"3d":	n

 !& 1 1D 8n
 t+n
 &&-n
   4'n
 #'n
 +,n
 
	n
  n
r,   r   )r2   r#   r0   r   r   r   r   r   )Ar(   r   r   dataclassesr   typingr   rQ   huggingface_hub.dataclassesr   r    r   r   modeling_outputsr	   modeling_utilsr
   processing_utilsr   utilsr   r   r   utils.genericr   r   utils.output_capturingr   clip.configuration_clipr   r   r   clip.modeling_clipr   r   r   r   r   r   r   r   r   r   r    r#   r0   r2   rI   rM   rT   rf   rs   ru   rw   ry   r{   r   r   r   r   r   r   r   __all__r+   r,   r-   <module>r     s      !   .  & : - & D D I 5 R R    /0& &  1&( /0&* &  1&( /0+5J +5  1+5\	J 	 
<; <  <" 
_[ _  _6@2 @	. 		} 		 		* 	* > (0 ( (V	[ 	U3+ U3p/} /(Q Q@H[9 H[V 
X
"8 X

X
v	r,   