
import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

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



def        lowerCamelCase_  (   __UpperCamelCase     :   str ,						__UpperCamelCase     :   Any=0.999 ,						__UpperCamelCase     :   str="cosine" ,						):
				if alpha_transform_type == "cosine":

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

				elif alpha_transform_type == "exp":

								def alpha_bar_fn(__UpperCamelCase     :   Union[str, Any]     ):
												return math.exp(t * -12.0     )

				else:
								raise ValueError(F"Unsupported alpha_tranform_type: {alpha_transform_type}"     )

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






class 					__lowercase		(					A							,       A       ):
					__magic_name__						:							List[str]     	=	[e.name for e in KarrasDiffusionSchedulers]
					__magic_name__						:							Optional[int]     	=	2


					@register_to_config
					def __init__(	self       ,       a__ = 1_0_0_0       ,       a__ = 0.0_00_85       ,       a__ = 0.0_12       ,       a__ = "linear"       ,       a__ = None       ,       a__ = "epsilon"       ,       a__ = "linspace"       ,       a__ = 0       ,       )		->							Any:





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

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

									#  set all values
									self.set_timesteps(a__       ,       a__       ,       a__						)


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__=None						)		->							str:





									'''simple docstring'''
									if schedule_timesteps is None:
													A_       	=  self.timesteps

									A_       	=  (schedule_timesteps == timestep).nonzero()

									# The sigma index that is taken for the **very** first `step`
									# is always the second index (or the last index if there is only 1)
									# This way we can ensure we don't accidentally skip a sigma in
									# case we start in the middle of the denoising schedule (e.g. for image-to-image)
									if len(self._index_counter						) == 0:
													A_       	=  1 if len(a__						) > 1 else 0
									else:
													A_       	=  timestep.cpu().item() if torch.is_tensor(a__						) else timestep
													A_       	=  self._index_counter[timestep_int]

									return indices[pos].item()


					@property
					def        lowerCAmelCase_    (	self						)		->							List[Any]:





									'''simple docstring'''
									# standard deviation of the initial noise distribution
									if self.config.timestep_spacing in ["linspace", "trailing"]:
													return self.sigmas.max()

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


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       )		->							torch.FloatTensor:





									'''simple docstring'''
									A_       	=  self.index_for_timestep(a__						)

									if self.state_in_first_order:
													A_       	=  self.sigmas[step_index]
									else:
													A_       	=  self.sigmas_interpol[step_index - 1]

									A_       	=  sample / ((sigma**2 + 1) ** 0.5)
									return sample


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__ = None       ,       a__ = None       ,       )		->							int:





									'''simple docstring'''
									A_       	=  num_inference_steps

									A_       	=  num_train_timesteps or self.config.num_train_timesteps

									# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
									if self.config.timestep_spacing == "linspace":
													A_       	=  np.linspace(0       ,       num_train_timesteps - 1       ,       a__       ,       dtype=a__						)[::-1].copy()
									elif self.config.timestep_spacing == "leading":
													A_       	=  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
													A_       	=  (np.arange(0       ,       a__						) * step_ratio).round()[::-1].copy().astype(a__						)
													timesteps += self.config.steps_offset
									elif self.config.timestep_spacing == "trailing":
													A_       	=  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
													A_       	=  (np.arange(a__       ,       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'."						)

									A_       	=  np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5						)
									A_       	=  torch.from_numpy(np.log(a__						)						).to(a__						)

									A_       	=  np.interp(a__       ,       np.arange(0       ,       len(a__						)						)       ,       a__						)
									A_       	=  np.concatenate([sigmas, [0.0]]						).astype(np.floataa						)
									A_       	=  torch.from_numpy(a__						).to(device=a__						)

									# compute up and down sigmas
									A_       	=  sigmas.roll(-1						)
									A_       	=  0.0
									A_       	=  (sigmas_next**2 * (sigmas**2 - sigmas_next**2) / sigmas**2) ** 0.5
									A_       	=  (sigmas_next**2 - sigmas_up**2) ** 0.5
									A_       	=  0.0

									# compute interpolated sigmas
									A_       	=  sigmas.log().lerp(sigmas_down.log()       ,       0.5						).exp()
									A_       	=  0.0

									# set sigmas
									A_       	=  torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2						), sigmas[-1:]]						)
									A_       	=  torch.cat(
									    [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2						), sigmas_interpol[-1:]]						)
									A_       	=  torch.cat([sigmas_up[:1], sigmas_up[1:].repeat_interleave(2						), sigmas_up[-1:]]						)
									A_       	=  torch.cat([sigmas_down[:1], sigmas_down[1:].repeat_interleave(2						), sigmas_down[-1:]]						)

									if str(a__						).startswith('''mps'''						):
													# mps does not support float64
													A_       	=  torch.from_numpy(a__						).to(a__       ,       dtype=torch.floataa						)
									else:
													A_       	=  torch.from_numpy(a__						).to(a__						)

									A_       	=  self.sigma_to_t(a__						).to(a__       ,       dtype=timesteps.dtype						)
									A_       	=  torch.stack((timesteps_interpol[:-2, None], timesteps[1:, None])       ,       dim=-1						).flatten()

									A_       	=  torch.cat([timesteps[:1], interleaved_timesteps]						)

									A_       	=  None

									# for exp beta schedules, such as the one for `pipeline_shap_e.py`
									# we need an index counter
									A_       	=  defaultdict(a__						)


					def        lowerCAmelCase_    (	self       ,       a__						)		->							Dict:





									'''simple docstring'''
									A_       	=  sigma.log()

									# get distribution
									A_       	=  log_sigma - self.log_sigmas[:, None]

									# get sigmas range
									A_       	=  dists.ge(0						).cumsum(dim=0						).argmax(dim=0						).clamp(max=self.log_sigmas.shape[0] - 2						)
									A_       	=  low_idx + 1

									A_       	=  self.log_sigmas[low_idx]
									A_       	=  self.log_sigmas[high_idx]

									# interpolate sigmas
									A_       	=  (low - log_sigma) / (low - high)
									A_       	=  w.clamp(0       ,       1						)

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


					@property
					def        lowerCAmelCase_    (	self						)		->							int:





									'''simple docstring'''
									return self.sample is None


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__       ,       a__ = None       ,       a__ = True       ,       )		->							Union[SchedulerOutput, Tuple]:





									'''simple docstring'''
									A_       	=  self.index_for_timestep(a__						)

									# advance index counter by 1
									A_       	=  timestep.cpu().item() if torch.is_tensor(a__						) else timestep
									self._index_counter[timestep_int] += 1

									if self.state_in_first_order:
													A_       	=  self.sigmas[step_index]
													A_       	=  self.sigmas_interpol[step_index]
													A_       	=  self.sigmas_up[step_index]
													A_       	=  self.sigmas_down[step_index - 1]
									else:
													# 2nd order / KPDM2's method
													A_       	=  self.sigmas[step_index - 1]
													A_       	=  self.sigmas_interpol[step_index - 1]
													A_       	=  self.sigmas_up[step_index - 1]
													A_       	=  self.sigmas_down[step_index - 1]

									# currently only gamma=0 is supported. This usually works best anyways.
									# We can support gamma in the future but then need to scale the timestep before
									# passing it to the model which requires a change in API
									A_       	=  0
									A_       	=  sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

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

									# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
									if self.config.prediction_type == "epsilon":
													A_       	=  sigma_hat if self.state_in_first_order else sigma_interpol
													A_       	=  sample - sigma_input * model_output
									elif self.config.prediction_type == "v_prediction":
													A_       	=  sigma_hat if self.state_in_first_order else sigma_interpol
													A_       	=  model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
													    sample / (sigma_input**2 + 1)
													)
									elif self.config.prediction_type == "sample":
													raise NotImplementedError('''prediction_type not implemented yet: sample'''						)
									else:
													raise ValueError(
													    F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"						)

									if self.state_in_first_order:
													# 2. Convert to an ODE derivative for 1st order
													A_       	=  (sample - pred_original_sample) / sigma_hat
													# 3. delta timestep
													A_       	=  sigma_interpol - sigma_hat

													# store for 2nd order step
													A_       	=  sample
													A_       	=  dt
													A_       	=  sample + derivative * dt
									else:
													# DPM-Solver-2
													# 2. Convert to an ODE derivative for 2nd order
													A_       	=  (sample - pred_original_sample) / sigma_interpol
													# 3. delta timestep
													A_       	=  sigma_down - sigma_hat

													A_       	=  self.sample
													A_       	=  None

													A_       	=  sample + derivative * dt
													A_       	=  prev_sample + noise * sigma_up

									if not return_dict:
													return (prev_sample,)

									return SchedulerOutput(prev_sample=a__						)


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__       ,       )		->							torch.FloatTensor:





									'''simple docstring'''
									A_       	=  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
													A_       	=  self.timesteps.to(original_samples.device       ,       dtype=torch.floataa						)
													A_       	=  timesteps.to(original_samples.device       ,       dtype=torch.floataa						)
									else:
													A_       	=  self.timesteps.to(original_samples.device						)
													A_       	=  timesteps.to(original_samples.device						)

									A_       	=  [self.index_for_timestep(a__       ,       a__						) for t in timesteps]

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

									A_       	=  original_samples + noise * sigma
									return noisy_samples


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





									'''simple docstring'''
									return self.config.num_train_timesteps

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



