





"""simple docstring"""





import argparse

import requests
import torch
from PIL import Image

from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							if "img_encoder.pos_embed" in name:
														__lowerCamelCase      :      List[Any]         =name.replace('''img_encoder.pos_embed'''    ,						'''vision_model.embeddings.position_embeddings'''   )
							if "img_encoder.patch_embed.proj" in name:
														__lowerCamelCase      :      List[str]         =name.replace('''img_encoder.patch_embed.proj'''    ,						'''vision_model.embeddings.patch_embeddings.projection'''   )
							if "img_encoder.patch_embed.norm" in name:
														__lowerCamelCase      :      str         =name.replace('''img_encoder.patch_embed.norm'''    ,						'''vision_model.embeddings.layernorm'''   )
							if "img_encoder.layers" in name:
														__lowerCamelCase      :      Dict         =name.replace('''img_encoder.layers'''    ,						'''vision_model.encoder.stages'''   )
							if "blocks" in name and "res" not in name:
														__lowerCamelCase      :      Union[str, Any]         =name.replace('''blocks'''    ,						'''layers'''   )
							if "attn" in name and "pre_assign" not in name:
														__lowerCamelCase      :      Tuple         =name.replace('''attn'''    ,						'''self_attn'''   )
							if "proj" in name and "self_attn" in name and "text" not in name:
														__lowerCamelCase      :      Optional[Any]         =name.replace('''proj'''    ,						'''out_proj'''   )
							if "pre_assign_attn.attn.proj" in name:
														__lowerCamelCase      :      str         =name.replace('''pre_assign_attn.attn.proj'''    ,						'''pre_assign_attn.attn.out_proj'''   )
							if "norm1" in name:
														__lowerCamelCase      :      str         =name.replace('''norm1'''    ,						'''layer_norm1'''   )
							if "norm2" in name and "pre_assign" not in name:
														__lowerCamelCase      :      Dict         =name.replace('''norm2'''    ,						'''layer_norm2'''   )
							if "img_encoder.norm" in name:
														__lowerCamelCase      :      Optional[Any]         =name.replace('''img_encoder.norm'''    ,						'''vision_model.layernorm'''   )
							# text encoder
							if "text_encoder.token_embedding" in name:
														__lowerCamelCase      :      Union[str, Any]         =name.replace('''text_encoder.token_embedding'''    ,						'''text_model.embeddings.token_embedding'''   )
							if "text_encoder.positional_embedding" in name:
														__lowerCamelCase      :      int         =name.replace('''text_encoder.positional_embedding'''    ,						'''text_model.embeddings.position_embedding.weight'''   )
							if "text_encoder.transformer.resblocks." in name:
														__lowerCamelCase      :      Optional[Any]         =name.replace('''text_encoder.transformer.resblocks.'''    ,						'''text_model.encoder.layers.'''   )
							if "ln_1" in name:
														__lowerCamelCase      :      int         =name.replace('''ln_1'''    ,						'''layer_norm1'''   )
							if "ln_2" in name:
														__lowerCamelCase      :      List[Any]         =name.replace('''ln_2'''    ,						'''layer_norm2'''   )
							if "c_fc" in name:
														__lowerCamelCase      :      Dict         =name.replace('''c_fc'''    ,						'''fc1'''   )
							if "c_proj" in name:
														__lowerCamelCase      :      List[Any]         =name.replace('''c_proj'''    ,						'''fc2'''   )
							if "text_encoder" in name:
														__lowerCamelCase      :      Union[str, Any]         =name.replace('''text_encoder'''    ,						'''text_model'''   )
							if "ln_final" in name:
														__lowerCamelCase      :      Union[str, Any]         =name.replace('''ln_final'''    ,						'''final_layer_norm'''   )
							# projection layers
							if "img_projector.linear_hidden." in name:
														__lowerCamelCase      :      int         =name.replace('''img_projector.linear_hidden.'''    ,						'''visual_projection.'''   )
							if "img_projector.linear_out." in name:
														__lowerCamelCase      :      List[str]         =name.replace('''img_projector.linear_out.'''    ,						'''visual_projection.3.'''   )
							if "text_projector.linear_hidden" in name:
														__lowerCamelCase      :      Optional[Any]         =name.replace('''text_projector.linear_hidden'''    ,						'''text_projection'''   )
							if "text_projector.linear_out" in name:
														__lowerCamelCase      :      Optional[Any]         =name.replace('''text_projector.linear_out'''    ,						'''text_projection.3'''   )

							return name



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Tuple    ,						SCREAMING_SNAKE_CASE       :							List[Any]   ):


							'''simple docstring'''







							for key in orig_state_dict.copy().keys():
														__lowerCamelCase      :      List[str]         =orig_state_dict.pop(SCREAMING_SNAKE_CASE   )

														if "qkv" in key:
																					# weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment:
																					# we need to split them up into separate matrices/vectors
																					__lowerCamelCase      :      Union[str, Any]         =key.split('''.'''   )
																					__lowerCamelCase    ,						__lowerCamelCase      :      Any         =int(key_split[2]   ), int(key_split[4]   )
																					__lowerCamelCase      :      Any         =config.vision_config.hidden_size
																					if "weight" in key:
																												__lowerCamelCase      :      Dict         =val[:dim, :]
																												__lowerCamelCase      :      List[str]         =val[dim : dim * 2, :]
																												__lowerCamelCase      :      Optional[int]         =val[-dim:, :]
																					else:
																												__lowerCamelCase      :      int         =val[:dim]
																												__lowerCamelCase      :      Tuple         =val[dim : dim * 2]
																												__lowerCamelCase      :      Dict         =val[-dim:]
														elif "in_proj" in key:
																					# weights and biases of the key, value and query projections of text encoder's attention layers require special treatment:
																					# we need to split them up into separate matrices/vectors
																					__lowerCamelCase      :      Optional[Any]         =key.split('''.'''   )
																					__lowerCamelCase      :      Optional[int]         =int(key_split[3]   )
																					__lowerCamelCase      :      Any         =config.text_config.hidden_size
																					if "weight" in key:
																												__lowerCamelCase      :      int         =val[:dim, :]
																												__lowerCamelCase      :      Union[str, Any]         =val[
																												    dim : dim * 2, :
																												]
																												__lowerCamelCase      :      List[str]         =val[-dim:, :]
																					else:
																												__lowerCamelCase      :      Union[str, Any]         =val[:dim]
																												__lowerCamelCase      :      str         =val[dim : dim * 2]
																												__lowerCamelCase      :      int         =val[-dim:]
														else:
																					__lowerCamelCase      :      Union[str, Any]         =rename_key(SCREAMING_SNAKE_CASE   )
																					# squeeze if necessary
																					if (
																					    "text_projection.0" in new_name
																					    or "text_projection.3" in new_name
																					    or "visual_projection.0" in new_name
																					    or "visual_projection.3" in new_name
																					):
																												__lowerCamelCase      :      List[Any]         =val.squeeze_()
																					else:
																												__lowerCamelCase      :      str         =val

							return orig_state_dict



