





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


def        __snake_case       (						lowerCAmelCase_  )							->	Dict:
    SCREAMING_SNAKE_CASE__       							= ConvNextConfig()

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

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

    SCREAMING_SNAKE_CASE__       							= '''huggingface/label-files'''
    SCREAMING_SNAKE_CASE__       							= num_labels
    SCREAMING_SNAKE_CASE__       							= json.load(open(hf_hub_download(__snake_case   ,       __snake_case   ,       repo_type='''dataset'''  )   ,       '''r'''  )  )
    SCREAMING_SNAKE_CASE__       							= {int(__snake_case  ): 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]
    SCREAMING_SNAKE_CASE__       							= idalabel
    SCREAMING_SNAKE_CASE__       							= {v: k for k, v in idalabel.items()}
    SCREAMING_SNAKE_CASE__       							= hidden_sizes
    SCREAMING_SNAKE_CASE__       							= depths

    return config, expected_shape


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

    return name


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


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

    # load HuggingFace model
    SCREAMING_SNAKE_CASE__       							= ConvNextForImageClassification(__snake_case  )
    model.load_state_dict(__snake_case  )
    model.eval()

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

    SCREAMING_SNAKE_CASE__       							= model(__snake_case  ).logits

    # note: the logits below were obtained without center cropping
    if checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth":
        SCREAMING_SNAKE_CASE__       							= 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":
        SCREAMING_SNAKE_CASE__       							= 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":
        SCREAMING_SNAKE_CASE__       							= torch.tensor([0.45_25, 0.75_39, 0.03_08]  )
    elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_384.pth":
        SCREAMING_SNAKE_CASE__       							= 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":
        SCREAMING_SNAKE_CASE__       							= torch.tensor([0.41_74, -0.09_89, 0.14_89]  )
    elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_384.pth":
        SCREAMING_SNAKE_CASE__       							= torch.tensor([0.25_13, -0.13_49, -0.16_13]  )
    elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_224.pth":
        SCREAMING_SNAKE_CASE__       							= torch.tensor([1.29_80, 0.36_31, -0.11_98]  )
    elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_224.pth":
        SCREAMING_SNAKE_CASE__       							= torch.tensor([1.29_63, 0.12_27, 0.17_23]  )
    elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_224.pth":
        SCREAMING_SNAKE_CASE__       							= 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":
        SCREAMING_SNAKE_CASE__       							= 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":
        SCREAMING_SNAKE_CASE__       							= 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":
        SCREAMING_SNAKE_CASE__       							= 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":
        SCREAMING_SNAKE_CASE__       							= 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":
        SCREAMING_SNAKE_CASE__       							= 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":
        SCREAMING_SNAKE_CASE__       							= 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]   ,       __snake_case   ,       atol=1e-3  )
    assert logits.shape == expected_shape

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

    print('''Pushing model to the hub...'''  )
    SCREAMING_SNAKE_CASE__       							= '''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(__snake_case   ,       __snake_case  )   ,       organization='''nielsr'''   ,       commit_message='''Add model'''   ,       )


if __name__ == "__main__":
  _A							= 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.""",
  )

  _A							= parser.parse_args()
  convert_convnext_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)







import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	str:
    SCREAMING_SNAKE_CASE__							,		SCREAMING_SNAKE_CASE__							,		SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.in_proj_weight'''].chunk(3   ,       dim=0  )
    SCREAMING_SNAKE_CASE__							,		SCREAMING_SNAKE_CASE__							,		SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.in_proj_bias'''].chunk(3   ,       dim=0  )

    SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.out_proj.weight''']
    SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.out_proj.bias''']

    SCREAMING_SNAKE_CASE__       							= q_proj
    SCREAMING_SNAKE_CASE__       							= q_proj_bias

    SCREAMING_SNAKE_CASE__       							= k_proj
    SCREAMING_SNAKE_CASE__       							= k_proj_bias

    SCREAMING_SNAKE_CASE__       							= v_proj
    SCREAMING_SNAKE_CASE__       							= v_proj_bias

    SCREAMING_SNAKE_CASE__       							= out_proj_weights
    SCREAMING_SNAKE_CASE__       							= out_proj_bias


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Dict:
    copy_linear(hf_mlp.fca   ,       lowerCAmelCase_   ,       f'''{prefix}.c_fc'''  )
    copy_linear(hf_mlp.fca   ,       lowerCAmelCase_   ,       f'''{prefix}.c_proj'''  )


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	str:
    SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.weight'''].data
    SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.bias'''].data


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Dict:
    # copy layer norms
    copy_linear(hf_layer.layer_norma   ,       lowerCAmelCase_   ,       f'''{prefix}.ln_1'''  )
    copy_linear(hf_layer.layer_norma   ,       lowerCAmelCase_   ,       f'''{prefix}.ln_2'''  )

    # copy MLP
    copy_mlp(hf_layer.mlp   ,       lowerCAmelCase_   ,       f'''{prefix}.mlp'''  )

    # copy attn
    copy_attn_layer(hf_layer.self_attn   ,       lowerCAmelCase_   ,       f'''{prefix}.attn'''  )


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Optional[int]:
    for layer_id, hf_layer in enumerate(lowerCAmelCase_  ):
        copy_layer(lowerCAmelCase_   ,       lowerCAmelCase_   ,       f'''{prefix}.{layer_id}'''  )


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Any:
    # copy projection
    SCREAMING_SNAKE_CASE__       							= pt_weights['''text_projection'''].data.T

    # copy text encoder
    for name, param in hf_model.text_model.named_parameters():
        SCREAMING_SNAKE_CASE__       							= pt_weights[f'''bert.{name}'''].data


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_  )							->	List[str]:
    # copy projection
    SCREAMING_SNAKE_CASE__       							= pt_weights['''visual.proj'''].data.T

    # copy layer norms
    copy_linear(hf_model.vision_model.pre_layrnorm   ,       lowerCAmelCase_   ,       '''visual.ln_pre'''  )
    copy_linear(hf_model.vision_model.post_layernorm   ,       lowerCAmelCase_   ,       '''visual.ln_post'''  )

    # copy embeddings
    SCREAMING_SNAKE_CASE__       							= pt_weights['''visual.conv1.weight'''].data
    SCREAMING_SNAKE_CASE__       							= pt_weights['''visual.class_embedding'''].data
    SCREAMING_SNAKE_CASE__       							= pt_weights['''visual.positional_embedding'''].data

    # copy encoder
    copy_layers(hf_model.vision_model.encoder.layers   ,       lowerCAmelCase_   ,       '''visual.transformer.resblocks'''  )


@torch.no_grad()
def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_=None  )							->	str:
    assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
    SCREAMING_SNAKE_CASE__       							= ChineseCLIPConfig.from_pretrained(lowerCAmelCase_  )

    SCREAMING_SNAKE_CASE__       							= ChineseCLIPModel(lowerCAmelCase_  ).eval()

    SCREAMING_SNAKE_CASE__       							= torch.load(lowerCAmelCase_   ,       map_location='''cpu'''  )['''state_dict''']
    SCREAMING_SNAKE_CASE__       							= {(name[7:] if name.startswith('''module.'''  ) else name): value for name, value in pt_weights.items()}

    copy_text_model_and_projection(lowerCAmelCase_   ,       lowerCAmelCase_  )
    copy_vision_model_and_projection(lowerCAmelCase_   ,       lowerCAmelCase_  )
    SCREAMING_SNAKE_CASE__       							= pt_weights['''logit_scale'''].data

    hf_model.save_pretrained(lowerCAmelCase_  )


if __name__ == "__main__":
  _A				:							Union[str, Any]							= argparse.ArgumentParser()
  parser.add_argument(
      """--pytorch_dump_folder_path""",
      default=None,
      type=str,
      help="""Path to the output folder storing converted hf PyTorch model.""",
  )
  parser.add_argument(
      """--checkpoint_path""", default=None, type=str, help="""Path to original github format ChineseCLIP checkpoint."""
  )
  parser.add_argument(
      """--config_path""", default=None, required=True, type=str, help="""Path to hf config.json of model to convert."""
  )
  _A				:							Union[str, Any]							= parser.parse_args()

  convert_chinese_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
  print("""The conversion is finished!""")