def        lowerCamelCase_  (   __UpperCamelCase     ):
				A_       	=  ConvNextVaConfig()

				if "atto" in checkpoint_url:
								A_       	=  [2, 2, 6, 2]
								A_       	=  [40, 80, 1_60, 3_20]
				if "femto" in checkpoint_url:
								A_       	=  [2, 2, 6, 2]
								A_       	=  [48, 96, 1_92, 3_84]
				if "pico" in checkpoint_url:
								A_       	=  [2, 2, 6, 2]
								A_       	=  [64, 1_28, 2_56, 5_12]
				if "nano" in checkpoint_url:
								A_       	=  [2, 2, 8, 2]
								A_       	=  [80, 1_60, 3_20, 6_40]
				if "tiny" in checkpoint_url:
								A_       	=  [3, 3, 9, 3]
								A_       	=  [96, 1_92, 3_84, 7_68]
				if "base" in checkpoint_url:
								A_       	=  [3, 3, 27, 3]
								A_       	=  [1_28, 2_56, 5_12, 10_24]
				if "large" in checkpoint_url:
								A_       	=  [3, 3, 27, 3]
								A_       	=  [1_92, 3_84, 7_68, 15_36]
				if "huge" in checkpoint_url:
								A_       	=  [3, 3, 27, 3]
								A_       	=  [3_52, 7_04, 14_08, 28_16]

				A_       	=  10_00
				A_       	=  '''imagenet-1k-id2label.json'''
				A_       	=  (1, 10_00)

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

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

				return config, expected_shape



