
"""simple docstring"""





import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from timm import create_model
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform

from transformers import BitConfig, BitForImageClassification, BitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging


logging.set_verbosity_info()
UpperCamelCase_					:						int				= logging.get_logger(__name__)
def 							A_     (__a				):

					'''simple docstring'''





					A_				 =						"huggingface/label-files"
					A_				 =						"imagenet-1k-id2label.json"
					A_				 =						json.load(open(hf_hub_download(__a				,   __a				,   repo_type="dataset"				)				,   "r"				)				)
					A_				 =						{int(__a				): v for k, v in idalabel.items()}
					A_				 =						{v: k for k, v in idalabel.items()}

					A_				 =						"std_conv" if "bit" in model_name else False

					# note that when using BiT as backbone for ViT-hybrid checkpoints,
					# one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same",
					# config.conv_layer = "std_conv_same"
					A_				 =						BitConfig(
					    conv_layer=__a				,   num_labels=1000				,   idalabel=__a				,   labelaid=__a				,   )

					return config
def 							A_     (__a				):

					'''simple docstring'''





					if "stem.conv" in name:
										A_				 =						name.replace("stem.conv"				,   "bit.embedder.convolution"				)
					if "blocks" in name:
										A_				 =						name.replace("blocks"				,   "layers"				)
					if "head.fc" in name:
										A_				 =						name.replace("head.fc"				,   "classifier.1"				)
					if name.startswith("norm"				):
										A_				 =						"bit." + name
					if "bit" not in name and "classifier" not in name:
										A_				 =						"bit.encoder." + name

					return name
def 							A_     ():

					'''simple docstring'''





					A_				 =						"http://images.cocodataset.org/val2017/000000039769.jpg"
					A_				 =						Image.open(requests.get(__a				,   stream=__a				).raw				)
					return im
@torch.no_grad()
def 							A_     (__a				,   __a				,   __a=False				):

					'''simple docstring'''





					A_				 =						get_config(__a				)

					# load original model from timm
					A_				 =						create_model(__a				,   pretrained=__a				)
					timm_model.eval()

					# load state_dict of original model
					A_				 =						timm_model.state_dict()
					for key in state_dict.copy().keys():
										A_				 =						state_dict.pop(__a				)
										A_				 =						val.squeeze() if "head" in key else val

					# load HuggingFace model
					A_				 =						BitForImageClassification(__a				)
					model.eval()
					model.load_state_dict(__a				)

					# create image processor
					A_				 =						create_transform(**resolve_data_config({}				,   model=__a				)				)
					A_				 =						transform.transforms

					A_				 =						{
					    "bilinear": PILImageResampling.BILINEAR,
					    "bicubic": PILImageResampling.BICUBIC,
					    "nearest": PILImageResampling.NEAREST,
					}

					A_				 =						BitImageProcessor(
					    do_resize=__a				,   size={"shortest_edge": timm_transforms[0].size}				,   resample=pillow_resamplings[timm_transforms[0].interpolation.value]				,   do_center_crop=__a				,   crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]}				,   do_normalize=__a				,   image_mean=timm_transforms[-1].mean.tolist()				,   image_std=timm_transforms[-1].std.tolist()				,   )

					A_				 =						prepare_img()
					A_				 =						transform(__a				).unsqueeze(0				)
					A_				 =						processor(__a				,   return_tensors="pt"				).pixel_values

					# verify pixel values
					assert torch.allclose(__a				,   __a				)

					# verify logits
					with torch.no_grad():
										A_				 =						model(__a				)
										A_				 =						outputs.logits

					print("Logits:"				,   logits[0, :3]				)
					print("Predicted class:"				,   model.config.idalabel[logits.argmax(-1				).item()]				)
					A_				 =						timm_model(__a				)
					assert timm_logits.shape == outputs.logits.shape
					assert torch.allclose(__a				,   outputs.logits				,   atol=1e-3				)
					print("Looks ok!"				)

					if pytorch_dump_folder_path is not None:
										Path(__a				).mkdir(exist_ok=__a				)
										print(f'Saving model {model_name} and processor to {pytorch_dump_folder_path}'				)
										model.save_pretrained(__a				)
										processor.save_pretrained(__a				)

					if push_to_hub:
										print(f'Pushing model {model_name} and processor to the hub'				)
										model.push_to_hub(f'ybelkada/{model_name}'				)
										processor.push_to_hub(f'ybelkada/{model_name}'				)


if __name__ == "__main__":
		UpperCamelCase_					:						List[Any]				= argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '''--model_name''',
		    default='''resnetv2_50x1_bitm''',
		    type=str,
		    help='''Name of the BiT timm model you\'d like to convert.''',
		)
		parser.add_argument(
		    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
		)
		parser.add_argument(
		    '''--push_to_hub''',
		    action='''store_true''',
		    help='''Whether to push the model to the hub.''',
		)

		UpperCamelCase_					:						Tuple				= parser.parse_args()
		convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)






"""simple docstring"""





import unittest

from transformers import load_tool

from .test_tools_common import ToolTesterMixin


UpperCamelCase_					:						int				= '''
Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.

In March 2021, Hugging Face raised $40 million in a Series B funding round.[3]

On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]
'''



class __lowerCAmelCase				(					unittest.TestCase     ,				_lowercase      ):




			"""simple docstring"""







			def      lowerCamelCase__     (				self						:					str	)      -> Dict:







								"""simple docstring"""
								A_				 =						load_tool("text-question-answering"	)
								self.tool.setup()
								A_				 =						load_tool("text-question-answering"       ,   remote=_snake_case	)




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







								"""simple docstring"""
								A_				 =						self.tool(_snake_case       ,   "What did Hugging Face do in April 2021?"	)
								self.assertEqual(_snake_case       ,   "launched the BigScience Research Workshop"	)




			def      lowerCamelCase__     (				self						:					Union[str, Any]	)      -> int:







								"""simple docstring"""
								A_				 =						self.remote_tool(_snake_case       ,   "What did Hugging Face do in April 2021?"	)
								self.assertEqual(_snake_case       ,   "launched the BigScience Research Workshop"	)




			def      lowerCamelCase__     (				self						:					Optional[Any]	)      -> Optional[Any]:







								"""simple docstring"""
								A_				 =						self.tool(text=_snake_case       ,   question="What did Hugging Face do in April 2021?"	)
								self.assertEqual(_snake_case       ,   "launched the BigScience Research Workshop"	)






			def      lowerCamelCase__     (				self						:					str	)      -> Optional[Any]:







								"""simple docstring"""
								A_				 =						self.remote_tool(text=_snake_case       ,   question="What did Hugging Face do in April 2021?"	)
								self.assertEqual(_snake_case       ,   "launched the BigScience Research Workshop"	)