def 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							__lowerCamelCase      :      Optional[Any]         ='''http://images.cocodataset.org/val2017/000000039769.jpg'''
							__lowerCamelCase      :      Dict         =Image.open(requests.get(SCREAMING_SNAKE_CASE    ,						stream=SCREAMING_SNAKE_CASE   ).raw   )
							return im



@torch.no_grad()
def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							str    ,						SCREAMING_SNAKE_CASE       :							Union[str, Any]    ,						SCREAMING_SNAKE_CASE       :							Optional[Any]="groupvit-gcc-yfcc"    ,						SCREAMING_SNAKE_CASE       :							Any=False   ):


							'''simple docstring'''







							__lowerCamelCase      :      Optional[int]         =GroupViTConfig()
							__lowerCamelCase      :      List[str]         =GroupViTModel(SCREAMING_SNAKE_CASE   ).eval()

							__lowerCamelCase      :      Any         =torch.load(SCREAMING_SNAKE_CASE    ,						map_location='''cpu'''   )['''model''']
							__lowerCamelCase      :      Optional[int]         =convert_state_dict(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   )
							__lowerCamelCase    ,						__lowerCamelCase      :      Any         =model.load_state_dict(SCREAMING_SNAKE_CASE    ,						strict=SCREAMING_SNAKE_CASE   )
							assert missing_keys == ["text_model.embeddings.position_ids"]
							assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(SCREAMING_SNAKE_CASE   ) == 0)

							# verify result
							__lowerCamelCase      :      List[str]         =CLIPProcessor.from_pretrained('''openai/clip-vit-base-patch32'''   )
							__lowerCamelCase      :      Optional[int]         =prepare_img()
							__lowerCamelCase      :      Any         =processor(text=['''a photo of a cat''', '''a photo of a dog''']    ,						images=SCREAMING_SNAKE_CASE    ,						padding=SCREAMING_SNAKE_CASE    ,						return_tensors='''pt'''   )

							with torch.no_grad():
														__lowerCamelCase      :      List[Any]         =model(**SCREAMING_SNAKE_CASE   )

							if model_name == "groupvit-gcc-yfcc":
														__lowerCamelCase      :      str         =torch.tensor([[13.3_523, 6.3_629]]   )
							elif model_name == "groupvit-gcc-redcaps":
														__lowerCamelCase      :      str         =torch.tensor([[16.1_873, 8.6_230]]   )
							else:
														raise ValueError(F'Model name {model_name} not supported.'   )
							assert torch.allclose(outputs.logits_per_image    ,						SCREAMING_SNAKE_CASE    ,						atol=1E-3   )

							processor.save_pretrained(SCREAMING_SNAKE_CASE   )
							model.save_pretrained(SCREAMING_SNAKE_CASE   )
							print('''Successfully saved processor and model to'''    ,						SCREAMING_SNAKE_CASE   )

							if push_to_hub:
														print('''Pushing to the hub...'''   )
														processor.push_to_hub(SCREAMING_SNAKE_CASE    ,						organization='''nielsr'''   )
														model.push_to_hub(SCREAMING_SNAKE_CASE    ,						organization='''nielsr'''   )


