a
    d7Q                     @   s   d Z ddlZddlZddlmZ ddlmZmZmZm	Z	m
Z
 erXddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ eeZddiZG dd deZG dd deZG dd deZG dd deZdS )z CLIP model configuration    NOrderedDict)TYPE_CHECKINGAnyMappingOptionalUnion   )ProcessorMixin)
TensorType)PretrainedConfig)
OnnxConfig)loggingzopenai/clip-vit-base-patch32zLhttps://huggingface.co/openai/clip-vit-base-patch32/resolve/main/config.jsonc                       sD   e Zd ZdZdZd fdd	Zeeee	j
f ddddZ  ZS )CLIPTextConfiga  
    This is the configuration class to store the configuration of a [`CLIPTextModel`]. It is used to instantiate a CLIP
    text encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
    with the defaults will yield a similar configuration to that of the text encoder of the CLIP
    [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        vocab_size (`int`, *optional*, defaults to 49408):
            Vocabulary size of the CLIP text model. Defines the number of different tokens that can be represented by
            the `inputs_ids` passed when calling [`CLIPModel`].
        hidden_size (`int`, *optional*, defaults to 512):
            Dimensionality of the encoder layers and the pooler layer.
        intermediate_size (`int`, *optional*, defaults to 2048):
            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        num_hidden_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 8):
            Number of attention heads for each attention layer in the Transformer encoder.
        max_position_embeddings (`int`, *optional*, defaults to 77):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
        layer_norm_eps (`float`, *optional*, defaults to 1e-5):
            The epsilon used by the layer normalization layers.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        initializer_factor (`float`, *optional*, defaults to 1):
            A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
            testing).

    Example:

    ```python
    >>> from transformers import CLIPTextConfig, CLIPTextModel

    >>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration
    >>> configuration = CLIPTextConfig()

    >>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
    >>> model = CLIPTextModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```Zclip_text_model               M   
quick_geluh㈵>        {Gz?      ?   r      c                    sf   t  jf |||d| || _|| _|| _|| _|| _|| _|| _|	| _	|| _
|| _|| _|
| _d S )N)pad_token_idbos_token_ideos_token_id)super__init__
vocab_sizehidden_sizeintermediate_sizeprojection_dimnum_hidden_layersnum_attention_headsmax_position_embeddingslayer_norm_eps
hidden_actinitializer_rangeinitializer_factorattention_dropout)selfr"   r#   r$   r%   r&   r'   r(   r*   r)   r-   r+   r,   r   r   r   kwargs	__class__ t/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/models/clip/configuration_clip.pyr!   ^   s    zCLIPTextConfig.__init__r   pretrained_model_name_or_pathreturnc                 K   s|   | j |fi |\}}|ddkr,|d }d|v rjt| drj|d | jkrjtd|d  d| j d | j|fi |S )N
model_typecliptext_configYou are using a model of type   to instantiate a model of type N. This is not supported for all configurations of models and can yield errors.Zget_config_dictgethasattrr7   loggerwarning	from_dictclsr5   r/   Zconfig_dictr2   r2   r3   from_pretrained   s     zCLIPTextConfig.from_pretrained)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __name__
__module____qualname____doc__r7   r!   classmethodr   strosPathLikerE   __classcell__r2   r2   r0   r3   r   (   s(   3               "r   c                       sD   e Zd ZdZdZd fdd	Zeeee	j
f ddddZ  ZS )CLIPVisionConfiga  
    This is the configuration class to store the configuration of a [`CLIPVisionModel`]. It is used to instantiate a
    CLIP vision encoder according to the specified arguments, defining the model architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of the vision encoder of the CLIP
    [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        hidden_size (`int`, *optional*, defaults to 768):
            Dimensionality of the encoder layers and the pooler layer.
        intermediate_size (`int`, *optional*, defaults to 3072):
            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        num_hidden_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 12):
            Number of attention heads for each attention layer in the Transformer encoder.
        image_size (`int`, *optional*, defaults to 224):
            The size (resolution) of each image.
        patch_size (`int`, *optional*, defaults to 32):
            The size (resolution) of each patch.
        hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
        layer_norm_eps (`float`, *optional*, defaults to 1e-5):
            The epsilon used by the layer normalization layers.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        initializer_factor (`float`, *optional*, defaults to 1):
            A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
            testing).

    Example:

    ```python
    >>> from transformers import CLIPVisionConfig, CLIPVisionModel

    >>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
    >>> configuration = CLIPVisionConfig()

    >>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
    >>> model = CLIPVisionModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```Zclip_vision_model      r   r   r	          r   r   r   r   r   c                    sd   t  jf i | || _|| _|| _|| _|| _|| _|| _|| _	|| _
