"""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 transformers import ConvNextConfig, ConvNextForImageClassification, ConvNextImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
lowerCAmelCase__  :  List[str]											=     logging.get_logger(__name__)



def   a_						( lowerCamelCase	):
				UpperCAmelCase__					=							ConvNextConfig()

				if "tiny" in checkpoint_url:
								UpperCAmelCase__					=							[3, 3, 9, 3]
								UpperCAmelCase__					=							[9_6, 1_9_2, 3_8_4, 7_6_8]
				if "small" in checkpoint_url:
								UpperCAmelCase__					=							[3, 3, 2_7, 3]
								UpperCAmelCase__					=							[9_6, 1_9_2, 3_8_4, 7_6_8]
				if "base" in checkpoint_url:
								UpperCAmelCase__					=							[3, 3, 2_7, 3]
								UpperCAmelCase__					=							[1_2_8, 2_5_6, 5_1_2, 1_0_2_4]
				if "large" in checkpoint_url:
								UpperCAmelCase__					=							[3, 3, 2_7, 3]
								UpperCAmelCase__					=							[1_9_2, 3_8_4, 7_6_8, 1_5_3_6]
				if "xlarge" in checkpoint_url:
								UpperCAmelCase__					=							[3, 3, 2_7, 3]
								UpperCAmelCase__					=							[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]

				if "1k" in checkpoint_url:
								UpperCAmelCase__					=							1_0_0_0
								UpperCAmelCase__					=							'imagenet-1k-id2label.json'
								UpperCAmelCase__					=							(1, 1_0_0_0)
				else:
								UpperCAmelCase__					=							2_1_8_4_1
								UpperCAmelCase__					=							'imagenet-22k-id2label.json'
								UpperCAmelCase__					=							(1, 2_1_8_4_1)

				UpperCAmelCase__					=							'huggingface/label-files'
				UpperCAmelCase__					=							num_labels
				UpperCAmelCase__					=							json.load(open(hf_hub_download(lowerCamelCase ,      lowerCamelCase ,      repo_type='dataset'	) ,      'r'	)	)
				UpperCAmelCase__					=							{int(lowerCamelCase	): v for k, v in idalabel.items()}
				if "1k" not in checkpoint_url:
								# this dataset contains 21843 labels but the model only has 21841
								# we delete the classes as mentioned in https://github.com/google-research/big_transfer/issues/18
								del idalabel[9_2_0_5]
								del idalabel[1_5_0_2_7]
				UpperCAmelCase__					=							idalabel
				UpperCAmelCase__					=							{v: k for k, v in idalabel.items()}
				UpperCAmelCase__					=							hidden_sizes
				UpperCAmelCase__					=							depths

				return config, expected_shape



def   a_						( lowerCamelCase	):
				if "downsample_layers.0.0" in name:
								UpperCAmelCase__					=							name.replace('downsample_layers.0.0' ,      'embeddings.patch_embeddings'	)
				if "downsample_layers.0.1" in name:
								UpperCAmelCase__					=							name.replace('downsample_layers.0.1' ,      'embeddings.norm'	)  # we rename to layernorm later on
				if "downsample_layers.1.0" in name:
								UpperCAmelCase__					=							name.replace('downsample_layers.1.0' ,      'stages.1.downsampling_layer.0'	)
				if "downsample_layers.1.1" in name:
								UpperCAmelCase__					=							name.replace('downsample_layers.1.1' ,      'stages.1.downsampling_layer.1'	)
				if "downsample_layers.2.0" in name:
								UpperCAmelCase__					=							name.replace('downsample_layers.2.0' ,      'stages.2.downsampling_layer.0'	)
				if "downsample_layers.2.1" in name:
								UpperCAmelCase__					=							name.replace('downsample_layers.2.1' ,      'stages.2.downsampling_layer.1'	)
				if "downsample_layers.3.0" in name:
								UpperCAmelCase__					=							name.replace('downsample_layers.3.0' ,      'stages.3.downsampling_layer.0'	)
				if "downsample_layers.3.1" in name:
								UpperCAmelCase__					=							name.replace('downsample_layers.3.1' ,      'stages.3.downsampling_layer.1'	)
				if "stages" in name and "downsampling_layer" not in name:
								# stages.0.0. for instance should be renamed to stages.0.layers.0.
								UpperCAmelCase__					=							name[: len('stages.0'	)] + '.layers' + name[len('stages.0'	) :]
				if "stages" in name:
								UpperCAmelCase__					=							name.replace('stages' ,      'encoder.stages'	)
				if "norm" in name:
								UpperCAmelCase__					=							name.replace('norm' ,      'layernorm'	)
				if "gamma" in name:
								UpperCAmelCase__					=							name.replace('gamma' ,      'layer_scale_parameter'	)
				if "head" in name:
								UpperCAmelCase__					=							name.replace('head' ,      'classifier'	)

				return name



def   a_						( ):
				UpperCAmelCase__					=							'http://images.cocodataset.org/val2017/000000039769.jpg'
				UpperCAmelCase__					=							Image.open(requests.get(lowerCamelCase ,      stream=lowerCamelCase	).raw	)
				return im



@torch.no_grad()
def   a_						( lowerCamelCase ,      lowerCamelCase	):
				UpperCAmelCase__				,     UpperCAmelCase__					=							get_convnext_config(lowerCamelCase	)
				# load original state_dict from URL
				UpperCAmelCase__					=							torch.hub.load_state_dict_from_url(lowerCamelCase	)['model']
				# rename keys
				for key in state_dict.copy().keys():
								UpperCAmelCase__					=							state_dict.pop(lowerCamelCase	)
								UpperCAmelCase__					=							val
				# add prefix to all keys expect classifier head
				for key in state_dict.copy().keys():
								UpperCAmelCase__					=							state_dict.pop(lowerCamelCase	)
								if not key.startswith('classifier'	):
												UpperCAmelCase__					=							'convnext.' + key
								UpperCAmelCase__					=							val

				# load HuggingFace model
				UpperCAmelCase__					=							ConvNextForImageClassification(lowerCamelCase	)
				model.load_state_dict(lowerCamelCase	)
				model.eval()

				# Check outputs on an image, prepared by ConvNextImageProcessor
				UpperCAmelCase__					=							2_2_4 if '224' in checkpoint_url else 3_8_4
				UpperCAmelCase__					=							ConvNextImageProcessor(size=lowerCamelCase	)
				UpperCAmelCase__					=							image_processor(images=prepare_img() ,      return_tensors='pt'	).pixel_values

				UpperCAmelCase__					=							model(lowerCamelCase	).logits

				# note: the logits below were obtained without center cropping
				if checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth":
								UpperCAmelCase__					=							torch.tensor([-0.1210, -0.6605, 0.1918]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_small_1k_224_ema.pth":
								UpperCAmelCase__					=							torch.tensor([-0.4473, -0.1847, -0.6365]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_224_ema.pth":
								UpperCAmelCase__					=							torch.tensor([0.4525, 0.7539, 0.0308]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_384.pth":
								UpperCAmelCase__					=							torch.tensor([0.3561, 0.6350, -0.0384]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_224_ema.pth":
								UpperCAmelCase__					=							torch.tensor([0.4174, -0.0989, 0.1489]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_384.pth":
								UpperCAmelCase__					=							torch.tensor([0.2513, -0.1349, -0.1613]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_224.pth":
								UpperCAmelCase__					=							torch.tensor([1.2980, 0.3631, -0.1198]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_224.pth":
								UpperCAmelCase__					=							torch.tensor([1.2963, 0.1227, 0.1723]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_224.pth":
								UpperCAmelCase__					=							torch.tensor([1.7956, 0.8390, 0.2820]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_224.pth":
								UpperCAmelCase__					=							torch.tensor([-0.2822, -0.0502, -0.0878]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_384.pth":
								UpperCAmelCase__					=							torch.tensor([-0.5672, -0.0730, -0.4348]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_224.pth":
								UpperCAmelCase__					=							torch.tensor([0.2681, 0.2365, 0.6246]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_384.pth":
								UpperCAmelCase__					=							torch.tensor([-0.2642, 0.3931, 0.5116]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_224_ema.pth":
								UpperCAmelCase__					=							torch.tensor([-0.6677, -0.1873, -0.8379]	)
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_384_ema.pth":
								UpperCAmelCase__					=							torch.tensor([-0.7749, -0.2967, -0.6444]	)
				else:
								raise ValueError(f'''Unknown URL: {checkpoint_url}'''	)

				assert torch.allclose(logits[0, :3] ,      lowerCamelCase ,      atol=1e-3	)
				assert logits.shape == expected_shape

				Path(lowerCamelCase	).mkdir(exist_ok=lowerCamelCase	)
				print(f'''Saving model to {pytorch_dump_folder_path}'''	)
				model.save_pretrained(lowerCamelCase	)
				print(f'''Saving image processor to {pytorch_dump_folder_path}'''	)
				image_processor.save_pretrained(lowerCamelCase	)

				print('Pushing model to the hub...'	)
				UpperCAmelCase__					=							'convnext'
				if "tiny" in checkpoint_url:
								model_name += "-tiny"
				elif "small" in checkpoint_url:
								model_name += "-small"
				elif "base" in checkpoint_url:
								model_name += "-base"
				elif "xlarge" in checkpoint_url:
								model_name += "-xlarge"
				elif "large" in checkpoint_url:
								model_name += "-large"
				if "224" in checkpoint_url:
								model_name += "-224"
				elif "384" in checkpoint_url:
								model_name += "-384"
				if "22k" in checkpoint_url and "1k" not in checkpoint_url:
								model_name += "-22k"
				if "22k" in checkpoint_url and "1k" in checkpoint_url:
								model_name += "-22k-1k"

				model.push_to_hub(
				    repo_path_or_name=Path(lowerCamelCase ,      lowerCamelCase	) ,      organization='nielsr' ,      commit_message='Add model' ,      )


if __name__ == "__main__":
						lowerCAmelCase__  :  Tuple											=     argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    '--checkpoint_url',
						    default='https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth',
						    type=str,
						    help='URL of the original ConvNeXT checkpoint you\'d like to convert.',
						)
						parser.add_argument(
						    '--pytorch_dump_folder_path',
						    default=None,
						    type=str,
						    required=True,
						    help='Path to the output PyTorch model directory.',
						)

						lowerCAmelCase__  :  Tuple											=     parser.parse_args()
						convert_convnext_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)




"""simple docstring"""






import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
						import torch


lowerCAmelCase__  :  Optional[Any]											=     logging.get_logger(__name__)
class     snake_case	:




					"""simple docstring"""

					def __init__(    self       :     Optional[Any]   ,lowerCamelCase__       :     Dict   ,lowerCamelCase__       :     Optional[Any]=21   ,lowerCamelCase__       :     str=[]   ,lowerCamelCase__       :     Any=None      ):
									UpperCAmelCase__					=							model
									UpperCAmelCase__					=							trace_batch_nums
									UpperCAmelCase__					=							abort_after_batch_num

									# keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence
									UpperCAmelCase__					=							collections.deque([]   ,lowerCamelCase__      )
									UpperCAmelCase__					=							[]
									UpperCAmelCase__					=							0
									UpperCAmelCase__					=							0
									UpperCAmelCase__					=							False
									UpperCAmelCase__					=							'                 '

									self.analyse_model()

									self.register_forward_hook()







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]   ,lowerCamelCase__       :     Tuple=None      ):
									if frame is not None:
													self.expand_frame(lowerCamelCase__      )
									self.frames.append('\n'.join(self.frame      )      )
									UpperCAmelCase__					=							[]  # start a new frame







					def 		__lowerCAmelCase						(    self       :     int   ,lowerCamelCase__       :     int      ):
									self.frame.append(lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     List[str]      ):
									print('\n'.join(self.frames      )      )
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Dict      ):
									print(f'''\nDetected inf/nan during batch_number={self.batch_number}'''      )
									print(f'''Last {len(self.frames      )} forward frames:'''      )
									print(f'''{"abs min":8} {"abs max":8} metadata'''      )
									print('\n'.join(self.frames      )      )
									print('\n\n'      )
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									# extract the fully qualified module names, to be able to report at run time. e.g.:
									# encoder.block.2.layer.0.SelfAttention.o
									#
									# for shared weights only the first shared module name will be registered
									UpperCAmelCase__					=							{m: name for name, m in self.model.named_modules()}
									# self.longest_module_name = max(len(v) for v in self.module_names.values())







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,lowerCamelCase__       :     int   ,lowerCamelCase__       :     List[Any]      ):
									if torch.is_tensor(lowerCamelCase__      ):
													self.expand_frame(get_abs_min_max(lowerCamelCase__   ,lowerCamelCase__      )      )
													if detect_overflow(lowerCamelCase__   ,lowerCamelCase__      ):
																	UpperCAmelCase__					=							True
									elif var is None:
													self.expand_frame(f'''{"None":>17} {ctx}'''      )
									else:
													self.expand_frame(f'''{"not a tensor":>17} {ctx}'''      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									self.expand_frame(f'''\n\n{self.prefix} *** Starting batch number={self.batch_number} ***'''      )
									self.expand_frame(f'''{"abs min":8} {"abs max":8} metadata'''      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									self.expand_frame(f'''{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n'''      )







					def 		__lowerCAmelCase						(    self       :     List[str]   ,lowerCamelCase__       :     List[str]   ,lowerCamelCase__       :     List[Any]   ,lowerCamelCase__       :     Optional[Any]      ):
									self.expand_frame(f'''{self.prefix} {self.module_names[module]} {module.__class__.__name__}'''      )

									# params
									for name, p in module.named_parameters(recurse=lowerCamelCase__      ):
													self.analyse_variable(lowerCamelCase__   ,lowerCamelCase__      )

									# inputs
									if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
													for i, x in enumerate(lowerCamelCase__      ):
																	self.analyse_variable(lowerCamelCase__   ,f'''input[{i}]'''      )
									else:
													self.analyse_variable(lowerCamelCase__   ,'input'      )

									# outputs
									if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
													for i, x in enumerate(lowerCamelCase__      ):
																	# possibly a tuple of tuples
																	if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
																					for j, y in enumerate(lowerCamelCase__      ):
																									self.analyse_variable(lowerCamelCase__   ,f'''output[{i}][{j}]'''      )
																	else:
																					self.analyse_variable(lowerCamelCase__   ,f'''output[{i}]'''      )
									else:
													self.analyse_variable(lowerCamelCase__   ,'output'      )

									self.save_frame()







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]      ):
									self.model.apply(self._register_forward_hook      )







					def 		__lowerCAmelCase						(    self       :     List[Any]   ,lowerCamelCase__       :     str      ):
									module.register_forward_hook(self.forward_hook      )







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,lowerCamelCase__       :     Any   ,lowerCamelCase__       :     str   ,lowerCamelCase__       :     Union[str, Any]      ):
									# - input is a tuple of packed inputs (could be non-Tensors)
									# - output could be a Tensor or a tuple of Tensors and non-Tensors

									UpperCAmelCase__					=							False

									UpperCAmelCase__					=							True if self.batch_number in self.trace_batch_nums else False
									if trace_mode:
													self.reset_saved_frames()

									if self.total_calls == 0:
													self.batch_start_frame()
									self.total_calls += 1

									# count batch numbers - the very first forward hook of the batch will be called when the
									# batch completes - i.e. it gets called very last - we know this batch has finished
									if module == self.model:
													self.batch_number += 1
													UpperCAmelCase__					=							True

									self.create_frame(lowerCamelCase__   ,lowerCamelCase__   ,lowerCamelCase__      )

									# if last_frame_of_batch:
									#     self.batch_end_frame()

									if trace_mode:
													self.trace_frames()

									if last_frame_of_batch:
													self.batch_start_frame()

									if self.detected_overflow and not trace_mode:
													self.dump_saved_frames()

													# now we can abort, as it's pointless to continue running
													raise ValueError(
													    'DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. '
													    'Please scroll up above this traceback to see the activation values prior to this event.'      )

									# abort after certain batch if requested to do so
									if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:
													raise ValueError(
													    f'''DebugUnderflowOverflow: aborting after {self.batch_number} batches due to'''
													    f''' `abort_after_batch_num={self.abort_after_batch_num}` arg'''      )






def   a_						( lowerCamelCase ,      lowerCamelCase	):
				UpperCAmelCase__					=							var.abs()
				return f'''{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'''



def   a_						( lowerCamelCase ,      lowerCamelCase	):
				UpperCAmelCase__					=							False
				if torch.isnan(lowerCamelCase	).any().item():
								UpperCAmelCase__					=							True
								print(f'''{ctx} has nans'''	)
				if torch.isinf(lowerCamelCase	).any().item():
								UpperCAmelCase__					=							True
								print(f'''{ctx} has infs'''	)

				# if needed to monitor large elements can enable the following
				if 0:  # and detected:
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0	)]
								if naaa.numel() > 0:
												print(f'''{ctx}:  n100={naaa.numel()}'''	)
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0_0	)]
								if naaaa.numel() > 0:
												print(f'''{ctx}: n1000={naaaa.numel()}'''	)
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0_0_0	)]
								if naaaaa.numel() > 0:
												print(f'''{ctx}: n10000={naaaaa.numel()}'''	)

				if 0:
								print(f'''min={var.min():9.2e} max={var.max():9.2e}'''	)

				if 0:
								print(f'''min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})'''	)

				return detected







class     snake_case	(			__UpperCAmelCase    ):




					"""simple docstring"""

					snake_case__       =			"underflow_overflow"
					snake_case__       =			"tpu_metrics_debug"