if __name__ == "__main__":
							_UpperCamelCase							=      argparse.ArgumentParser()
							parser.add_argument(
							    '--pytorch_dump_folder_path', default=None, type=str, help='Path to dump the processor and PyTorch model.'
							)
							parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to GroupViT checkpoint')
							parser.add_argument(
							    '--model_name',
							    default='groupvit-gccy-fcc',
							    type=str,
							    help='Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'',
							)
							parser.add_argument(
							    '--push_to_hub',
							    action='store_true',
							    help='Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.',
							)
							_UpperCamelCase							=      parser.parse_args()

							convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)











"""simple docstring"""





from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_UpperCamelCase							=      logging.get_logger(__name__)

_UpperCamelCase							=      {
    'huggingface/time-series-transformer-tourism-monthly': (
        'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json'
    ),
    # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
}
class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
				"""simple docstring"""
				__snake_case   :       Union[str, Any]	 =		"""time_series_transformer"""
				__snake_case   :       Any	 =		{
				    """hidden_size""": """d_model""",
				    """num_attention_heads""": """encoder_attention_heads""",
				    """num_hidden_layers""": """encoder_layers""",
				}




				def __init__(     self  :List[Any]						,    __lowercase  :Optional[int] = None						,    __lowercase  :Optional[int] = None						,    __lowercase  :str = "student_t"						,    __lowercase  :str = "nll"						,    __lowercase  :int = 1						,    __lowercase  :List[int] = [1, 2, 3, 4, 5, 6, 7]						,    __lowercase  :Optional[Union[str, bool]] = "mean"						,    __lowercase  :int = 0						,    __lowercase  :int = 0						,    __lowercase  :int = 0						,    __lowercase  :int = 0						,    __lowercase  :Optional[List[int]] = None						,    __lowercase  :Optional[List[int]] = None						,    __lowercase  :int = 32						,    __lowercase  :int = 32						,    __lowercase  :int = 2						,    __lowercase  :int = 2						,    __lowercase  :int = 2						,    __lowercase  :int = 2						,    __lowercase  :bool = True						,    __lowercase  :str = "gelu"						,    __lowercase  :int = 64						,    __lowercase  :float = 0.1						,    __lowercase  :float = 0.1						,    __lowercase  :float = 0.1						,    __lowercase  :float = 0.1						,    __lowercase  :float = 0.1						,    __lowercase  :int = 100						,    __lowercase  :float = 0.02						,    __lowercase  :int=True						,    **__lowercase  :Optional[Any]						,    ):
											# time series specific configuration
											__lowerCamelCase      :      Tuple         =prediction_length
											__lowerCamelCase      :      List[Any]         =context_length or prediction_length
											__lowerCamelCase      :      Dict         =distribution_output
											__lowerCamelCase      :      str         =loss
											__lowerCamelCase      :      Tuple         =input_size
											__lowerCamelCase      :      int         =num_time_features
											__lowerCamelCase      :      int         =lags_sequence
											__lowerCamelCase      :      Optional[int]         =scaling
											__lowerCamelCase      :      str         =num_dynamic_real_features
											__lowerCamelCase      :      Optional[Any]         =num_static_real_features
											__lowerCamelCase      :      List[Any]         =num_static_categorical_features
											if cardinality and num_static_categorical_features > 0:
																		if len(__lowercase			) != num_static_categorical_features:
																									raise ValueError(
																									    '''The cardinality should be a list of the same length as `num_static_categorical_features`'''			)
																		__lowerCamelCase      :      Optional[int]         =cardinality
											else:
																		__lowerCamelCase      :      str         =[0]
											if embedding_dimension and num_static_categorical_features > 0:
																		if len(__lowercase			) != num_static_categorical_features:
																									raise ValueError(
																									    '''The embedding dimension should be a list of the same length as `num_static_categorical_features`'''			)
																		__lowerCamelCase      :      int         =embedding_dimension
											else:
																		__lowerCamelCase      :      Optional[int]         =[min(50						,    (cat + 1) // 2			) for cat in self.cardinality]
											__lowerCamelCase      :      List[str]         =num_parallel_samples

											# Transformer architecture configuration
											__lowerCamelCase      :      str         =input_size * len(__lowercase			) + self._number_of_features
											__lowerCamelCase      :      Union[str, Any]         =d_model
											__lowerCamelCase      :      int         =encoder_attention_heads
											__lowerCamelCase      :      int         =decoder_attention_heads
											__lowerCamelCase      :      Dict         =encoder_ffn_dim
											__lowerCamelCase      :      int         =decoder_ffn_dim
											__lowerCamelCase      :      List[Any]         =encoder_layers
											__lowerCamelCase      :      int         =decoder_layers

											__lowerCamelCase      :      Union[str, Any]         =dropout
											__lowerCamelCase      :      Optional[Any]         =attention_dropout
											__lowerCamelCase      :      List[str]         =activation_dropout
											__lowerCamelCase      :      List[str]         =encoder_layerdrop
											__lowerCamelCase      :      int         =decoder_layerdrop

											__lowerCamelCase      :      Tuple         =activation_function
											__lowerCamelCase      :      str         =init_std

											__lowerCamelCase      :      Dict         =use_cache

											super().__init__(is_encoder_decoder=__lowercase						,    **__lowercase			)




				@property
				def 					__lowercase  (     self  :int			):
											return (
											    sum(self.embedding_dimension			)
											    + self.num_dynamic_real_features
											    + self.num_time_features
											    + self.num_static_real_features
											    + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
											)