|| _|| _|
| _|	| _d S )N)r    r!   r#   r$   r%   r&   r'   num_channels
patch_size
image_sizer+   r,   r-   r)   r*   )r.   r#   r$   r%   r&   r'   rU   rW   rV   r*   r)   r-   r+   r,   r/   r0   r2   r3   r!      s    zCLIPVisionConfig.__init__r   r4   c                 K   s|   | j |fi |\}}|ddkr,|d }d|v rjt| drj|d | jkrjtd|d  d| j d | j|fi |S )Nr7   r8   vision_configr:   r;   r<   r=   rC   r2   r2   r3   rE      s     z CLIPVisionConfig.from_pretrained)rQ   rR   r   r   r   r	   rS   rT   r   r   r   r   r   rF   r2   r2   r0   r3   rP      s$   2             !rP   c                       sF   e Zd ZdZdZdZd fdd	Zeee	d	d
dZ
dd Z  ZS )
CLIPConfigaL  
    [`CLIPConfig`] is the configuration class to store the configuration of a [`CLIPModel`]. It is used to instantiate
    a CLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
    a configuration with the defaults will yield a similar configuration to that of the CLIP
    [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        text_config (`dict`, *optional*):
            Dictionary of configuration options used to initialize [`CLIPTextConfig`].
        vision_config (`dict`, *optional*):
            Dictionary of configuration options used to initialize [`CLIPVisionConfig`].
        projection_dim (`int`, *optional*, defaults to 512):
            Dimentionality of text and vision projection layers.
        logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
            The inital value of the *logit_scale* paramter. Default is used as per the original CLIP implementation.
        kwargs (*optional*):
            Dictionary of keyword arguments.

    Example:

    ```python
    >>> from transformers import CLIPConfig, CLIPModel

    >>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration
    >>> configuration = CLIPConfig()

    >>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
    >>> model = CLIPModel(configuration)

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

    >>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig
    >>> from transformers import CLIPTextConfig, CLIPVisionConfig

    >>> # Initializing a CLIPText and CLIPVision configuration
    >>> config_text = CLIPTextConfig()
    >>> config_vision = CLIPVisionConfig()

    >>> config = CLIPConfig.from_text_vision_configs(config_text, config_vision)
    ```r8   TNr   /L
F@c                    s  | dd }| dd }t jf i | |d ur|d u r>i }tf i | }| D ]V\}	}
|	|v rX|
||	 krX|	dvrX|	|v rd|	 d|	 d}nd|	 d}t| qX|| |d urz|d u ri }t	f i | }d	|v rd
d |d	  D |d	< | D ]`\}	}
|	|v r|
||	 kr|	dvr|	|v rVd|	 d|	 d}nd|	 d}t| q|| |d u ri }t
d |d u ri }t
d tf i || _t	f i || _|| _|| _d| _d S )Ntext_config_dictvision_config_dict)Ztransformers_version`zp` is found in both `text_config_dict` and `text_config` but with different values. The value `text_config_dict["z"]` will be used instead.zj`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The value `text_config["z"]` will be overriden.Zid2labelc                 S   s   i | ]\}}t ||qS r2   )rL   ).0keyvaluer2   r2   r3   
<dictcomp>Z  s   z'CLIPConfig.__init__.<locals>.<dictcomp>zv` is found in both `vision_config_dict` and `vision_config` but with different values. The value `vision_config_dict["zp`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. The value `vision_config["zO`text_config` is `None`. Initializing the `CLIPTextConfig` with default values.zS`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values.r   )popr    r!   r   to_dictitemsr@   rA   updaterP   infor9   rX   r%   logit_scale_init_valuer,   )r.   r9   rX   r%   rg   r/   r[   r\   Z_text_config_dictr_   r`   messageZ_vision_config_dictr0   r2   r3   r!   )  sh    




"





zCLIPConfig.__init__r9   rX   c                 K   s   | f |  |  d|S )z
        Instantiate a [`CLIPConfig`] (or a derived class) from clip text model configuration and clip vision model
        configuration.

        Returns:
            [`CLIPConfig`]: An instance of a configuration object
        ri   )rc   )rD   r9   rX   r/   r2   r2   r3   from_text_vision_configs  s    
z#CLIPConfig.from_text_vision_configsc                 C   s8   t | j}| j |d< | j |d< | jj|d< |S )z
        Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].

        Returns:
            `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
        r9   rX   r7   )copydeepcopy__dict__r9   rc   rX   r1   r7   )r.   outputr2   r2   r3   rc     s
    zCLIPConfig.to_dict)NNr   rZ   )rG   rH   rI   rJ   r7   Zis_compositionr!   rK   r   rP   rj   rc   rO   r2   r2   r0   r3   rY      s   - XrY   c                       s   e Zd Zeeeeeef f dddZeeeeeef f dddZee	dddZ
dd
eeed eeef d fddZeedddZ  ZS )CLIPOnnxConfig)r6   c                 C   s0   t ddddfdddddd	fd
dddfgS )NZ	input_idsbatchsequence)r   r   Zpixel_valuesrU   heightwidth)r   r   r   r	   Zattention_maskr   r.   r2   r2   r3   inputs  s    zCLIPOnnxConfig.inputsc                 C   s0   t dddifdddifdddifdddifgS )NZlogits_per_imager   rp   Zlogits_per_textZtext_embedsZimage_embedsr   rt   r2   r2   r3   outputs  s    



zCLIPOnnxConfig.outputsc                 C   s   dS )Ng-C6?r2   rt   r2   r2   r3   atol_for_validation  s    z"CLIPOnnxConfig.atol_for_validationNr
   r   )	processor
batch_size
seq_length	frameworkr6   c                    s6   t  j|j|||d}t  j|j||d}i ||S )N)rz   r{   r|   )rz   r|   )r    generate_dummy_inputs	tokenizerZfeature_extractor)r.   ry   rz   r{   r|   Ztext_input_dictZimage_input_dictr0   r2   r3   r}     s    
z$CLIPOnnxConfig.generate_dummy_inputsc                 C   s   dS )N   r2   rt   r2   r2   r3   default_onnx_opset  s    z!CLIPOnnxConfig.default_onnx_opset)rx   rx   N)rG   rH   rI   propertyr   rL   intru   rv   floatrw   r   r   r}   r   rO   r2   r2   r0   r3   ro     s$    	 
   
ro   )rJ   rk   rM   collectionsr   typingr   r   r   r   r   Zprocessing_utilsr
   utilsr   Zconfiguration_utilsr   Zonnxr   r   Z
get_loggerrG   r@   Z"CLIP_PRETRAINED_CONFIG_ARCHIVE_MAPr   rP   rY   ro   r2   r2   r2   r3   <module>   s$   
ig $