
'''simple docstring'''
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin


lowerCAmelCase :  Any      =      logging.get_logger(__name__)  # pylint: disable=invalid-name


@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerDiscrete
class        SCREAMING_SNAKE_CASE__	(			snake_case_):
				lowerCAmelCase_			       =				42
				lowerCAmelCase_			       =				None







def 						A_(			A		:						Any						,			A		:						Optional[Any]=0.999						,			A		:						Tuple="cosine"						,			):
							if alpha_transform_type == "cosine":

														def alpha_bar_fn(A		:						Tuple):
																					return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2

							elif alpha_transform_type == "exp":

														def alpha_bar_fn(A		:						Optional[Any]):
																					return math.exp(t * -12.0)

							else:
														raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''')

							UpperCamelCase					       =			[]
							for i in range(A):
														UpperCamelCase					       =			i / num_diffusion_timesteps
														UpperCamelCase					       =			(i + 1) / num_diffusion_timesteps
														betas.append(min(1 - alpha_bar_fn(A) / alpha_bar_fn(A)						,			A))
							return torch.tensor(A						,			dtype=torch.floataa)





class        SCREAMING_SNAKE_CASE__	(			snake_case_				,    snake_case_):
				lowerCAmelCase_			       =				[e.name for e in KarrasDiffusionSchedulers]
				lowerCAmelCase_			       =				1







				@register_to_config
				def __init__(    self		,							A_ = 1000		,							A_ = 0.0_001		,							A_ = 0.02		,							A_ = "linear"		,							A_ = None		,							A_ = "epsilon"		,							A_ = "linear"		,							A_ = False		,							A_ = "linspace"		,							A_ = 0		,							)->						Optional[Any]:







											'''simple docstring'''






											if trained_betas is not None:
																		UpperCamelCase					       =			torch.tensor(A_		,							dtype=torch.floataa			)
											elif beta_schedule == "linear":
																		UpperCamelCase					       =			torch.linspace(A_		,							A_		,							A_		,							dtype=torch.floataa			)
											elif beta_schedule == "scaled_linear":
																		# this schedule is very specific to the latent diffusion model.
																		UpperCamelCase					       =			(
																		    torch.linspace(beta_start**0.5		,							beta_end**0.5		,							A_		,							dtype=torch.floataa			) ** 2
																		)
											elif beta_schedule == "squaredcos_cap_v2":
																		# Glide cosine schedule
																		UpperCamelCase					       =			betas_for_alpha_bar(A_			)
											else:
																		raise NotImplementedError(F'''{beta_schedule} does is not implemented for {self.__class__}'''			)

											UpperCamelCase					       =			1.0 - self.betas
											UpperCamelCase					       =			torch.cumprod(self.alphas		,							dim=0			)

											UpperCamelCase					       =			np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5			)
											UpperCamelCase					       =			np.concatenate([sigmas[::-1], [0.0]]			).astype(np.floataa			)
											UpperCamelCase					       =			torch.from_numpy(A_			)

											# setable values
											UpperCamelCase					       =			None
											UpperCamelCase					       =			np.linspace(0		,							num_train_timesteps - 1		,							A_		,							dtype=A_			)[::-1].copy()
											UpperCamelCase					       =			torch.from_numpy(A_			)
											UpperCamelCase					       =			False
											UpperCamelCase					       =			use_karras_sigmas







				@property
				def 		UpperCAmelCase_  (    self			)->						Any:







											'''simple docstring'''






											if self.config.timestep_spacing in ["linspace", "trailing"]:
																		return self.sigmas.max()

											return (self.sigmas.max() ** 2 + 1) ** 0.5







				def 		UpperCAmelCase_  (    self		,							A_		,							A_			)->						torch.FloatTensor:







											'''simple docstring'''






											if isinstance(A_		,							torch.Tensor			):
																		UpperCamelCase					       =			timestep.to(self.timesteps.device			)
											UpperCamelCase					       =			(self.timesteps == timestep).nonzero().item()
											UpperCamelCase					       =			self.sigmas[step_index]

											UpperCamelCase					       =			sample / ((sigma**2 + 1) ** 0.5)

											UpperCamelCase					       =			True
											return sample







				def 		UpperCAmelCase_  (    self		,							A_		,							A_ = None			)->						List[str]:







											'''simple docstring'''






											UpperCamelCase					       =			num_inference_steps

											# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
											if self.config.timestep_spacing == "linspace":
																		UpperCamelCase					       =			np.linspace(0		,							self.config.num_train_timesteps - 1		,							A_		,							dtype=A_			)[
																		    ::-1
																		].copy()
											elif self.config.timestep_spacing == "leading":
																		UpperCamelCase					       =			self.config.num_train_timesteps // self.num_inference_steps
																		# creates integer timesteps by multiplying by ratio
																		# casting to int to avoid issues when num_inference_step is power of 3
																		UpperCamelCase					       =			(np.arange(0		,							A_			) * step_ratio).round()[::-1].copy().astype(A_			)
																		timesteps += self.config.steps_offset
											elif self.config.timestep_spacing == "trailing":
																		UpperCamelCase					       =			self.config.num_train_timesteps / self.num_inference_steps
																		# creates integer timesteps by multiplying by ratio
																		# casting to int to avoid issues when num_inference_step is power of 3
																		UpperCamelCase					       =			(np.arange(self.config.num_train_timesteps		,							0		,							-step_ratio			)).round().copy().astype(A_			)
																		timesteps -= 1
											else:
																		raise ValueError(
																		    F'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'''			)

											UpperCamelCase					       =			np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5			)
											UpperCamelCase					       =			np.log(A_			)

											if self.config.interpolation_type == "linear":
																		UpperCamelCase					       =			np.interp(A_		,							np.arange(0		,							len(A_			)			)		,							A_			)
											elif self.config.interpolation_type == "log_linear":
																		UpperCamelCase					       =			torch.linspace(np.log(sigmas[-1]			)		,							np.log(sigmas[0]			)		,							num_inference_steps + 1			).exp()
											else:
																		raise ValueError(
																		    F'''{self.config.interpolation_type} is not implemented. Please specify interpolation_type to either'''
																		    ' \'linear\' or \'log_linear\''			)

											if self.use_karras_sigmas:
																		UpperCamelCase					       =			self._convert_to_karras(in_sigmas=A_		,							num_inference_steps=self.num_inference_steps			)
																		UpperCamelCase					       =			np.array([self._sigma_to_t(A_		,							A_			) for sigma in sigmas]			)

											UpperCamelCase					       =			np.concatenate([sigmas, [0.0]]			).astype(np.floataa			)
											UpperCamelCase					       =			torch.from_numpy(A_			).to(device=A_			)
											if str(A_			).startswith('mps'			):
																		# mps does not support float64
																		UpperCamelCase					       =			torch.from_numpy(A_			).to(A_		,							dtype=torch.floataa			)
											else:
																		UpperCamelCase					       =			torch.from_numpy(A_			).to(device=A_			)







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







											'''simple docstring'''






											UpperCamelCase					       =			np.log(A_			)

											# get distribution
											UpperCamelCase					       =			log_sigma - log_sigmas[:, np.newaxis]

											# get sigmas range
											UpperCamelCase					       =			np.cumsum((dists >= 0)		,							axis=0			).argmax(axis=0			).clip(max=log_sigmas.shape[0] - 2			)
											UpperCamelCase					       =			low_idx + 1

											UpperCamelCase					       =			log_sigmas[low_idx]
											UpperCamelCase					       =			log_sigmas[high_idx]

											# interpolate sigmas
											UpperCamelCase					       =			(low - log_sigma) / (low - high)
											UpperCamelCase					       =			np.clip(A_		,							0		,							1			)

											# transform interpolation to time range
											UpperCamelCase					       =			(1 - w) * low_idx + w * high_idx
											UpperCamelCase					       =			t.reshape(sigma.shape			)
											return t







				def 		UpperCAmelCase_  (    self		,							A_		,							A_			)->						torch.FloatTensor:







											'''simple docstring'''






											UpperCamelCase					       =			in_sigmas[-1].item()
											UpperCamelCase					       =			in_sigmas[0].item()

											UpperCamelCase					       =			7.0  # 7.0 is the value used in the paper
											UpperCamelCase					       =			np.linspace(0		,							1		,							A_			)
											UpperCamelCase					       =			sigma_min ** (1 / rho)
											UpperCamelCase					       =			sigma_max ** (1 / rho)
											UpperCamelCase					       =			(max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
											return sigmas







				def 		UpperCAmelCase_  (    self		,							A_		,							A_		,							A_		,							A_ = 0.0		,							A_ = 0.0		,							A_ = float('inf'			)		,							A_ = 1.0		,							A_ = None		,							A_ = True		,							)->						Union[EulerDiscreteSchedulerOutput, Tuple]:







											'''simple docstring'''






											if (
											    isinstance(A_		,							A_			)
											    or isinstance(A_		,							torch.IntTensor			)
											    or isinstance(A_		,							torch.LongTensor			)
											):
																		raise ValueError(
																		    (
																		        'Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to'
																		        ' `EulerDiscreteScheduler.step()` is not supported. Make sure to pass'
																		        ' one of the `scheduler.timesteps` as a timestep.'
																		    )		,							)

											if not self.is_scale_input_called:
																		logger.warning(
																		    'The `scale_model_input` function should be called before `step` to ensure correct denoising. '
																		    'See `StableDiffusionPipeline` for a usage example.'			)

											if isinstance(A_		,							torch.Tensor			):
																		UpperCamelCase					       =			timestep.to(self.timesteps.device			)

											UpperCamelCase					       =			(self.timesteps == timestep).nonzero().item()
											UpperCamelCase					       =			self.sigmas[step_index]

											UpperCamelCase					       =			min(s_churn / (len(self.sigmas			) - 1)		,							2**0.5 - 1			) if s_tmin <= sigma <= s_tmax else 0.0

											UpperCamelCase					       =			randn_tensor(
											    model_output.shape		,							dtype=model_output.dtype		,							device=model_output.device		,							generator=A_			)

											UpperCamelCase					       =			noise * s_noise
											UpperCamelCase					       =			sigma * (gamma + 1)

											if gamma > 0:
																		UpperCamelCase					       =			sample + eps * (sigma_hat**2 - sigma**2) ** 0.5

											# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
											# NOTE: "original_sample" should not be an expected prediction_type but is left in for
											# backwards compatibility
											if self.config.prediction_type == "original_sample" or self.config.prediction_type == "sample":
																		UpperCamelCase					       =			model_output
											elif self.config.prediction_type == "epsilon":
																		UpperCamelCase					       =			sample - sigma_hat * model_output
											elif self.config.prediction_type == "v_prediction":
																		# * c_out + input * c_skip
																		UpperCamelCase					       =			model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
											else:
																		raise ValueError(
																		    F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'''			)

											# 2. Convert to an ODE derivative
											UpperCamelCase					       =			(sample - pred_original_sample) / sigma_hat

											UpperCamelCase					       =			self.sigmas[step_index + 1] - sigma_hat

											UpperCamelCase					       =			sample + derivative * dt

											if not return_dict:
																		return (prev_sample,)

											return EulerDiscreteSchedulerOutput(prev_sample=A_		,							pred_original_sample=A_			)







				def 		UpperCAmelCase_  (    self		,							A_		,							A_		,							A_		,							)->						torch.FloatTensor:







											'''simple docstring'''






											UpperCamelCase					       =			self.sigmas.to(device=original_samples.device		,							dtype=original_samples.dtype			)
											if original_samples.device.type == "mps" and torch.is_floating_point(A_			):
																		# mps does not support float64
																		UpperCamelCase					       =			self.timesteps.to(original_samples.device		,							dtype=torch.floataa			)
																		UpperCamelCase					       =			timesteps.to(original_samples.device		,							dtype=torch.floataa			)
											else:
																		UpperCamelCase					       =			self.timesteps.to(original_samples.device			)
																		UpperCamelCase					       =			timesteps.to(original_samples.device			)

											UpperCamelCase					       =			[(schedule_timesteps == t).nonzero().item() for t in timesteps]

											UpperCamelCase					       =			sigmas[step_indices].flatten()
											while len(sigma.shape			) < len(original_samples.shape			):
																		UpperCamelCase					       =			sigma.unsqueeze(-1			)

											UpperCamelCase					       =			original_samples + noise * sigma
											return noisy_samples







				def __len__(    self			)->						Optional[int]:







											'''simple docstring'''






											return self.config.num_train_timesteps






'''simple docstring'''
import argparse
import json
import os

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ConvNextImageProcessor, ConvNextVaConfig, ConvNextVaForImageClassification
from transformers.image_utils import PILImageResampling
from transformers.utils import logging


logging.set_verbosity_info()
lowerCAmelCase :  Union[str, Any]      =      logging.get_logger(__name__)







def 						A_(			A		:						int):
							UpperCamelCase					       =			ConvNextVaConfig()

							if "atto" in checkpoint_url:
														UpperCamelCase					       =			[2, 2, 6, 2]
														UpperCamelCase					       =			[40, 80, 160, 320]
							if "femto" in checkpoint_url:
														UpperCamelCase					       =			[2, 2, 6, 2]
														UpperCamelCase					       =			[48, 96, 192, 384]
							if "pico" in checkpoint_url:
														UpperCamelCase					       =			[2, 2, 6, 2]
														UpperCamelCase					       =			[64, 128, 256, 512]
							if "nano" in checkpoint_url:
														UpperCamelCase					       =			[2, 2, 8, 2]
														UpperCamelCase					       =			[80, 160, 320, 640]
							if "tiny" in checkpoint_url:
														UpperCamelCase					       =			[3, 3, 9, 3]
														UpperCamelCase					       =			[96, 192, 384, 768]
							if "base" in checkpoint_url:
														UpperCamelCase					       =			[3, 3, 27, 3]
														UpperCamelCase					       =			[128, 256, 512, 1024]
							if "large" in checkpoint_url:
														UpperCamelCase					       =			[3, 3, 27, 3]
														UpperCamelCase					       =			[192, 384, 768, 1536]
							if "huge" in checkpoint_url:
														UpperCamelCase					       =			[3, 3, 27, 3]
														UpperCamelCase					       =			[352, 704, 1408, 2816]

							UpperCamelCase					       =			1000
							UpperCamelCase					       =			'imagenet-1k-id2label.json'
							UpperCamelCase					       =			(1, 1000)

							UpperCamelCase					       =			'huggingface/label-files'
							UpperCamelCase					       =			num_labels
							UpperCamelCase					       =			json.load(open(hf_hub_download(A						,			A						,			repo_type='dataset')						,			'r'))
							UpperCamelCase					       =			{int(A): v for k, v in idalabel.items()}

							UpperCamelCase					       =			idalabel
							UpperCamelCase					       =			{v: k for k, v in idalabel.items()}
							UpperCamelCase					       =			hidden_sizes
							UpperCamelCase					       =			depths

							return config, expected_shape







def 						A_(			A		:						int):
							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 "gamma" in name:
														UpperCamelCase					       =			name.replace('gamma'						,			'weight')
							if "beta" in name:
														UpperCamelCase					       =			name.replace('beta'						,			'bias')
							if "stages" in name:
														UpperCamelCase					       =			name.replace('stages'						,			'encoder.stages')
							if "norm" in name:
														UpperCamelCase					       =			name.replace('norm'						,			'layernorm')
							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(A						,			stream=A).raw)
							return im







def 						A_(			A		:						Tuple):
							if "224" in checkpoint_url:
														UpperCamelCase					       =			224
														UpperCamelCase					       =			224 / 256
							elif "384" in checkpoint_url:
														UpperCamelCase					       =			384
														UpperCamelCase					       =			None
							else:
														UpperCamelCase					       =			512
														UpperCamelCase					       =			None

							return ConvNextImageProcessor(
							    size=A						,			crop_pct=A						,			image_mean=[0.485, 0.456, 0.406]						,			image_std=[0.229, 0.224, 0.225]						,			resample=PILImageResampling.BICUBIC						,			)







@torch.no_grad()
def 						A_(			A		:						List[str]						,			A		:						List[str]						,			A		:						Any						,			A		:						int):
							print('Downloading original model from checkpoint...')
							# define ConvNeXTV2 configuration based on URL
							UpperCamelCase       ,     UpperCamelCase					       =			get_convnextva_config(A)
							# load original state_dict from URL
							UpperCamelCase					       =			torch.hub.load_state_dict_from_url(A)['model']

							print('Converting model parameters...')
							# rename keys
							for key in state_dict.copy().keys():
														UpperCamelCase					       =			state_dict.pop(A)
														UpperCamelCase					       =			val
							# add prefix to all keys expect classifier head
							for key in state_dict.copy().keys():
														UpperCamelCase					       =			state_dict.pop(A)
														if not key.startswith('classifier'):
																					UpperCamelCase					       =			'convnextv2.' + key
														UpperCamelCase					       =			val

							# load HuggingFace model
							UpperCamelCase					       =			ConvNextVaForImageClassification(A)
							model.load_state_dict(A)
							model.eval()

							# Check outputs on an image, prepared by ConvNextImageProcessor
							UpperCamelCase					       =			convert_preprocessor(A)
							UpperCamelCase					       =			preprocessor(images=prepare_img()						,			return_tensors='pt')
							UpperCamelCase					       =			model(**A).logits

							# note: the logits below were obtained without center cropping
							if checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_atto_1k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.3_930, 0.1_747, -0.5_246, 0.4_177, 0.4_295])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_femto_1k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.1_727, -0.5_341, -0.7_818, -0.4_745, -0.6_566])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_pico_1k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.0_333, 0.1_563, -0.9_137, 0.1_054, 0.0_381])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_nano_1k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.1_744, -0.1_555, -0.0_713, 0.0_950, -0.1_431])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_tiny_1k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([0.9_996, 0.1_966, -0.4_386, -0.3_472, 0.6_661])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_base_1k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.2_553, -0.6_708, -0.1_359, 0.2_518, -0.2_488])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_large_1k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.0_673, -0.5_627, -0.3_753, -0.2_722, 0.0_178])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_huge_1k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.6_377, -0.7_458, -0.2_150, 0.1_184, -0.0_597])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_nano_22k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([1.0_799, 0.2_322, -0.8_860, 1.0_219, 0.6_231])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_nano_22k_384_ema.pt":
														UpperCamelCase					       =			torch.tensor([0.3_766, 0.4_917, -1.1_426, 0.9_942, 0.6_024])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_tiny_22k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([0.4_220, -0.6_919, -0.4_317, -0.2_881, -0.6_609])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_tiny_22k_384_ema.pt":
														UpperCamelCase					       =			torch.tensor([0.1_082, -0.8_286, -0.5_095, 0.4_681, -0.8_085])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_base_22k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.2_419, -0.6_221, 0.2_176, -0.0_980, -0.7_527])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_base_22k_384_ema.pt":
														UpperCamelCase					       =			torch.tensor([0.0_391, -0.4_371, 0.3_786, 0.1_251, -0.2_784])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_large_22k_224_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.0_504, 0.5_636, -0.1_729, -0.6_507, -0.3_949])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_large_22k_384_ema.pt":
														UpperCamelCase					       =			torch.tensor([0.3_560, 0.9_486, 0.3_149, -0.2_667, -0.5_138])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_huge_22k_384_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.2_469, -0.4_550, -0.5_853, -0.0_810, 0.0_309])
							elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_huge_22k_512_ema.pt":
														UpperCamelCase					       =			torch.tensor([-0.3_090, 0.0_802, -0.0_682, -0.1_979, -0.2_826])
							else:
														raise ValueError(f'''Unknown URL: {checkpoint_url}''')

							assert torch.allclose(logits[0, :5]						,			A						,			atol=1E-3)
							assert logits.shape == expected_shape
							print('Model outputs match the original results!')

							if save_model:
														print('Saving model to local...')
														# Create folder to save model
														if not os.path.isdir(A):
																					os.mkdir(A)

														model.save_pretrained(A)
														preprocessor.save_pretrained(A)

							UpperCamelCase					       =			'convnextv2'
							if "atto" in checkpoint_url:
														model_name += "-atto"
							if "femto" in checkpoint_url:
														model_name += "-femto"
							if "pico" in checkpoint_url:
														model_name += "-pico"
							if "nano" in checkpoint_url:
														model_name += "-nano"
							elif "tiny" in checkpoint_url:
														model_name += "-tiny"
							elif "base" in checkpoint_url:
														model_name += "-base"
							elif "large" in checkpoint_url:
														model_name += "-large"
							elif "huge" in checkpoint_url:
														model_name += "-huge"
							if "22k" in checkpoint_url and "1k" not in checkpoint_url:
														model_name += "-22k"
							elif "22k" in checkpoint_url and "1k" in checkpoint_url:
														model_name += "-22k-1k"
							elif "1k" in checkpoint_url:
														model_name += "-1k"
							if "224" in checkpoint_url:
														model_name += "-224"
							elif "384" in checkpoint_url:
														model_name += "-384"
							elif "512" in checkpoint_url:
														model_name += "-512"

							if push_to_hub:
														print(f'''Pushing {model_name} to the hub...''')
														model.push_to_hub(A)
														preprocessor.push_to_hub(A)


if __name__ == "__main__":
						lowerCAmelCase :  List[Any]      =      argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    '--checkpoint_url',
						    default='https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_atto_1k_224_ema.pt',
						    type=str,
						    help='URL of the original ConvNeXTV2 checkpoint you\'d like to convert.',
						)
						parser.add_argument(
						    '--pytorch_dump_folder_path',
						    default='model',
						    type=str,
						    help='Path to the output PyTorch model directory.',
						)
						parser.add_argument('--save_model', action='store_true', help='Save model to local')
						parser.add_argument('--push_to_hub', action='store_true', help='Push model and image preprocessor to the hub')

						lowerCAmelCase :  int      =      parser.parse_args()
						convert_convnextva_checkpoint(
						    args.checkpoint_url, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub
						)




