




'''simple docstring'''

import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)


def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase=False      )						->   Union[str, Any]:

					'''simple docstring'''

					try:
										snake_case_		     =							os.environ[key]
					except KeyError:
										# KEY isn't set, default to `default`.
										snake_case_		     =							default
					else:
										# KEY is set, convert it to True or False.
										try:
															snake_case_		     =							strtobool(__UpperCAmelCase      )
										except ValueError:
															# More values are supported, but let's keep the message simple.
															raise ValueError(F"If set, {key} must be yes or no."      )
					return _value


a    :							Optional[int]										=    parse_flag_from_env('RUN_SLOW', default=False)


def 						__magic_name__       (      __UpperCAmelCase      )						->   Optional[int]:

					'''simple docstring'''

					return unittest.skip('''Test was skipped'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Optional[Any]:

					'''simple docstring'''

					return unittest.skipUnless(_run_slow_tests, '''test is slow'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   List[str]:

					'''simple docstring'''

					return unittest.skipUnless(not torch.cuda.is_available(), '''test requires only a CPU'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Tuple:

					'''simple docstring'''

					return unittest.skipUnless(torch.cuda.is_available(), '''test requires a GPU'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   List[Any]:

					'''simple docstring'''

					return unittest.skipUnless(is_xpu_available(), '''test requires a XPU'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   str:

					'''simple docstring'''

					return unittest.skipUnless(is_mps_available(), '''test requires a `mps` backend support in `torch`'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   List[str]:

					'''simple docstring'''

					return unittest.skipUnless(
					    is_transformers_available() and is_datasets_available(), '''test requires the Hugging Face suite'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Optional[Any]:

					'''simple docstring'''

					return unittest.skipUnless(is_bnb_available(), '''test requires the bitsandbytes library'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Optional[Any]:

					'''simple docstring'''

					return unittest.skipUnless(is_tpu_available(), '''test requires TPU'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   int:

					'''simple docstring'''

					return unittest.skipUnless(torch.cuda.device_count() == 1, '''test requires a GPU'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Tuple:

					'''simple docstring'''

					return unittest.skipUnless(torch.xpu.device_count() == 1, '''test requires a XPU'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   List[str]:

					'''simple docstring'''

					return unittest.skipUnless(torch.cuda.device_count() > 1, '''test requires multiple GPUs'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Optional[int]:

					'''simple docstring'''

					return unittest.skipUnless(torch.xpu.device_count() > 1, '''test requires multiple XPUs'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Union[str, Any]:

					'''simple docstring'''

					return unittest.skipUnless(is_safetensors_available(), '''test requires safetensors'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   List[str]:

					'''simple docstring'''

					return unittest.skipUnless(is_deepspeed_available(), '''test requires DeepSpeed'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Tuple:

					'''simple docstring'''

					return unittest.skipUnless(is_torch_version('''>=''', '''1.12.0'''      ), '''test requires torch version >= 1.12.0'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase=None, __UpperCAmelCase=None      )						->   List[str]:

					'''simple docstring'''

					if test_case is None:
										return partial(__UpperCAmelCase, version=__UpperCAmelCase      )
					return unittest.skipUnless(is_torch_version('''>=''', __UpperCAmelCase      ), F"test requires torch version >= {version}"      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   List[Any]:

					'''simple docstring'''

					return unittest.skipUnless(is_tensorboard_available(), '''test requires Tensorboard'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Optional[int]:

					'''simple docstring'''

					return unittest.skipUnless(is_wandb_available(), '''test requires wandb'''      )(__UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase      )						->   Any:

					'''simple docstring'''

					return unittest.skipUnless(is_comet_ml_available(), '''test requires comet_ml'''      )(__UpperCAmelCase      )


a    :							List[Any]										=    (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)


def 						__magic_name__       (      __UpperCAmelCase      )						->   Tuple:

					'''simple docstring'''

					return unittest.skipUnless(
					    _atleast_one_tracker_available, '''test requires at least one tracker to be available and for `comet_ml` to not be installed''', )(__UpperCAmelCase      )






class 		a							(  unittest.TestCase	):
				snake_case_           =						True


				@classmethod
				def     A_					(						cls       :   Union[str, Any]   ):
									snake_case_		     =							tempfile.mkdtemp()


				@classmethod
				def     A_					(						cls       :   Tuple   ):
									if os.path.exists(cls.tmpdir   ):
														shutil.rmtree(cls.tmpdir   )


				def     A_					(						self       :   str   ):
									if self.clear_on_setup:
														for path in Path(self.tmpdir   ).glob('''**/*'''   ):
																			if path.is_file():
																								path.unlink()
																			elif path.is_dir():
																								shutil.rmtree(lowercase_   )







class 		a							(  unittest.TestCase	):


				def     A_					(						self       :   int   ):
									super().tearDown()
									# Reset the state of the AcceleratorState singleton.
									AcceleratorState._reset_state()
									PartialState._reset_state()







class 		a							(  unittest.TestCase	):


				def     A_					(						self       :   List[Any]			,							lowercase_       :   Union[mock.Mock, List[mock.Mock]]   ):
									snake_case_		     =							mocks if isinstance(lowercase_			,							(tuple, list)   ) else [mocks]
									for m in self.mocks:
														m.start()
														self.addCleanup(m.stop   )







def 						__magic_name__       (      __UpperCAmelCase      )						->   Optional[int]:

					'''simple docstring'''

					snake_case_		     =							AcceleratorState()
					snake_case_		     =							tensor[None].clone().to(state.device      )
					snake_case_		     =							gather(__UpperCAmelCase      ).cpu()
					snake_case_		     =							tensor[0].cpu()
					for i in range(tensors.shape[0]      ):
										if not torch.equal(tensors[i], __UpperCAmelCase      ):
															return False
					return True






class 		a							:


				def __init__(						self       :   Tuple			,							lowercase_       :   str			,							lowercase_       :   Dict			,							lowercase_       :   str   ):
									snake_case_		     =							returncode
									snake_case_		     =							stdout
									snake_case_		     =							stderr







async def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase      )						->   Optional[Any]:

					'''simple docstring'''

					while True:
										snake_case_		     =							await stream.readline()
										if line:
															callback(__UpperCAmelCase      )
										else:
															break


async def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase=None, __UpperCAmelCase=None, __UpperCAmelCase=None, __UpperCAmelCase=False, __UpperCAmelCase=False      )						->   _RunOutput:

					'''simple docstring'''

					if echo:
										print('''\nRunning: ''', ''' '''.join(__UpperCAmelCase      )      )

					snake_case_		     =							await asyncio.create_subprocess_exec(
					    cmd[0], *cmd[1:], stdin=__UpperCAmelCase, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=__UpperCAmelCase, )

					# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
					# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
					#
					# If it starts hanging, will need to switch to the following code. The problem is that no data
					# will be seen until it's done and if it hangs for example there will be no debug info.
					# out, err = await p.communicate()
					# return _RunOutput(p.returncode, out, err)

					snake_case_		     =							[]
					snake_case_		     =							[]

					def tee(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase=""      ):
										snake_case_		     =							line.decode('''utf-8'''      ).rstrip()
										sink.append(__UpperCAmelCase      )
										if not quiet:
															print(__UpperCAmelCase, __UpperCAmelCase, file=__UpperCAmelCase      )

    # XXX: the timeout doesn't seem to make any difference here
					await asyncio.wait(
					    [
					        asyncio.create_task(_read_stream(p.stdout, lambda __UpperCAmelCase      : tee(__UpperCAmelCase, __UpperCAmelCase, sys.stdout, label='''stdout:'''      )      )      ),
					        asyncio.create_task(_read_stream(p.stderr, lambda __UpperCAmelCase      : tee(__UpperCAmelCase, __UpperCAmelCase, sys.stderr, label='''stderr:'''      )      )      ),
					    ], timeout=__UpperCAmelCase, )
					return _RunOutput(await p.wait(), __UpperCAmelCase, __UpperCAmelCase      )


def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase=None, __UpperCAmelCase=None, __UpperCAmelCase=180, __UpperCAmelCase=False, __UpperCAmelCase=True      )						->   _RunOutput:

					'''simple docstring'''

					snake_case_		     =							asyncio.get_event_loop()
					snake_case_		     =							loop.run_until_complete(
					    _stream_subprocess(__UpperCAmelCase, env=__UpperCAmelCase, stdin=__UpperCAmelCase, timeout=__UpperCAmelCase, quiet=__UpperCAmelCase, echo=__UpperCAmelCase      )      )

					snake_case_		     =							''' '''.join(__UpperCAmelCase      )
					if result.returncode > 0:
										snake_case_		     =							'''\n'''.join(result.stderr      )
										raise RuntimeError(
										    F"'{cmd_str}' failed with returncode {result.returncode}\n\n"
										    F"The combined stderr from workers follows:\n{stderr}"      )

					return result






class 		a							(  _lowerCamelCase	):
				pass







def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase=False      )						->   Tuple:

					'''simple docstring'''

					try:
										snake_case_		     =							subprocess.check_output(__UpperCAmelCase, stderr=subprocess.STDOUT      )
										if return_stdout:
															if hasattr(__UpperCAmelCase, '''decode'''      ):
																				snake_case_		     =							output.decode('''utf-8'''      )
															return output
					except subprocess.CalledProcessError as e:
										raise SubprocessCallException(
										    F"Command `{' '.join(__UpperCAmelCase      )}` failed with the following error:\n\n{e.output.decode()}"      ) from e







'''simple docstring'''

import argparse

import requests
import torch
from PIL import Image

from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel


def 						__magic_name__       (      __UpperCAmelCase      )						->   str:

					'''simple docstring'''

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

					return name


def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase      )						->   Dict:

					'''simple docstring'''

					for key in orig_state_dict.copy().keys():
										snake_case_		     =							orig_state_dict.pop(__UpperCAmelCase      )

										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
															snake_case_		     =							key.split('''.'''      )
															snake_case_     ,snake_case_		     =							int(key_split[2]      ), int(key_split[4]      )
															snake_case_		     =							config.vision_config.hidden_size
															if "weight" in key:
																				snake_case_		     =							val[:dim, :]
																				snake_case_		     =							val[dim : dim * 2, :]
																				snake_case_		     =							val[-dim:, :]
															else:
																				snake_case_		     =							val[:dim]
																				snake_case_		     =							val[dim : dim * 2]
																				snake_case_		     =							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
															snake_case_		     =							key.split('''.'''      )
															snake_case_		     =							int(key_split[3]      )
															snake_case_		     =							config.text_config.hidden_size
															if "weight" in key:
																				snake_case_		     =							val[:dim, :]
																				snake_case_		     =							val[
																				    dim : dim * 2, :
																				]
																				snake_case_		     =							val[-dim:, :]
															else:
																				snake_case_		     =							val[:dim]
																				snake_case_		     =							val[dim : dim * 2]
																				snake_case_		     =							val[-dim:]
										else:
															snake_case_		     =							rename_key(__UpperCAmelCase      )
															# 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
															):
																				snake_case_		     =							val.squeeze_()
															else:
																				snake_case_		     =							val

					return orig_state_dict


def 						__magic_name__       (      )						->   Union[str, Any]:

					'''simple docstring'''

					snake_case_		     =							'''http://images.cocodataset.org/val2017/000000039769.jpg'''
					snake_case_		     =							Image.open(requests.get(__UpperCAmelCase, stream=__UpperCAmelCase      ).raw      )
					return im


@torch.no_grad()
def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase="groupvit-gcc-yfcc", __UpperCAmelCase=False      )						->   List[str]:

					'''simple docstring'''

					snake_case_		     =							GroupViTConfig()
					snake_case_		     =							GroupViTModel(__UpperCAmelCase      ).eval()

					snake_case_		     =							torch.load(__UpperCAmelCase, map_location='''cpu'''      )['''model''']
					snake_case_		     =							convert_state_dict(__UpperCAmelCase, __UpperCAmelCase      )
					snake_case_     ,snake_case_		     =							model.load_state_dict(__UpperCAmelCase, strict=__UpperCAmelCase      )
					assert missing_keys == ["text_model.embeddings.position_ids"]
					assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(__UpperCAmelCase      ) == 0)

					# verify result
					snake_case_		     =							CLIPProcessor.from_pretrained('''openai/clip-vit-base-patch32'''      )
					snake_case_		     =							prepare_img()
					snake_case_		     =							processor(text=['''a photo of a cat''', '''a photo of a dog'''], images=__UpperCAmelCase, padding=__UpperCAmelCase, return_tensors='''pt'''      )

					with torch.no_grad():
										snake_case_		     =							model(**__UpperCAmelCase      )

					if model_name == "groupvit-gcc-yfcc":
										snake_case_		     =							torch.tensor([[1_3.3_5_2_3, 6.3_6_2_9]]      )
					elif model_name == "groupvit-gcc-redcaps":
										snake_case_		     =							torch.tensor([[1_6.1_8_7_3, 8.6_2_3_0]]      )
					else:
										raise ValueError(F"Model name {model_name} not supported."      )
					assert torch.allclose(outputs.logits_per_image, __UpperCAmelCase, atol=1e-3      )

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

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


if __name__ == "__main__":
							a    :							Optional[int]										=    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`.',
							)
							a    :							str										=    parser.parse_args()

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

