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							   =      logging.get_logger(__name__)







def 	UpperCAmelCase       (		lowerCAmelCase_       )	->	str:
     a  :    int				=						ConvNextConfig()

     if "tiny" in checkpoint_url:
          a  :    Optional[Any]				=						[3, 3, 9, 3]
          a  :    List[Any]				=						[9_6, 1_9_2, 3_8_4, 7_6_8]
     if "small" in checkpoint_url:
          a  :    List[str]				=						[3, 3, 2_7, 3]
          a  :    str				=						[9_6, 1_9_2, 3_8_4, 7_6_8]
     if "base" in checkpoint_url:
          a  :    Any				=						[3, 3, 2_7, 3]
          a  :    List[str]				=						[1_2_8, 2_5_6, 5_1_2, 1_0_2_4]
     if "large" in checkpoint_url:
          a  :    int				=						[3, 3, 2_7, 3]
          a  :    Dict				=						[1_9_2, 3_8_4, 7_6_8, 1_5_3_6]
     if "xlarge" in checkpoint_url:
          a  :    Tuple				=						[3, 3, 2_7, 3]
          a  :    List[str]				=						[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]

     if "1k" in checkpoint_url:
          a  :    Union[str, Any]				=						1_0_0_0
          a  :    Optional[Any]				=						'''imagenet-1k-id2label.json'''
          a  :    Union[str, Any]				=						(1, 1_0_0_0)
     else:
          a  :    Dict				=						2_1_8_4_1
          a  :    Tuple				=						'''imagenet-22k-id2label.json'''
          a  :    Dict				=						(1, 2_1_8_4_1)

     a  :    Any				=						'''huggingface/label-files'''
     a  :    Optional[Any]				=						num_labels
     a  :    List[str]				=						json.load(open(hf_hub_download(lowerCAmelCase_						,      lowerCAmelCase_						,      repo_type='''dataset'''       )						,      '''r'''       )       )
     a  :    Dict				=						{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]
     a  :    Tuple				=						idalabel
     a  :    Optional[Any]				=						{v: k for k, v in idalabel.items()}
     a  :    Union[str, Any]				=						hidden_sizes
     a  :    Optional[Any]				=						depths

     return config, expected_shape







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

     return name







