




import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    level=logging.INFO,
)
__UpperCamelCase      : Optional[int]					      =   logging.getLogger(__name__)

__UpperCamelCase      : List[Any]					      =   int(10_000)  # Hardcoded max length to avoid infinite loop

__UpperCamelCase      : Union[str, Any]					      =   {
    "gpt2": (GPTaLMHeadModel, GPTaTokenizer),
    "ctrl": (CTRLLMHeadModel, CTRLTokenizer),
    "openai-gpt": (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    "xlnet": (XLNetLMHeadModel, XLNetTokenizer),
    "transfo-xl": (TransfoXLLMHeadModel, TransfoXLTokenizer),
    "xlm": (XLMWithLMHeadModel, XLMTokenizer),
    "gptj": (GPTJForCausalLM, AutoTokenizer),
    "bloom": (BloomForCausalLM, BloomTokenizerFast),
    "llama": (LlamaForCausalLM, LlamaTokenizer),
    "opt": (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
__UpperCamelCase      : int					      =   "In 1991, the remains of Russian Tsar Nicholas II and his family\n(except for Alexei and Maria) are discovered.\nThe voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the\nremainder of the story. 1883 Western Siberia,\na young Grigori Rasputin is asked by his father and a group of men to perform magic.\nRasputin has a vision and denounces one of the men as a horse thief. Although his\nfather initially slaps him for making such an accusation, Rasputin watches as the\nman is chased outside and beaten. Twenty years later, Rasputin sees a vision of\nthe Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\nwith people, even a bishop, begging for his blessing. <eod> </s> <eos>"





def 	__A	(			__lowerCamelCase					)   -> List[Any]:
	np.random.seed(args.seed					)
	torch.manual_seed(args.seed					)
	if args.n_gpu > 0:
		torch.cuda.manual_seed_all(args.seed					)





def 	__A	(			__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)   -> Optional[int]:
	if args.temperature > 0.7:
		logger.info("""CTRL typically works better with lower temperatures (and lower top_k)."""					)

	a		       =							tokenizer.encode(__lowerCamelCase							,    add_special_tokens=__lowerCamelCase					)
	if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()					):
		logger.info("""WARNING! You are not starting your generation from a control code so you won't get good results"""					)
	return prompt_text





def 	__A	(			__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)   -> str:
	# kwargs = {"language": None, "mask_token_id": None}

	# Set the language
	a		       =							hasattr(model.config							,    """use_lang_emb"""					) and model.config.use_lang_emb
	if hasattr(model.config							,    """lang2id"""					) and use_lang_emb:
		a		       =							model.config.langaid.keys()
		if args.xlm_language in available_languages:
			a		       =							args.xlm_language
		else:
			a		       =							None
			while language not in available_languages:
				a		       =							input("""Using XLM. Select language in """ + str(list(__lowerCamelCase					)					) + """ >>> """					)

		a		       =							model.config.langaid[language]
		# kwargs["language"] = tokenizer.lang2id[language]

	# TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
	# XLM masked-language modeling (MLM) models need masked token
	# is_xlm_mlm = "mlm" in args.model_name_or_path
	# if is_xlm_mlm:
	#     kwargs["mask_token_id"] = tokenizer.mask_token_id

	return prompt_text





def 	__A	(			__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)   -> Tuple:
	a		       =							args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
	a		       =							prefix + prompt_text
	return prompt_text





def 	__A	(			__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)   -> List[str]:
	a		       =							args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
	a		       =							prefix + prompt_text
	return prompt_text


__UpperCamelCase      : Optional[Any]					      =   {
    "ctrl": prepare_ctrl_input,
    "xlm": prepare_xlm_input,
    "xlnet": prepare_xlnet_input,
    "transfo-xl": prepare_transfoxl_input,
}





def 	__A	(			__lowerCamelCase							,    __lowerCamelCase					)   -> int:
	if length < 0 and max_sequence_length > 0:
		a		       =							max_sequence_length
	elif 0 < max_sequence_length < length:
		a		       =							max_sequence_length  # No generation bigger than model size
	elif length < 0:
		a		       =							MAX_LENGTH  # avoid infinite loop
	return length





def 	__A	(			__lowerCamelCase					)   -> Tuple:
	a		       =							None
	if hasattr(__lowerCamelCase							,    """hidden_size"""					):
		a		       =							model_config.hidden_size
	elif hasattr(__lowerCamelCase							,    """n_embed"""					):
		a		       =							model_config.n_embed
	elif hasattr(__lowerCamelCase							,    """n_embd"""					):
		a		       =							model_config.n_embd

	a		       =							None
	if hasattr(__lowerCamelCase							,    """num_attention_heads"""					):
		a		       =							model_config.num_attention_heads
	elif hasattr(__lowerCamelCase							,    """n_head"""					):
		a		       =							model_config.n_head

	if embedding_size is None or num_head is None or num_head == 0:
		raise ValueError("""Check the model config"""					)

	a		       =							int(embedding_size / num_head					)
	if hasattr(__lowerCamelCase							,    """n_layer"""					):
		a		       =							model_config.n_layer
	elif hasattr(__lowerCamelCase							,    """num_hidden_layers"""					):
		a		       =							model_config.num_hidden_layers
	else:
		raise ValueError("""Number of hidden layers couldn't be determined from the model config"""					)

	return num_layer, num_head, num_embedding_size_per_head





def 	__A	(			__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)   -> Any:
	a       ,				a       ,				a		       =							sparse_model_config(model.config					)
	if model.config.model_type == "bloom":
		a		       =							tuple(
		    (
		        torch.empty(int(num_attention_heads * batch_size					)							,    __lowerCamelCase							,    __lowerCamelCase					)
		        .to(model.dtype					)
		        .to(model.device					),
		        torch.empty(int(num_attention_heads * batch_size					)							,    __lowerCamelCase							,    __lowerCamelCase					)
		        .to(model.dtype					)
		        .to(model.device					),
		    )
		    for _ in range(__lowerCamelCase					)					)
	else:
		a		       =							tuple(
		    (
		        torch.empty(__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)
		        .to(model.dtype					)
		        .to(model.device					),
		        torch.empty(__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)
		        .to(model.dtype					)
		        .to(model.device					),
		    )
		    for _ in range(__lowerCamelCase					)					)
	return past_key_values





def 	__A	(			__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)   -> Union[str, Any]:
	a		       =							len(__lowerCamelCase					)
	a		       =							tokenizer.batch_encode_plus(__lowerCamelCase							,    return_tensors="""pt"""					)
	a		       =							dummy_input.to(model.device					)
	if model.config.use_cache:
		a		       =							generate_past_key_values(__lowerCamelCase							,    __lowerCamelCase							,    1					)
	a		       =							torch.cat(
	    [
	        torch.zeros(dummy_input["""attention_mask"""].shape[0]							,    1					)
	        .to(dummy_input["""attention_mask"""].dtype					)
	        .to(model.device					),
	        dummy_input["""attention_mask"""],
	    ]							,    -1							,    )
	return dummy_input

class 	__lowerCAmelCase			(			__magic_name__				):
							UpperCamelCase__        =						('''_optimized''', '''_default''')
							def __init__(		self		:Optional[Any]	,   __magic_name__		:str	,   __magic_name__		:Tuple       ):







								'''simple docstring'''







								a		       =							optimized
								a		       =							default
							def __call__(		self		:List[str]	,   *__magic_name__		:List[Any]	,   **__magic_name__		:str       ):







								'''simple docstring'''







								if kwargs["past_key_values"] is None and self._default.config.use_cache:
									a		       =							generate_past_key_values(self._default	,   kwargs["""input_ids"""].shape[0]	,   0       )
								kwargs.pop("""position_ids"""	,   __magic_name__       )
								for k in list(kwargs.keys()       ):
									if kwargs[k] is None or isinstance(kwargs[k]	,   __magic_name__       ):
										kwargs.pop(__magic_name__       )
								a		       =							self._optimized(**__magic_name__       )
								a		       =							outputs[0]
								a		       =							outputs[1]
								a		       =							CausalLMOutputWithPast(
								    loss=__magic_name__	,   logits=__magic_name__	,   past_key_values=__magic_name__	,   hidden_states=__magic_name__	,   attentions=__magic_name__	,   )
								return fixed_output
							def __getattr__(		self		:Dict	,   __magic_name__		:Union[str, Any]       ):







								'''simple docstring'''







								return getattr(self._default	,   __magic_name__       )
							def    lowerCamelCase__							(		self		:Union[str, Any]	,   __magic_name__		:List[Any]	,   __magic_name__		:Optional[int]=None	,   __magic_name__		:Dict=None	,   __magic_name__		:Tuple=None	,   **__magic_name__		:Optional[Any]       ):







								'''simple docstring'''







								return self._default.prepare_inputs_for_generation(
								    __magic_name__	,   past_key_values=__magic_name__	,   inputs_embeds=__magic_name__	,   use_cache=__magic_name__	,   **__magic_name__       )





							def    lowerCamelCase__							(		self		:Optional[int]	,   __magic_name__		:Tuple[Tuple[torch.Tensor]]	,   __magic_name__		:torch.Tensor       ):







								'''simple docstring'''







								return self._default._reorder_cache(__magic_name__	,   __magic_name__       )







def 	__A	(			)   -> Union[str, Any]:
	a		       =							argparse.ArgumentParser()
	parser.add_argument(
	    """--model_type"""							,    default=__lowerCamelCase							,    type=__lowerCamelCase							,    required=__lowerCamelCase							,    help="""Model type selected in the list: """ + """, """.join(MODEL_CLASSES.keys()					)							,    )
	parser.add_argument(
	    """--model_name_or_path"""							,    default=__lowerCamelCase							,    type=__lowerCamelCase							,    required=__lowerCamelCase							,    help="""Path to pre-trained model or shortcut name selected in the list: """ + """, """.join(MODEL_CLASSES.keys()					)							,    )

	parser.add_argument("""--prompt"""							,    type=__lowerCamelCase							,    default=""""""					)
	parser.add_argument("""--length"""							,    type=__lowerCamelCase							,    default=20					)
	parser.add_argument("""--stop_token"""							,    type=__lowerCamelCase							,    default=__lowerCamelCase							,    help="""Token at which text generation is stopped"""					)

	parser.add_argument(
	    """--temperature"""							,    type=__lowerCamelCase							,    default=1.0							,    help="""temperature of 1.0 has no effect, lower tend toward greedy sampling"""							,    )
	parser.add_argument(
	    """--repetition_penalty"""							,    type=__lowerCamelCase							,    default=1.0							,    help="""primarily useful for CTRL model; in that case, use 1.2"""					)
	parser.add_argument("""--k"""							,    type=__lowerCamelCase							,    default=0					)
	parser.add_argument("""--p"""							,    type=__lowerCamelCase							,    default=0.9					)

	parser.add_argument("""--prefix"""							,    type=__lowerCamelCase							,    default=""""""							,    help="""Text added prior to input."""					)
	parser.add_argument("""--padding_text"""							,    type=__lowerCamelCase							,    default=""""""							,    help="""Deprecated, the use of `--prefix` is preferred."""					)
	parser.add_argument("""--xlm_language"""							,    type=__lowerCamelCase							,    default=""""""							,    help="""Optional language when used with the XLM model."""					)

	parser.add_argument("""--seed"""							,    type=__lowerCamelCase							,    default=42							,    help="""random seed for initialization"""					)
	parser.add_argument("""--no_cuda"""							,    action="""store_true"""							,    help="""Avoid using CUDA when available"""					)
	parser.add_argument("""--num_return_sequences"""							,    type=__lowerCamelCase							,    default=1							,    help="""The number of samples to generate."""					)
	parser.add_argument(
	    """--fp16"""							,    action="""store_true"""							,    help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit"""							,    )
	parser.add_argument("""--jit"""							,    action="""store_true"""							,    help="""Whether or not to use jit trace to accelerate inference"""					)
	a		       =							parser.parse_args()

	a		       =							torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""					)
	a		       =							0 if args.no_cuda else torch.cuda.device_count()

	logger.warning(f'device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}'					)

	set_seed(__lowerCamelCase					)

	# Initialize the model and tokenizer
	try:
		a		       =							args.model_type.lower()
		a       ,				a		       =							MODEL_CLASSES[args.model_type]
	except KeyError:
		raise KeyError("""the model {} you specified is not supported. You are welcome to add it and open a PR :)"""					)

	a		       =							tokenizer_class.from_pretrained(args.model_name_or_path					)
	if tokenizer.pad_token is None:
		a		       =							tokenizer.eos_token
	a		       =							model_class.from_pretrained(args.model_name_or_path					)
	model.to(args.device					)

	if args.fpaa:
		model.half()
	a		       =							getattr(model.config							,    """max_position_embeddings"""							,    0					)
	a		       =							adjust_length_to_model(args.length							,    max_sequence_length=__lowerCamelCase					)
	logger.info(__lowerCamelCase					)

	a		       =							args.prompt if args.prompt else input("""Model prompt >>> """					)

	# Different models need different input formatting and/or extra arguments
	a		       =							args.model_type in PREPROCESSING_FUNCTIONS.keys()
	if requires_preprocessing:
		a		       =							PREPROCESSING_FUNCTIONS.get(args.model_type					)
		a		       =							prepare_input(__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)

		if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
			a		       =							{"""add_space_before_punct_symbol""": True}
		else:
			a		       =							{}

		a		       =							tokenizer.encode(
		    __lowerCamelCase							,    add_special_tokens=__lowerCamelCase							,    return_tensors="""pt"""							,    **__lowerCamelCase					)
	else:
		a		       =							args.prefix if args.prefix else args.padding_text
		a		       =							tokenizer.encode(prefix + prompt_text							,    add_special_tokens=__lowerCamelCase							,    return_tensors="""pt"""					)
	a		       =							encoded_prompt.to(args.device					)

	if encoded_prompt.size()[-1] == 0:
		a		       =							None
	else:
		a		       =							encoded_prompt

	if args.jit:
		a		       =							["""enable jit"""]
		a		       =							prepare_jit_inputs(__lowerCamelCase							,    __lowerCamelCase							,    __lowerCamelCase					)
		torch._C._jit_set_texpr_fuser_enabled(__lowerCamelCase					)
		a		       =							False
		if hasattr(__lowerCamelCase							,    """forward"""					):
			a		       =							inspect.signature(model.forward					)
		else:
			a		       =							inspect.signature(model.__call__					)
		a		       =							tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(__lowerCamelCase							,    __lowerCamelCase					) is not None					)
		a		       =							torch.jit.trace(__lowerCamelCase							,    __lowerCamelCase							,    strict=__lowerCamelCase					)
		a		       =							torch.jit.freeze(traced_model.eval()					)
		traced_model(*__lowerCamelCase					)
		traced_model(*__lowerCamelCase					)

		a		       =							_ModelFallbackWrapper(__lowerCamelCase							,    __lowerCamelCase					)

	a		       =							model.generate(
	    input_ids=__lowerCamelCase							,    max_length=args.length + len(encoded_prompt[0]					)							,    temperature=args.temperature							,    top_k=args.k							,    top_p=args.p							,    repetition_penalty=args.repetition_penalty							,    do_sample=__lowerCamelCase							,    num_return_sequences=args.num_return_sequences							,    )

	# Remove the batch dimension when returning multiple sequences
	if len(output_sequences.shape					) > 2:
		output_sequences.squeeze_()

	a		       =							[]

	for generated_sequence_idx, generated_sequence in enumerate(__lowerCamelCase					):
		print(f'=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==='					)
		a		       =							generated_sequence.tolist()

		# Decode text
		a		       =							tokenizer.decode(__lowerCamelCase							,    clean_up_tokenization_spaces=__lowerCamelCase					)

		# Remove all text after the stop token
		a		       =							text[: text.find(args.stop_token					) if args.stop_token else None]

		# Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
		a		       =							(
		    prompt_text + text[len(tokenizer.decode(encoded_prompt[0]							,    clean_up_tokenization_spaces=__lowerCamelCase					)					) :]
		)

		generated_sequences.append(__lowerCamelCase					)
		print(__lowerCamelCase					)

	return generated_sequences


if __name__ == "__main__":
		main()







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()
__UpperCamelCase      : List[Any]					      =   logging.get_logger(__name__)





def 	__A	(			__lowerCamelCase					)   -> Optional[int]:
	a		       =							ConvNextConfig()

	if "tiny" in checkpoint_url:
		a		       =							[3, 3, 9, 3]
		a		       =							[96, 192, 384, 768]
	if "small" in checkpoint_url:
		a		       =							[3, 3, 27, 3]
		a		       =							[96, 192, 384, 768]
	if "base" in checkpoint_url:
		a		       =							[3, 3, 27, 3]
		a		       =							[128, 256, 512, 1024]
	if "large" in checkpoint_url:
		a		       =							[3, 3, 27, 3]
		a		       =							[192, 384, 768, 1536]
	if "xlarge" in checkpoint_url:
		a		       =							[3, 3, 27, 3]
		a		       =							[256, 512, 1024, 2048]

	if "1k" in checkpoint_url:
		a		       =							1000
		a		       =							"""imagenet-1k-id2label.json"""
		a		       =							(1, 1000)
	else:
		a		       =							2_1841
		a		       =							"""imagenet-22k-id2label.json"""
		a		       =							(1, 2_1841)

	a		       =							"""huggingface/label-files"""
	a		       =							num_labels
	a		       =							json.load(open(hf_hub_download(__lowerCamelCase							,    __lowerCamelCase							,    repo_type="""dataset"""					)							,    """r"""					)					)
	a		       =							{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[9205]
		del idalabel[1_5027]
	a		       =							idalabel
	a		       =							{v: k for k, v in idalabel.items()}
	a		       =							hidden_sizes
	a		       =							depths

	return config, expected_shape





def 	__A	(			__lowerCamelCase					)   -> int:
	if "downsample_layers.0.0" in name:
		a		       =							name.replace("""downsample_layers.0.0"""							,    """embeddings.patch_embeddings"""					)
	if "downsample_layers.0.1" in name:
		a		       =							name.replace("""downsample_layers.0.1"""							,    """embeddings.norm"""					)  # we rename to layernorm later on
	if "downsample_layers.1.0" in name:
		a		       =							name.replace("""downsample_layers.1.0"""							,    """stages.1.downsampling_layer.0"""					)
	if "downsample_layers.1.1" in name:
		a		       =							name.replace("""downsample_layers.1.1"""							,    """stages.1.downsampling_layer.1"""					)
	if "downsample_layers.2.0" in name:
		a		       =							name.replace("""downsample_layers.2.0"""							,    """stages.2.downsampling_layer.0"""					)
	if "downsample_layers.2.1" in name:
		a		       =							name.replace("""downsample_layers.2.1"""							,    """stages.2.downsampling_layer.1"""					)
	if "downsample_layers.3.0" in name:
		a		       =							name.replace("""downsample_layers.3.0"""							,    """stages.3.downsampling_layer.0"""					)
	if "downsample_layers.3.1" in name:
		a		       =							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.
		a		       =							name[: len("""stages.0"""					)] + """.layers""" + name[len("""stages.0"""					) :]
	if "stages" in name:
		a		       =							name.replace("""stages"""							,    """encoder.stages"""					)
	if "norm" in name:
		a		       =							name.replace("""norm"""							,    """layernorm"""					)
	if "gamma" in name:
		a		       =							name.replace("""gamma"""							,    """layer_scale_parameter"""					)
	if "head" in name:
		a		       =							name.replace("""head"""							,    """classifier"""					)

	return name





def 	__A	(			)   -> Optional[Any]:
	a		       =							"""http://images.cocodataset.org/val2017/000000039769.jpg"""
	a		       =							Image.open(requests.get(__lowerCamelCase							,    stream=__lowerCamelCase					).raw					)
	return im





@torch.no_grad()
def 	__A	(			__lowerCamelCase							,    __lowerCamelCase					)   -> List[Any]:
	a       ,				a		       =							get_convnext_config(__lowerCamelCase					)
	# load original state_dict from URL
	a		       =							torch.hub.load_state_dict_from_url(__lowerCamelCase					)["""model"""]
	# rename keys
	for key in state_dict.copy().keys():
		a		       =							state_dict.pop(__lowerCamelCase					)
		a		       =							val
	# add prefix to all keys expect classifier head
	for key in state_dict.copy().keys():
		a		       =							state_dict.pop(__lowerCamelCase					)
		if not key.startswith("""classifier"""					):
			a		       =							"""convnext.""" + key
		a		       =							val

	# load HuggingFace model
	a		       =							ConvNextForImageClassification(__lowerCamelCase					)
	model.load_state_dict(__lowerCamelCase					)
	model.eval()

	# Check outputs on an image, prepared by ConvNextImageProcessor
	a		       =							224 if """224""" in checkpoint_url else 384
	a		       =							ConvNextImageProcessor(size=__lowerCamelCase					)
	a		       =							image_processor(images=prepare_img()							,    return_tensors="""pt"""					).pixel_values

	a		       =							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":
		a		       =							torch.tensor([-0.1210, -0.6605, 0.1918]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_small_1k_224_ema.pth":
		a		       =							torch.tensor([-0.4473, -0.1847, -0.6365]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_224_ema.pth":
		a		       =							torch.tensor([0.4525, 0.7539, 0.0308]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_384.pth":
		a		       =							torch.tensor([0.3561, 0.6350, -0.0384]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_224_ema.pth":
		a		       =							torch.tensor([0.4174, -0.0989, 0.1489]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_384.pth":
		a		       =							torch.tensor([0.2513, -0.1349, -0.1613]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_224.pth":
		a		       =							torch.tensor([1.2980, 0.3631, -0.1198]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_224.pth":
		a		       =							torch.tensor([1.2963, 0.1227, 0.1723]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_224.pth":
		a		       =							torch.tensor([1.7956, 0.8390, 0.2820]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_224.pth":
		a		       =							torch.tensor([-0.2822, -0.0502, -0.0878]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_384.pth":
		a		       =							torch.tensor([-0.5672, -0.0730, -0.4348]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_224.pth":
		a		       =							torch.tensor([0.2681, 0.2365, 0.6246]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_384.pth":
		a		       =							torch.tensor([-0.2642, 0.3931, 0.5116]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_224_ema.pth":
		a		       =							torch.tensor([-0.6677, -0.1873, -0.8379]					)
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_384_ema.pth":
		a		       =							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..."""					)
	a		       =							"""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__":
		__UpperCamelCase      : int					      =   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.",
		)

		__UpperCamelCase      : List[Any]					      =   parser.parse_args()
		convert_convnext_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)