def        lowerCamelCase_  (   __UpperCamelCase     ):
				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 "gamma" in name:
								A_       	=  name.replace('''gamma''' ,						'''weight'''     )
				if "beta" in name:
								A_       	=  name.replace('''beta''' ,						'''bias'''     )
				if "stages" in name:
								A_       	=  name.replace('''stages''' ,						'''encoder.stages'''     )
				if "norm" in name:
								A_       	=  name.replace('''norm''' ,						'''layernorm'''     )
				if "head" in name:
								A_       	=  name.replace('''head''' ,						'''classifier'''     )

				return name



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



def        lowerCamelCase_  (   __UpperCamelCase     ):
				if "224" in checkpoint_url:
								A_       	=  2_24
								A_       	=  2_24 / 2_56
				elif "384" in checkpoint_url:
								A_       	=  3_84
								A_       	=  None
				else:
								A_       	=  5_12
								A_       	=  None

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



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

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

				# load HuggingFace model
				A_       	=  ConvNextVaForImageClassification(__UpperCamelCase     )
				model.load_state_dict(__UpperCamelCase     )
				model.eval()

				# Check outputs on an image, prepared by ConvNextImageProcessor
				A_       	=  convert_preprocessor(__UpperCamelCase     )
				A_       	=  preprocessor(images=prepare_img() ,						return_tensors='''pt'''     )
				A_       	=  model(**__UpperCamelCase     ).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":
								A_       	=  torch.tensor([-0.3930, 0.1747, -0.5246, 0.4177, 0.4295]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_femto_1k_224_ema.pt":
								A_       	=  torch.tensor([-0.1727, -0.5341, -0.7818, -0.4745, -0.6566]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_pico_1k_224_ema.pt":
								A_       	=  torch.tensor([-0.0333, 0.1563, -0.9137, 0.1054, 0.0381]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_nano_1k_224_ema.pt":
								A_       	=  torch.tensor([-0.1744, -0.1555, -0.0713, 0.0950, -0.1431]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_tiny_1k_224_ema.pt":
								A_       	=  torch.tensor([0.9996, 0.1966, -0.4386, -0.3472, 0.6661]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_base_1k_224_ema.pt":
								A_       	=  torch.tensor([-0.2553, -0.6708, -0.1359, 0.2518, -0.2488]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_large_1k_224_ema.pt":
								A_       	=  torch.tensor([-0.0673, -0.5627, -0.3753, -0.2722, 0.0178]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_huge_1k_224_ema.pt":
								A_       	=  torch.tensor([-0.6377, -0.7458, -0.2150, 0.1184, -0.0597]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_nano_22k_224_ema.pt":
								A_       	=  torch.tensor([1.0799, 0.2322, -0.8860, 1.0219, 0.6231]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_nano_22k_384_ema.pt":
								A_       	=  torch.tensor([0.3766, 0.4917, -1.1426, 0.9942, 0.6024]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_tiny_22k_224_ema.pt":
								A_       	=  torch.tensor([0.4220, -0.6919, -0.4317, -0.2881, -0.6609]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_tiny_22k_384_ema.pt":
								A_       	=  torch.tensor([0.1082, -0.8286, -0.5095, 0.4681, -0.8085]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_base_22k_224_ema.pt":
								A_       	=  torch.tensor([-0.2419, -0.6221, 0.2176, -0.0980, -0.7527]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_base_22k_384_ema.pt":
								A_       	=  torch.tensor([0.0391, -0.4371, 0.3786, 0.1251, -0.2784]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_large_22k_224_ema.pt":
								A_       	=  torch.tensor([-0.0504, 0.5636, -0.1729, -0.6507, -0.3949]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_large_22k_384_ema.pt":
								A_       	=  torch.tensor([0.3560, 0.9486, 0.3149, -0.2667, -0.5138]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_huge_22k_384_ema.pt":
								A_       	=  torch.tensor([-0.2469, -0.4550, -0.5853, -0.0810, 0.0309]     )
				elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_huge_22k_512_ema.pt":
								A_       	=  torch.tensor([-0.3090, 0.0802, -0.0682, -0.1979, -0.2826]     )
				else:
								raise ValueError(F"Unknown URL: {checkpoint_url}"     )

				assert torch.allclose(logits[0, :5] ,						__UpperCamelCase ,						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(__UpperCamelCase     ):
												os.mkdir(__UpperCamelCase     )

								model.save_pretrained(__UpperCamelCase     )
								preprocessor.save_pretrained(__UpperCamelCase     )

				A_       	=  '''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(__UpperCamelCase     )
								preprocessor.push_to_hub(__UpperCamelCase     )


if __name__ == "__main__":
						SCREAMING_SNAKE_CASE   :		Tuple					 =       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")

						SCREAMING_SNAKE_CASE   :		Dict					 =       parser.parse_args()
						convert_convnextva_checkpoint(
						    args.checkpoint_url, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub
						)