U
    ,-exQ                     @   s   d Z ddlZddlmZ ddlmZmZmZmZm	Z	 ddl
mZ ddlmZ ddlmZ ertd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 GroupViT model configuration    NOrderedDict)TYPE_CHECKINGAnyMappingOptionalUnion   )PretrainedConfig)
OnnxConfig)logging)ProcessorMixin)
TensorTypeznvidia/groupvit-gcc-yfcczHhttps://huggingface.co/nvidia/groupvit-gcc-yfcc/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 )GroupViTTextConfiga?  
    This is the configuration class to store the configuration of a [`GroupViTTextModel`]. It is used to instantiate an
    GroupViT model according to the specified arguments, defining the model architecture. Instantiating a configuration
    with the defaults will yield a similar configuration to that of the GroupViT
    [nvidia/groupvit-gcc-yfcc](https://huggingface.co/nvidia/groupvit-gcc-yfcc) 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 GroupViT text model. Defines the number of different tokens that can be represented
            by the `inputs_ids` passed when calling [`GroupViTModel`].
        hidden_size (`int`, *optional*, defaults to 256):
            Dimensionality of the encoder layers and the pooler layer.
        intermediate_size (`int`, *optional*, defaults to 1024):
            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 4):
            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.
        dropout (`float`, *optional*, defaults to 0.0):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        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.0):
            A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
            testing).

    Example:

    ```python
    >>> from transformers import GroupViTTextConfig, GroupViTTextModel

    >>> # Initializing a GroupViTTextModel with nvidia/groupvit-gcc-yfcc style configuration
    >>> configuration = GroupViTTextConfig()

    >>> model = GroupViTTextModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```Zgroupvit_text_model               M   
quick_geluh㈵>        {Gz?      ?       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dropout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/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/groupvit/configuration_groupvit.pyr"   ]   s    zGroupViTTextConfig.__init__r
   pretrained_model_name_or_pathreturnc                 K   s~   |  | | j|f|\}}|ddkr2|d }d|krpt| drp|d | jkrptd|d  d| j d | j|f|S )N
model_typegroupvit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_set_token_in_kwargsZget_config_dictgethasattrr8   loggerwarning	from_dictclsr6   r0   Zconfig_dictr3   r3   r4   from_pretrained   s    
 z"GroupViTTextConfig.from_pretrained)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __name__
__module____qualname____doc__r8   r"   classmethodr   strosPathLikerF   __classcell__r3   r3   r1   r4   r   &   s(   4               "r   c                       s~   e Zd ZdZdZdddddgddd	d
gdd	d	gdddddddddddddgf fdd	Zeeee	j
f ddddZ  ZS )GroupViTVisionConfigaB  
    This is the configuration class to store the configuration of a [`GroupViTVisionModel`]. It is used to instantiate
    an GroupViT model according to the specified arguments, defining the model architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of the GroupViT
    [nvidia/groupvit-gcc-yfcc](https://huggingface.co/nvidia/groupvit-gcc-yfcc) 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 384):
            Dimensionality of the encoder layers and the pooler layer.
        intermediate_size (`int`, *optional*, defaults to 1536):
            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        depths (`List[int]`, *optional*, defaults to [6, 3, 3]):
            The number of layers in each encoder block.
        num_group_tokens (`List[int]`, *optional*, defaults to [64, 8, 0]):
            The number of group tokens for each stage.
        num_output_groups (`List[int]`, *optional*, defaults to [64, 8, 8]):
            The number of output groups for each stage, 0 means no group.
        num_attention_heads (`int`, *optional*, defaults to 6):
            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 16):
            The size (resolution) of each patch.
        hidden_act (`str` or `function`, *optional*, defaults to `"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.
        dropout (`float`, *optional*, defaults to 0.0):
            The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
        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.0):
            A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
            testing).

    Example:

    ```python
    >>> from transformers import GroupViTVisionConfig, GroupViTVisionModel

    >>> # Initializing a GroupViTVisionModel with nvidia/groupvit-gcc-yfcc style configuration
    >>> configuration = GroupViTVisionConfig()

    >>> model = GroupViTVisionModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```Zgroupvit_vision_modeli  i      r	   r   @      r         Zgelur   r   r   r   g      ?r   c                    s   t  jf | || _|| _|| _|t|krFtd| dt|  || _|| _	|| _
|| _|| _|	| _|
| _|| _|| _|| _|| _|| _|| _|| _|| _d S )Nz&Manually setting num_hidden_layers to z1, but we expect num_hidden_layers = sum(depth) = )r!   r"   r$   r%   depthssumrA   rB   r'   num_group_tokensnum_output_groupsr(   
image_size
patch_sizenum_channelsr+   r*   r&   r.   r,   r-   
assign_epsassign_mlp_ratio)r/   r$   r%   rW   r'   rY   rZ   r(   r[   r\   r]   r+   r*   r&   r.   r,   r-   r^   r_   r0   r1   r3   r4   r"      s.    zGroupViTVisionConfig.__init__r
   r5   c                 K   s~   |  | | j|f|\}}|ddkr2|d }d|krpt| drp|d | jkrptd|d  d| j d | j|f|S )Nr8   r9   vision_configr;   r<   r=   r>   rD   r3   r3   r4   rF      s    
 z$GroupViTVisionConfig.from_pretrainedrG   r3   r3   r1   r4   rQ      s.   70rQ   c                       s:   e Zd ZdZdZd fdd	Zeeed	d
dZ	  Z
S )GroupViTConfiga  
    [`GroupViTConfig`] is the configuration class to store the configuration of a [`GroupViTModel`]. It is used to
    instantiate a GroupViT 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 GroupViT
    [nvidia/groupvit-gcc-yfcc](https://huggingface.co/nvidia/groupvit-gcc-yfcc) 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 [`GroupViTTextConfig`].
        vision_config (`dict`, *optional*):
            Dictionary of configuration options used to initialize [`GroupViTVisionConfig`].
        projection_dim (`int`, *optional*, defaults to 256):
            Dimentionality of text and vision projection layers.
        projection_intermediate_dim (`int`, *optional*, defaults to 4096):
            Dimentionality of intermediate layer of text and vision projection layers.
        logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
            The inital value of the *logit_scale* parameter. Default is used as per the original GroupViT
            implementation.
        kwargs (*optional*):
            Dictionary of keyword arguments.
    r9   Nr      /L
F@c                    s  | dd }| dd }t jf | |d k	r|d kr:i }tf | }	|	 D ]V\}
}|
|krP|||
 krP|
dkrP|
|krd|
 d|
 d}nd|
 d}t| qP||	 |d k	rl|d kri }t	f | }d	|krd
d |d	  D |d	< | D ]`\}
}|
|kr |||
 kr |
