Ë
    ÛÓ^jËg  ã                   ó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d8¬9«       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<€N�D˜‘I  c¨3 h¡Ñ/Ó;Ø€J�ÓØ'(Ð Ó(Ø-0Ð˜u s™{Ó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\   … ñ	ð (,€FˆE×Ñ Ñ$Ó+Ø:>€M�5˜×*Ñ*¨CÐ/Ñ0°4Ñ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$   è ø€ Ò^È1¤Z°´;Ô%?�Q—Z‘Z”\ÀQÓFÑ^ùs   ‚,.)rC   Úvalues)Úselfs    r-   r_   z'CLIPSegImageSegmentationOutput.to_tuple¼   s   € ÜÑ^ÐPT×P[Ñ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Ñ
"Ó)Ø'+€FˆE×Ñ Ñ$Ó+Ø7;Ð˜E×-Ñ-°Ñ4Ó;Ø.2€M�5×$Ñ$ tÑ+Ó2Ø6:ÐÐ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^×YeÑYe÷ @ñ @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
        «      r¸t        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{®Gáz”?)Ú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	  € ô 	×%Ñ% d¨FÔ3Ø—‘×/Ñ/ˆÜ�fÔ3Ô4Ü�L‰L˜×/Ñ/×6Ñ6¸SÀfÈtÁmÕTÜ�L‰L˜×2Ñ2×9Ñ9ÀÈÐRVÉÕWÜ�J‰J�v×*Ñ*¬E¯L©L¸×9LÑ9L×9RÑ9RÐSUÑ9VÓ,W×,^Ñ,^Ð_fÓ,gÕhÜ˜Ô 7Õ8Ü�L‰L˜×/Ñ/°c¸v×?OÑ?OÐQUÑ?UÐX^Ñ?^Õ_Ü�L‰L˜×/Ñ/×6Ñ6¸F¿M¹M×<[Ñ<[Ð^dÑ<dÕeÜ�L‰L˜×2Ñ2×9Ñ9¸v¿}¹}×?^Ñ?^ÐagÑ?gÕhÜ�J‰J�v×*Ñ*¬E¯L©L¸×9MÑ9MÓ,N×,UÑ,UÐV]Ó,^Õ_Ü˜Ô 0Ô1Ø!×+Ñ+¨TÑ1°q¸6¿=¹=×;ZÑ;ZÑ7ZÐ_cÑ6cÑdÐgmÑmˆKØ"×,Ñ,¨dÑ2°fÑ<ˆLÜ�L‰L˜Ÿ™×-Ñ-°;Õ?Ü�L‰L˜Ÿ™×-Ñ-°;Õ?Ü�L‰L˜Ÿ™×-Ñ-°;Õ?Ü�L‰L˜Ÿ™×/Ñ/°\ÖBÜ˜¤