def 	UpperCAmelCase       (		)	->	List[str]:
     a  :    Union[str, Any]				=						'''http://images.cocodataset.org/val2017/000000039769.jpg'''
     a  :    List[Any]				=						Image.open(requests.get(lowerCAmelCase_						,      stream=lowerCAmelCase_       ).raw       )
     return im







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

     # load HuggingFace model
     a  :    int				=						ConvNextForImageClassification(lowerCAmelCase_       )
     model.load_state_dict(lowerCAmelCase_       )
     model.eval()

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

     a  :    Optional[int]				=						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  :    int				=						torch.tensor([-0.12_10, -0.66_05, 0.19_18]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_small_1k_224_ema.pth":
          a  :    List[Any]				=						torch.tensor([-0.44_73, -0.18_47, -0.63_65]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_224_ema.pth":
          a  :    Tuple				=						torch.tensor([0.45_25, 0.75_39, 0.03_08]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_384.pth":
          a  :    Optional[int]				=						torch.tensor([0.35_61, 0.63_50, -0.03_84]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_224_ema.pth":
          a  :    List[Any]				=						torch.tensor([0.41_74, -0.09_89, 0.14_89]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_384.pth":
          a  :    Tuple				=						torch.tensor([0.25_13, -0.13_49, -0.16_13]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_224.pth":
          a  :    List[str]				=						torch.tensor([1.29_80, 0.36_31, -0.11_98]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_224.pth":
          a  :    List[Any]				=						torch.tensor([1.29_63, 0.12_27, 0.17_23]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_224.pth":
          a  :    Optional[int]				=						torch.tensor([1.79_56, 0.83_90, 0.28_20]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_224.pth":
          a  :    Tuple				=						torch.tensor([-0.28_22, -0.05_02, -0.08_78]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_384.pth":
          a  :    List[str]				=						torch.tensor([-0.56_72, -0.07_30, -0.43_48]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_224.pth":
          a  :    Optional[Any]				=						torch.tensor([0.26_81, 0.23_65, 0.62_46]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_384.pth":
          a  :    str				=						torch.tensor([-0.26_42, 0.39_31, 0.51_16]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_224_ema.pth":
          a  :    Dict				=						torch.tensor([-0.66_77, -0.18_73, -0.83_79]       )
     elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_384_ema.pth":
          a  :    List[Any]				=						torch.tensor([-0.77_49, -0.29_67, -0.64_44]       )
     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  :    Tuple				=						'''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							   =      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							   =      parser.parse_args()
  convert_convnext_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block






@dataclass
class 							_SCREAMING_SNAKE_CASE(   snake_case__	):
   UpperCamelCase_				:						torch.FloatTensor






class 							_SCREAMING_SNAKE_CASE(   snake_case__       ,      snake_case__	):
   @register_to_config
   def __init__(    self							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = 3							,     lowerCAmelCase_ = 3							,     lowerCAmelCase_ = False							,     lowerCAmelCase_ = "positional"							,     lowerCAmelCase_ = 0							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")							,     lowerCAmelCase_ = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")							,     lowerCAmelCase_ = (2_24, 4_48, 6_72, 8_96)							,     lowerCAmelCase_ = 2							,     lowerCAmelCase_ = 1							,     lowerCAmelCase_ = 1							,     lowerCAmelCase_ = "conv"							,     lowerCAmelCase_ = "conv"							,     lowerCAmelCase_ = "silu"							,     lowerCAmelCase_ = 8							,     lowerCAmelCase_ = 32							,     lowerCAmelCase_ = 1e-5							,     lowerCAmelCase_ = "default"							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = None							,     )	->Tuple:
        super().__init__()

        a  :    List[Any]				=						sample_size
        a  :    List[Any]				=						block_out_channels[0] * 4

        # Check inputs
        if len(lowerCAmelCase_    ) != len(lowerCAmelCase_    ):
             raise ValueError(
                 F"""Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."""    )

        if len(lowerCAmelCase_    ) != len(lowerCAmelCase_    ):
             raise ValueError(
                 F"""Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."""    )

        # input
        a  :    List[Any]				=						nn.Convad(lowerCAmelCase_							,     block_out_channels[0]							,     kernel_size=3							,     padding=(1, 1)    )

        # time
        if time_embedding_type == "fourier":
             a  :    List[Any]				=						GaussianFourierProjection(embedding_size=block_out_channels[0]							,     scale=16    )
             a  :    List[Any]				=						2 * block_out_channels[0]
        elif time_embedding_type == "positional":
             a  :    Dict				=						Timesteps(block_out_channels[0]							,     lowerCAmelCase_							,     lowerCAmelCase_    )
             a  :    List[str]				=						block_out_channels[0]

        a  :    List[str]				=						TimestepEmbedding(lowerCAmelCase_							,     lowerCAmelCase_    )

        # class embedding
        if class_embed_type is None and num_class_embeds is not None:
             a  :    Dict				=						nn.Embedding(lowerCAmelCase_							,     lowerCAmelCase_    )
        elif class_embed_type == "timestep":
             a  :    str				=						TimestepEmbedding(lowerCAmelCase_							,     lowerCAmelCase_    )
        elif class_embed_type == "identity":
             a  :    List[str]				=						nn.Identity(lowerCAmelCase_							,     lowerCAmelCase_    )
        else:
             a  :    Optional[Any]				=						None

        a  :    str				=						nn.ModuleList([]    )
        a  :    Any				=						None
        a  :    List[Any]				=						nn.ModuleList([]    )

        # down
        a  :    List[Any]				=						block_out_channels[0]
        for i, down_block_type in enumerate(lowerCAmelCase_    ):
             a  :    Dict				=						output_channel
             a  :    Union[str, Any]				=						block_out_channels[i]
             a  :    int				=						i == len(lowerCAmelCase_    ) - 1

             a  :    Tuple				=						get_down_block(
                 lowerCAmelCase_							,     num_layers=lowerCAmelCase_							,     in_channels=lowerCAmelCase_							,     out_channels=lowerCAmelCase_							,     temb_channels=lowerCAmelCase_							,     add_downsample=not is_final_block							,     resnet_eps=lowerCAmelCase_							,     resnet_act_fn=lowerCAmelCase_							,     resnet_groups=lowerCAmelCase_							,     attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel							,     downsample_padding=lowerCAmelCase_							,     resnet_time_scale_shift=lowerCAmelCase_							,     downsample_type=lowerCAmelCase_							,     )
             self.down_blocks.append(lowerCAmelCase_    )

        # mid
        a  :    int				=						UNetMidBlockaD(
            in_channels=block_out_channels[-1]							,     temb_channels=lowerCAmelCase_							,     resnet_eps=lowerCAmelCase_							,     resnet_act_fn=lowerCAmelCase_							,     output_scale_factor=lowerCAmelCase_							,     resnet_time_scale_shift=lowerCAmelCase_							,     attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]							,     resnet_groups=lowerCAmelCase_							,     add_attention=lowerCAmelCase_							,     )

        # up
        a  :    Optional[int]				=						list(reversed(lowerCAmelCase_    )    )
        a  :    Tuple				=						reversed_block_out_channels[0]
        for i, up_block_type in enumerate(lowerCAmelCase_    ):
             a  :    List[Any]				=						output_channel
             a  :    Optional[Any]				=						reversed_block_out_channels[i]
             a  :    Dict				=						reversed_block_out_channels[min(i + 1							,     len(lowerCAmelCase_    ) - 1    )]

             a  :    Any				=						i == len(lowerCAmelCase_    ) - 1

             a  :    List[Any]				=						get_up_block(
                 lowerCAmelCase_							,     num_layers=layers_per_block + 1							,     in_channels=lowerCAmelCase_							,     out_channels=lowerCAmelCase_							,     prev_output_channel=lowerCAmelCase_							,     temb_channels=lowerCAmelCase_							,     add_upsample=not is_final_block							,     resnet_eps=lowerCAmelCase_							,     resnet_act_fn=lowerCAmelCase_							,     resnet_groups=lowerCAmelCase_							,     attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel							,     resnet_time_scale_shift=lowerCAmelCase_							,     upsample_type=lowerCAmelCase_							,     )
             self.up_blocks.append(lowerCAmelCase_    )
             a  :    Any				=						output_channel

        # out
        a  :    str				=						norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4							,     32    )
        a  :    Tuple				=						nn.GroupNorm(num_channels=block_out_channels[0]							,     num_groups=lowerCAmelCase_							,     eps=lowerCAmelCase_    )
        a  :    Any				=						nn.SiLU()
        a  :    List[Any]				=						nn.Convad(block_out_channels[0]							,     lowerCAmelCase_							,     kernel_size=3							,     padding=1    )


   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = True							,     )	->Union[UNetaDOutput, Tuple]:
        # 0. center input if necessary
        if self.config.center_input_sample:
             a  :    Any				=						2 * sample - 1.0

        # 1. time
        a  :    Optional[Any]				=						timestep
        if not torch.is_tensor(lowerCAmelCase_    ):
             a  :    Dict				=						torch.tensor([timesteps]							,     dtype=torch.long							,     device=sample.device    )
        elif torch.is_tensor(lowerCAmelCase_    ) and len(timesteps.shape    ) == 0:
             a  :    Any				=						timesteps[None].to(sample.device    )

        # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
        a  :    Optional[Any]				=						timesteps * torch.ones(sample.shape[0]							,     dtype=timesteps.dtype							,     device=timesteps.device    )

        a  :    Dict				=						self.time_proj(lowerCAmelCase_    )

        # timesteps does not contain any weights and will always return f32 tensors
        # but time_embedding might actually be running in fp16. so we need to cast here.
        # there might be better ways to encapsulate this.
        a  :    Optional[Any]				=						t_emb.to(dtype=self.dtype    )
        a  :    Dict				=						self.time_embedding(lowerCAmelCase_    )

        if self.class_embedding is not None:
             if class_labels is None:
                  raise ValueError('''class_labels should be provided when doing class conditioning'''    )

             if self.config.class_embed_type == "timestep":
                  a  :    List[str]				=						self.time_proj(lowerCAmelCase_    )

             a  :    Any				=						self.class_embedding(lowerCAmelCase_    ).to(dtype=self.dtype    )
             a  :    Optional[int]				=						emb + class_emb

        # 2. pre-process
        a  :    int				=						sample
        a  :    Dict				=						self.conv_in(lowerCAmelCase_    )

        # 3. down
        a  :    Union[str, Any]				=						(sample,)
        for downsample_block in self.down_blocks:
             if hasattr(lowerCAmelCase_							,     '''skip_conv'''    ):
                  a			,							a			,							a  :    str				=						downsample_block(
                      hidden_states=lowerCAmelCase_							,     temb=lowerCAmelCase_							,     skip_sample=lowerCAmelCase_    )
             else:
                  a			,							a  :    List[str]				=						downsample_block(hidden_states=lowerCAmelCase_							,     temb=lowerCAmelCase_    )

             down_block_res_samples += res_samples

        # 4. mid
        a  :    str				=						self.mid_block(lowerCAmelCase_							,     lowerCAmelCase_    )

        # 5. up
        a  :    int				=						None
        for upsample_block in self.up_blocks:
             a  :    List[str]				=						down_block_res_samples[-len(upsample_block.resnets    ) :]
             a  :    Any				=						down_block_res_samples[: -len(upsample_block.resnets    )]

             if hasattr(lowerCAmelCase_							,     '''skip_conv'''    ):
                  a			,							a  :    Any				=						upsample_block(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
             else:
                  a  :    Union[str, Any]				=						upsample_block(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )

        # 6. post-process
        a  :    Tuple				=						self.conv_norm_out(lowerCAmelCase_    )
        a  :    Optional[Any]				=						self.conv_act(lowerCAmelCase_    )
        a  :    Tuple				=						self.conv_out(lowerCAmelCase_    )

        if skip_sample is not None:
             sample += skip_sample

        if self.config.time_embedding_type == "fourier":
             a  :    Optional[Any]				=						timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]    )))    )
             a  :    int				=						sample / timesteps

        if not return_dict:
             return (sample,)

        return UNetaDOutput(sample=lowerCAmelCase_    )