dkr |
|krHd|
 d|
 d}nd|
 d}t| q || |d kri }t
d |d kri }t
d tf || _t	f || _|| _|| _|| _d| _d| _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.zn`text_config_dict` is provided which will be used to initialize `GroupViTTextConfig`. The value `text_config["z"]` will be overriden.Zid2labelc                 S   s   i | ]\}}t ||qS r3   )rM   ).0keyvaluer3   r3   r4   
<dictcomp>b  s     z+GroupViTConfig.__init__.<locals>.<dictcomp>zv` is found in both `vision_config_dict` and `vision_config` but with different values. The value `vision_config_dict["zt`vision_config_dict` is provided which will be used to initialize `GroupViTVisionConfig`. The value `vision_config["zS`text_config` is `None`. Initializing the `GroupViTTextConfig` with default values.zW`vision_config` is `None`. initializing the `GroupViTVisionConfig` with default values.r   r   F)popr!   r"   r   to_dictitemsrA   rB   updaterQ   infor:   r`   projection_dimprojection_intermediate_dimlogit_scale_init_valuer,   r-   Zoutput_segmentation)r/   r:   r`   rp   rq   rr   r0   rd   re   Z_text_config_dictrh   ri   messageZ_vision_config_dictr1   r3   r4   r"   +  s^    




"






zGroupViTConfig.__init__r:   r`   c                 K   s   | f |  |  d|S )z
        Instantiate a [`GroupViTConfig`] (or a derived class) from groupvit text model configuration and groupvit
        vision model configuration.

        Returns:
            [`GroupViTConfig`]: An instance of a configuration object
        rt   )rl   )rE   r:   r`   r0   r3   r3   r4   from_text_vision_configs  s    
z'GroupViTConfig.from_text_vision_configs)NNr   rb   rc   )rH   rI   rJ   rK   r8   r"   rL   r   rQ   ru   rP   r3   r3   r1   r4   ra     s        ara   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 )GroupViTOnnxConfig)r7   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_valuesr]   heightwidth)r   r      r	   Zattention_maskr   r/   r3   r3   r4   inputs  s    zGroupViTOnnxConfig.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   rw   Zlogits_per_textZtext_embedsZimage_embedsr   r|   r3   r3   r4   outputs  s    



zGroupViTOnnxConfig.outputsc                 C   s   dS )Ng-C6?r3   r|   r3   r3   r4   atol_for_validation  s    z&GroupViTOnnxConfig.atol_for_validationNr   r   )	processor
batch_size
seq_length	frameworkr7   c                    s2   t  j|j|||d}t  j|j||d}||S )N)r   r   r   )r   r   )r!   generate_dummy_inputsZ	tokenizerZimage_processor)r/   r   r   r   r   Ztext_input_dictZimage_input_dictr1   r3   r4   r     s         z(GroupViTOnnxConfig.generate_dummy_inputsc                 C   s   dS )N   r3   r|   r3   r3   r4   default_onnx_opset  s    z%GroupViTOnnxConfig.default_onnx_opset)r   r   N)rH   rI   rJ   propertyr   rM   intr}   r~   floatr   r   r   r   r   rP   r3   r3   r1   r4   rv     s$    	 
   
rv   )rK   rN   collectionsr   typingr   r   r   r   r   Zconfiguration_utilsr
   Zonnxr   utilsr   Zprocessing_utilsr   r   Z
get_loggerrH   rA   Z&GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAPr   rQ   ra   rv   r3   r3   r3   r4   <module>   s$   
 l} 