Ô+Ø!Ÿ=™=×4Ñ4°dÑ:ÀÀFÇMÁM×DcÑDcÑ@cÐhlÑ?lÑmÐpvÑvˆKØ˜&Ÿ-™-×3Ñ3Ñ3¸Ñ<¸vÑEˆFÜ�L‰L˜Ÿ™×*Ñ*°Õ7Ü�L‰L˜Ÿ™×*Ñ*°Ö<Ü˜¤Ô-Ü�L‰LØ×&Ñ&×-Ñ-Ø×)Ñ)¨4Ñ/°&Ñ8õô �L‰LØ×(Ñ(×/Ñ/Ø×+Ñ+¨TÑ1°FÑ:öð .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¸×9JÑ9JÓKˆŒÜŸ	™	 &×"7Ñ"7¸×9JÑ9JÓKˆŒà×4Ò4Ø"(×"6Ñ"6×"AÑ"AÀQÑ"FÈ×H\ÑH\×HgÑHgÐklÑHlÐ!mÐä*,¯-©-Ü—	‘	˜&×+Ñ+¨V×->Ñ->ÈAÐWXÔYÜ—‘“	Ü×"Ñ"Ø×%Ñ%Ø×%Ñ%¨Ñ*Ø 2°1Ñ 5Ø-¨aÑ0ô	ô —‘“	Ü×"Ñ"Ø×%Ñ%¨Ñ*¨AÐ;MÈaÑ;PÐYkÐlmÑYnôó+ˆDÕ'ô +-×*<Ñ*<Ø×!Ñ! 1 f×&:Ñ&:×&EÑ&EÈf×NbÑNb×NmÑNmô+ˆDÔ'ô �F×)Ñ)Ó*ˆÜ—}‘}ÜUZÐ[`ÓUaÖbÐPQŒR�Y‰Y�v×+Ñ+×7Ñ7¸×9JÑ9JÕKÒbó
ˆŒô Ÿ™ v×';Ñ';Ó<ˆØ%+×%6Ñ%6ˆÔ"Ø-3×-OÑ-OˆÔ*Ø+1×+KÑ+KˆÔ(Ø$*ˆÔ!Ü—m‘mÔRWÔX[Ð\b×\qÑ\qÓXrÓRsÖ$tÈQÔ%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  € ð $¡D b DÑ)ˆàˆÜ.7¼¸KÈÏÉÐVZ×VbÑVbÓ8cÓ.dò 	BÑ*ˆAÑ*�
˜E 6ØÐ!Ù 
Ó+¨fÑ4‘á 
Ó+�à�D×*Ñ*Ò*ØŸ™Ð'=Ó>ÀÇÁÐPQÐSTÐVWÓAXÑXÐ[_×[hÑ[hØ*ó\ñ �ð  Ÿ™¨¨1¨aÓ0�á˜6ÑA°$ÐA¸&ÑA‰Fð	Bð š˜1™2šq˜Ñ!×+Ñ+¨A¨qÓ1ˆä”4—9‘9˜VŸ\™\¨!™_Ó-Ó.ˆà+×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 	‰‰ÑZÐ1IÐ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Ñ)EÐF^Ó)_×)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 �]‰]‹_ñ 	Ø-1ˆFÐ)Ñ*Ø9˜TŸY™Y×9Ñ9ð Ø)Ø)Añð ñˆNð
 +×8Ñ8ˆMà*×8Ñ8ˆMà9=×9LÑ9LÖM°A˜=¨¨Q©Ó/ÐMˆKÐMô 8Ø"0×"BÑ"BØ,×:Ñ:Ø,×:Ñ:Ø)×4Ñ4ô	ˆN÷	ð, "Ð)Ø%)×%DÑ%DØ'×-Ñ-¨aÑ0Ø#Ø-Ø)Ø)Að &Eó &Ñ"ð &×+Ñ+¨AÑ.°,×2DÑ2DÀQÑ2GÒGÜ Ømóð ð &×+Ñ+¨AÑ.°$·+±+×2LÑ2LÒLÜ ð0óð ð '˜$Ÿ,™,ØØ"ñ
ð ñ
ˆð
 !×'Ñ'ˆàˆØÐà—Y‘Y˜vŸ}™}Ó-ˆFÜ×*Ñ*Ó,ˆGÙ˜6 6Ó*ˆ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Ø,0Ø8<ñ&à˜$‘Jð&ð —<‘< $Ñ&ð&ð Ÿ™ tÑ+ð	&ð
 —l‘l TÑ)ð&ð #(§,¡,°Ñ"5ð&ð 
×	Ñ	ó&ð: Øð /3Ø15Ø=AØ;?Ø.2Ø04Ø*.Ø)-ñn
à×$Ñ$ tÑ+ðn
ð ×'Ñ'¨$Ñ.ðn
ð #(×"3Ñ"3°dÑ":ð	n
ð
 !&× 1Ñ 1°DÑ 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Øô+5�Jó +5ó ó 1ð+5ô\	�Jô 	ð Ø
ô<˜;ó <ó ó ð<ð" Ø
ô_ [ó _ó ó ð_ô6@Ð2ô @ô	Ð.ô 	ô	�}ô 	ô	�ô 	ô	Ð*ô 	ôÐ*ô ð> ô(Ð0ó (ó ð(ôV	�[ô 	ôU3Ð+ô U3ôp/�}ô /ô(Q˜ô Qô@H[�9ô H[ñV ðôô
X
Ð"8ó X
óð
X
òv	�r,   